content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.grayherring.devtalks.ui import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith /** * Instrumentation test, which will execute on an Android device. * * @see [Testing documentation](http://d.android.com/tools/testing) */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test @Throws(Exception::class) fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.grayherring.devtalks", appContext.packageName) } }
example/app/src/androidTest/java/com/grayherring/devtalks/ui/ExampleInstrumentedTest.kt
2354941796
package au.com.codeka.warworlds.server.world import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.DeviceInfo import au.com.codeka.warworlds.common.proto.Empire import au.com.codeka.warworlds.common.proto.Notification import au.com.codeka.warworlds.server.store.DataStore import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingException import com.google.firebase.messaging.Message import java.util.* class NotificationManager { fun start() {} /** * Sends the given [Notification] to the given [Empire]. * @param empire The [Empire] to send to. * @param notification The [Notification] to send. */ fun sendNotification(empire: Empire, notification: Notification) { val notificationBase64 = Base64.getEncoder().encodeToString(notification.encode()) val devices: List<DeviceInfo> = DataStore.i.empires().getDevicesForEmpire(empire.id) for (device in devices) { sendNotification(device, notificationBase64) } } private fun sendNotification(device: DeviceInfo, notificationBase64: String) { val msg = Message.builder() .putData("notification", notificationBase64) .setToken(device.fcm_device_info!!.token) .build() try { val resp = FirebaseMessaging.getInstance().send(msg) log.info("Firebase message sent: %s", resp) } catch (e: FirebaseMessagingException) { log.error("Error sending firebase notification: %s", e.errorCode, e) } } companion object { private val log = Log("EmpireManager") val i = NotificationManager() } }
server/src/main/kotlin/au/com/codeka/warworlds/server/world/NotificationManager.kt
143350743
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("GroovyProjectWizardUtils") package org.jetbrains.plugins.groovy.config.wizard import com.intellij.framework.library.FrameworkLibraryVersion import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.UIBundle import com.intellij.ui.dsl.builder.* import com.intellij.util.castSafelyTo import com.intellij.util.containers.orNull import com.intellij.util.download.DownloadableFileSetVersions import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.config.GroovyConfigUtils import org.jetbrains.plugins.groovy.config.loadLatestGroovyVersions import java.awt.Component import java.util.* import javax.swing.ComboBoxModel import javax.swing.DefaultListCellRenderer import javax.swing.JList import javax.swing.SwingUtilities const val GROOVY_SDK_FALLBACK_VERSION = "3.0.9" private const val MAIN_FILE = "Main.groovy" private const val MAIN_GROOVY_TEMPLATE = "template.groovy" fun Row.groovySdkComboBox(property : GraphProperty<Optional<String>>) { comboBox(getInitializedModel(), fallbackAwareRenderer) .columns(COLUMNS_MEDIUM) .bindItem(property) .validationOnInput { if (property.get().isEmpty) { warning(GroovyBundle.message("new.project.wizard.groovy.retrieving.has.failed")) } else { null } } } fun Panel.addSampleCodeCheckbox(property : GraphProperty<Boolean>) { row { checkBox(UIBundle.message("label.project.wizard.new.project.add.sample.code")) .bindSelected(property) }.topGap(TopGap.SMALL) } fun ModuleBuilder.createSampleGroovyCodeFile(project: Project, sourceDirectory: VirtualFile) { WriteCommandAction.runWriteCommandAction(project, GroovyBundle.message("new.project.wizard.groovy.creating.main.file"), null, Runnable { val fileTemplate = FileTemplateManager.getInstance(project).getCodeTemplate(MAIN_GROOVY_TEMPLATE) val helloWorldFile = sourceDirectory.createChildData(this, MAIN_FILE) VfsUtil.saveText(helloWorldFile, fileTemplate.text) }) } private val fallbackAwareRenderer: DefaultListCellRenderer = object : DefaultListCellRenderer() { override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { val representation = value.castSafelyTo<Optional<*>>()?.orNull()?.castSafelyTo<String>() ?: GROOVY_SDK_FALLBACK_VERSION // NON-NLS return super.getListCellRendererComponent(list, representation, index, isSelected, cellHasFocus) } } private fun getInitializedModel(): ComboBoxModel<Optional<String>> { val model = CollectionComboBoxModel<Optional<String>>() loadLatestGroovyVersions(object : DownloadableFileSetVersions.FileSetVersionsCallback<FrameworkLibraryVersion>() { override fun onSuccess(versions: MutableList<out FrameworkLibraryVersion>) { SwingUtilities.invokeLater { for (version in versions.sortedWith(::moveUnstableVersionToTheEnd)) { model.add(Optional.of(version.versionString)) } model.selectedItem = model.items.first() } } override fun onError(errorMessage: String) { model.add(Optional.empty()) model.selectedItem = model.items.first() } }) return model } internal fun moveUnstableVersionToTheEnd(left: FrameworkLibraryVersion, right: FrameworkLibraryVersion): Int { val leftVersion = left.versionString val rightVersion = right.versionString val leftUnstable = GroovyConfigUtils.isUnstable(leftVersion) val rightUnstable = GroovyConfigUtils.isUnstable(rightVersion) return when { leftUnstable == rightUnstable -> -GroovyConfigUtils.compareSdkVersions(leftVersion, rightVersion) leftUnstable -> 1 else -> -1 } }
plugins/groovy/src/org/jetbrains/plugins/groovy/config/wizard/GroovyProjectWizardUtils.kt
3916477173
class Doo { fun test() { } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/extension/Doo.kt
1690245742
package test actual class <!LINE_MARKER("descr='Has declaration in common module'")!>Expect<!> { actual fun <!LINE_MARKER("descr='Has declaration in common module'")!>commonFun<!>(): String = "" fun platformFun(): Int = 42 } fun topLevelPlatformFun(): String = ""
plugins/kotlin/idea/tests/testData/multiplatform/transitiveDependencyOnCommonSourceSets/jvmMpp/jvm.kt
3679588517
package synchronizedBlock fun main() { //Breakpoint! val a = 5 } // EXPRESSION: synchronized(Any()) { "foo" } // RESULT: "foo": Ljava/lang/String;
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/synchronizedBlock.kt
1635858664
var Int.prop: String get() = TODO() set(value) { <caret> }
plugins/kotlin/idea/tests/testData/codeInsight/breadcrumbs/PropertyAccessor.kt
1371076228
import de.fabmax.webidl.generator.js.JsInterfaceGenerator import de.fabmax.webidl.parser.WebIdlParser import org.gradle.api.DefaultTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.TaskAction import java.io.File import java.io.FileNotFoundException open class PhysxJsGenerator : DefaultTask() { @Input var idlSource = "" @Input var generatorOutput = "./generated" @TaskAction fun generate() { val idlFile = File(idlSource) if (!idlFile.exists()) { throw FileNotFoundException("PhysX WebIDL definition not found!") } val model = WebIdlParser().parse(idlFile.path) JsInterfaceGenerator().apply { outputDirectory = generatorOutput packagePrefix = "physx" moduleName = "physx-js-webidl" nullableAttributes += "PxBatchQueryDesc.preFilterShader" nullableAttributes += "PxBatchQueryDesc.postFilterShader" nullableParameters += "PxArticulationBase.createLink" to "parent" nullableReturnValues += "PxArticulationLink.getInboundJoint" }.generate(model) } }
buildSrc/src/main/java/PhysxJsGenerator.kt
403261425
package com.tofi.peekazoo.activities import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import com.tofi.peekazoo.R import com.tofi.peekazoo.SharedPreferencesManager import com.tofi.peekazoo.api.InkbunnyApi import com.tofi.peekazoo.api.SubmissionRequestHelper import com.tofi.peekazoo.api.WeasylApi import com.tofi.peekazoo.di.components.ActivityComponent import com.tofi.peekazoo.lists.adapters.SubmissionResultsAdapter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_submissions.* import javax.inject.Inject class SubmissionsActivity : BaseActivity() { @Inject lateinit var sharedPreferencesManager: SharedPreferencesManager @Inject lateinit var inkbunnyApi: InkbunnyApi @Inject lateinit var weasylApi: WeasylApi private lateinit var submissionRequestHelper: SubmissionRequestHelper private var adapter: SubmissionResultsAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_submissions) submissionRequestHelper = SubmissionRequestHelper(activityComponent) val sid = sharedPreferencesManager.getStringPreference(SharedPreferencesManager.SESSION_ID, "") if (sid.isBlank()) { inkbunnyApi.login("guest", "") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({(sid, _, _) -> sharedPreferencesManager.writeStringPreference(SharedPreferencesManager.SESSION_ID, sid) startSearchRequest() }, {}) } else { startSearchRequest() } } override fun inject(component: ActivityComponent) { activityComponent.inject(this) } private fun startSearchRequest() { submissionRequestHelper.fetchSubmissions() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({submissions -> if (adapter == null) { adapter = SubmissionResultsAdapter(activityComponent, submissions) listSearchResults.adapter = adapter listSearchResults.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) } }) } }
app/src/main/java/com/tofi/peekazoo/activities/SubmissionsActivity.kt
167143947
package com.cn29.aac.datasource.auth.remote import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.cn29.aac.datasource.api.ApiResponse import com.cn29.aac.repo.user.LoginBean import retrofit2.Response class FacebookAuth { fun getLogin(email: String?): LiveData<ApiResponse<LoginBean>> { val liveData = MutableLiveData<ApiResponse<LoginBean>>() val loginBean = LoginBean(email!!, "Facebook") loginBean.isLogin = 1 liveData.value = ApiResponse(Response.success(loginBean)) return liveData } }
app/src/main/java/com/cn29/aac/datasource/auth/remote/FacebookAuth.kt
895642174
// WITH_RUNTIME // INTENTION_TEXT: "Replace with 'map{}.minOrNull()'" // INTENTION_TEXT_2: "Replace with 'asSequence().map{}.minOrNull()'" fun getMinLineWidth(lineCount: Int): Double { var min_width = Double.MAX_VALUE <caret>for (i in 0..lineCount - 1) { val width = getLineWidth(i) min_width = if (min_width > width) min_width else width } return min_width } fun getLineWidth(i: Int): Double = TODO()
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/maxMin/min3.kt
243576916
// WITH_RUNTIME fun foo(value: Int?): Int? { return value<caret>?.let { it + 1 } }
plugins/kotlin/idea/tests/testData/intentions/branched/safeAccessToIfThen/let.kt
1033423391
fun a() { val somelong = 3 + 4 - ( <caret> ) } // SET_TRUE: ALIGN_MULTILINE_BINARY_OPERATION // IGNORE_FORMATTER
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParenthesisInBinaryExpression/InExpressionsParentheses4.after.kt
3382538793
// WITH_RUNTIME // IS_APPLICABLE: false class MyClass { fun foo1() = Unit fun foo2(a: MyClass) = Unit fun foo3() = Unit fun foo4(a: MyClass) { val a = MyClass() a.foo1() a.foo2(this) a.foo3()<caret> } }
plugins/kotlin/idea/tests/testData/intentions/convertToScope/convertToApply/thisParameter2.kt
4154974228
package org.schabi.newpipe.ktx import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import java.io.IOException import java.io.InterruptedIOException import java.net.SocketException import javax.net.ssl.SSLException class ThrowableExtensionsTest { @Test fun `assignable causes`() { assertTrue(Throwable().hasAssignableCause<Throwable>()) assertTrue(Exception().hasAssignableCause<Exception>()) assertTrue(IOException().hasAssignableCause<Exception>()) assertTrue(IOException().hasAssignableCause<IOException>()) assertTrue(Exception(SocketException()).hasAssignableCause<IOException>()) assertTrue(Exception(IllegalStateException()).hasAssignableCause<RuntimeException>()) assertTrue(Exception(Exception(IOException())).hasAssignableCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(IOException()))).hasAssignableCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(SocketException()))).hasAssignableCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(SSLException("IO")))).hasAssignableCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasAssignableCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasAssignableCause<RuntimeException>()) assertTrue(IllegalStateException().hasAssignableCause<Throwable>()) assertTrue(IllegalStateException().hasAssignableCause<Exception>()) assertTrue(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasAssignableCause<InterruptedIOException>()) } @Test fun `no assignable causes`() { assertFalse(Throwable().hasAssignableCause<Exception>()) assertFalse(Exception().hasAssignableCause<IOException>()) assertFalse(Exception(IllegalStateException()).hasAssignableCause<IOException>()) assertFalse(Exception(NullPointerException()).hasAssignableCause<IOException>()) assertFalse(Exception(IllegalStateException(Exception(Exception()))).hasAssignableCause<IOException>()) assertFalse(Exception(IllegalStateException(Exception(SocketException()))).hasAssignableCause<InterruptedIOException>()) assertFalse(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasAssignableCause<InterruptedException>()) } @Test fun `exact causes`() { assertTrue(Throwable().hasExactCause<Throwable>()) assertTrue(Exception().hasExactCause<Exception>()) assertTrue(IOException().hasExactCause<IOException>()) assertTrue(Exception(SocketException()).hasExactCause<SocketException>()) assertTrue(Exception(Exception(IOException())).hasExactCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(IOException()))).hasExactCause<IOException>()) assertTrue(Exception(IllegalStateException(Exception(SocketException()))).hasExactCause<SocketException>()) assertTrue(Exception(IllegalStateException(Exception(SSLException("IO")))).hasExactCause<SSLException>()) assertTrue(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasExactCause<InterruptedIOException>()) assertTrue(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasExactCause<IllegalStateException>()) } @Test fun `no exact causes`() { assertFalse(Throwable().hasExactCause<Exception>()) assertFalse(Exception().hasExactCause<Throwable>()) assertFalse(SocketException().hasExactCause<IOException>()) assertFalse(IllegalStateException().hasExactCause<RuntimeException>()) assertFalse(Exception(SocketException()).hasExactCause<IOException>()) assertFalse(Exception(IllegalStateException(Exception(IOException()))).hasExactCause<RuntimeException>()) assertFalse(Exception(IllegalStateException(Exception(SocketException()))).hasExactCause<IOException>()) assertFalse(Exception(IllegalStateException(Exception(InterruptedIOException()))).hasExactCause<IOException>()) } }
app/src/test/java/org/schabi/newpipe/ktx/ThrowableExtensionsTest.kt
3628867122
import java.io.File class C : File("") { override fun isFile(): Boolean { return true } } fun f(pair: Pair<out File, out Any>) { if (pair.first !is C) return pair.first.<caret> } // EXIST: {"lookupString":"absolutePath","tailText":" (from getAbsolutePath())","typeText":"String","attributes":"bold","allLookupStrings":"absolutePath, getAbsolutePath","itemText":"absolutePath"} // EXIST: { lookupString: "isFile", itemText: "isFile", tailText: " (from isFile())", typeText: "Boolean", attributes: "bold" }
plugins/kotlin/completion/tests/testData/basic/java/boldOrGrayed/NonPredictableSmartCast1.kt
243143241
package ppp class C { val xxx = "" fun xxx() = "" fun xxx(p: Int) = "" fun foo() { xx<caret> } } val C.xxx: Int get() = 1 fun C.xxx() = 1 fun C.xxx(p: Int) = 1 fun C.xxx(p: String) = 1 // EXIST: { lookupString: "xxx", itemText: "xxx", tailText: null, typeText: "String" } // EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "()", typeText: "String" } // EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "(p: Int)", typeText: "String" } // EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "(p: String) for C in ppp", typeText: "Int" } // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/basic/common/shadowing/PreferMemberToExtension.kt
1033468907
package com.baulsupp.oksocial.output import okio.Path import java.nio.file.Files actual fun errPrintln(string: String) = System.err.println(string) actual fun mimeType(path: Path) = Files.probeContentType(path.toNioPath())
src/jvmMain/kotlin/com/baulsupp/oksocial/output/platform.kt
1181324245
package org.intellij.plugins.markdown.ui.actions.styling import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.project.Project import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.psi.PsiElement import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.MarkdownBundle.messagePointer import org.intellij.plugins.markdown.MarkdownIcons import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAt import org.intellij.plugins.markdown.editor.lists.ListUtils.items import org.intellij.plugins.markdown.editor.lists.ListUtils.list import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownList import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem import org.intellij.plugins.markdown.util.hasType import org.jetbrains.annotations.Nls import java.util.function.Supplier import javax.swing.Icon /** * Not expected to be used directly. * Check [CreateOrChangeListPopupAction]. */ internal class CreateOrChangeListActionGroup: DefaultActionGroup( UnorderedList(), OrderedList(), CheckmarkList() ) { override fun isPopup(): Boolean = true class OrderedList: CreateListImpl( text = messagePointer("markdown.create.list.popup.ordered.action.text"), icon = MarkdownIcons.EditorActions.NumberedList ) { override fun isSameMarker(markerElement: PsiElement): Boolean { return !hasCheckbox(markerElement) && obtainMarkerText(markerElement)?.toIntOrNull() != null } override fun createMarkerText(index: Int): String { return "${index + 1}." } } class UnorderedList: CreateListImpl( text = messagePointer("markdown.create.list.popup.unordered.action.text"), icon = MarkdownIcons.EditorActions.BulletList ) { override fun isSameMarker(markerElement: PsiElement): Boolean { return !hasCheckbox(markerElement) && obtainMarkerText(markerElement) == "*" } override fun createMarkerText(index: Int): String { return "*" } } class CheckmarkList: CreateListImpl( text = messagePointer("markdown.create.list.popup.checkmark.action.text"), icon = MarkdownIcons.EditorActions.CheckmarkList ) { override fun isSameMarker(markerElement: PsiElement): Boolean { return hasCheckbox(markerElement) } override fun createMarkerText(index: Int): String { return "${index + 1}. [ ]" } override fun processListElement(originalChild: MarkdownListItem, index: Int): PsiElement { val (marker, checkbox) = MarkdownPsiElementFactory.createListMarkerWithCheckbox( originalChild.project, "${index + 1}.", true ) val addedMarker = originalChild.markerElement!!.replace(marker) originalChild.addAfter(checkbox, addedMarker) return originalChild } } abstract class CreateListImpl( text: Supplier<@Nls String>, description: Supplier<@Nls String> = text, icon: Icon ): ToggleAction(text, description, icon) { override fun setSelected(event: AnActionEvent, state: Boolean) { val project = event.project ?: return val editor = event.getData(CommonDataKeys.EDITOR) ?: return val caret = event.getData(CommonDataKeys.CARET) ?: return val file = event.getData(CommonDataKeys.PSI_FILE) as? MarkdownFile ?: return val caretOffset = caret.selectionStart val document = editor.document val list = findList(file, document, caretOffset) runWriteAction { executeCommand(project) { when { state && list == null -> createListFromText(project, document, caret) state && list != null -> replaceList(list) !state && list != null -> replaceListWithText(document, list) } } } } override fun isSelected(event: AnActionEvent): Boolean { val file = event.getData(CommonDataKeys.PSI_FILE) as? MarkdownFile ?: return false val editor = event.getData(CommonDataKeys.EDITOR) ?: return false val caretOffset = editor.caretModel.currentCaret.offset val document = editor.document val list = findList(file, document, caretOffset) ?: return false val marker = list.items.firstOrNull()?.markerElement ?: return false return isSameMarker(marker) } abstract fun isSameMarker(markerElement: PsiElement): Boolean abstract fun createMarkerText(index: Int): String open fun processListElement(originalChild: MarkdownListItem, index: Int): PsiElement { val marker = MarkdownPsiElementFactory.createListMarker(originalChild.project, createMarkerText(index)) val originalMarker = originalChild.markerElement ?: return originalChild if (hasCheckbox(originalMarker)) { originalMarker.nextSibling?.delete() } originalMarker.replace(marker) return originalChild } private fun replaceList(list: MarkdownList): MarkdownList { val resultList = MarkdownPsiElementFactory.createEmptyList(list.project, true) val children = list.firstChild?.siblings(forward = true, withSelf = true) ?: return list var itemIndex = 0 for (child in children) { when (child) { is MarkdownListItem -> { resultList.add(processListElement(child, itemIndex)) itemIndex += 1 } else -> resultList.add(child) } } return list.replace(resultList) as MarkdownList } private fun createListFromText(project: Project, document: Document, caret: Caret) { val startLine = document.getLineNumber(caret.selectionStart) val endLine = document.getLineNumber(caret.selectionEnd) val text = document.charsSequence val lines = (startLine..endLine).asSequence().map { text.substring(document.getLineStartOffset(it), document.getLineEndOffset(it)) } val list = MarkdownPsiElementFactory.createList(project, lines.asIterable(), ::createMarkerText) document.replaceString(document.getLineStartOffset(startLine), document.getLineEndOffset(endLine), list.text) } companion object { private fun findList(file: MarkdownFile, document: Document, offset: Int): MarkdownList? { return file.getListItemAt(offset, document)?.list } private fun replaceListWithText(document: Document, list: MarkdownList) { val firstItem = list.items.firstOrNull() ?: return val builder = StringBuilder() for (element in firstItem.siblings(forward = true)) { val text = when (element) { is MarkdownListItem -> element.itemText ?: "" else -> element.text } builder.append(text) } val range = list.textRange document.replaceString(range.startOffset, range.endOffset, builder.toString()) } } } companion object { private fun obtainMarkerText(markerElement: PsiElement): String? { return markerElement.text?.trimEnd('.', ')', ' ') } private fun hasCheckbox(element: PsiElement): Boolean { return element.nextSibling?.hasType(MarkdownTokenTypes.CHECK_BOX) == true } } }
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/CreateOrChangeListActionGroup.kt
753417362
package io.rg.mp.drive.data class ExpenseList(val list: List<Expense>)
app/src/main/kotlin/io/rg/mp/drive/data/ExpenseList.kt
3653945979
package com.github.bjansen.intellij.pebble.config import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.project.Project class PebbleProjectSettings(private val project: Project) : SearchableConfigurable, Disposable { private val form = PebbleSettingsForm(project) override fun isModified(): Boolean { val config = PropertiesComponent.getInstance(project) return form.customPrefix != config.getValue(prefixProperty) ?: "" || form.customSuffix != config.getValue(suffixProperty) ?: "" } override fun reset() { val config = PropertiesComponent.getInstance(project) form.customPrefix = config.getValue(prefixProperty) form.customSuffix = config.getValue(suffixProperty) } override fun apply() { val config = PropertiesComponent.getInstance(project) config.setValue(prefixProperty, form.customPrefix) config.setValue(suffixProperty, form.customSuffix) } override fun getId() = PebbleProjectSettings::javaClass.name override fun getDisplayName() = "Pebble" override fun createComponent() = form.createCenterPanel() override fun dispose() = form.disposable.dispose() companion object { val prefixProperty = "pebble.loader.prefix" val suffixProperty = "pebble.loader.suffix" } }
src/main/kotlin/com/github/bjansen/intellij/pebble/config/PebbleProjectSettings.kt
3249717962
package test actual class C { actual fun foo() { } actual fun baz(n: Int) { } actual fun bar(n: Int) { } } fun test(c: C) { c.foo() c.baz(1) c.bar(1) }
plugins/kotlin/idea/tests/testData/refactoring/changeSignatureMultiModule/headersAndImplsByImplClassMemberFun/after/JVM/src/test/test.kt
3106745106
// 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.searching.inheritors import com.intellij.model.search.SearchService import com.intellij.model.search.Searcher import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.util.* import com.intellij.util.concurrency.annotations.RequiresReadLock import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.idea.search.ideaExtensions.JavaOverridingMethodsSearcherFromKotlinParameters import org.jetbrains.kotlin.idea.searching.inheritors.DirectKotlinOverridingCallableSearch.SearchParameters import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject object DirectKotlinOverridingCallableSearch { data class SearchParameters( val ktCallableDeclaration: KtCallableDeclaration, val searchScope: SearchScope ) : com.intellij.model.search.SearchParameters<PsiElement> { override fun getProject(): Project { return ktCallableDeclaration.project } override fun areValid(): Boolean { return ktCallableDeclaration.isValid } } fun search(ktFunction: KtCallableDeclaration): Query<PsiElement> { return search(ktFunction, ktFunction.useScope) } fun search(ktFunction: KtCallableDeclaration, searchScope: SearchScope): Query<PsiElement> { return search(SearchParameters(ktFunction, searchScope)) } fun search(parameters: SearchParameters): Query<PsiElement> { return SearchService.getInstance().searchParameters(parameters) } } class DirectKotlinOverridingMethodSearcher : Searcher<SearchParameters, PsiElement> { @RequiresReadLock override fun collectSearchRequest(parameters: SearchParameters): Query<out PsiElement>? { val klass = parameters.ktCallableDeclaration.containingClassOrObject if (klass !is KtClass) return null return DirectKotlinClassInheritorsSearch.search(klass, parameters.searchScope) .flatMapping { ktClassOrObject -> if (ktClassOrObject !is KtClassOrObject) EmptyQuery.getEmptyQuery() else object : AbstractQuery<PsiElement>() { override fun processResults(consumer: Processor<in PsiElement>): Boolean { val superFunction = analyze(parameters.ktCallableDeclaration) { parameters.ktCallableDeclaration.getSymbol() } analyze(ktClassOrObject) { (ktClassOrObject.getSymbol() as KtClassOrObjectSymbol).getDeclaredMemberScope() .getCallableSymbols { it == parameters.ktCallableDeclaration.nameAsName } .forEach { overridingSymbol -> val function = overridingSymbol.psi if (function != null && overridingSymbol.getAllOverriddenSymbols().any { it == superFunction } && !consumer.process(function)) { return false } } return true } } } } } } private val oldSearchers = setOf( "org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinOverridingMethodsWithFlexibleTypesSearcher", "org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinOverridingMethodsWithGenericsSearcher" ) private val EVERYTHING_BUT_KOTLIN = object : QueryFactory<PsiMethod, OverridingMethodsSearch.SearchParameters>() { init { OverridingMethodsSearch.EP_NAME.extensionList .filterNot { oldSearchers.contains(it::class.java.name) } .forEach { registerExecutor(it) } } } internal class DirectKotlinOverridingMethodDelegatedSearcher : Searcher<SearchParameters, PsiElement> { @RequiresReadLock override fun collectSearchRequests(parameters: SearchParameters): Collection<Query<out PsiElement>> { val baseFunction = parameters.ktCallableDeclaration val methods = baseFunction.toLightMethods() val queries = methods.map { it -> EVERYTHING_BUT_KOTLIN.createQuery(JavaOverridingMethodsSearcherFromKotlinParameters(it, parameters.searchScope, false)) } return queries } }
plugins/kotlin/kotlin.searching/src/org/jetbrains/kotlin/idea/searching/inheritors/DirectKotlinOverridingCallableSearch.kt
1038279685
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.LintFix import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.android.tools.lint.detector.api.isKotlin import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.ULocalVariable import org.jetbrains.uast.UPostfixExpression import org.jetbrains.uast.UQualifiedReferenceExpression import org.jetbrains.uast.USimpleNameReferenceExpression import org.jetbrains.uast.getContainingUClass import org.jetbrains.uast.kotlin.KotlinUFunctionCallExpression import org.jetbrains.uast.skipParenthesizedExprDown import org.jetbrains.uast.skipParenthesizedExprUp import org.jetbrains.uast.toUElement import org.jetbrains.uast.tryResolve import java.util.Locale /** * Androidx added new "require____()" versions of common "get___()" APIs, such as * getContext/getActivity/getArguments/etc. Rather than wrap these in something like * requireNotNull() or null-checking with `!!` in Kotlin, using these APIs will allow the * underlying component to try to tell you _why_ it was null, and thus yield a better error * message. */ @Suppress("UnstableApiUsage") class UseRequireInsteadOfGet : Detector(), SourceCodeScanner { companion object { val ISSUE: Issue = Issue.create( "UseRequireInsteadOfGet", "Use the 'require_____()' API rather than 'get____()' API for more " + "descriptive error messages when it's null.", """ AndroidX added new "require____()" versions of common "get___()" APIs, such as \ getContext/getActivity/getArguments/etc. Rather than wrap these in something like \ requireNotNull(), using these APIs will allow the underlying component to try \ to tell you _why_ it was null, and thus yield a better error message. """, Category.CORRECTNESS, 6, Severity.ERROR, Implementation(UseRequireInsteadOfGet::class.java, Scope.JAVA_FILE_SCOPE) ) private const val FRAGMENT_FQCN = "androidx.fragment.app.Fragment" internal val REQUIRABLE_METHODS = setOf( "getArguments", "getContext", "getActivity", "getFragmentManager", "getHost", "getParentFragment", "getView" ) // Convert 'getArguments' to 'arguments' internal val REQUIRABLE_REFERENCES = REQUIRABLE_METHODS.map { it.removePrefix("get").decapitalize(Locale.US) } internal val KNOWN_NULLCHECKS = setOf( "checkNotNull", "requireNonNull" ) } override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { super.visitMethodCall(context, node, method) } override fun getApplicableUastTypes(): List<Class<out UElement>>? { return listOf(UCallExpression::class.java, USimpleNameReferenceExpression::class.java) } override fun createUastHandler(context: JavaContext): UElementHandler? { val isKotlin = isKotlin(context.psiFile) return object : UElementHandler() { /** This covers Kotlin accessor syntax expressions like "fragment.arguments" */ override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression) { val parent = skipParenthesizedExprUp(node.uastParent) if (parent is UQualifiedReferenceExpression) { checkReferenceExpression(parent, node.identifier) { parent.receiver.getExpressionType() ?.let { context.evaluator.findClass(it.canonicalText) } } } else { // It's a member of the enclosing class checkReferenceExpression(node, node.identifier) { node.getContainingUClass() } } } private fun checkReferenceExpression( node: UExpression, identifier: String, resolveEnclosingClass: () -> PsiClass? ) { if (identifier in REQUIRABLE_REFERENCES) { // If this is a local variable do nothing // We are doing this to avoid false positives on local variables that shadow // Kotlin property accessors. There is probably a better way to organize // this Lint rule. val element = node.tryResolve() if (element != null && element.toUElement() is ULocalVariable) { return } val enclosingClass = resolveEnclosingClass() ?: return if (context.evaluator.extendsClass(enclosingClass, FRAGMENT_FQCN, false)) { checkForIssue(node, identifier) } } } /** This covers function/method calls like "fragment.getArguments()" */ override fun visitCallExpression(node: UCallExpression) { val targetMethod = node.resolve() ?: return val containingClass = targetMethod.containingClass ?: return if (targetMethod.name in REQUIRABLE_METHODS && context.evaluator.extendsClass(containingClass, FRAGMENT_FQCN, false) ) { checkForIssue(node, targetMethod.name, "${targetMethod.name}()") } } /** Called only when we know we're looking at an exempted method call type. */ private fun checkForIssue( node: UExpression, targetMethodName: String, targetExpression: String = targetMethodName ) { // Note we go up potentially two parents - the first one may just be the qualified reference expression val nearestNonQualifiedReferenceParent = skipParenthesizedExprUp(node.nearestNonQualifiedReferenceParent) ?: return if (isKotlin && nearestNonQualifiedReferenceParent.isNullCheckBlock()) { // We're a double-bang expression (!!) val parentSourceToReplace = nearestNonQualifiedReferenceParent.asSourceString() var correctMethod = correctMethod( parentSourceToReplace, "$targetExpression!!", targetMethodName ) if (correctMethod == parentSourceToReplace.removeSingleParentheses()) { correctMethod = parentSourceToReplace.removeSingleParentheses().replace( "$targetExpression?", "$targetExpression!!" ).replaceFirstOccurrenceAfter("!!", "", "$targetExpression!!") } report(nearestNonQualifiedReferenceParent, parentSourceToReplace, correctMethod) } else if (nearestNonQualifiedReferenceParent is UCallExpression) { // See if we're in a "requireNotNull(...)" or similar expression val enclosingMethodCall = ( skipParenthesizedExprUp( nearestNonQualifiedReferenceParent ) as UCallExpression ).resolve() ?: return if (enclosingMethodCall.name in KNOWN_NULLCHECKS) { // Only match for single (specified) parameter. If existing code had a // custom failure message, we don't want to overwrite it. val singleParameterSpecified = isSingleParameterSpecified( enclosingMethodCall, nearestNonQualifiedReferenceParent ) if (singleParameterSpecified) { // Grab the source of this argument as it's represented. val source = nearestNonQualifiedReferenceParent.valueArguments[0] .skipParenthesizedExprDown()!!.asSourceString() val parentToReplace = nearestNonQualifiedReferenceParent.fullyQualifiedNearestParent() .asSourceString() val correctMethod = correctMethod(source, targetExpression, targetMethodName) report( nearestNonQualifiedReferenceParent, parentToReplace, correctMethod ) } } } } private fun isSingleParameterSpecified( enclosingMethodCall: PsiMethod, nearestNonQualifiedRefParent: UCallExpression ) = enclosingMethodCall.parameterList.parametersCount == 1 || ( isKotlin && nearestNonQualifiedRefParent is KotlinUFunctionCallExpression && nearestNonQualifiedRefParent.getArgumentForParameter(1) == null ) private fun correctMethod( source: String, targetExpression: String, targetMethodName: String ): String { return source.removeSingleParentheses().replace( targetExpression, "require${targetMethodName.removePrefix("get").capitalize(Locale.US)}()" ) } // Replaces the first occurrence of a substring after given String private fun String.replaceFirstOccurrenceAfter( oldValue: String, newValue: String, prefix: String ): String = prefix + substringAfter(prefix).replaceFirst(oldValue, newValue) private fun report(node: UElement, targetExpression: String, correctMethod: String) { context.report( ISSUE, context.getLocation(node), "Use $correctMethod instead of $targetExpression", LintFix.create() .replace() .name("Replace with $correctMethod") .text(targetExpression) .with(correctMethod) .autoFix() .build() ) } } } } /** * Copy of the currently experimental Kotlin stdlib version. Can be removed once the stdlib version * comes out of experimental. */ internal fun String.decapitalize(locale: Locale): String { return if (isNotEmpty() && !this[0].isLowerCase()) { substring(0, 1).lowercase(locale) + substring(1) } else { this } } /** * Copy of the currently experimental Kotlin stdlib version. Can be removed once the stdlib version * comes out of experimental. */ internal fun String.capitalize(locale: Locale): String { if (isNotEmpty()) { val firstChar = this[0] if (firstChar.isLowerCase()) { return buildString { val titleChar = firstChar.titlecaseChar() if (titleChar != firstChar.uppercaseChar()) { append(titleChar) } else { append([email protected](0, 1).uppercase(locale)) } append([email protected](1)) } } } return this } internal fun UElement.isNullCheckBlock(): Boolean { return this is UPostfixExpression && operator.text == "!!" } internal fun String.removeSingleParentheses(): String { return this.replace("[(](?=[^)])".toRegex(), "") .replace("(?<![(])[)]".toRegex(), "") }
fragment/fragment-lint/src/main/java/androidx/fragment/lint/UseRequireInsteadOfGet.kt
486010592
package com.sedsoftware.yaptalker.presentation.base.enums.lifecycle import androidx.annotation.LongDef class ActivityLifecycle { companion object { const val CREATE = 0L const val START = 1L const val RESUME = 2L const val PAUSE = 3L const val STOP = 4L const val DESTROY = 5L } @Retention(AnnotationRetention.SOURCE) @LongDef(CREATE, START, RESUME, PAUSE, STOP, DESTROY) annotation class Event }
app/src/main/java/com/sedsoftware/yaptalker/presentation/base/enums/lifecycle/ActivityLifecycle.kt
2352381434
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.glance.wear.tiles import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.wear.tiles.ColorBuilders.argb import androidx.wear.tiles.DimensionBuilders.expand import androidx.wear.tiles.DimensionBuilders.sp import androidx.wear.tiles.LayoutElementBuilders.LayoutElement import androidx.wear.tiles.LayoutElementBuilders.Box import androidx.wear.tiles.LayoutElementBuilders.Column import androidx.wear.tiles.LayoutElementBuilders.FONT_WEIGHT_BOLD import androidx.wear.tiles.LayoutElementBuilders.FontStyle import androidx.wear.tiles.LayoutElementBuilders.HORIZONTAL_ALIGN_CENTER import androidx.wear.tiles.LayoutElementBuilders.VERTICAL_ALIGN_CENTER import androidx.wear.tiles.LayoutElementBuilders.TEXT_ALIGN_CENTER import androidx.wear.tiles.LayoutElementBuilders.Text import androidx.wear.tiles.ModifiersBuilders.Background import androidx.wear.tiles.ModifiersBuilders.Modifiers internal fun errorUiLayout(): LayoutElement = Box.Builder() .setWidth(expand()) .setHeight(expand()) .setHorizontalAlignment(HORIZONTAL_ALIGN_CENTER) .setVerticalAlignment(VERTICAL_ALIGN_CENTER) .addContent( Column.Builder() .setWidth(expand()) .setHorizontalAlignment(HORIZONTAL_ALIGN_CENTER) .setModifiers( Modifiers.Builder() .setBackground( Background.Builder() .setColor(argb(Color.DarkGray.toArgb())) .build() ) .build() ) .addContent( Text.Builder() .setText("Glance Wear Tile Error") .setFontStyle( FontStyle.Builder() .setSize(sp(18.toFloat())) .setWeight(FONT_WEIGHT_BOLD) .build() ) .build() ) .addContent( Text.Builder() .setText( "Check the exact error using \"adb logcat\"," + " searching for $GlanceWearTileTag" ) .setMaxLines(6) .setMultilineAlignment(TEXT_ALIGN_CENTER) .setFontStyle( FontStyle.Builder() .setSize(sp(14.toFloat())) .build() ) .build() ) .build() ) .build()
glance/glance-wear-tiles/src/androidMain/kotlin/androidx/glance/wear/tiles/ErrorUiLayout.kt
83592636
package ogl_dev.tut05 /** * Created by elect on 23/04/2017. */ import glm.vec._2.Vec2i import glm.vec._3.Vec3 import ogl_dev.GlfwWindow import ogl_dev.common.readFile import ogl_dev.glfw import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.* import uno.buffer.floatBufferBig import uno.buffer.intBufferBig import uno.glf.semantic import uno.gln.glBindBuffer import uno.gln.glDrawArrays import kotlin.properties.Delegates import glm.Glm.sin private var window by Delegates.notNull<GlfwWindow>() fun main(args: Array<String>) { with(glfw) { // Initialize GLFW. Most GLFW functions will not work before doing this. // It also setups an error callback. The default implementation will print the error message in System.err. init() windowHint { doubleBuffer = true } // Configure GLFW } window = GlfwWindow(300, "Tutorial 5") // Create the window with(window) { pos = Vec2i(100) // Set the window position makeContextCurrent() // Make the OpenGL context current show() // Make the window visible } /* This line is critical for LWJGL's interoperation with GLFW's OpenGL context, or any context that is managed externally. LWJGL detects the context that is current in the current thread, creates the GLCapabilities instance and makes the OpenGL bindings available for use. */ GL.createCapabilities() println("GL version: ${glGetString(GL_VERSION)}") glClearColor(0.0f, 0.0f, 0.0f, 0.0f) createVertexBuffer() compileShaders() // Run the rendering loop until the user has attempted to close the window or has pressed the ESCAPE key. while (!window.shouldClose) { renderScene() glfw.pollEvents() // Poll for window events. The key callback above will only be invoked during this call. } window.dispose() glfw.terminate() // Terminate GLFW and free the error callback } val vbo = intBufferBig(1) var scaleLocation = 0 val vsFileName = "tut05/shader.vert" val fsFileName = "tut05/shader.frag" var scale = 0.0f fun createVertexBuffer() { val vertices = floatBufferBig(Vec3.SIZE * 3) Vec3(-1.0f, -1.0f, 0.0f) to vertices Vec3(1.0f, -1.0f, 0.0f).to(vertices, Vec3.length) Vec3(0.0f, 1.0f, 0.0f).to(vertices, Vec3.length * 2) glGenBuffers(vbo) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW) } fun compileShaders() { val shaderProgram = glCreateProgram() if (shaderProgram == 0) throw Error("Error creating shader program") val vs = readFile(vsFileName) val fs = readFile(fsFileName) addShader(shaderProgram, vs, GL_VERTEX_SHADER) addShader(shaderProgram, fs, GL_FRAGMENT_SHADER) glLinkProgram(shaderProgram) if (glGetProgrami(shaderProgram, GL_LINK_STATUS) == GL_FALSE) { val errorLog = glGetProgramInfoLog(shaderProgram) throw Error("Error linking shader program: $errorLog") } glValidateProgram(shaderProgram) if (glGetProgrami(shaderProgram, GL_VALIDATE_STATUS) != GL_TRUE) { val errorLog = glGetProgramInfoLog(shaderProgram) throw Error("Invalid shader program: $errorLog") } glUseProgram(shaderProgram) scaleLocation = glGetUniformLocation(shaderProgram, "gScale") assert(scaleLocation != -1) } fun addShader(shaderProgram: Int, shaderText: String, shaderType: Int) { val shaderObj = glCreateShader(shaderType) if (shaderObj == 0) throw Error("Error creating shader type $shaderType") glShaderSource(shaderObj, shaderText) glCompileShader(shaderObj) if (glGetShaderi(shaderObj, GL_COMPILE_STATUS) != GL_TRUE) { val infoLog = glGetShaderInfoLog(shaderObj) throw Error("Error compiling shader type $shaderType: $infoLog") } glAttachShader(shaderProgram, shaderObj) } fun renderScene() { glClear(GL_COLOR_BUFFER_BIT) scale += 0.01f glUniform1f(scaleLocation, sin(scale)) glEnableVertexAttribArray(semantic.attr.POSITION) glBindBuffer(GL_ARRAY_BUFFER, vbo) glVertexAttribPointer(semantic.attr.POSITION, Vec3.length, GL_FLOAT, false, Vec3.SIZE, 0) glDrawArrays(GL_TRIANGLES, 3) glDisableVertexAttribArray(semantic.attr.POSITION) window.swapBuffers() }
src/main/kotlin/ogl_dev/tut05/uniform-variables.kt
4250133954
package de.droidcon.berlin2018.ui.speakerdetail import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import de.droidcon.berlin2018.model.Session import de.droidcon.berlin2018.model.Speaker import de.droidcon.berlin2018.ui.navigation.Navigator import de.droidcon.berlin2018.ui.sessiondetails.SessionDetailsController /** * * * @author Hannes Dorfmann */ class SpeakerDetailsNavigator(private val controller: Controller) : Navigator { override fun showHome() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSessions() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showMySchedule() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSpeakers() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSpeakerDetails(speaker: Speaker) { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSessionDetails(session: Session) { controller.router.pushController( RouterTransaction.with( SessionDetailsController(session.id()) ) .popChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler()) ) } override fun showTweets() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSearch() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun popSelfFromBackstack() { controller.router.popCurrentController() } override fun showLicences() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSourceCode() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } }
app/src/main/java/de/droidcon/berlin2018/ui/speakerdetail/SpeakerDetailsNavigator.kt
3473630149
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.testing import android.view.Surface import androidx.camera.camera2.pipe.CameraController import androidx.camera.camera2.pipe.StreamId internal class FakeCameraController : CameraController { var started = false var closed = false var surfaceMap: Map<StreamId, Surface>? = null override fun start() { started = true } override fun stop() { started = false } override fun close() { closed = true started = false } override fun updateSurfaceMap(surfaceMap: Map<StreamId, Surface>) { this.surfaceMap = surfaceMap } }
camera/camera-camera2-pipe/src/test/java/androidx/camera/camera2/pipe/testing/FakeCameraController.kt
1466963708
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.ui.branch import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.diverged import com.intellij.dvcs.ui.DvcsBundle import com.intellij.dvcs.ui.RepositoryChangesBrowserNode import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.components.service import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.PopupStep.FINAL_CHOICE import com.intellij.openapi.ui.popup.SpeedSearchFilter import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.TextRange import com.intellij.psi.codeStyle.MinusculeMatcher import com.intellij.psi.codeStyle.NameUtil import com.intellij.ui.ExperimentalUI import com.intellij.ui.RowIcon import com.intellij.ui.popup.ActionPopupStep import com.intellij.ui.popup.PopupFactoryImpl import com.intellij.util.PlatformIcons import com.intellij.util.containers.FList import git4idea.GitBranch import git4idea.GitLocalBranch import git4idea.GitRemoteBranch import git4idea.GitVcs import git4idea.actions.branch.GitBranchActionsUtil import git4idea.branch.GitBranchIncomingOutgoingManager import git4idea.branch.GitBranchType import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.ui.branch.GitBranchPopupActions.EXPERIMENTAL_BRANCH_POPUP_ACTION_GROUP import icons.DvcsImplIcons import org.jetbrains.annotations.Nls import javax.swing.Icon import javax.swing.tree.TreeModel import javax.swing.tree.TreePath class GitBranchesTreePopupStep(private val project: Project, internal val repositories: List<GitRepository>, private val isFirstStep: Boolean) : PopupStep<Any> { private var finalRunnable: Runnable? = null override fun getFinalRunnable() = finalRunnable private val _treeModel: GitBranchesTreeModel val treeModel: TreeModel get() = _treeModel init { val topLevelItems = mutableListOf<Any>() if (ExperimentalUI.isNewUI() && isFirstStep) { val experimentalUIActionsGroup = ActionManager.getInstance().getAction(EXPERIMENTAL_BRANCH_POPUP_ACTION_GROUP) as? ActionGroup if (experimentalUIActionsGroup != null) { topLevelItems.addAll(createActionItems(experimentalUIActionsGroup, project, repositories).addSeparators()) topLevelItems.add(GitBranchesTreePopup.createTreeSeparator()) } } val actionGroup = ActionManager.getInstance().getAction(TOP_LEVEL_ACTION_GROUP) as? ActionGroup if (actionGroup != null) { // get selected repo inside actions topLevelItems.addAll(createActionItems(actionGroup, project, repositories).addSeparators()) topLevelItems.add(GitBranchesTreePopup.createTreeSeparator()) } _treeModel = GitBranchesTreeModelImpl(project, repositories, topLevelItems) } private fun List<PopupFactoryImpl.ActionItem>.addSeparators(): List<Any> { val actionsWithSeparators = mutableListOf<Any>() for (action in this) { if (action.isPrependWithSeparator) { actionsWithSeparators.add(GitBranchesTreePopup.createTreeSeparator(action.separatorText)) } actionsWithSeparators.add(action) } return actionsWithSeparators } fun isBranchesDiverged(): Boolean { return repositories.size > 1 && repositories.diverged() && GitBranchActionsUtil.userWantsSyncControl(project) } fun getPreferredSelection(): TreePath? { return _treeModel.getPreferredSelection() } internal fun setPrefixGrouping(state: Boolean) { _treeModel.isPrefixGrouping = state } private val LOCAL_SEARCH_PREFIX = "/l" private val REMOTE_SEARCH_PREFIX = "/r" fun setSearchPattern(pattern: String?) { if (pattern == null || pattern == "/") { _treeModel.filterBranches() return } var branchType: GitBranchType? = null var processedPattern = pattern if (pattern.startsWith(LOCAL_SEARCH_PREFIX)) { branchType = GitBranchType.LOCAL processedPattern = pattern.removePrefix(LOCAL_SEARCH_PREFIX).trimStart() } if (pattern.startsWith(REMOTE_SEARCH_PREFIX)) { branchType = GitBranchType.REMOTE processedPattern = pattern.removePrefix(REMOTE_SEARCH_PREFIX).trimStart() } val matcher = PreferStartMatchMatcherWrapper(NameUtil.buildMatcher("*$processedPattern").build()) _treeModel.filterBranches(branchType, matcher) } override fun hasSubstep(selectedValue: Any?): Boolean { val userValue = selectedValue ?: return false return userValue is GitRepository || userValue is GitBranch || (userValue is PopupFactoryImpl.ActionItem && userValue.isEnabled && userValue.action is ActionGroup) } fun isSelectable(node: Any?): Boolean { val userValue = node ?: return false return userValue is GitRepository || userValue is GitBranch || (userValue is PopupFactoryImpl.ActionItem && userValue.isEnabled) } override fun onChosen(selectedValue: Any?, finalChoice: Boolean): PopupStep<out Any>? { if (selectedValue is GitRepository) { return GitBranchesTreePopupStep(project, listOf(selectedValue), false) } if (selectedValue is GitBranch) { val actionGroup = ActionManager.getInstance().getAction(BRANCH_ACTION_GROUP) as? ActionGroup ?: DefaultActionGroup() return createActionStep(actionGroup, project, repositories, selectedValue) } if (selectedValue is PopupFactoryImpl.ActionItem) { if (!selectedValue.isEnabled) return FINAL_CHOICE val action = selectedValue.action if (action is ActionGroup && (!finalChoice || !selectedValue.isPerformGroup)) { return createActionStep(action, project, repositories) } else { finalRunnable = Runnable { ActionUtil.invokeAction(action, createDataContext(project, repositories), ACTION_PLACE, null, null) } } } return FINAL_CHOICE } override fun getTitle(): String? = when { !isFirstStep -> null repositories.size > 1 -> DvcsBundle.message("branch.popup.vcs.name.branches", GitVcs.DISPLAY_NAME.get()) else -> repositories.single().let { DvcsBundle.message("branch.popup.vcs.name.branches.in.repo", it.vcs.displayName, DvcsUtil.getShortRepositoryName(it)) } } fun getIncomingOutgoingIconWithTooltip(treeNode: Any?): Pair<Icon?, @Nls(capitalization = Nls.Capitalization.Sentence) String?> { val empty = null to null val value = treeNode ?: return empty return when (value) { is GitBranch -> getIncomingOutgoingIconWithTooltip(value) else -> empty } } private fun getIncomingOutgoingIconWithTooltip(branch: GitBranch): Pair<Icon?, String?> { val branchName = branch.name val incomingOutgoingManager = project.service<GitBranchIncomingOutgoingManager>() val hasIncoming = repositories.any { incomingOutgoingManager.hasIncomingFor(it, branchName) } val hasOutgoing = repositories.any { incomingOutgoingManager.hasOutgoingFor(it, branchName) } val tooltip = GitBranchPopupActions.LocalBranchActions.constructIncomingOutgoingTooltip(hasIncoming, hasOutgoing).orEmpty() return when { hasIncoming && hasOutgoing -> RowIcon(DvcsImplIcons.Incoming, DvcsImplIcons.Outgoing) hasIncoming -> DvcsImplIcons.Incoming hasOutgoing -> DvcsImplIcons.Outgoing else -> null } to tooltip } private val colorManager = RepositoryChangesBrowserNode.getColorManager(project) fun getNodeIcon(treeNode: Any?, isSelected: Boolean): Icon? { val value = treeNode ?: return null return when (value) { is PopupFactoryImpl.ActionItem -> value.getIcon(isSelected) is GitRepository -> RepositoryChangesBrowserNode.getRepositoryIcon(value, colorManager) else -> null } } fun getIcon(treeNode: Any?, isSelected: Boolean): Icon? { val value = treeNode ?: return null return when (value) { is GitBranchesTreeModel.BranchesPrefixGroup -> PlatformIcons.FOLDER_ICON is GitBranch -> getBranchIcon(value, isSelected) else -> null } } private fun getBranchIcon(branch: GitBranch, isSelected: Boolean): Icon { val isCurrent = repositories.all { it.currentBranch == branch } val branchManager = project.service<GitBranchManager>() val isFavorite = repositories.all { branchManager.isFavorite(GitBranchType.of(branch), it, branch.name) } return when { isSelected && isFavorite -> AllIcons.Nodes.Favorite isSelected -> AllIcons.Nodes.NotFavoriteOnHover isCurrent && isFavorite -> DvcsImplIcons.CurrentBranchFavoriteLabel isCurrent -> DvcsImplIcons.CurrentBranchLabel isFavorite -> AllIcons.Nodes.Favorite else -> AllIcons.Vcs.BranchNode } } fun getText(treeNode: Any?): @NlsSafe String? { val value = treeNode ?: return null return when (value) { GitBranchType.LOCAL -> { if (repositories.size > 1) GitBundle.message("common.local.branches") else GitBundle.message("group.Git.Local.Branch.title") } GitBranchType.REMOTE -> { if (repositories.size > 1) GitBundle.message("common.remote.branches") else GitBundle.message("group.Git.Remote.Branch.title") } is GitBranchesTreeModel.BranchesPrefixGroup -> value.prefix.last() is GitRepository -> DvcsUtil.getShortRepositoryName(value) is GitBranch -> { if (_treeModel.isPrefixGrouping) value.name.split('/').last() else value.name } is PopupFactoryImpl.ActionItem -> value.text else -> value.toString() } } fun getSecondaryText(treeNode: Any?): @NlsSafe String? { return when (treeNode) { is PopupFactoryImpl.ActionItem -> KeymapUtil.getFirstKeyboardShortcutText(treeNode.action) is GitRepository -> treeNode.currentBranch?.name.orEmpty() is GitLocalBranch -> { treeNode.getCommonTrackedBranch(repositories)?.name } else -> null } } private fun GitLocalBranch.getCommonTrackedBranch(repositories: List<GitRepository>): GitRemoteBranch? { var commonTrackedBranch: GitRemoteBranch? = null for (repository in repositories) { val trackedBranch = findTrackedBranch(repository) ?: return null if (commonTrackedBranch == null) { commonTrackedBranch = trackedBranch } else if (commonTrackedBranch.name != trackedBranch.name) { return null } } return commonTrackedBranch } override fun canceled() {} override fun isMnemonicsNavigationEnabled() = false override fun getMnemonicNavigationFilter() = null override fun isSpeedSearchEnabled() = true override fun getSpeedSearchFilter() = SpeedSearchFilter<Any> { node -> when (node) { is GitBranch -> node.name else -> node?.let(::getText) ?: "" } } override fun isAutoSelectionEnabled() = false companion object { internal const val HEADER_SETTINGS_ACTION_GROUP = "Git.Branches.Popup.Settings" private const val TOP_LEVEL_ACTION_GROUP = "Git.Branches.List" internal const val SPEED_SEARCH_DEFAULT_ACTIONS_GROUP = "Git.Branches.Popup.SpeedSearch" private const val BRANCH_ACTION_GROUP = "Git.Branch" internal val ACTION_PLACE = ActionPlaces.getPopupPlace("GitBranchesPopup") private fun createActionItems(actionGroup: ActionGroup, project: Project, repositories: List<GitRepository>): List<PopupFactoryImpl.ActionItem> { val dataContext = createDataContext(project, repositories) return ActionPopupStep .createActionItems(actionGroup, dataContext, false, false, false, false, ACTION_PLACE, null) } private fun createActionStep(actionGroup: ActionGroup, project: Project, repositories: List<GitRepository>, branch: GitBranch? = null): ListPopupStep<*> { val dataContext = createDataContext(project, repositories, branch) return JBPopupFactory.getInstance() .createActionsStep(actionGroup, dataContext, ACTION_PLACE, false, true, null, null, true, 0, false) } internal fun createDataContext(project: Project, repositories: List<GitRepository>, branch: GitBranch? = null): DataContext = SimpleDataContext.builder() .add(CommonDataKeys.PROJECT, project) .add(GitBranchActionsUtil.REPOSITORIES_KEY, repositories) .add(GitBranchActionsUtil.BRANCHES_KEY, branch?.let(::listOf)) .build() /** * Adds weight to match offset. Degree of match is increased with the earlier the pattern was found in the name. */ private class PreferStartMatchMatcherWrapper(private val delegate: MinusculeMatcher) : MinusculeMatcher() { override fun getPattern(): String = delegate.pattern override fun matchingFragments(name: String): FList<TextRange>? = delegate.matchingFragments(name) override fun matchingDegree(name: String, valueStartCaseMatch: Boolean, fragments: FList<out TextRange>?): Int { var degree = delegate.matchingDegree(name, valueStartCaseMatch, fragments) if (fragments.isNullOrEmpty()) return degree degree += MATCH_OFFSET - fragments.head.startOffset return degree } companion object { private const val MATCH_OFFSET = 10000 } } } }
plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopupStep.kt
2734951323
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.ml.features import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.codeInsight.completion.ml.MLFeatureValue import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.util.Version internal object MLFeaturesUtil { fun getRawValue(featureValue: MLFeatureValue): Any { return when (featureValue) { is MLFeatureValue.BinaryValue -> if (featureValue.value) 1 else 0 is MLFeatureValue.FloatValue -> featureValue.value is MLFeatureValue.CategoricalValue -> featureValue.value is MLFeatureValue.ClassNameValue -> getClassNameSafe(featureValue) is MLFeatureValue.VersionValue -> getVersionSafe(featureValue) } } private data class ClassNames(val simpleName: String, val fullName: String) private fun Class<*>.getNames(): ClassNames { return ClassNames(simpleName, name) } private val THIRD_PARTY_NAME = ClassNames("third.party", "third.party") private val CLASS_NAMES_CACHE = Caffeine.newBuilder().maximumSize(100).build<String, ClassNames>() fun getClassNameSafe(feature: MLFeatureValue.ClassNameValue): String { val clazz = feature.value val names = CLASS_NAMES_CACHE.get(clazz.name) { if (getPluginInfo(clazz).isSafeToReport()) clazz.getNames() else THIRD_PARTY_NAME }!! return if (feature.useSimpleName) names.simpleName else names.fullName } private const val INVALID_VERSION = "invalid.version" private fun getVersionSafe(featureValue: MLFeatureValue.VersionValue): String = Version.parseVersion(featureValue.value)?.toString() ?: INVALID_VERSION }
plugins/completion-ml-ranking/src/com/intellij/completion/ml/features/MLFeaturesUtil.kt
2327715618
// 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.uast.java import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiPostfixExpression import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* @ApiStatus.Internal class JavaUPostfixExpression( override val sourcePsi: PsiPostfixExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UPostfixExpression { override val operand: UExpression by lz { JavaConverter.convertOrEmpty(sourcePsi.operand, this) } override val operatorIdentifier: UIdentifier get() = UIdentifier(sourcePsi.operationSign, this) override fun resolveOperator(): Nothing? = null override val operator: UastPostfixOperator = when (sourcePsi.operationTokenType) { JavaTokenType.PLUSPLUS -> UastPostfixOperator.INC JavaTokenType.MINUSMINUS -> UastPostfixOperator.DEC else -> UastPostfixOperator.UNKNOWN } }
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUPostfixExpression.kt
3797709218
// 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.usages.impl.rules import com.intellij.openapi.project.Project import com.intellij.usages.Usage import com.intellij.usages.UsageTarget import com.intellij.usages.rules.UsageFilteringRule import com.intellij.usages.rules.GeneratedSourceUsageFilter internal class UsageInGeneratedCodeFilteringRule(private val project: Project) : UsageFilteringRule { override fun getActionId(): String = "UsageFiltering.GeneratedCode" override fun isVisible(usage: Usage, targets: Array<out UsageTarget>): Boolean { for (filter in GeneratedSourceUsageFilter.EP_NAME.extensions) { if (filter.isGeneratedSource(usage, project)) { return false } } return true } }
platform/usageView-impl/src/com/intellij/usages/impl/rules/UsageInGeneratedCodeFilteringRule.kt
1895282600
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaClassConstructorDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddNamesInCommentToJavaCallArgumentsIntention : SelfTargetingIntention<KtCallElement>( KtCallElement::class.java, KotlinBundle.lazyMessage("add.names.in.comment.to.call.arguments") ) { override fun isApplicableTo(element: KtCallElement, caretOffset: Int): Boolean = resolveValueParameterDescriptors(element, anyBlockCommentsWithName = true) != null override fun applyTo(element: KtCallElement, editor: Editor?) { val resolvedCall = element.resolveToCall() ?: return val psiFactory = KtPsiFactory(element) for ((argument, parameter) in element.valueArguments.filterIsInstance<KtValueArgument>().resolve(resolvedCall)) { val parent = argument.parent parent.addBefore(psiFactory.createComment(parameter.toParameterNameComment()), argument) parent.addBefore(psiFactory.createWhiteSpace(), argument) if (parameter.isVararg) break } } companion object { fun resolveValueParameterDescriptors( element: KtCallElement, anyBlockCommentsWithName: Boolean ): List<Pair<KtValueArgument, ValueParameterDescriptor>>? { val arguments = element.valueArguments.filterIsInstance<KtValueArgument>().filterNot { it is KtLambdaArgument } if (arguments.isEmpty() || arguments.any { it.isNamed() } || (anyBlockCommentsWithName && arguments.any { it.hasBlockCommentWithName() }) || (!anyBlockCommentsWithName && arguments.none { it.hasBlockCommentWithName() }) ) return null val resolvedCall = element.resolveToCall() ?: return null val descriptor = resolvedCall.candidateDescriptor if (descriptor !is JavaMethodDescriptor && descriptor !is JavaClassConstructorDescriptor) return null val resolve = arguments.resolve(resolvedCall) if (arguments.size != resolve.size) return null return resolve } fun ValueParameterDescriptor.toParameterNameComment(): String = canonicalParameterNameComment(if (isVararg) "...$name" else name.asString()) private fun canonicalParameterNameComment(parameterName: String): String = "/* $parameterName = */" fun PsiComment.isParameterNameComment(parameter: ValueParameterDescriptor): Boolean { if (this.elementType != KtTokens.BLOCK_COMMENT) return false val parameterName = text .removePrefix("/*").removeSuffix("*/").trim() .takeIf { it.endsWith("=") }?.removeSuffix("=")?.trim() ?: return false return canonicalParameterNameComment(parameterName) == parameter.toParameterNameComment() } private fun KtValueArgument.hasBlockCommentWithName(): Boolean = blockCommentWithName() != null fun KtValueArgument.blockCommentWithName(): PsiComment? = siblings(forward = false, withSelf = false) .takeWhile { it is PsiWhiteSpace || it is PsiComment } .filterIsInstance<PsiComment>() .firstOrNull { it.elementType == KtTokens.BLOCK_COMMENT && it.text.removeSuffix("*/").trim().endsWith("=") } fun List<KtValueArgument>.resolve( resolvedCall: ResolvedCall<out CallableDescriptor> ): List<Pair<KtValueArgument, ValueParameterDescriptor>> = mapNotNull { if (it is KtLambdaArgument) return@mapNotNull null val parameter = resolvedCall.getArgumentMapping(it).safeAs<ArgumentMatch>()?.valueParameter ?: return@mapNotNull null it to parameter } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddNamesInCommentToJavaCallArgumentsIntention.kt
2965354008
class A { fun test() { toInl<caret>ine() } companion object : B() { fun toInline() = Unit } } class B { init { println("Hey!") } }
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/companionWithSuperType.kt
3597436771
// "Import extension function 'Companion.foobar'" "true" package p open class T1 { companion object fun T1.Companion.foobar() {} } open class T2 : T1() open class T3 : T2() object TObject : T3() fun usage() { T1.<caret>foobar() }
plugins/kotlin/idea/tests/testData/quickfix/autoImports/callablesDeclaredInClasses/companionObjectDeepInheritance.kt
1109894810
// "Surround with intArrayOf(...)" "true" fun foo(vararg s: Int) {} fun test() { foo(s = <caret>1) }
plugins/kotlin/idea/tests/testData/quickfix/surroundWithArrayOfForNamedArgumentsToVarargs/replaceToArrayOfPrimitiveTypes.fir.kt
3060227136
package test public class ClassA() { public fun meth1() {} private fun meth2() {} }
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/privateMethodDeleted/ClassA.kt
1060042486
// "Introduce import alias" "true" // WITH_STDLIB // ACTION: Add explicit type arguments // ACTION: Convert to 'forEachIndexed' // ACTION: Do not show return expression hints // ACTION: Introduce import alias // ACTION: Replace with a 'for' loop fun foo() { listOf("a", "b", "c").<caret>forEach { } }
plugins/kotlin/idea/tests/testData/quickfix/importAlias/simple.kt
953721650
// 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.openapi.externalSystem.settings import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.externalSystem.ExternalSystemManager import com.intellij.openapi.project.Project /** * Allows registering [ExternalSystemSettingsListener] by extension point */ interface ExternalSystemSettingsListenerEx { /** * @see ExternalSystemSettingsListener.onProjectsLoaded */ @JvmDefault fun onProjectsLoaded(project: Project, manager: ExternalSystemManager<*, *, *, *, *>, settings: Collection<ExternalProjectSettings>) {} /** * @see ExternalSystemSettingsListener.onProjectsLinked */ @JvmDefault fun onProjectsLinked(project: Project, manager: ExternalSystemManager<*, *, *, *, *>, settings: Collection<ExternalProjectSettings>) {} /** * @see ExternalSystemSettingsListener.onProjectsUnlinked */ @JvmDefault fun onProjectsUnlinked(project: Project, manager: ExternalSystemManager<*, *, *, *, *>, linkedProjectPaths: Set<String>) {} companion object { private val EP_NAME = ExtensionPointName<ExternalSystemSettingsListenerEx>("com.intellij.externalSystemSettingsListener") fun onProjectsLoaded(project: Project, manager: ExternalSystemManager<*, *, *, *, *>, settings: Collection<ExternalProjectSettings>) { EP_NAME.forEachExtensionSafe { it.onProjectsLoaded(project, manager, settings) } } fun onProjectsLinked(project: Project, manager: ExternalSystemManager<*, *, *, *, *>, settings: Collection<ExternalProjectSettings>) { EP_NAME.forEachExtensionSafe { it.onProjectsLinked(project, manager, settings) } } fun onProjectsUnlinked(project: Project, manager: ExternalSystemManager<*, *, *, *, *>, linkedProjectPaths: Set<String>) { EP_NAME.forEachExtensionSafe { it.onProjectsUnlinked(project, manager, linkedProjectPaths) } } } }
platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsListenerEx.kt
3176651088
fun a() { a.forEach { (<caret>)} } // SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS // SET_FALSE: ALIGN_MULTILINE_BINARY_OPERATION // IGNORE_FORMATTER
plugins/kotlin/idea/tests/testData/editor/enterHandler/emptyParameters/EmptyParameterInDestructuringDeclaration3.kt
1720642026
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.jsr223 import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.repl.* import org.jetbrains.kotlin.daemon.client.DaemonReportMessage import org.jetbrains.kotlin.daemon.client.DaemonReportingTargets import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient import org.jetbrains.kotlin.daemon.client.KotlinRemoteReplCompilerClient import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.utils.KotlinPaths import org.jetbrains.kotlin.utils.KotlinPathsFromHomeDir import java.io.File import java.util.concurrent.locks.ReentrantReadWriteLock import javax.script.ScriptContext import javax.script.ScriptEngineFactory import javax.script.ScriptException import kotlin.io.path.exists import kotlin.reflect.KClass // TODO: need to manage resources here, i.e. call replCompiler.dispose when engine is collected class KotlinJsr223JvmScriptEngine4Idea( factory: ScriptEngineFactory, templateClasspath: List<File>, templateClassName: String, private val getScriptArgs: (ScriptContext, Array<out KClass<out Any>>?) -> ScriptArgsWithTypes?, private val scriptArgsTypes: Array<out KClass<out Any>>? ) : KotlinJsr223JvmScriptEngineBase(factory) { private val daemon by lazy { val libPath = KotlinPathsFromHomeDir(KotlinPluginLayout.kotlinc) val classPath = libPath.classPath(KotlinPaths.ClassPaths.CompilerWithScripting) assert(classPath.all { it.toPath().exists() }) val compilerId = CompilerId.makeCompilerId(classPath) val daemonOptions = configureDaemonOptions() val daemonJVMOptions = DaemonJVMOptions() val daemonReportMessages = arrayListOf<DaemonReportMessage>() KotlinCompilerClient.connectToCompileService( compilerId, daemonJVMOptions, daemonOptions, DaemonReportingTargets(null, daemonReportMessages), autostart = true, checkId = true ) ?: throw ScriptException( "Unable to connect to repl server:" + daemonReportMessages.joinToString("\n ", prefix = "\n ") { "${it.category.name} ${it.message}" } ) } private val messageCollector = MyMessageCollector() override val replCompiler: ReplCompilerWithoutCheck by lazy { KotlinRemoteReplCompilerClient( daemon, makeAutodeletingFlagFile("idea-jsr223-repl-session"), CompileService.TargetPlatform.JVM, emptyArray(), messageCollector, templateClasspath, templateClassName ) } override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = getScriptArgs(getContext(), scriptArgsTypes) private val localEvaluator: ReplFullEvaluator by lazy { GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader) } override val replEvaluator: ReplFullEvaluator get() = localEvaluator override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock) private class MyMessageCollector : MessageCollector { private var hasErrors: Boolean = false override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) { System.err.println(message) // TODO: proper location printing if (!hasErrors) { hasErrors = severity == CompilerMessageSeverity.EXCEPTION || severity == CompilerMessageSeverity.ERROR } } override fun clear() {} override fun hasErrors(): Boolean = hasErrors } }
plugins/kotlin/repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt
1752034345
// FIR_COMPARISON // CONFIGURE_LIBRARY: Coroutines import kotlinx.coroutines.flow.flowOf suspend fun main() { flowOf(1, 2, 3).coll<caret> } // WITH_ORDER // EXIST: { itemText: "collect", tailText:"() (kotlinx.coroutines.flow) for Flow<*>" } // EXIST: { itemText: "collect", tailText:"(collector: FlowCollector<T>)" }
plugins/kotlin/completion/testData/basic/java/FlowCollectMethodLowerPriority.fir.kt
1791427283
// PROBLEM: none // WITH_STDLIB fun foo(s: String, i: Int) = s.length + i fun test() { val s = "" s.let<caret> { x -> foo("", x.length) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/functionCall4.kt
856645105
// IntelliJ API Decompiler stub source generated from a class file // Implementation of methods is not available package test private var i: kotlin.Int /* compiled code */ public val p: kotlin.Int /* compiled code */ public fun f(): kotlin.Unit { /* compiled code */ } public fun kotlin.Int.plus(i: kotlin.Int /* = compiled code */): kotlin.Int { /* compiled code */ }
plugins/kotlin/idea/tests/testData/decompiler/decompiledTextJvm/TestKt.expected.kt
2237992556
fun test(some: (Int) -> Int) { } operator fun String.invoke(action: (String) -> Unit) { action(this) } fun foo() { test() { it } "foo" { println(it) } "bar" { println(it) } }
plugins/kotlin/idea/tests/testData/formatter/SpaceBeforeFunctionLiteral.after.kt
2771625883
// ERROR: Property must be initialized or be abstract class Test { private val myName: String internal var a: Boolean = false internal var b: Double = 0.toDouble() internal var c: Float = 0.toFloat() internal var d: Long = 0 internal var e: Int = 0 protected var f: Short = 0 protected var g: Char = ' ' constructor() {} constructor(name: String) { myName = foo(name) } companion object { internal fun foo(n: String): String { return "" } } } object User { fun main() { val t = Test("name") } }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/constructors/withManyDefaultParams.kt
1104240221
// IS_APPLICABLE: false // MOVE: down fun foo(n: Int) { when (n) { 0 -> { } 1 -> { } else -> { } }<caret> val x = "" }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/closingBraces/when/when1.kt
1518805129
package zielu.gittoolbox.ui import zielu.gittoolbox.util.Count internal data class ExtendedRepoInfo( val changedCount: Count = Count.EMPTY ) { fun hasChanged(): Boolean { return !changedCount.isEmpty() } }
src/main/kotlin/zielu/gittoolbox/ui/ExtendedRepoInfo.kt
2633329813
// PROBLEM: More arguments provided (1) than placeholders specified (0) // FIX: none package org.apache.logging.log4j private val logger: Logger? = null fun foo(a: Int, b: Int) { logger?.atDebug()?.log("<caret>test", 1, Exception()) } interface LogBuilder:{ fun log(format: String, param1: Any, param2: Any) } interface Logger { fun atDebug(): LogBuilder }
plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/placeholderCountMatchesArgumentCount/log4jBuilder/logException.kt
3512194743
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.util import android.annotation.SuppressLint import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Shader import android.graphics.drawable.Drawable import android.graphics.drawable.PaintDrawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RectShape import android.util.LruCache import android.view.Gravity import kotlin.math.max import kotlin.math.pow private val cubicGradientScrimCache = LruCache<Int, Drawable>(10) /** * Creates an approximated cubic gradient using a multi-stop linear gradient. See * [this post](https://plus.google.com/+RomanNurik/posts/2QvHVFWrHZf) for more * details. */ @SuppressLint("RtlHardcoded") fun makeCubicGradientScrimDrawable( gravity: Int, alpha: Int = 0xFF, red: Int = 0x0, green: Int = 0x0, blue: Int = 0x0, requestedStops: Int = 8 ): Drawable { var numStops = requestedStops // Generate a cache key by hashing together the inputs, based on the method described in the Effective Java book var cacheKeyHash = Color.argb(alpha, red, green, blue) cacheKeyHash = 31 * cacheKeyHash + numStops cacheKeyHash = 31 * cacheKeyHash + gravity val cachedGradient = cubicGradientScrimCache.get(cacheKeyHash) if (cachedGradient != null) { return cachedGradient } numStops = max(numStops, 2) val paintDrawable = PaintDrawable().apply { shape = RectShape() } val stopColors = IntArray(numStops) for (i in 0 until numStops) { val x = i * 1f / (numStops - 1) val opacity = x.toDouble().pow(3.0).toFloat().constrain(0f, 1f) stopColors[i] = Color.argb((alpha * opacity).toInt(), red, green, blue) } val x0: Float val x1: Float val y0: Float val y1: Float when (gravity and Gravity.HORIZONTAL_GRAVITY_MASK) { Gravity.LEFT -> { x0 = 1f x1 = 0f } Gravity.RIGHT -> { x0 = 0f x1 = 1f } else -> { x0 = 0f x1 = 0f } } when (gravity and Gravity.VERTICAL_GRAVITY_MASK) { Gravity.TOP -> { y0 = 1f y1 = 0f } Gravity.BOTTOM -> { y0 = 0f y1 = 1f } else -> { y0 = 0f y1 = 0f } } paintDrawable.shaderFactory = object : ShapeDrawable.ShaderFactory() { override fun resize(width: Int, height: Int): Shader { return LinearGradient( width * x0, height * y0, width * x1, height * y1, stopColors, null, Shader.TileMode.CLAMP) } } cubicGradientScrimCache.put(cacheKeyHash, paintDrawable) return paintDrawable }
main/src/main/java/com/google/android/apps/muzei/util/ScrimUtil.kt
3684836317
class Kotlin : Main() { fun t() { setSmth("") } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/javaMethodSyntheticSet/Kotlin.kt
1929890556
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.asJava import com.intellij.psi.* import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin import org.jetbrains.kotlin.asJava.classes.lazyPub import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.idea.frontend.api.isValid import org.jetbrains.kotlin.idea.frontend.api.symbols.KtKotlinPropertySymbol import org.jetbrains.kotlin.idea.frontend.api.symbols.KtPropertySymbol import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSimpleConstantValue import org.jetbrains.kotlin.psi.KtDeclaration internal class FirLightFieldForPropertySymbol( private val propertySymbol: KtPropertySymbol, private val fieldName: String, containingClass: FirLightClassBase, lightMemberOrigin: LightMemberOrigin?, isTopLevel: Boolean, forceStatic: Boolean, takePropertyVisibility: Boolean ) : FirLightField(containingClass, lightMemberOrigin) { override val kotlinOrigin: KtDeclaration? = propertySymbol.psi as? KtDeclaration private val _returnedType: PsiType by lazyPub { propertySymbol.annotatedType.asPsiType( propertySymbol, this@FirLightFieldForPropertySymbol, FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE ) } private val _isDeprecated: Boolean by lazyPub { propertySymbol.hasDeprecatedAnnotation(AnnotationUseSiteTarget.FIELD) } override fun isDeprecated(): Boolean = _isDeprecated private val _identifier: PsiIdentifier by lazyPub { FirLightIdentifier(this, propertySymbol) } override fun getNameIdentifier(): PsiIdentifier = _identifier override fun getType(): PsiType = _returnedType override fun getName(): String = fieldName private val _modifierList: PsiModifierList by lazyPub { val modifiers = mutableSetOf<String>() val suppressFinal = !propertySymbol.isVal propertySymbol.computeModalityForMethod( isTopLevel = isTopLevel, suppressFinal = suppressFinal, result = modifiers ) if (forceStatic) { modifiers.add(PsiModifier.STATIC) } val visibility = if (takePropertyVisibility) propertySymbol.toPsiVisibilityForMember(isTopLevel = false) else PsiModifier.PRIVATE modifiers.add(visibility) if (!suppressFinal) { modifiers.add(PsiModifier.FINAL) } if (propertySymbol.hasAnnotation("kotlin/jvm/Transient", null)) { modifiers.add(PsiModifier.TRANSIENT) } if (propertySymbol.hasAnnotation("kotlin/jvm/Volatile", null)) { modifiers.add(PsiModifier.VOLATILE) } val nullability = if (!(propertySymbol is KtKotlinPropertySymbol && propertySymbol.isLateInit)) propertySymbol.annotatedType.type.getTypeNullability(propertySymbol, FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE) else NullabilityType.Unknown val annotations = propertySymbol.computeAnnotations( parent = this, nullability = nullability, annotationUseSiteTarget = AnnotationUseSiteTarget.FIELD, ) FirLightClassModifierList(this, modifiers, annotations) } override fun getModifierList(): PsiModifierList = _modifierList private val _initializer by lazyPub { if (propertySymbol !is KtKotlinPropertySymbol) return@lazyPub null if (!propertySymbol.isConst) return@lazyPub null if (!propertySymbol.isVal) return@lazyPub null (propertySymbol.initializer as? KtSimpleConstantValue<*>)?.createPsiLiteral(this) } override fun getInitializer(): PsiExpression? = _initializer override fun equals(other: Any?): Boolean = this === other || (other is FirLightFieldForPropertySymbol && kotlinOrigin == other.kotlinOrigin && propertySymbol == other.propertySymbol) override fun hashCode(): Int = kotlinOrigin.hashCode() override fun isValid(): Boolean = super.isValid() && propertySymbol.isValid() }
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/fields/FirLightFieldForPropertySymbol.kt
3618592980
/* * 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.samples.apps.sunflower import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.core.app.ShareCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import com.google.android.material.composethemeadapter.MdcTheme import com.google.samples.apps.sunflower.compose.plantdetail.PlantDetailsScreen import com.google.samples.apps.sunflower.viewmodels.PlantDetailViewModel import dagger.hilt.android.AndroidEntryPoint import kotlin.text.Typography.dagger /** * A fragment representing a single Plant detail screen. */ @AndroidEntryPoint class PlantDetailFragment : Fragment() { private val plantDetailViewModel: PlantDetailViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = ComposeView(requireContext()).apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { // Create a Compose MaterialTheme inheriting the existing colors, typography // and shapes of the current View system's theme MdcTheme { PlantDetailsScreen( plantDetailViewModel, onBackClick = { findNavController().navigateUp() }, onShareClick = { createShareIntent() } ) } } } private fun navigateToGallery() { plantDetailViewModel.plant.value?.let { plant -> val direction = PlantDetailFragmentDirections.actionPlantDetailFragmentToGalleryFragment(plant.name) findNavController().navigate(direction) } } // Helper function for calling a share functionality. // Should be used when user presses a share button/menu item. @Suppress("DEPRECATION") private fun createShareIntent() { val shareText = plantDetailViewModel.plant.value.let { plant -> if (plant == null) { "" } else { getString(R.string.share_text_plant, plant.name) } } val shareIntent = ShareCompat.IntentBuilder.from(requireActivity()) .setText(shareText) .setType("text/plain") .createChooserIntent() .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK) startActivity(shareIntent) } }
app/src/main/java/com/google/samples/apps/sunflower/PlantDetailFragment.kt
1292057965
package com.stustirling.ribotviewer.data.local.model import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import java.util.* /** * Created by Stu Stirling on 23/09/2017. */ @Entity(tableName = "ribots") data class LocalRibot( @PrimaryKey var id: String, @ColumnInfo(name = "first_name") var firstName: String, @ColumnInfo(name = "last_name") var lastName: String, var email: String, @ColumnInfo(name = "dob") var dateOfBirth: Date, var color: String, var bio: String? = null, var avatar: String? = null, @ColumnInfo(name = "active") var isActive: Boolean)
data/src/main/java/com/stustirling/ribotviewer/data/local/model/LocalRibot.kt
3636872722
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.editor.Document import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.xdebugger.XSourcePositionWrapper import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation import com.intellij.xdebugger.frame.presentation.XStringValuePresentation import com.intellij.xdebugger.frame.presentation.XValuePresentation import org.jetbrains.concurrency.* import org.jetbrains.debugger.values.* import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.regex.Pattern import javax.swing.Icon fun VariableView(variable: Variable, context: VariableContext) = VariableView(variable.name, variable, context) class VariableView(name: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(name), VariableContext { @Volatile private var value: Value? = null // lazy computed private var memberFilter: MemberFilter? = null @Volatile private var remainingChildren: List<Variable>? = null @Volatile private var remainingChildrenOffset: Int = 0 override fun watchableAsEvaluationExpression() = context.watchableAsEvaluationExpression() override fun getViewSupport() = context.viewSupport override fun getParent() = context override fun getMemberFilter(): Promise<MemberFilter> { return context.viewSupport.getMemberFilter(this) } override fun computePresentation(node: XValueNode, place: XValuePlace) { value = variable.value if (value != null) { computePresentation(value!!, node) return } if (variable !is ObjectProperty || variable.getter == null) { // it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables) evaluateContext.evaluate(variable.name) .done(node) { if (it.wasThrown) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(value, null), null, node) } else { value = it.value computePresentation(it.value, node) } } .rejected(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) } return } node.setPresentation(null, object : XValuePresentation() { override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderValue("\u2026") } }, false) node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { val valueModifier = variable.valueModifier assert(valueModifier != null) valueModifier!!.evaluateGet(variable, evaluateContext) .done(node) { callback.evaluated("") setEvaluatedValue(it, null, node) } } }.setShowValuePopup(false)) } private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) { if (value == null) { node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false) } else { this.value = value computePresentation(value, node) } } private fun computePresentation(value: Value, node: XValueNode) { when (value.type) { ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon) ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true) ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon) ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false) ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false) ValueType.STRING -> { node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false) // isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation), // so, even in case of StringValue, we check value string length if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) { node.setFullValueEvaluator(MyFullValueEvaluator(value)) } } else -> node.setPresentation(icon, null, value.valueString!!, true) } } override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) if (value !is ObjectValue) { node.addChildren(XValueChildrenList.EMPTY, true) return } val list = remainingChildren if (list != null) { val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size) val isLast = to == list.size node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, memberFilter), isLast) if (!isLast) { node.tooManyChildren(list.size - to) remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW } return } val objectValue = value as ObjectValue val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO val promises = SmartList<Promise<*>>() val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node) if (additionalProperties != null) { promises.add(additionalProperties) } // we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified if (hasIndexedProperties) { promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null)) } if (hasNamedProperties) { // named properties should be added after additional properties if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) { promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null)) } else { promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) }) } } if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) { Promise.all(promises).processed(object : ObsolescentConsumer<Any?>(node) { override fun consume(aVoid: Any?) = node.addChildren(XValueChildrenList.EMPTY, true) }) } } abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() { override fun isObsolete() = node.isObsolete } private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> { return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) { override fun consumeRanges(ranges: IntArray?) { if (ranges == null) { val groupList = XValueChildrenList() LazyVariablesGroup.addGroups(value, LazyVariablesGroup.GROUP_FACTORY, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView) node.addChildren(groupList, isLastChildren) } else { LazyVariablesGroup.addRanges(value, ranges, node, this@VariableView, isLastChildren) } } override fun consumeVariables(variables: List<Variable>) { node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren) } }, null) } private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables -> [email protected] = memberFilter if (value.type == ValueType.ARRAY && value !is ArrayValue) { computeArrayRanges(variables, node) return@processVariables } var functionValue = value as? FunctionValue if (functionValue != null && functionValue.hasScopes() == ThreeState.NO) { functionValue = null } remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null) if (remainingChildren != null) { remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW } if (functionValue != null) { // we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren) } } private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) { val variables = filterAndSort(properties, memberFilter!!) var count = variables.size val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW if (count <= bucketSize) { node.addChildren(createVariablesList(variables, this, null), true) return } while (count > 0) { if (Character.isDigit(variables.get(count - 1).name[0])) { break } count-- } val groupList = XValueChildrenList() if (count > 0) { LazyVariablesGroup.addGroups(variables, VariablesGroup.GROUP_FACTORY, groupList, 0, count, bucketSize, this) } var notGroupedVariablesOffset: Int if ((variables.size - count) > bucketSize) { notGroupedVariablesOffset = variables.size while (notGroupedVariablesOffset > 0) { if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) { break } notGroupedVariablesOffset-- } if (notGroupedVariablesOffset > 0) { LazyVariablesGroup.addGroups(variables, VariablesGroup.GROUP_FACTORY, groupList, count, notGroupedVariablesOffset, bucketSize, this) } } else { notGroupedVariablesOffset = count } for (i in notGroupedVariablesOffset..variables.size - 1) { val variable = variables.get(i) groupList.add(VariableView(memberFilter!!.rawNameToSource(variable), variable, this)) } node.addChildren(groupList, true) } private val icon: Icon get() = getIcon(value!!) override fun getModifier(): XValueModifier? { if (!variable.isMutable) { return null } return object : XValueModifier() { override fun getInitialValueEditorText(): String? { if (value!!.type == ValueType.STRING) { val string = value!!.valueString!! val builder = StringBuilder(string.length) builder.append('"') StringUtil.escapeStringCharacters(string.length, string, builder) builder.append('"') return builder.toString() } else { return if (value!!.type.isObjectType) null else value!!.valueString } } override fun setValue(expression: String, callback: XValueModifier.XModificationCallback) { variable.valueModifier!!.setValue(variable, expression, evaluateContext) .done { value = null callback.valueModified() } .rejected { callback.errorOccurred(it.message!!) } } } } override fun getEvaluateContext() = context.evaluateContext fun getValue() = variable.value override fun canNavigateToSource() = value is FunctionValue || viewSupport.canNavigateToSource(variable, context) override fun computeSourcePosition(navigatable: XNavigatable) { if (value is FunctionValue) { (value as FunctionValue).resolve() .done { function -> viewSupport.vm!!.scriptManager.getScript(function) .done { val position = if (it == null) null else viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) navigatable.setSourcePosition(if (position == null) null else object : XSourcePositionWrapper(position) { override fun createNavigatable(project: Project): Navigatable { val result = PsiVisitors.visit(myPosition, project, object : PsiVisitors.Visitor<Navigatable>() { override fun visit(element: PsiElement, positionOffset: Int, document: Document): Navigatable? { // element will be "open paren", but we should navigate to function name, // we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression) var referenceCandidate: PsiElement? = element var psiReference: PsiElement? = null while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } if (psiReference == null) { referenceCandidate = element.parent while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } } return (if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable } }, null) return result ?: super.createNavigatable(project) } }) } } } else { viewSupport.computeSourcePosition(name, value!!, variable, context, navigatable) } } override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback) = viewSupport.computeInlineDebuggerData(name, variable, context, callback) override fun getEvaluationExpression(): String? { if (!watchableAsEvaluationExpression()) { return null } val list = SmartList(variable.name) var parent: VariableContext? = context while (parent != null && parent.name != null) { list.add(parent.name!!) parent = parent.parent } return context.viewSupport.propertyNamesToString(list, false) } private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { if (value !is StringValue || !value.isTruncated) { callback.evaluated(value.valueString!!) return } val evaluated = AtomicBoolean() value.fullString .done { if (!callback.isObsolete && evaluated.compareAndSet(false, true)) { callback.evaluated(value.valueString!!) } } .rejected { callback.errorOccurred(it.message!!) } } } override fun getScope() = context.scope companion object { fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) { node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO) } fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) { assert(value.type == ValueType.ARRAY) if (value is ArrayValue) { val length = value.length node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0) return } val valueString = value.valueString // only WIP reports normal description if (valueString != null && valueString.endsWith("]") && ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) { node.setPresentation(icon, null, valueString, true) } else { context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false) .done(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) } .rejected(node) { node.setPresentation(icon, null, "Internal error: $it", false) } } } fun getIcon(value: Value): Icon { val type = value.type return when (type) { ValueType.FUNCTION -> AllIcons.Nodes.Function ValueType.ARRAY -> AllIcons.Debugger.Db_array else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive } } } } fun getClassName(value: ObjectValue): String { val className = value.className return if (className.isNullOrEmpty()) "Object" else className!! } fun getObjectValueDescription(value: ObjectValue): String { val description = value.valueString return if (description.isNullOrEmpty()) getClassName(value) else description!! } internal fun trimFunctionDescription(value: Value): String { val presentableValue = value.valueString ?: return "" var endIndex = 0 while (endIndex < presentableValue.length && !StringUtil.isLineBreak(presentableValue[endIndex])) { endIndex++ } while (endIndex > 0 && Character.isWhitespace(presentableValue[endIndex - 1])) { endIndex-- } return presentableValue.substring(0, endIndex) } private fun createNumberPresentation(value: String): XValuePresentation { return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value) } private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+\\[\\d+\\]$") private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() { private val length = Integer.toString(length) private val className = if (className.isNullOrEmpty()) "Array" else className!! override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderSpecialSymbol(className) renderer.renderSpecialSymbol("[") renderer.renderSpecialSymbol(length) renderer.renderSpecialSymbol("]") } }
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.kt
849851871
package com.jraska.console.sample import android.app.Application import android.util.Log import com.jraska.console.timber.ConsoleTree import timber.log.Timber import java.text.SimpleDateFormat import java.util.Locale class ConsoleApp : Application() { override fun onCreate() { super.onCreate() val consoleTree = ConsoleTree.builder() .minPriority(Log.VERBOSE) .verboseColor(0xff909090.toInt()) .debugColor(0xffc88b48.toInt()) .infoColor(0xffc9c9c9.toInt()) .warnColor(0xffa97db6.toInt()) .errorColor(0xffff534e.toInt()) .assertColor(0xffff5540.toInt()) .timeFormat(SimpleDateFormat("HH:mm:ss.SSS", Locale.US)) .build() Timber.plant(consoleTree) Timber.i("Test message before attach of any view") } }
console-sample/src/main/java/com/jraska/console/sample/ConsoleApp.kt
302954351
package pt.joaomneto.titancompanion.adventure.impl.fragments.com import android.app.AlertDialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.AdapterView.OnItemLongClickListener import android.widget.ArrayAdapter import android.widget.EditText import kotlinx.android.synthetic.main.fragment_30com_adventure_notes.* import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.impl.COMAdventure import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment class COMAdventureNotesFragment : AdventureNotesFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { baseLayout = R.layout.fragment_30com_adventure_notes return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adv = this.activity as COMAdventure buttonAddCypher.setOnClickListener( OnClickListener { val alert = AlertDialog.Builder(adv) alert.setTitle(R.string.note) // Set an EditText view to get user input val input = EditText(adv) val imm = adv.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT) input.requestFocus() alert.setView(input) alert.setPositiveButton( R.string.ok, { _, _ -> val value = input.text.toString() if (value.isNotBlank()) { adv.cyphers = adv.cyphers.plus(value.trim { it <= ' ' }) (cypherList!!.adapter as ArrayAdapter<String>).notifyDataSetChanged() } } ) alert.setNegativeButton( R.string.cancel ) { _, _ -> // Canceled. } alert.show() } ) val adapter = ArrayAdapter( adv, android.R.layout.simple_list_item_1, android.R.id.text1, adv.cyphers ) cypherList.adapter = adapter cypherList.onItemLongClickListener = OnItemLongClickListener { _, _, arg2, _ -> val builder = AlertDialog.Builder(adv) builder.setTitle(R.string.deleteKeyword) .setCancelable(false) .setNegativeButton( R.string.close ) { dialog, _ -> dialog.cancel() } builder.setPositiveButton(R.string.ok) { _, _ -> adv.cyphers = adv.cyphers.minus(adv.cyphers[arg2]) (cypherList!!.adapter as ArrayAdapter<String>).notifyDataSetChanged() } val alert = builder.create() alert.show() true } } override fun refreshScreensFromResume() { super.refreshScreensFromResume() (cypherList.adapter as ArrayAdapter<String>).notifyDataSetChanged() } }
src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/com/COMAdventureNotesFragment.kt
241621997
package com.sksamuel.kotest.engine.spec.multilinename import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe // tests that multi line test names are normalized class ShouldSpecMultiLineTest : ShouldSpec() { init { val names = mutableSetOf<String>() afterSpec { names shouldBe setOf("should test case 1", "should test case 2") } should( """ test case 1 """ ) { names.add(this.testCase.displayName) } context("context") { should( """ test case 2 """ ) { names.add(this.testCase.displayName) } } } }
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/spec/multilinename/ShouldSpecMultiLineTest.kt
1991617449
package cz.filipproch.reactor.ui.events import cz.filipproch.reactor.base.view.ReactorUiEvent import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import org.assertj.core.api.Assertions import org.junit.Before import org.junit.Test /** * TODO * * @author Filip Prochazka (@filipproch) */ abstract class BaseEventFilterTest { val allReceivedEvents = mutableListOf<ReactorUiEvent>() val validReceivedEvents = mutableListOf<ReactorUiEvent>() lateinit var subject: PublishSubject<ReactorUiEvent> @Before fun prepareTests() { subject = PublishSubject.create<ReactorUiEvent>() subject.subscribe { allReceivedEvents.add(it) } filterStream(subject).subscribe { validReceivedEvents.add(it) } } @Test fun runFilterTest() { subject.onNext(TestEvent) Assertions.assertThat(allReceivedEvents).hasSize(1) Assertions.assertThat(validReceivedEvents).hasSize(0) subject.onNext(getValidEventInstance()) Assertions.assertThat(allReceivedEvents).hasSize(2) Assertions.assertThat(validReceivedEvents).hasSize(1) } abstract fun filterStream(stream: Observable<ReactorUiEvent>): Observable<out ReactorUiEvent> abstract fun getValidEventInstance(): ReactorUiEvent }
library/src/test/java/cz/filipproch/reactor/ui/events/BaseEventFilterTest.kt
519859208
package glorantq.ramszesz.commands import com.cedarsoftware.util.io.JsonWriter import com.overzealous.remark.Remark import glorantq.ramszesz.osuKey import glorantq.ramszesz.utils.BotUtils import okhttp3.* import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.parser.JSONParser import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.util.EmbedBuilder import java.io.IOException import java.net.URLEncoder import java.text.DecimalFormat import java.util.* import java.util.regex.Pattern class OsuCommand : ICommand { override val commandName: String get() = "osu" override val description: String get() = "Check an osu! player's stats" override val permission: Permission get() = Permission.USER override val usage: String get() = "username" override val availableInDM: Boolean get() = true private val httpClient: OkHttpClient by lazy { OkHttpClient.Builder().build() } private val numberFormat: DecimalFormat = DecimalFormat("###,###") /* <:A_small:352910388892925953> <:B_small:352910392210620417> <:C_small:352910397734387713> <:D_small:352910397529128961> <:S_small:352910397667409931> <:SH_small:352910397755359233> <:XH_small:352910397897965568> */ override fun execute(event: MessageReceivedEvent, args: List<String>) { if (args.isEmpty()) { BotUtils.sendUsageEmbed("Specify a user!", "osu! statistics", event.author, event, this) } else { val username: String = buildString { for(s: String in args) { append(s) append(" ") } setLength(length - 1) } val encodedName: String = URLEncoder.encode(username, "UTF-8").replace("+", "%20") val requestURL: String = "https://osu.ppy.sh/api/get_user?k=$osuKey&u=$encodedName" val request: Request = Request.Builder().url(requestURL).get().build() httpClient.newCall(request).enqueue(object : Callback { override fun onFailure(p0: Call, p1: IOException) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("osu! statistics", "Failed to look up `$username`'s stats because @glorantq can't code!", event.author), event.channel) } override fun onResponse(p0: Call, p1: Response) { val rawJson: String = p1.body()!!.string() val root: Any = JSONParser().parse(rawJson) if (root is JSONObject) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("osu! statistics", buildString { append("Failed to look up `$username`'s stats because @glorantq can't code!") if (root.containsKey("error")) { append(" (${root["error"].toString()})") } }, event.author), event.channel) return } root as JSONArray if (root.isEmpty()) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("osu! statistics", "The user `$username` is invalid!", event.author), event.channel) return } val user: JSONObject = root[0] as JSONObject val embed: EmbedBuilder = BotUtils.embed("osu! statistics for ${user["username"]}", event.author) embed.withAuthorUrl("https://osu.ppy.sh/u/$encodedName") embed.withAuthorIcon("https://osu.ppy.sh/images/layout/osu-logo.png") embed.withThumbnail("https://a.ppy.sh/${user["user_id"]}") embed.appendField("PP", formatNumber(user["pp_raw"]), true) embed.appendField("Global Rank", "#${user["pp_rank"]}", true) embed.appendField("Country", ":flag_${user["country"].toString().toLowerCase()}: ${Locale("", user["country"].toString()).displayCountry}", true) embed.appendField("Country Rank", "#${user["pp_country_rank"]}", true) embed.appendField("Ranked Score", formatNumber(user["ranked_score"]), true) embed.appendField("Total Score", formatNumber(user["total_score"]), true) embed.appendField("Level", formatNumber(user["level"]), true) embed.appendField("Accuracy", "${String.format("%.2f", user["accuracy"].toString().toDouble())}%", true) embed.appendField("Play Count", formatNumber(user["playcount"]), true) embed.appendField("Ranks (SS/S/A)", "${user["count_rank_ss"]}/${user["count_rank_s"]}/${user["count_rank_a"]}", true) val events: JSONArray = user["events"] as JSONArray if(events.isNotEmpty()) { val eventBuilder = StringBuilder() for(osuEvent: Any? in events) { osuEvent as JSONObject var title: String = osuEvent["display_html"].toString() title = title.replace("<img src='/images/A_small.png'/>", "<:A_small:352910388892925953>") title = title.replace("<img src='/images/B_small.png'/>", "<:B_small:352910392210620417>") title = title.replace("<img src='/images/C_small.png'/>", "<:C_small:352910397734387713>") title = title.replace("<img src='/images/D_small.png'/>", "<:D_small:352910397529128961>") title = title.replace("<img src='/images/S_small.png'/>", "<:S_small:352910397667409931>") title = title.replace("<img src='/images/SH_small.png'/>", "<:SH_small:352910397755359233>") title = title.replace("<img src='/images/XH_small.png'/>", "<:XH_small:352910397897965568>") title = Remark().convert(title) title = title.replace("\\_", "_") if(eventBuilder.length + title.length > 1024) { break } eventBuilder.append(title) eventBuilder.append("\n") } eventBuilder.setLength(eventBuilder.length - 1) embed.appendField("Recent Events", eventBuilder.toString(), false) } BotUtils.sendMessage(embed.build(), event.channel) } }) } } private fun formatNumber(input: Any?): String { val number: Double = Math.round( try { input.toString().toDouble() } catch (e: Exception) { e.printStackTrace() -1.0 }).toDouble() return numberFormat.format(number) } }
src/glorantq/ramszesz/commands/OsuCommand.kt
1915286551
package net.nonylene.gradle.external import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.Storage import com.intellij.openapi.components.State import com.intellij.openapi.components.StoragePathMacros @State(name = "ExternalPreferenceProvider", storages = arrayOf(Storage(file = "${StoragePathMacros.APP_CONFIG}/externalBuild.xml"))) class ExternalPreferenceProvider : PersistentStateComponent<ExternalPreferenceProvider.State> { class State { var workingDirectory: String? = null var program: String? = null var parameters: String? = null } private var state: State? = State() override fun getState(): State? { return state } override fun loadState(state: State?) { this.state = state } }
src/net/nonylene/gradle/external/ExternalPreferenceProvider.kt
3650978835
package koma.gui.view.window.chatroom.roominfo import de.jensd.fx.glyphs.materialicons.MaterialIcon import de.jensd.fx.glyphs.materialicons.utils.MaterialIconFactory import javafx.beans.property.SimpleBooleanProperty import javafx.geometry.Pos import javafx.scene.Scene import javafx.scene.control.Hyperlink import javafx.scene.control.TextField import javafx.scene.layout.Priority import javafx.stage.Stage import javafx.stage.Window import koma.gui.view.window.chatroom.roominfo.about.RoomAliasForm import koma.gui.view.window.chatroom.roominfo.about.requests.chooseUpdateRoomIcon import koma.gui.view.window.chatroom.roominfo.about.requests.requestUpdateRoomName import koma.matrix.UserId import koma.matrix.event.room_message.RoomEventType import koma.matrix.room.naming.RoomId import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import link.continuum.database.models.getChangeStateAllowed import link.continuum.desktop.database.RoomDataStorage import link.continuum.desktop.database.hashColor import link.continuum.desktop.gui.* import link.continuum.desktop.gui.icon.avatar.Avatar2L import link.continuum.desktop.gui.view.AccountContext import link.continuum.desktop.util.getOrNull class RoomInfoDialog( datas: RoomDataStorage, context: AccountContext, room: RoomId, user: UserId ) { private val scope = MainScope() val root= VBox(10.0) private val roomicon = Avatar2L() val stage = Stage() fun openWindow(owner: Window) { stage.initOwner(owner) stage.scene = Scene(root) stage.show() } init { stage.setOnHidden { roomicon.cancelScope() scope.cancel() } datas.latestAvatarUrl.receiveUpdates(room).onEach { roomicon.updateUrl(it?.getOrNull(), context.account.server) }.launchIn(scope) val color = room.hashColor() var name: String? = null datas.latestDisplayName(room).onEach { name = it roomicon.updateName(it, color) stage.title = "$it Info" }.launchIn(scope) val data = datas.data val canEditName = SimpleBooleanProperty(false) val canEditAvatar = SimpleBooleanProperty(false) scope.launch { val n =data.runOp { getChangeStateAllowed(this, room, user, RoomEventType.Name.toString()) } canEditName.set(n) canEditAvatar.set(data.runOp { getChangeStateAllowed(this, room, user, RoomEventType.Avatar.toString()) }) } stage.title = "Update Info of Room" val aliasDialog = RoomAliasForm(room, user, datas) with(root) { padding = UiConstants.insets5 hbox(5.0) { vbox { spacing = 5.0 hbox(5.0) { alignment = Pos.CENTER text("Name") val input = TextField(name) input.editableProperty().bind(canEditName) add(input) button("Set") { removeWhen(canEditName.not()) action { requestUpdateRoomName(room, input.text) } } } } hbox { HBox.setHgrow(this, Priority.ALWAYS) } vbox() { spacing = 5.0 padding = UiConstants.insets5 alignment = Pos.CENTER add(roomicon.root) val camera = MaterialIconFactory.get().createIcon(MaterialIcon.PHOTO_CAMERA) add(Hyperlink().apply { graphic = camera removeWhen(canEditAvatar.not()) setOnAction { chooseUpdateRoomIcon(room) } }) } } add(aliasDialog.root) } } }
src/main/kotlin/koma/gui/view/window/chatroom/roominfo/RoomInfoView.kt
364745634
package com.jtransc.debugger.v8 import com.jtransc.async.EventLoop import com.jtransc.async.Promise import com.jtransc.async.syncWait import com.jtransc.debugger.JTranscDebugger import com.jtransc.json.Json import com.jtransc.json.JsonObject import com.jtransc.sourcemaps.Sourcemaps import com.jtransc.net.TcpClientAsync import com.jtransc.vfs.UTF8 import java.io.File import java.nio.charset.Charset import java.util.* // https://github.com/v8/v8/wiki/Debugging%20Protocol class V8JTranscDebugger( private val port: Int, private val host: String = "127.0.0.1", handler: EventHandler ) : JTranscDebugger(handler) { private val socket = createV8DebugSocket(port, host) override var currentPosition: SourcePosition = SourcePosition("unknown", 0) init { socket.handle { //println(it) } socket.handleEvents(object : V8EventHandlers() { override fun handleBreak(body: BreakResponseBody) { currentPosition = body.script.toSourcePosition() handler.onBreak() } override fun handleAfterCompile(body: AfterCompileResponseBody) { } }) socket.cmdRequestScriptsAsync().then { } } override fun pause() { //socket.cmdPause().syncWait() } override fun resume() { socket.cmdResume().syncWait() } override fun stepOver() { socket.cmdStepNext().syncWait() } override fun stepInto() { socket.cmdStepIn().syncWait() } override fun stepOut() { socket.cmdStepOut().syncWait() } override fun disconnect() { socket.cmdDisconnect() } override fun setBreakpoint(script: String, line: Int): Breakpoint { return V8Breakpoint(socket.cmdScriptBreakpoint(script, line).syncWait()) } class V8Breakpoint(val id: Int) : Breakpoint() override fun backtrace(): List<Frame> { val frames = socket.cmdRequestFrames().syncWait() val lookupResult = socket.cmdLookup(frames.frames.map { it.script.ref }.distinct()).syncWait() return frames.frames.map { frame -> V8Frame(this, frame, lookupResult) } } private val sourceMaps = hashMapOf<String, Sourcemaps.SourceMap?>() private fun getSourceMap(path: String): Sourcemaps.SourceMap? { if (path !in sourceMaps) { val sourceMap = File(path + ".map") sourceMaps[path] = if (sourceMap.exists()) Sourcemaps.decodeFile(sourceMap.readText(UTF8)) else null } return sourceMaps[path] } private fun getScript(path: String, line: Int, deep:Int = 0): SourcePosition { if (deep < 10) { val sourceMap = getSourceMap(path) val result = sourceMap?.decodePos(line) if (result != null) { return getScript(result.name, result.line, deep + 1) } } return SourcePosition(path, line) } class V8Frame(val debugger: V8JTranscDebugger, val frame: V8FrameResponse, scriptsByHandle: Map<Int, Any?>) : Frame() { val socket = debugger.socket val script2 = scriptsByHandle[frame.script.ref] as V8ScriptResponse? override val position: SourcePosition get() = debugger.getScript(script2?.name ?: "unknown.js", frame.line) override val locals: List<Local> get() { val localsMap = socket.cmdLookup(frame.locals.map { it.value.ref }.distinct()).syncWait() return frame.locals.map { V8Local(it, localsMap) } } override fun evaluate(expr: String): Any? = socket.cmdEvaluate(frame.index, expr).syncWait() } class V8Local(val local: com.jtransc.debugger.v8.V8Local, val localsMap: Map<Int, Any?>) : Local() { override val name: String get() = local.name override val value: Value get() = V8Value(localsMap[local.value.ref] as Map<*, *>?) } class V8Value(val param: Map<*, *>?) : Value() { val obj = JsonObject(param ?: mapOf<Any?, Any?>()) init { //println("V8Value: $param") } override val type: String = obj.getString("type") ?: "type" override val value: String = obj.getString("name") ?: "value" } private fun ScriptPosition.toSourcePosition(): JTranscDebugger.SourcePosition { return JTranscDebugger.SourcePosition(this.name, this.lineOffset) } } internal fun normalizePath(path: String): String { if (path.startsWith("file://")) return normalizePath(path.substring(7)) return path } class ScriptPosition { @JvmField var id: Int = 0 @JvmField var name: String = "" @JvmField var lineOffset: Int = 0 @JvmField var columnOffset: Int = 0 @JvmField var lineCount: Int = 0 override fun toString(): String { return "ScriptPosition(id=$id, name='$name', lineOffset=$lineOffset, columnOffset=$columnOffset, lineCount=$lineCount)" } } class BreakResponseBody { @JvmField var invocationText: String = "" @JvmField var sourceLine: Int = 0 @JvmField var sourceColumn: Int = 0 @JvmField var sourceLineText: String = "" @JvmField var script: ScriptPosition = ScriptPosition() @JvmField var breakpoints: List<Int> = listOf() override fun toString(): String { return "BreakResponseBody(invocationText='$invocationText', sourceLine=$sourceLine, sourceColumn=$sourceColumn, sourceLineText='$sourceLineText', script=$script, breakpoints=$breakpoints)" } } class AfterCompileResponseBody { @JvmField var script = V8ScriptResponse() } open class V8EventHandlers { open fun handleBreak(body: BreakResponseBody) { } open fun handleAfterCompile(body: AfterCompileResponseBody) { } } fun V8DebugSocket.handleEvents(handler: V8EventHandlers) { this.handleEvent { message -> when (message.getString("event")) { "break" -> handler.handleBreak(Json.decodeTo<BreakResponseBody>(message.getJsonObject("body").toString())) "afterCompile" -> handler.handleAfterCompile(Json.decodeTo<AfterCompileResponseBody>(message.getJsonObject("body").toString())) else -> Unit } } } class V8ScriptResponse { @JvmField var handle = 0 @JvmField var id = 0L @JvmField var type = "" @JvmField var name = "" @JvmField var lineCount = 0 @JvmField var lineOffset = 0 @JvmField var columnOffset = 0 @JvmField var sourceStart = "" @JvmField var sourceLength = 0 @JvmField var scriptType = 0 @JvmField var compilationType = 0 @JvmField var context = V8Ref() @JvmField var text = "" override fun toString(): String { return "V8ScriptResponse(handle=$handle, id=$id, type='$type', name='$name', lineCount=$lineCount, lineOffset=$lineOffset, columnOffset=$columnOffset, sourceStart='$sourceStart', sourceLength=$sourceLength, scriptType=$scriptType, compilationType=$compilationType, context=$context, text='$text')" } } fun V8DebugSocket.cmdRequestScriptsAsync(includeSource: Boolean = false): Promise<List<V8ScriptResponse>> { return this.sendRequestAndWaitAsync("scripts", mapOf("includeSource" to includeSource)).then { //println("SCRIPTS:" + it.encodePrettily()) //it it.getArray("array").map { Json.decodeTo<V8ScriptResponse>(Json.encodeAny(it)) } //listOf<V8ScriptResponse>() //DATA({"seq":2,"type":"response","command":"scripts","success":true,"body":[{"handle":14,"type":"script","name":"node.js","id":37,"lineOffset":0,"columnOffset":0,"lineCount":446,"sourceStart":"// Hello, and welcome to hacking node.js!\n//\n// This file is invoked by node::Lo","sourceLength":13764,"scriptType":2,"compilationType":0,"context":{"ref":13},"text":"node.js (lines: 446)"},{"handle":16,"type":"script","name":"events.js","id":38,"lineOffset":0,"columnOffset":0,"lineCount":478,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nvar","sourceLength":13015,"scriptType":2,"compilationType":0,"context":{"ref":15},"text":"events.js (lines: 478)"},{"handle":18,"type":"script","name":"util.js","id":39,"lineOffset":0,"columnOffset":0,"lineCount":927,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":25960,"scriptType":2,"compilationType":0,"context":{"ref":17},"text":"util.js (lines: 927)"},{"handle":20,"type":"script","name":"buffer.js","id":40,"lineOffset":0,"columnOffset":0,"lineCount":1295,"sourceStart":"(function (exports, require, module, __filename, __dirname) { /* eslint-disable ","sourceLength":32678,"scriptType":2,"compilationType":0,"context":{"ref":19},"text":"buffer.js (lines: 1295)"},{"handle":22,"type":"script","name":"internal/util.js","id":41,"lineOffset":0,"columnOffset":0,"lineCount":94,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":2710,"scriptType":2,"compilationType":0,"context":{"ref":21},"text":"internal/util.js (lines: 94)"},{"handle":24,"type":"script","name":"timers.js","id":42,"lineOffset":0,"columnOffset":0,"lineCount":636,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":17519,"scriptType":2,"compilationType":0,"context":{"ref":23},"text":"timers.js (lines: 636)"},{"handle":26,"type":"script","name":"internal/linkedlist.js","id":43,"lineOffset":0,"columnOffset":0,"lineCount":59,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nfun","sourceLength":1098,"scriptType":2,"compilationType":0,"context":{"ref":25},"text":"internal/linkedlist.js (lines: 59)"},{"handle":28,"type":"script","name":"assert.js","id":44,"lineOffset":0,"columnOffset":0,"lineCount":364,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // http://wiki.com","sourceLength":12444,"scriptType":2,"compilationType":0,"context":{"ref":27},"text":"assert.js (lines: 364)"},{"handle":30,"type":"script","name":"internal/process.js","id":45,"lineOffset":0,"columnOffset":0,"lineCount":188,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nvar","sourceLength":4628,"scriptType":2,"compilationType":0,"context":{"ref":29},"text":"internal/process.js (lines: 188)"},{"handle":32,"type":"script","name":"internal/process/warning.js","id":46,"lineOffset":0,"columnOffset":0,"lineCount":51,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":1773,"scriptType":2,"compilationType":0,"context":{"ref":31},"text":"internal/process/warning.js (lines: 51)"},{"handle":34,"type":"script","name":"internal/process/next_tick.js","id":47,"lineOffset":0,"columnOffset":0,"lineCount":159,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nexp","sourceLength":4392,"scriptType":2,"compilationType":0,"context":{"ref":33},"text":"internal/process/next_tick.js (lines: 159)"},{"handle":36,"type":"script","name":"internal/process/promises.js","id":48,"lineOffset":0,"columnOffset":0,"lineCount":63,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":1942,"scriptType":2,"compilationType":0,"context":{"ref":35},"text":"internal/process/promises.js (lines: 63)"},{"handle":38,"type":"script","name":"internal/process/stdio.js","id":49,"lineOffset":0,"columnOffset":0,"lineCount":163,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nexp","sourceLength":4260,"scriptType":2,"compilationType":0,"context":{"ref":37},"text":"internal/process/stdio.js (lines: 163)"},{"handle":40,"type":"script","name":"path.js","id":50,"lineOffset":0,"columnOffset":0,"lineCount":1597,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":46529,"scriptType":2,"compilationType":0,"context":{"ref":39},"text":"path.js (lines: 1597)"},{"handle":42,"type":"script","name":"module.js","id":51,"lineOffset":0,"columnOffset":0,"lineCount":641,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":18241,"scriptType":2,"compilationType":0,"context":{"ref":41},"text":"module.js (lines: 641)"},{"handle":44,"type":"script","name":"internal/module.js","id":52,"lineOffset":0,"columnOffset":0,"lineCount":98,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nexp","sourceLength":2625,"scriptType":2,"compilationType":0,"context":{"ref":43},"text":"internal/module.js (lines: 98)"},{"handle":46,"type":"script","name":"vm.js","id":53,"lineOffset":0,"columnOffset":0,"lineCount":59,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\ncon","sourceLength":1697,"scriptType":2,"compilationType":0,"context":{"ref":45},"text":"vm.js (lines: 59)"},{"handle":48,"type":"script","name":"fs.js","id":54,"lineOffset":0,"columnOffset":0,"lineCount":2035,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // Maintainers, ke","sourceLength":51790,"scriptType":2,"compilationType":0,"context":{"ref":47},"text":"fs.js (lines: 2035)"},{"handle":50,"type":"script","name":"stream.js","id":56,"lineOffset":0,"columnOffset":0,"lineCount":109,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nmod","sourceLength":2506,"scriptType":2,"compilationType":0,"context":{"ref":49},"text":"stream.js (lines: 109)"},{"handle":52,"type":"script","name":"_stream_readable.js","id":57,"lineOffset":0,"columnOffset":0,"lineCount":930,"sourceStart":"(function (exports, require, module, __filename, __dirname) { 'use strict';\n\nmod","sourceLength":25764,"scriptType":2,"compilationType":0,"context":{"ref":51},"text":"_stream_readable.js (lines: 930)"},{"handle":54,"type":"script","name":"_stream_writable.js","id":58,"lineOffset":0,"columnOffset":0,"lineCount":531,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // A bit simpler t","sourceLength":14353,"scriptType":2,"compilationType":0,"context":{"ref":53},"text":"_stream_writable.js (lines: 531)"},{"handle":56,"type":"script","name":"_stream_duplex.js","id":59,"lineOffset":0,"columnOffset":0,"lineCount":59,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // a duplex stream","sourceLength":1501,"scriptType":2,"compilationType":0,"context":{"ref":55},"text":"_stream_duplex.js (lines: 59)"},{"handle":58,"type":"script","name":"_stream_transform.js","id":60,"lineOffset":0,"columnOffset":0,"lineCount":194,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // a transform str","sourceLength":6414,"scriptType":2,"compilationType":0,"context":{"ref":57},"text":"_stream_transform.js (lines: 194)"},{"handle":60,"type":"script","name":"_stream_passthrough.js","id":61,"lineOffset":0,"columnOffset":0,"lineCount":24,"sourceStart":"(function (exports, require, module, __filename, __dirname) { // a passthrough s","sourceLength":592,"scriptType":2,"compilationType":0,"context":{"ref":59},"text":"_stream_passthrough.js (lines: 24)"},{"handle":12,"type":"script","name":"/Users/soywiz/Projects/jtransc/jtransc/jtransc-debugger/target/test-classes/test.js","id":62,"lineOffset":0,"columnOffset":0,"lineCount":2,"sourceStart":"(function (exports, require, module, __filename, __dirname) { console.log('test'","sourceLength":86,"scriptType":2,"compilationType":0,"context":{"ref":11},"text":"/Users/soywiz/Projects/jtransc/jtransc/jtransc-debugger/target/test-classes/test.js (lines: 2)"}],"refs":[{"handle":13,"type":"context","text":"#<ContextMirror>"},{"handle":15,"type":"context","text":"#<ContextMirror>"},{"handle":17,"type":"context","text":"#<ContextMirror>"},{"handle":19,"type":"context","text":"#<ContextMirror>"},{"handle":21,"type":"context","text":"#<ContextMirror>"},{"handle":23,"type":"context","text":"#<ContextMirror>"},{"handle":25,"type":"context","text":"#<ContextMirror>"},{"handle":27,"type":"context","text":"#<ContextMirror>"},{"handle":29,"type":"context","text":"#<ContextMirror>"},{"handle":31,"type":"context","text":"#<ContextMirror>"},{"handle":33,"type":"context","text":"#<ContextMirror>"},{"handle":35,"type":"context","text":"#<ContextMirror>"},{"handle":37,"type":"context","text":"#<ContextMirror>"},{"handle":39,"type":"context","text":"#<ContextMirror>"},{"handle":41,"type":"context","text":"#<ContextMirror>"},{"handle":43,"type":"context","text":"#<ContextMirror>"},{"handle":45,"type":"context","text":"#<ContextMirror>"},{"handle":47,"type":"context","text":"#<ContextMirror>"},{"handle":49,"type":"context","text":"#<ContextMirror>"},{"handle":51,"type":"context","text":"#<ContextMirror>"},{"handle":53,"type":"context","text":"#<ContextMirror>"},{"handle":55,"type":"context","text":"#<ContextMirror>"},{"handle":57,"type":"context","text":"#<ContextMirror>"},{"handle":59,"type":"context","text":"#<ContextMirror>"},{"handle":11,"type":"context","text":"#<ContextMirror>"}],"running":false}) } } fun V8DebugSocket.cmdStepIn(count: Int = 1): Promise<JsonObject> { return cmdContinue("in", count) } fun V8DebugSocket.cmdStepNext(count: Int = 1): Promise<JsonObject> { return cmdContinue("next", count) } fun V8DebugSocket.cmdStepOut(count: Int = 1): Promise<JsonObject> { return cmdContinue("out", count) } fun V8DebugSocket.cmdDisconnect() { this.sendRequestAndWaitAsync("disconnect") } fun V8DebugSocket.cmdScriptBreakpoint(target:String, line:Int): Promise<Int> { return this.sendRequestAndWaitAsync("setbreakpoint", mapOf("type" to "script", "target" to target, "line" to line)).then { it.getInteger("breakpoint") } } fun V8DebugSocket.cmdResume(): Promise<JsonObject> { return this.sendRequestAndWaitAsync("continue") } fun V8DebugSocket.cmdContinue(action: String, count: Int = 1): Promise<JsonObject> { return this.sendRequestAndWaitAsync("continue", mapOf("stepaction" to action, "stepcount" to count)) } // https://github.com/v8/v8/wiki/Debugging-Protocol#request-source class SourceResponse { var source: String = "" var fromLine: Int = 0 var toLine: Int = 0 var fromPosition: Int = 0 var toPosition: Int = 0 var totalLines: Int = 0 override fun toString() = "SourceResponse(source='$source', fromLine=$fromLine, toLine=$toLine, fromPosition=$fromPosition, toPosition=$toPosition, totalLines=$totalLines)" } fun V8DebugSocket.cmdRequestSource(fromLine: Int = -1, toLine: Int = Int.MAX_VALUE): Promise<SourceResponse> { return this.sendRequestAndWaitAsync("source", mapOf("fromLine" to fromLine, "toLine" to toLine)).then { Json.decodeTo(it.encode(), SourceResponse::class.java) } } class V8Ref { @JvmField var ref: Int = 0 override fun toString() = "V8Ref(ref=$ref)" } class V8Arguments { @JvmField var name: String = "" @JvmField var value: V8Ref = V8Ref() } class V8Local { @JvmField var name: String = "" @JvmField var value: V8Ref = V8Ref() } class V8Scope { @JvmField var type: Int = 0 @JvmField var index: Int = 0 } class V8FrameResponse { @JvmField var type: String = "" @JvmField var index: Int = 0 @JvmField var receiver: V8Ref = V8Ref() @JvmField var func: V8Ref = V8Ref() @JvmField var script: V8Ref = V8Ref() @JvmField var constructCall: Boolean = false @JvmField var atReturn: Boolean = false @JvmField var debuggerFrame: Boolean = false @JvmField var arguments: List<V8Arguments> = arrayListOf() @JvmField var returnValue: Any? = Unit @JvmField var locals: List<V8Local> = arrayListOf() @JvmField var scopes: List<V8Scope> = arrayListOf() @JvmField var position: Int = 0 @JvmField var line: Int = 0 @JvmField var column: Int = 0 @JvmField var sourceLineText: String = "" @JvmField var text: String = "" override fun toString() = "V8FrameResponse(type='$type', index=$index, receiver=$receiver, func=$func, script=$script, constructCall=$constructCall, atReturn=$atReturn, debuggerFrame=$debuggerFrame, arguments=$arguments, locals=$locals, scopes=$scopes, position=$position, line=$line, column=$column, sourceLineText='$sourceLineText', text='$text')" } class V8BacktraceResponse { @JvmField var fromFrame: Int = 0 @JvmField var toFrame: Int = 0 @JvmField var totalFrames: Int = 0 @JvmField var frames: List<V8FrameResponse> = arrayListOf() override fun toString() = "V8BacktraceResponse(fromFrame=$fromFrame, toFrame=$toFrame, totalFrames=$totalFrames, frames=$frames)" } fun V8DebugSocket.cmdRequestFrames(fromFrame: Int = 0, toFrame: Int = 10): Promise<V8BacktraceResponse> { return this.sendRequestAndWaitAsync("backtrace", mapOf("fromFrame" to fromFrame, "toFrame" to toFrame)).then { //println("BACKTRACE: ${it.encodePrettily()}") Json.decodeTo<V8BacktraceResponse>(it.toString()) } } fun V8DebugSocket.cmdLookup(handles: List<Int>, includeSource: Boolean = false): Promise<Map<Int, Any>> { return this.sendRequestAndWaitAsync("lookup", mapOf("handles" to handles, "includeSource" to includeSource)).then { body -> body.map { pair -> val obj = pair.value as Map<*, *>? Pair("${pair.key}".toInt(), try { when (obj?.get("type")) { "script" -> JsonObject(obj as Map<Any?, Any?>).to<V8ScriptResponse>() else -> obj } ?: Unit } catch (e:Throwable) { println("ERROR: $e") Unit }) }.toMap() } } //{"seq":117,"type":"request","command":"evaluate","arguments":{"expression":"1+2"}} fun V8DebugSocket.cmdEvaluate(expression: String): Promise<Any> { return this.sendRequestAndWaitAsync("evaluate", mapOf("expression" to expression)).then { it.getValue("value") ?: Unit } } fun V8DebugSocket.cmdEvaluate(frame: Int, expression: String): Promise<Any> { return this.sendRequestAndWaitAsync("evaluate", mapOf("frame" to frame, "expression" to expression)).then { it.getValue("value") ?: Unit } } fun V8DebugSocket.sendRequestAndWaitAsync(command: String, arguments: Map<String, Any?>? = null): Promise<JsonObject> { val obj = LinkedHashMap<String, Any?>() obj["seq"] = seq++ obj["type"] = "request" obj["command"] = command if (arguments != null) obj["arguments"] = arguments return this.writeAndWaitAsync(JsonObject(obj)).then { message -> if (message.getBoolean("success")) { val result = message.getValue("body") when (result) { is JsonObject -> result is Map<*, *> -> JsonObject(result) is Iterable<*> -> JsonObject(mapOf("array" to result)) else -> JsonObject(mapOf<Any?, Any?>()) } } else { throw RuntimeException(message.getString("message")) } } } fun createV8DebugSocket(port: Int = 5858, host: String = "127.0.0.1") = V8DebugSocket(port, host) class V8DebugSocket(val port: Int = 5858, val host: String = "127.0.0.1") { private val handlers = Collections.synchronizedList(arrayListOf<(message: JsonObject) -> Unit>()) private var state = State.HEADER @Volatile private var buffer = byteArrayOf() var contentLength = 0 private val UTF8 = Charsets.UTF_8 var seq = 1 enum class State { HEADER, HEADER_SPACE, BODY } private var client = TcpClientAsync(host, port, object : TcpClientAsync.Handler { override fun onOpen() { println("Connected!") } override fun onData(data: ByteArray) { buffer += data processBuffer() } override fun onClose() { println("Disconnected!") } }).apply { println("Connecting...") } private fun readBuffer(len: Int): ByteArray { val out = buffer.sliceArray(0 until len) buffer = buffer.sliceArray(len until buffer.size) return out } private fun tryReadLine(): String? { val index = buffer.indexOf('\n'.toByte()) if (index >= 0) { return readBuffer(index + 1).toString(UTF8) } else { return null } } private fun processBuffer() { main@while (true) { when (state) { State.HEADER -> { while (true) { val line = (tryReadLine() ?: return).trim() //println("HEADER: '$line'") val result = Regex("content-length:\\s*(\\d+)", RegexOption.IGNORE_CASE).find(line) if (result != null) { contentLength = result.groupValues[1].toInt() state = State.HEADER_SPACE continue@main } } } State.HEADER_SPACE -> { val line = tryReadLine() ?: return //println("EMPTY line($line)") state = State.BODY continue@main } State.BODY -> { if (buffer.size < contentLength) return val data = readBuffer(contentLength).toString(UTF8) if (data.length > 0) { if (DEBUG) println("RECV: $data") val message = JsonObject(data) for (handler in handlers.toList()) { EventLoop.queue { handler(message) } } } state = State.HEADER continue@main } } } } fun handle(handler: (message: JsonObject) -> Unit) { handlers += handler } fun handleEvent(handler: (message: JsonObject) -> Unit) { handlers += { message -> if (message.getString("type") == "event") { println("EVENT: " + message.encodePrettily()) handler(message) } } } fun write(data: ByteArray) { client.write(data) //println("SEND: ${data.toString(Charsets.UTF_8)}") } fun write(message: JsonObject) { val bodyString = message.encode() val body = bodyString.toByteArray(Charset.forName("UTF-8")) val head = "Content-Length: ${body.size}\r\n\r\n".toByteArray(Charset.forName("UTF-8")) if (DEBUG) println("SEND: $bodyString") write(head + body) } fun writeAndWaitAsync(message: JsonObject): Promise<JsonObject> { val deferred = Promise.Deferred<JsonObject>() val seq = message.getInteger("seq") var myhandler: ((obj: JsonObject) -> Unit)? = null myhandler = { message: JsonObject -> if (message.getInteger("request_seq") == seq) { handlers -= myhandler!! deferred.resolve(message) } } write(message) handlers += myhandler return deferred.promise } } //const val DEBUG = true const val DEBUG = false
jtransc-debugger/src/com/jtransc/debugger/v8/v8.kt
3817983091
package com.quran.mobile.feature.downloadmanager.ui import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Surface import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.quran.data.model.audio.Qari import com.quran.labs.androidquran.common.audio.model.QariItem import com.quran.labs.androidquran.common.ui.core.QuranTheme import com.quran.mobile.feature.downloadmanager.R import com.quran.mobile.feature.downloadmanager.model.DownloadedSheikhUiModel import com.quran.mobile.feature.downloadmanager.ui.common.DownloadCommonRow @OptIn(ExperimentalComposeUiApi::class) @Composable fun SheikhDownloadSummary( downloadedSheikhUiModel: DownloadedSheikhUiModel, onQariItemClicked: ((QariItem) -> Unit) ) { val (color, tintColor) = if (downloadedSheikhUiModel.downloadedSuras > 0) { Color(0xff5e8900) to MaterialTheme.colorScheme.onPrimary } else { MaterialTheme.colorScheme.tertiary to MaterialTheme.colorScheme.onTertiary } DownloadCommonRow( title = downloadedSheikhUiModel.qariItem.name, subtitle = pluralStringResource( R.plurals.audio_manager_files_downloaded, downloadedSheikhUiModel.downloadedSuras, downloadedSheikhUiModel.downloadedSuras ), onRowPressed = { onQariItemClicked(downloadedSheikhUiModel.qariItem) } ) { Image( painterResource(id = R.drawable.ic_download), contentDescription = "", colorFilter = ColorFilter.tint(tintColor), modifier = Modifier .align(Alignment.CenterVertically) .clip(CircleShape) .background(color) .padding(8.dp) ) } } @Preview @Preview("arabic", locale = "ar") @Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun SheikhDownloadSummaryPreview() { val qari = Qari( id = 1, nameResource = com.quran.labs.androidquran.common.audio.R.string.qari_minshawi_murattal_gapless, url = "https://download.quranicaudio.com/quran/muhammad_siddeeq_al-minshaawee/", path = "minshawi_murattal", hasGaplessAlternative = false, db = "minshawi_murattal" ) val downloadedSheikhModel = DownloadedSheikhUiModel( QariItem.fromQari(LocalContext.current, qari), downloadedSuras = 1 ) QuranTheme { Surface(color = MaterialTheme.colorScheme.surface) { SheikhDownloadSummary(downloadedSheikhUiModel = downloadedSheikhModel) { } } } }
feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/SheikhDownloadSummary.kt
2325576836
package motocitizen.utils import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import motocitizen.content.accident.Accident import motocitizen.dictionary.Medicine import java.util.* const val DEFAULT_ZOOM = 16f private const val DENSE = 1f private const val SEMI_DENSE = 0.5f private const val TRANSPARENT = 0.2f fun GoogleMap.accidentMarker(accident: Accident): Marker = addMarker(makeMarker(accident)) private fun calculateAlpha(accident: Accident): Float { val age = ((Date().time - accident.time.time) / MS_IN_HOUR).toInt() return when { age < 2 -> DENSE age < 6 -> SEMI_DENSE else -> TRANSPARENT } } private fun markerTitle(accident: Accident): String { val medicine = if (accident.medicine === Medicine.NO) "" else ", " + accident.medicine.text val interval = accident.time.getIntervalFromNowInText() return "${accident.type.text}$medicine, $interval назад" } private fun makeMarker(accident: Accident) = MarkerOptions() .position(accident.coordinates) .title(markerTitle(accident)) .icon(accident.type.icon) .alpha(calculateAlpha(accident))
Motocitizen/src/motocitizen/utils/MapUtils.kt
1005727559
package com.like.common.view.dragview.entity import android.os.Parcel import android.os.Parcelable /** * @param originLeft 原始imageview的left * @param originTop 原始imageview的top * @param originWidth 原始imageview的width * @param originHeight 原始imageview的height * @param thumbImageUrl 缩略图的url * @param imageUrl 原图url * @param videoUrl 视频url * @param isClicked 是否当前点击的那张图片 */ class DragInfo(val originLeft: Float, val originTop: Float, val originWidth: Float, val originHeight: Float, val thumbImageUrl: String = "", val imageUrl: String = "", val videoUrl: String = "", val isClicked: Boolean = false) : Parcelable { // 下面是根据原始尺寸计算出来的辅助尺寸 var originCenterX: Float = originLeft + originWidth / 2 var originCenterY: Float = originTop + originHeight / 2 constructor(parcel: Parcel) : this( parcel.readFloat(), parcel.readFloat(), parcel.readFloat(), parcel.readFloat(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readByte() != 0.toByte()) { originCenterX = parcel.readFloat() originCenterY = parcel.readFloat() } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeFloat(originLeft) parcel.writeFloat(originTop) parcel.writeFloat(originWidth) parcel.writeFloat(originHeight) parcel.writeString(thumbImageUrl) parcel.writeString(imageUrl) parcel.writeString(videoUrl) parcel.writeByte(if (isClicked) 1 else 0) parcel.writeFloat(originCenterX) parcel.writeFloat(originCenterY) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<DragInfo> { override fun createFromParcel(parcel: Parcel): DragInfo { return DragInfo(parcel) } override fun newArray(size: Int): Array<DragInfo?> { return arrayOfNulls(size) } } }
common/src/main/java/com/like/common/view/dragview/entity/DragInfo.kt
3679789416
package com.orgzly.android.db.dao import androidx.room.* import com.orgzly.android.db.entity.BookSync @Dao interface BookSyncDao : BaseDao<BookSync> { @Query("SELECT * FROM book_syncs WHERE book_id = :bookId") fun get(bookId: Long): BookSync? @Transaction fun upsert(bookId: Long, versionedRookId: Long) { val sync = get(bookId) if (sync == null) { insert(BookSync(bookId, versionedRookId)) } else { update(sync.copy(versionedRookId = versionedRookId)) } } }
app/src/main/java/com/orgzly/android/db/dao/BookSyncDao.kt
1347450207
/* * Copyright 2019 Ross 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.characters.bukkit.event.character import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.core.bukkit.event.RPKBukkitEvent import org.bukkit.event.Cancellable import org.bukkit.event.HandlerList class RPKBukkitCharacterDeleteEvent( override val character: RPKCharacter ): RPKBukkitEvent(), RPKCharacterDeleteEvent, Cancellable { companion object { @JvmStatic val handlerList = HandlerList() } private var cancel: Boolean = false override fun isCancelled(): Boolean { return cancel } override fun setCancelled(cancel: Boolean) { this.cancel = cancel } override fun getHandlers(): HandlerList { return handlerList } }
bukkit/rpk-character-lib-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/event/character/RPKBukkitCharacterDeleteEvent.kt
1774749344
package motocitizen.utils import android.location.Location import motocitizen.content.Content import motocitizen.content.accident.Accident import motocitizen.dictionary.Medicine typealias Id = Int fun Id.name() = Content.volunteerName(this) fun Accident.getAccidentTextToCopy(): String { val medicineText = if (medicine == Medicine.UNKNOWN) "" else medicine.text + ". " return "${time.dateTimeString()} ${owner.name()}: ${type.text}.$medicineText $address. $description." } val Accident.latitude inline get() = coordinates.latitude val Accident.longitude inline get() = coordinates.longitude fun Accident.distanceString(): String = coordinates.distanceString() fun Accident.distanceTo(location: Location) = coordinates.distanceTo(location)
Motocitizen/src/motocitizen/utils/AccidentUtils.kt
4263524281
package com.taylorsloan.jobseer.view.joblist.common import com.taylorsloan.jobseer.domain.job.models.Job import com.taylorsloan.jobseer.view.BasePresenter /** * Created by taylo on 10/29/2017. */ interface JobListContract { interface View { fun showJobs(jobs: List<Job>) fun showLoading() fun hideLoading() fun hideRefreshing() fun showJobDetail(job: Job) fun searchJobs(query: String, location: String, fullTime: Boolean) } interface Presenter : BasePresenter{ fun loadMore(page: Int) fun refresh() fun openJobDetail(job: Job) fun searchJobs(query: String, location: String, fullTime: Boolean) } }
app/src/main/java/com/taylorsloan/jobseer/view/joblist/common/JobListContract.kt
300602940
package org.evomaster.core.search.gene.sql import org.evomaster.core.search.gene.numeric.IntegerGene import org.evomaster.core.search.gene.datetime.DateGene import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class SqlMultiRangeGeneTest { @Test fun testEmptyMultirange() { val multirangeGene = SqlMultiRangeGene("multiint4rangegene", template = SqlRangeGene("int4range", template = IntegerGene("int4") )) assertEquals("\"{}\"", multirangeGene.getValueAsPrintableString()) } @Test fun testNonEmptyIntMultirange() { val multirangeGene = SqlMultiRangeGene("multiint4rangegene", template = SqlRangeGene("int4range", template = IntegerGene("int4") )) val rangeGene = multirangeGene.template.copy() as SqlRangeGene<IntegerGene> multirangeGene.rangeGenes.addElement(rangeGene) assertEquals("\"{[ 0 , 0 ]}\"", multirangeGene.getValueAsPrintableString()) } @Test fun testManyIntRangesMultirange() { val multirangeGene = SqlMultiRangeGene("multiint4rangegene", template = SqlRangeGene("int4range", template = IntegerGene("int4") )) val rangeGene0 = multirangeGene.template.copy() as SqlRangeGene<IntegerGene> multirangeGene.rangeGenes.addElement(rangeGene0) val rangeGene1 = multirangeGene.template.copy() as SqlRangeGene<IntegerGene> multirangeGene.rangeGenes.addElement(rangeGene1) assertEquals("\"{[ 0 , 0 ], [ 0 , 0 ]}\"", multirangeGene.getValueAsPrintableString()) } @Test fun testManyDateRangesMultirange() { val multirangeGene = SqlMultiRangeGene("multirange", template = SqlRangeGene("range", template = DateGene("date"))) val rangeGene0 = multirangeGene.template.copy() as SqlRangeGene<DateGene> multirangeGene.rangeGenes.addElement(rangeGene0) val rangeGene1 = multirangeGene.template.copy() as SqlRangeGene<DateGene> multirangeGene.rangeGenes.addElement(rangeGene1) assertEquals("\"{[ 2016-03-12 , 2016-03-12 ], [ 2016-03-12 , 2016-03-12 ]}\"", multirangeGene.getValueAsPrintableString()) } }
core/src/test/kotlin/org/evomaster/core/search/gene/sql/SqlMultiRangeGeneTest.kt
465358848
package com.github.badoualy.telegram.api.utils import com.github.badoualy.telegram.tl.api.* val TLAbsMessage?.date: Int get() = when (this) { is TLMessage -> date is TLMessageService -> date else -> 0 } val TLAbsMessage?.fromId: Int? get() = when (this) { is TLMessage -> fromId is TLMessageService -> fromId else -> null } fun TLAbsMessage?.getMessageOrEmpty() = when (this) { is TLMessage -> message!! else -> "" } val TLAbsMessage?.toId: TLAbsPeer? get() = when (this) { is TLMessage -> toId is TLMessageService -> toId else -> null } val TLAbsMessage.isReply: Boolean get() = this is TLMessage && replyToMsgId != null val TLAbsMessage.replyToMsgId: Int? get() = if (this is TLMessage) replyToMsgId else null val TLMessage.isForward: Boolean get() = fwdFrom != null val TLAbsMessage.isSticker: Boolean get() { if (this !is TLMessage) return false if (media == null || media !is TLMessageMediaDocument) return false val media = this.media as TLMessageMediaDocument if (media.document.isEmpty) return false return media.document.asDocument.attributes.any { it is TLDocumentAttributeSticker } } fun TLAbsMessage.getStickerAlt() = when (isSticker) { true -> ((this as? TLMessage)?.media as? TLMessageMediaDocument)?.document?.asDocument?.attributes ?.filterIsInstance<TLDocumentAttributeSticker>()?.first()?.alt false -> null } fun TLAbsMessage.getSticker(): TLDocument? = when (isSticker) { true -> ((this as? TLMessage)?.media as? TLMessageMediaDocument)?.document?.asDocument false -> null }
api/src/main/kotlin/com/github/badoualy/telegram/api/utils/TLMessageUtils.kt
2446705383
package org.kaqui.mainmenu import android.os.Bundle import android.view.Gravity import org.jetbrains.anko.* import org.kaqui.* import org.kaqui.model.TestType import org.kaqui.settings.ClassSelectionActivity import org.kaqui.settings.SelectionMode import java.io.Serializable class VocabularyMenuActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) verticalLayout { gravity = Gravity.CENTER scrollView { verticalLayout { padding = dip(8) appTitleImage(this@VocabularyMenuActivity).lparams(width = matchParent, height = dip(80)) { margin = dip(8) } verticalLayout { button(R.string.word_to_reading) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.WORD_TO_READING) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(4) } button(R.string.reading_to_word) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.READING_TO_WORD) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(4) } button(R.string.word_to_meaning) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.WORD_TO_MEANING) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(4) } button(R.string.meaning_to_word) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.MEANING_TO_WORD) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(4) } separator(this@VocabularyMenuActivity).lparams(height = dip(1)) { margin = dip(8) } button(R.string.word_selection) { setOnClickListener { startActivity<ClassSelectionActivity>("mode" to SelectionMode.WORD as Serializable) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(4) } } } }.lparams(width = menuWidth) } } }
app/src/main/java/org/kaqui/mainmenu/VocabularyMenuActivity.kt
1573167426
package me.proxer.library import me.proxer.library.ProxerException.ErrorType /** * Common Exception for all errors, occurring around the api. * * [errorType] returns the general type of error. This could for example be an [ErrorType.IO] error, * or invalid JSON data (leading to [ErrorType.PARSING]). If the type is [ErrorType.SERVER], * [serverErrorType] returns the type of server error. Moreover, message is set in that case. * * @author Ruben Gees */ class ProxerException : Exception { /** * Returns the error type of this exception. */ val errorType: ErrorType /** * Returns the server error type if, and only if, [errorType] returns [ErrorType.SERVER]. */ val serverErrorType: ServerErrorType? /** * Constructs an instance from the passed [error], [serverErrorType], [message] and [cause]. */ @JvmOverloads constructor( errorType: ErrorType, serverErrorType: ServerErrorType? = null, message: String? = null, cause: Exception? = null ) : super(message, cause) { this.errorType = errorType this.serverErrorType = serverErrorType } /** * Constructs an instance from the passed [error], [serverErrorCode] and [message]. * * If a invalid number is passed for the [serverErrorCode], an error is thrown. */ constructor(errorType: ErrorType, serverErrorCode: Int?, message: String?) : super(message) { this.errorType = errorType this.serverErrorType = ServerErrorType.fromErrorCode(serverErrorCode) } /** * Enum containing the available general error types. */ enum class ErrorType { SERVER, TIMEOUT, IO, PARSING, CANCELLED, UNKNOWN } /** * Enum containing the server error types. */ enum class ServerErrorType(val code: Int) { UNKNOWN_API(1000), API_REMOVED(1001), INVALID_API_CLASS(1002), INVALID_API_FUNCTION(1003), INSUFFICIENT_PERMISSIONS(1004), INVALID_TOKEN(1005), FUNCTION_BLOCKED(1006), SERVER_MAINTENANCE(1007), API_MAINTENANCE(1008), IP_BLOCKED(2000), NEWS(2001), LOGIN_MISSING_CREDENTIALS(3000), LOGIN_INVALID_CREDENTIALS(3001), NOTIFICATIONS_LOGIN_REQUIRED(3002), USERINFO_INVALID_ID(3003), UCP_LOGIN_REQUIRED(3004), UCP_INVALID_CATEGORY(3005), UCP_INVALID_ID(3006), INFO_INVALID_ID(3007), INFO_INVALID_TYPE(3008), INFO_LOGIN_REQUIRED(3009), INFO_ENTRY_ALREADY_IN_LIST(3010), INFO_EXCEEDED_MAXIMUM_ENTRIES(3011), LOGIN_ALREADY_LOGGED_IN(3012), LOGIN_DIFFERENT_USER_ALREADY_LOGGED_IN(3013), USER_INSUFFICIENT_PERMISSIONS(3014), LIST_INVALID_CATEGORY(3015), LIST_INVALID_MEDIUM(3016), MEDIA_INVALID_STYLE(3017), MEDIA_INVALID_ENTRY(3018), MANGA_INVALID_CHAPTER(3019), ANIME_INVALID_EPISODE(3020), ANIME_INVALID_STREAM(3021), UCP_INVALID_EPISODE(3022), MESSAGES_LOGIN_REQUIRED(3023), MESSAGES_INVALID_CONFERENCE(3024), MESSAGES_INVALID_REPORT_INPUT(3025), MESSAGES_INVALID_MESSAGE(3026), MESSAGES_INVALID_USER(3027), MESSAGES_EXCEEDED_MAXIMUM_USERS(3028), MESSAGES_INVALID_TOPIC(3029), MESSAGES_MISSING_USER(3030), CHAT_INVALID_ROOM(3031), CHAT_INVALID_PERMISSIONS(3032), CHAT_INVALID_MESSAGE(3033), CHAT_LOGIN_REQUIRED(3034), LIST_INVALID_LANGUAGE(3035), LIST_INVALID_TYPE(3036), LIST_INVALID_ID(3037), USER_2FA_SECRET_REQUIRED(3038), USER_ACCOUNT_EXPIRED(3039), USER_ACCOUNT_BLOCKED(3040), USER(3041), ERRORLOG_INVALID_INPUT(3042), LIST_INVALID_SUBJECT(3043), FORUM_INVALID_ID(3044), APPS_INVALID_ID(3045), LIST_TOP_ACCESS_RESET(3046), AUTH_INVALID_USER(3047), AUTH_INVALID_CODE(3048), AUTH_CODE_ALREADY_EXISTS(3049), AUTH_CODE_DOES_NOT_EXIST(3050), AUTH_CODE_REJECTED(3051), AUTH_CODE_PENDING(3052), AUTH_CODE_INVALID_NAME(3053), AUTH_CODE_DUPLICATE(3054), CHAT_SEVEN_DAY_PROTECTION(3055), CHAT_USER_ON_BLACKLIST(3056), CHAT_NO_PERMISSIONS(3057), CHAT_INVALID_THANK_YOU(3058), CHAT_INVALID_INPUT(3059), FORUM_INVALID_PERMISSIONS(3060), INFO_DELETE_COMMENT_INVALID_INPUT(3061), UCP_INVALID_SETTINGS(3062), ANIME_LOGIN_REQUIRED(3063), IP_AUTHENTICATION_REQUIRED(3064), MEDIA_NO_VAST_TAG(3065), LIST_NO_ENTRIES_LEFT(3066), COMMENT_LOGIN_REQUIRED(3067), COMMENT_INVALID_ID(3068), COMMENT_INVALID_COMMENT(3069), COMMENT_INSUFFICIENT_PERMISSIONS(3070), COMMENT_INVALID_RATING(3071), COMMENT_INVALID_EPISODE(3072), COMMENT_NOT_ACTIVE_YET(3073), COMMENT_INVALID_STATUS(3074), COMMENT_SAVE_ERROR(3075), COMMENT_INVALID_ENTRY_ID(3076), COMMENT_INVALID_CONTENT(3077), COMMENT_ALREADY_EXISTS(3078), UNKNOWN(10_000), RATE_LIMIT(99_998), INTERNAL(99_999); companion object { internal fun fromErrorCode(errorCode: Int?): ServerErrorType { return enumValues<ServerErrorType>().find { it.code == errorCode } ?: UNKNOWN } } internal val isLoginError get() = when (this) { INVALID_TOKEN, NOTIFICATIONS_LOGIN_REQUIRED, UCP_LOGIN_REQUIRED, INFO_LOGIN_REQUIRED, LOGIN_ALREADY_LOGGED_IN, LOGIN_DIFFERENT_USER_ALREADY_LOGGED_IN, MESSAGES_LOGIN_REQUIRED, CHAT_LOGIN_REQUIRED, USER_2FA_SECRET_REQUIRED, ANIME_LOGIN_REQUIRED, IP_AUTHENTICATION_REQUIRED, COMMENT_LOGIN_REQUIRED -> true else -> false } } }
library/src/main/kotlin/me/proxer/library/ProxerException.kt
1176464335
package me.wozappz.whatsthatflag.data.model import me.wozappz.whatsthatflag.screens.menu.CONTINENT /** * Created by olq on 11.01.18. */ interface Model { val totalFlagList: List<Pair<String, String>> val flagList: List<Pair<String, String>> fun loadTotalFlagList() fun selectFlags(gameData: Pair<CONTINENT, Int>) fun getButtonNames(flagId: Int): List<String> fun getURLFromName(countryName: String): String fun fetchFlags() }
app/src/main/java/me/wozappz/whatsthatflag/data/model/Model.kt
1355483292
package com.github.prologdb.runtime.module import com.github.prologdb.async.LazySequenceBuilder import com.github.prologdb.async.Principal import com.github.prologdb.runtime.* import com.github.prologdb.runtime.exception.PrologStackTraceElement import com.github.prologdb.runtime.proofsearch.AbstractProofSearchContext import com.github.prologdb.runtime.proofsearch.Authorization import com.github.prologdb.runtime.proofsearch.PrologCallable import com.github.prologdb.runtime.proofsearch.ProofSearchContext import com.github.prologdb.runtime.query.PredicateInvocationQuery import com.github.prologdb.runtime.term.Atom import com.github.prologdb.runtime.term.CompoundTerm import com.github.prologdb.runtime.term.Term import com.github.prologdb.runtime.unification.Unification import com.github.prologdb.runtime.unification.VariableBucket /** * All code declared inside a module only has access to predicates declared in the same module and * imported into that module explicitly **but not** to predicates visible in the scope where the * module is being imported into. This [ProofSearchContext] ensures that isolation: running code of * module within the proper [ModuleScopeProofSearchContext] achieves that behaviour. */ class ModuleScopeProofSearchContext( val module: Module, private val runtimeEnvironment: DefaultPrologRuntimeEnvironment, private val lookupTable: Map<ClauseIndicator, Pair<ModuleReference, PrologCallable>>, override val principal: Principal, override val randomVariableScope: RandomVariableScope, override val authorization: Authorization ) : ProofSearchContext, AbstractProofSearchContext() { override val operators = module.localOperators override suspend fun LazySequenceBuilder<Unification>.doInvokePredicate(query: PredicateInvocationQuery, variables: VariableBucket): Unification? { val (fqIndicator, callable, invocableGoal) = resolveHead(query.goal) if (!authorization.mayRead(fqIndicator)) throw PrologPermissionError("Not allowed to read/invoke $fqIndicator") return callable.fulfill(this, invocableGoal.arguments, this@ModuleScopeProofSearchContext) } override fun getStackTraceElementOf(query: PredicateInvocationQuery) = PrologStackTraceElement( query.goal, query.goal.sourceInformation.orElse(query.sourceInformation), module ) private fun findImport(indicator: ClauseIndicator): Pair<ModuleReference, PrologCallable>? = lookupTable[indicator] override fun resolveModuleScopedCallable(goal: Clause): Triple<FullyQualifiedClauseIndicator, PrologCallable, Array<out Term>>? { if (goal.functor != ":" || goal.arity != 2 || goal !is CompoundTerm) { return null } val moduleNameTerm = goal.arguments[0] val unscopedGoal = goal.arguments[1] if (moduleNameTerm !is Atom || unscopedGoal !is CompoundTerm) { return null } val simpleIndicator = ClauseIndicator.of(unscopedGoal) if (moduleNameTerm.name == this.module.declaration.moduleName) { val callable = module.allDeclaredPredicates[simpleIndicator] ?: throw PredicateNotDefinedException(simpleIndicator, module) val fqIndicator = FullyQualifiedClauseIndicator(this.module.declaration.moduleName, simpleIndicator) return Triple(fqIndicator, callable, unscopedGoal.arguments) } val module = runtimeEnvironment.getLoadedModule(moduleNameTerm.name) val callable = module.exportedPredicates[simpleIndicator] ?: if (simpleIndicator in module.allDeclaredPredicates) { throw PredicateNotExportedException(FullyQualifiedClauseIndicator(module.declaration.moduleName, simpleIndicator), this.module) } else { throw PredicateNotDefinedException(simpleIndicator, module) } return Triple( FullyQualifiedClauseIndicator(module.declaration.moduleName, simpleIndicator), callable, unscopedGoal.arguments ) } override fun resolveCallable(simpleIndicator: ClauseIndicator): Pair<FullyQualifiedClauseIndicator, PrologCallable> { module.allDeclaredPredicates[simpleIndicator]?.let { callable -> val fqIndicator = FullyQualifiedClauseIndicator(module.declaration.moduleName, simpleIndicator) return Pair(fqIndicator, callable) } findImport(simpleIndicator)?.let { (sourceModule, callable) -> val fqIndicator = FullyQualifiedClauseIndicator(sourceModule.moduleName, ClauseIndicator.of(callable)) return Pair(fqIndicator, callable) } throw PredicateNotDefinedException(simpleIndicator, module) } override fun deriveForModuleContext(moduleName: String): ProofSearchContext { return runtimeEnvironment.deriveProofSearchContextForModule(this, moduleName) } override fun toString() = "context of module ${module.declaration.moduleName}" }
core/src/main/kotlin/com/github/prologdb/runtime/module/ModuleScopeProofSearchContext.kt
3348101161
package org.profit.app.service interface StockService { fun execute() }
src/main/java/org/profit/app/service/StockService.kt
3011095606
package com.jukebot.jukebot.manager import com.pengrad.telegrambot.model.Message import com.pengrad.telegrambot.request.BaseRequest import com.pengrad.telegrambot.response.BaseResponse import java.util.concurrent.LinkedBlockingDeque /** * Created by Ting. */ object MessageManager { private var msgQ: LinkedBlockingDeque<Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>> = LinkedBlockingDeque() private var callback: () -> Unit = {} private var responseExpectedRequest = HashMap<Pair<Long, Int>, (Message) -> Unit>() fun iter(): MutableIterator<Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>> = msgQ.iterator() fun enqueue(msg: Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>) { msgQ.offer(msg) callback() } fun dequeue(): Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>? = msgQ.poll() fun onEnqueue(callback: () -> Unit) { this.callback = callback } fun ignoreEnqueue() { callback = {} } fun registerReplyCallback(chatId: Long, msgId: Int, callback: (Message) -> Unit) { responseExpectedRequest[Pair(chatId, msgId)] = callback } fun unregisterReplyCallback(chatId: Long, msgId: Int): ((Message) -> Unit)? = responseExpectedRequest.remove(Pair(chatId, msgId)) }
app/src/main/java/com/jukebot/jukebot/manager/MessageManager.kt
3935246222
package org.profit.app.analyse import org.profit.app.StockHall import org.profit.app.pojo.StockHistory import org.profit.util.DateUtils import org.profit.util.FileUtils import org.profit.util.StockUtils import java.lang.Exception /** * 【积】周期内,连续上涨天数较多 */ class StockUpAnalyzer(code: String, private val statCount: Int, private val upPercent: Double) : StockAnalyzer(code) { /** * 1.周期内总天数 * 2.周期内连续上涨最大天数 * 3.周内总上涨天数 */ override fun analyse(results: MutableList<String>) { // 获取数据,后期可以限制天数 val list = readHistories(statCount) // 如果没有数据 if (list.size < statCount) { return } val totalDay = list.size val riseDays = list.count { it.close > it.open } val risePercent = (list[0].close - list[statCount - 1].open).div(list[statCount - 1].open) * 100 if (riseDays > totalDay * upPercent) { val content = "$code${StockHall.stockName(code)} 一共$totalDay 天,累计一共上涨$riseDays 天,区间涨幅${StockUtils.twoDigits(risePercent)}% ,快速查看: http://stockpage.10jqka.com.cn/$code/" FileUtils.writeStat(content) } } }
src/main/java/org/profit/app/analyse/StockUpAnalyzer.kt
1073997981
package com.gdgchicagowest.windycitydevcon.features.speakerdetail import com.gdgchicagowest.windycitydevcon.features.shared.Mvp import com.gdgchicagowest.windycitydevcon.model.Speaker interface SpeakerDetailMvp { interface View : Mvp.View { fun showSpeaker(speaker: Speaker) } interface Presenter : Mvp.Presenter<View> { fun setSpeakerId(speakerId: String) } }
core/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/speakerdetail/SpeakerDetailMvp.kt
1095814722
package ch.romasch.gradle.yaml.config.nodes import org.yaml.snakeyaml.nodes.ScalarNode sealed class ConfigNode { class Assignment(val name: String, val value: ConfigNode) : ConfigNode() class ConfigGroup(val members: List<ConfigNode>) : ConfigNode() class ScalarConfigValue(val node: ScalarNode) : ConfigNode() class ListConfigValue(val nodes: List<ScalarConfigValue>) : ConfigNode() } abstract class ConfigVisitor { fun visit(config: ConfigNode):Unit = when(config) { is ConfigNode.Assignment -> visitAssignment(config) is ConfigNode.ConfigGroup -> visitConfigGroup(config) is ConfigNode.ScalarConfigValue -> visitScalarConfigValue(config) is ConfigNode.ListConfigValue -> visitListConfigValue(config) } open fun visitAssignment(assignment: ConfigNode.Assignment) = visit(assignment.value) open fun visitConfigGroup(group: ConfigNode.ConfigGroup) = group.members.forEach(this::visit) open fun visitScalarConfigValue(scalar: ConfigNode.ScalarConfigValue) = Unit open fun visitListConfigValue( list: ConfigNode.ListConfigValue) = list.nodes.forEach(this::visit) }
src/main/kotlin/ch/romasch/gradle/yaml/config/nodes/ConfigNode.kt
3207578826
/* * Copyright 2017 Alexey Shtanko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.shtanko.picasagallery.ui.album import android.os.Bundle import dagger.Lazy import io.shtanko.picasagallery.Config.ALBUM_ID_KEY import io.shtanko.picasagallery.Config.PHOTO_ID_KEY import io.shtanko.picasagallery.R import io.shtanko.picasagallery.ui.base.BaseActivity import javax.inject.Inject class InternalAlbumsActivity : BaseActivity() { // region injection @Inject lateinit var internalAlbumsPresenter: InternalAlbumsPresenter @Inject lateinit var internalAlbumsFragmentProvider: Lazy<InternalAlbumsFragment> // endregion override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.container_activity) val photoId = intent.getStringExtra(PHOTO_ID_KEY) val albumId = intent.getStringExtra(ALBUM_ID_KEY) val bundle = Bundle() bundle.putString(PHOTO_ID_KEY, photoId) bundle.putString(ALBUM_ID_KEY, albumId) internalAlbumsFragmentProvider.get() .arguments = bundle addFragment(R.id.content_frame, internalAlbumsFragmentProvider) } }
app/src/main/kotlin/io/shtanko/picasagallery/ui/album/InternalAlbumsActivity.kt
1207021032
/* * 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.samples.apps.sunflower.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.samples.apps.sunflower.data.GardenPlantingRepository import com.google.samples.apps.sunflower.data.PlantRepository import com.google.samples.apps.sunflower.plantdetail.PlantDetailFragment import kotlinx.coroutines.launch /** * The ViewModel used in [PlantDetailFragment]. */ class PlantDetailViewModel( plantRepository: PlantRepository, private val gardenPlantingRepository: GardenPlantingRepository, private val plantId: String ) : ViewModel() { val isPlanted = gardenPlantingRepository.isPlanted(plantId) val plant = plantRepository.getPlant(plantId) fun addPlantToGarden() { viewModelScope.launch { gardenPlantingRepository.createGardenPlanting(plantId) } } }
MigrationCodelab/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModel.kt
179429726
package tech.summerly.quiet.data.model.helper import okhttp3.Cookie import okhttp3.HttpUrl import org.jetbrains.anko.attempt import java.io.* import java.util.* /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/8/23 * desc : 用于持续保存Cookie */ abstract class CookieStore { abstract fun add(url: HttpUrl, cookie: Cookie) abstract fun get(url: HttpUrl): List<Cookie> abstract fun removeAll(): Boolean abstract fun remove(url: HttpUrl, cookie: Cookie): Boolean abstract fun getCookies(): List<Cookie> protected fun getCookieToken(cookie: Cookie): String { return cookie.name() + "@" + cookie.domain() } /** * cookies 序列化成 string * * @param cookie 要序列化的cookie * @return 序列化之后的string */ protected fun encodeCookie(cookie: SerializableOkHttpCookies): String { val os = ByteArrayOutputStream() try { val outputStream = ObjectOutputStream(os) outputStream.writeObject(cookie) } catch (e: IOException) { error("IOException in encodeCookie") } return byteArrayToHexString(os.toByteArray()) } /** * 将字符串反序列化成cookies * * @param cookieString cookies string * @return cookie object */ protected fun decodeCookie(cookieString: String): Cookie? { val cookie = attempt { val bytes = hexStringToByteArray(cookieString) val byteArrayInputStream = ByteArrayInputStream(bytes) val objectInputStream = ObjectInputStream(byteArrayInputStream) (objectInputStream.readObject() as SerializableOkHttpCookies).cookies } return cookie.value } /** * 二进制数组转十六进制字符串 * * @param bytes byte array to be converted * @return string containing hex values */ private fun byteArrayToHexString(bytes: ByteArray): String { val sb = StringBuilder(bytes.size * 2) for (element in bytes) { val v = element.toInt() and 0xff if (v < 16) { sb.append('0') } sb.append(Integer.toHexString(v)) } return sb.toString().toUpperCase(Locale.US) } /** * 十六进制字符串转二进制数组 * * @param hexString string of hex-encoded values * @return decoded byte array */ private fun hexStringToByteArray(hexString: String): ByteArray { val len = hexString.length val data = ByteArray(len / 2) var i = 0 while (i < len) { data[i / 2] = ((Character.digit(hexString[i], 16) shl 4) + Character.digit(hexString[i + 1], 16)).toByte() i += 2 } return data } }
app/src/main/java/tech/summerly/quiet/data/model/helper/CookieStore.kt
479599730
/* * Licensed under Apache-2.0 * * Designed and developed by Aidan Follestad (@afollestad) */ package com.afollestad.iconrequest import io.reactivex.Observable /** @author Aidan Follestad (afollestad) */ internal interface SendInteractor { fun send( selectedApps: List<AppModel>, request: ArcticRequest ): Observable<Boolean> }
library/src/main/java/com/afollestad/iconrequest/SendInteractor.kt
367680958
package com.bastien7.transport.analyzer.park.entityTFL import com.bastien7.transport.analyzer.park.entity.Park data class ParkTFL( val type: String = "", val geometry: GeometryTFL = GeometryTFL(), val properties: PropertiesTFL = PropertiesTFL() ) { fun toPark(): Park { val paymentMethods: PaymentMethodsTFL? = this.properties.meta?.payment_methods var paid: Boolean = false if (paymentMethods is PaymentMethodsTFL) { paid = paymentMethods.amex || paymentMethods.call2park || paymentMethods.cash || paymentMethods.eurocard || paymentMethods.mastercard || paymentMethods.visa || paymentMethods.vpay } return Park(id = this.properties.id, name = this.properties.name, availablePlaces = this.properties.free ?: 0, totalPlaces = this.properties.total ?: 0, trend = this.properties.trend, open = this.properties.meta?.open ?: false, paid = paid, address = this.properties.meta?.address?.street ?: "") } }
src/main/com/bastien7/transport/analyzer/park/entityTFL/ParkTFL.kt
1150175139
package com.bracketcove.postrainer.reminderlist import com.bracketcove.postrainer.BaseLogic import com.bracketcove.postrainer.ERROR_GENERIC import com.bracketcove.postrainer.REMINDER_CANCELLED import com.bracketcove.postrainer.REMINDER_SET import com.bracketcove.postrainer.dependencyinjection.AndroidReminderProvider import com.wiseassblog.common.ResultWrapper import com.wiseassblog.domain.domainmodel.Reminder import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext /** * Retrieves a List of any Reminders which are Present in ReminderDatabase (Realm Database), and * displays passes them to the View. * Created by Ryan on 05/03/2017. */ class ReminderListLogic( private val view: ReminderListContract.View, //Service Locator private val provider: AndroidReminderProvider, dispatcher: CoroutineDispatcher ) : BaseLogic<ReminderListEvent>(dispatcher) { //Note: these come from BaseLogic base abstract class override val coroutineContext: CoroutineContext get() = main + jobTracker override fun handleEvent(eventType: ReminderListEvent) { when (eventType) { is ReminderListEvent.OnStart -> getAlarmList() is ReminderListEvent.OnSettingsClick -> showSettings() is ReminderListEvent.OnMovementsClick -> showMovements() is ReminderListEvent.OnCreateButtonClick -> createAlarm() is ReminderListEvent.OnReminderToggled -> onToggle(eventType.isActive, eventType.reminder) is ReminderListEvent.OnReminderIconClick -> onIconClick(eventType.reminder) } } private fun showMovements() { view.startMovementsView() } private fun onIconClick(reminder: Reminder) = launch { if (reminder.isActive) provider.cancelReminder.execute(reminder) //since there isn't much I can do if this thing fails, not bothering //to check the result currently view.startReminderDetailView(reminder.reminderId!!) } private fun onToggle(active: Boolean, reminder: Reminder) { if (active) setAlarm(reminder) else cancelAlarm(reminder) } private fun cancelAlarm(reminder: Reminder) = launch { val result = provider.cancelReminder.execute(reminder) when (result) { is ResultWrapper.Success -> alarmCancelled() is ResultWrapper.Error -> handleError() } } private fun alarmCancelled() { view.showMessage(REMINDER_CANCELLED) } private fun setAlarm(reminder: Reminder) = launch { val result = provider.setReminder.execute(reminder) when (result) { is ResultWrapper.Success -> alarmSet() is ResultWrapper.Error -> handleError() } } private fun alarmSet() { view.showMessage(REMINDER_SET) } private fun createAlarm() { view.startReminderDetailView("") } private fun showSettings() { view.startSettingsActivity() } private fun getAlarmList() = launch { val result = provider.getReminderList.execute() when (result){ is ResultWrapper.Success -> updateView(result.value) is ResultWrapper.Error -> { view.setNoReminderListDataFound() handleError() } } } private fun handleError() { view.showMessage(ERROR_GENERIC) } private fun updateView(value: List<Reminder>) { if (value.size == 0) view.setNoReminderListDataFound() else view.setReminderListData(value) } }
app/src/main/java/com/bracketcove/postrainer/reminderlist/ReminderListLogic.kt
4189557869
package siosio.jsr352.jsl import kotlin.reflect.* data class Item<T : Any>( private val itemName: String, private val itemClass: KClass<T> ) : Properties { override val properties: MutableList<Property> = mutableListOf() fun buildItem(): String { val xml = StringBuilder() xml.append("<$itemName ref='${beanName(itemClass)}'>") xml.append(buildProperties()) xml.append("</$itemName>") return xml.toString() } }
src/main/kotlin/siosio/jsr352/jsl/Item.kt
391918032
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2018 Benoit 'BoD' Lubek ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jraf.android.ticker.util.location import android.location.Location import com.beust.klaxon.JsonObject import com.beust.klaxon.Parser import org.slf4j.LoggerFactory import java.net.HttpURLConnection import java.net.URL internal class IpApiClient { companion object { private var LOGGER = LoggerFactory.getLogger(IpApiClient::class.java) private const val URL_API = "http://ip-api.com/json" } private var _currentLocation: Location? = null val currentLocation: Location? get() { if (_currentLocation != null) return _currentLocation _currentLocation = try { callIpApi() } catch (e: Throwable) { LOGGER.warn("Could not call api", e) null } return _currentLocation } private fun callIpApi(): Location { val connection = URL(URL_API).openConnection() as HttpURLConnection return try { val jsonStr = connection.inputStream.bufferedReader().readText() val rootJson: JsonObject = Parser().parse(StringBuilder(jsonStr)) as JsonObject Location("").apply { latitude = rootJson.float("lat")!!.toDouble() longitude = rootJson.float("lon")!!.toDouble() } } finally { connection.disconnect() } } }
app/src/main/kotlin/org/jraf/android/ticker/util/location/IpApiClient.kt
2800821254
package com.etesync.syncadapter.ui import android.accounts.Account import android.content.Context import android.content.Intent import android.os.Bundle import android.provider.CalendarContract import android.provider.ContactsContract import android.text.format.DateFormat import android.text.format.DateUtils import android.view.* import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import at.bitfire.ical4android.Event import at.bitfire.ical4android.InvalidCalendarException import at.bitfire.ical4android.Task import at.bitfire.ical4android.TaskProvider import at.bitfire.vcard4android.Contact import com.etesync.syncadapter.App import com.etesync.syncadapter.Constants import com.etesync.syncadapter.R import com.etesync.syncadapter.model.CollectionInfo import com.etesync.syncadapter.model.JournalEntity import com.etesync.journalmanager.model.SyncEntry import com.etesync.syncadapter.resource.* import com.etesync.syncadapter.ui.journalviewer.ListEntriesFragment.Companion.setJournalEntryView import com.etesync.syncadapter.utils.EventEmailInvitation import com.etesync.syncadapter.utils.TaskProviderHandling import com.google.android.material.tabs.TabLayout import ezvcard.util.PartialDate import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import java.io.IOException import java.io.StringReader import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.Future class JournalItemActivity : BaseActivity(), Refreshable { private var journalEntity: JournalEntity? = null private lateinit var account: Account protected lateinit var info: CollectionInfo private lateinit var syncEntry: SyncEntry private var emailInvitationEvent: Event? = null private var emailInvitationEventString: String? = null override fun refresh() { val data = (applicationContext as App).data journalEntity = JournalEntity.fetch(data, info.getServiceEntity(data), info.uid) if (journalEntity == null || journalEntity!!.isDeleted) { finish() return } account = intent.extras!!.getParcelable(ViewCollectionActivity.EXTRA_ACCOUNT)!! info = journalEntity!!.info title = info.displayName setJournalEntryView(findViewById(R.id.journal_list_item), info, syncEntry) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.journal_item_activity) supportActionBar!!.setDisplayHomeAsUpEnabled(true) info = intent.extras!!.getSerializable(Constants.KEY_COLLECTION_INFO) as CollectionInfo syncEntry = intent.extras!!.getSerializable(KEY_SYNC_ENTRY) as SyncEntry refresh() val viewPager = findViewById<View>(R.id.viewpager) as ViewPager viewPager.adapter = TabsAdapter(supportFragmentManager, this, info, syncEntry) val tabLayout = findViewById<View>(R.id.tabs) as TabLayout tabLayout.setupWithViewPager(viewPager) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_journal_item, menu) menu.setGroupVisible(R.id.journal_item_menu_event_invite, emailInvitationEvent != null) return true } fun allowSendEmail(event: Event?, icsContent: String) { emailInvitationEvent = event emailInvitationEventString = icsContent invalidateOptionsMenu() } fun sendEventInvite(item: MenuItem) { val intent = EventEmailInvitation(this, account).createIntent(emailInvitationEvent!!, emailInvitationEventString!!) startActivity(intent) } fun restoreItem(item: MenuItem) { // FIXME: This code makes the assumption that providers are all available. May not be true for tasks, and potentially others too. when (info.enumType) { CollectionInfo.Type.CALENDAR -> { val provider = contentResolver.acquireContentProviderClient(CalendarContract.CONTENT_URI)!! val localCalendar = LocalCalendar.findByName(account, provider, LocalCalendar.Factory, info.uid!!)!! val event = Event.eventsFromReader(StringReader(syncEntry.content))[0] var localEvent = localCalendar.findByUid(event.uid!!) if (localEvent != null) { localEvent.updateAsDirty(event) } else { localEvent = LocalEvent(localCalendar, event, event.uid, null) localEvent.addAsDirty() } } CollectionInfo.Type.TASKS -> { TaskProviderHandling.getWantedTaskSyncProvider(applicationContext)?.let { val provider = TaskProvider.acquire(this, it)!! val localTaskList = LocalTaskList.findByName(account, provider, LocalTaskList.Factory, info.uid!!)!! val task = Task.tasksFromReader(StringReader(syncEntry.content))[0] var localTask = localTaskList.findByUid(task.uid!!) if (localTask != null) { localTask.updateAsDirty(task) } else { localTask = LocalTask(localTaskList, task, task.uid, null) localTask.addAsDirty() } } } CollectionInfo.Type.ADDRESS_BOOK -> { val provider = contentResolver.acquireContentProviderClient(ContactsContract.RawContacts.CONTENT_URI)!! val localAddressBook = LocalAddressBook.findByUid(this, provider, account, info.uid!!)!! val contact = Contact.fromReader(StringReader(syncEntry.content), null)[0] if (contact.group) { // FIXME: not currently supported } else { var localContact = localAddressBook.findByUid(contact.uid!!) as LocalContact? if (localContact != null) { localContact.updateAsDirty(contact) } else { localContact = LocalContact(localAddressBook, contact, contact.uid, null) localContact.createAsDirty() } } } } val dialog = AlertDialog.Builder(this) .setTitle(R.string.journal_item_restore_action) .setIcon(R.drawable.ic_restore_black) .setMessage(R.string.journal_item_restore_dialog_body) .setPositiveButton(android.R.string.ok) { dialog, which -> // dismiss } .create() dialog.show() } private class TabsAdapter(fm: FragmentManager, private val context: Context, private val info: CollectionInfo, private val syncEntry: SyncEntry) : FragmentPagerAdapter(fm) { override fun getCount(): Int { // FIXME: Make it depend on info enumType (only have non-raw for known types) return 2 } override fun getPageTitle(position: Int): CharSequence? { return if (position == 0) { context.getString(R.string.journal_item_tab_main) } else { context.getString(R.string.journal_item_tab_raw) } } override fun getItem(position: Int): Fragment { return if (position == 0) { PrettyFragment.newInstance(info, syncEntry) } else { TextFragment.newInstance(syncEntry) } } } class TextFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.text_fragment, container, false) val tv = v.findViewById<View>(R.id.content) as TextView val syncEntry = arguments!!.getSerializable(KEY_SYNC_ENTRY) as SyncEntry tv.text = syncEntry.content return v } companion object { fun newInstance(syncEntry: SyncEntry): TextFragment { val frag = TextFragment() val args = Bundle(1) args.putSerializable(KEY_SYNC_ENTRY, syncEntry) frag.arguments = args return frag } } } class PrettyFragment : Fragment() { internal lateinit var info: CollectionInfo internal lateinit var syncEntry: SyncEntry private var asyncTask: Future<Unit>? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { var v: View? = null info = arguments!!.getSerializable(Constants.KEY_COLLECTION_INFO) as CollectionInfo syncEntry = arguments!!.getSerializable(KEY_SYNC_ENTRY) as SyncEntry when (info.enumType) { CollectionInfo.Type.ADDRESS_BOOK -> { v = inflater.inflate(R.layout.contact_info, container, false) asyncTask = loadContactTask(v) } CollectionInfo.Type.CALENDAR -> { v = inflater.inflate(R.layout.event_info, container, false) asyncTask = loadEventTask(v) } CollectionInfo.Type.TASKS -> { v = inflater.inflate(R.layout.task_info, container, false) asyncTask = loadTaskTask(v) } } return v } override fun onDestroyView() { super.onDestroyView() if (asyncTask != null) asyncTask!!.cancel(true) } private fun loadEventTask(view: View): Future<Unit> { return doAsync { var event: Event? = null val inputReader = StringReader(syncEntry.content) try { event = Event.eventsFromReader(inputReader, null)[0] } catch (e: InvalidCalendarException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } if (event != null) { uiThread { val loader = view.findViewById<View>(R.id.event_info_loading_msg) loader.visibility = View.GONE val contentContainer = view.findViewById<View>(R.id.event_info_scroll_view) contentContainer.visibility = View.VISIBLE setTextViewText(view, R.id.title, event.summary) val dtStart = event.dtStart?.date?.time val dtEnd = event.dtEnd?.date?.time if ((dtStart == null) || (dtEnd == null)) { setTextViewText(view, R.id.when_datetime, getString(R.string.loading_error_title)) } else { setTextViewText(view, R.id.when_datetime, getDisplayedDatetime(dtStart, dtEnd, event.isAllDay(), context)) } setTextViewText(view, R.id.where, event.location) val organizer = event.organizer if (organizer != null) { val tv = view.findViewById<View>(R.id.organizer) as TextView tv.text = organizer.calAddress.toString().replaceFirst("mailto:".toRegex(), "") } else { val organizerView = view.findViewById<View>(R.id.organizer_container) organizerView.visibility = View.GONE } setTextViewText(view, R.id.description, event.description) var first = true var sb = StringBuilder() for (attendee in event.attendees) { if (first) { first = false sb.append(getString(R.string.journal_item_attendees)).append(": ") } else { sb.append(", ") } sb.append(attendee.calAddress.toString().replaceFirst("mailto:".toRegex(), "")) } setTextViewText(view, R.id.attendees, sb.toString()) first = true sb = StringBuilder() for (alarm in event.alarms) { if (first) { first = false sb.append(getString(R.string.journal_item_reminders)).append(": ") } else { sb.append(", ") } sb.append(alarm.trigger.value) } setTextViewText(view, R.id.reminders, sb.toString()) if (event.attendees.isNotEmpty() && activity != null) { (activity as JournalItemActivity).allowSendEmail(event, syncEntry.content) } } } } } private fun loadTaskTask(view: View): Future<Unit> { return doAsync { var task: Task? = null val inputReader = StringReader(syncEntry.content) try { task = Task.tasksFromReader(inputReader)[0] } catch (e: InvalidCalendarException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } if (task != null) { uiThread { val loader = view.findViewById<View>(R.id.task_info_loading_msg) loader.visibility = View.GONE val contentContainer = view.findViewById<View>(R.id.task_info_scroll_view) contentContainer.visibility = View.VISIBLE setTextViewText(view, R.id.title, task.summary) setTextViewText(view, R.id.where, task.location) val organizer = task.organizer if (organizer != null) { val tv = view.findViewById<View>(R.id.organizer) as TextView tv.text = organizer.calAddress.toString().replaceFirst("mailto:".toRegex(), "") } else { val organizerView = view.findViewById<View>(R.id.organizer_container) organizerView.visibility = View.GONE } setTextViewText(view, R.id.description, task.description) } } } } private fun loadContactTask(view: View): Future<Unit> { return doAsync { var contact: Contact? = null val reader = StringReader(syncEntry.content) try { contact = Contact.fromReader(reader, null)[0] } catch (e: IOException) { e.printStackTrace() } if (contact != null) { uiThread { val loader = view.findViewById<View>(R.id.loading_msg) loader.visibility = View.GONE val contentContainer = view.findViewById<View>(R.id.content_container) contentContainer.visibility = View.VISIBLE val tv = view.findViewById<View>(R.id.display_name) as TextView tv.text = contact.displayName if (contact.group) { showGroup(contact) } else { showContact(contact) } } } } } private fun showGroup(contact: Contact) { val view = this.view!! val mainCard = view.findViewById<View>(R.id.main_card) as ViewGroup addInfoItem(view.context, mainCard, getString(R.string.journal_item_member_count), null, contact.members.size.toString()) for (member in contact.members) { addInfoItem(view.context, mainCard, getString(R.string.journal_item_member), null, member) } } private fun showContact(contact: Contact) { val view = this.view!! val mainCard = view.findViewById<View>(R.id.main_card) as ViewGroup val aboutCard = view.findViewById<View>(R.id.about_card) as ViewGroup aboutCard.findViewById<View>(R.id.title_container).visibility = View.VISIBLE // TEL for (labeledPhone in contact.phoneNumbers) { val types = labeledPhone.property.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, mainCard, getString(R.string.journal_item_phone), type, labeledPhone.property.text) } // EMAIL for (labeledEmail in contact.emails) { val types = labeledEmail.property.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, mainCard, getString(R.string.journal_item_email), type, labeledEmail.property.value) } // ORG, TITLE, ROLE if (contact.organization != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_organization), contact.jobTitle, contact.organization?.values!![0]) } if (contact.jobDescription != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_job_description), null, contact.jobTitle) } // IMPP for (labeledImpp in contact.impps) { addInfoItem(view.context, mainCard, getString(R.string.journal_item_impp), labeledImpp.property.protocol, labeledImpp.property.handle) } // NICKNAME if (contact.nickName != null && !contact.nickName?.values?.isEmpty()!!) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_nickname), null, contact.nickName?.values!![0]) } // ADR for (labeledAddress in contact.addresses) { val types = labeledAddress.property.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, mainCard, getString(R.string.journal_item_address), type, labeledAddress.property.label) } // NOTE if (contact.note != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_note), null, contact.note) } // URL for (labeledUrl in contact.urls) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_website), null, labeledUrl.property.value) } // ANNIVERSARY if (contact.anniversary != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_anniversary), null, getDisplayedDate(contact.anniversary?.date, contact.anniversary?.partialDate)) } // BDAY if (contact.birthDay != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_birthday), null, getDisplayedDate(contact.birthDay?.date, contact.birthDay?.partialDate)) } // RELATED for (related in contact.relations) { val types = related.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, aboutCard, getString(R.string.journal_item_relation), type, related.text) } // PHOTO // if (contact.photo != null) } private fun getDisplayedDate(date: Date?, partialDate: PartialDate?): String? { if (date != null) { val epochDate = date.time return getDisplayedDatetime(epochDate, epochDate, true, context) } else if (partialDate != null){ val formatter = SimpleDateFormat("d MMMM", Locale.getDefault()) val calendar = GregorianCalendar() calendar.set(Calendar.DAY_OF_MONTH, partialDate.date!!) calendar.set(Calendar.MONTH, partialDate.month!! - 1) return formatter.format(calendar.time) } return null } companion object { fun newInstance(info: CollectionInfo, syncEntry: SyncEntry): PrettyFragment { val frag = PrettyFragment() val args = Bundle(1) args.putSerializable(Constants.KEY_COLLECTION_INFO, info) args.putSerializable(KEY_SYNC_ENTRY, syncEntry) frag.arguments = args return frag } private fun addInfoItem(context: Context, parent: ViewGroup, type: String, label: String?, value: String?): View { val layout = parent.findViewById<View>(R.id.container) as ViewGroup val infoItem = LayoutInflater.from(context).inflate(R.layout.contact_info_item, layout, false) layout.addView(infoItem) setTextViewText(infoItem, R.id.type, type) setTextViewText(infoItem, R.id.title, label) setTextViewText(infoItem, R.id.content, value) parent.visibility = View.VISIBLE return infoItem } private fun setTextViewText(parent: View, id: Int, text: String?) { val tv = parent.findViewById<View>(id) as TextView if (text == null) { tv.visibility = View.GONE } else { tv.text = text } } fun getDisplayedDatetime(startMillis: Long, endMillis: Long, allDay: Boolean, context: Context?): String? { // Configure date/time formatting. val flagsDate = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY var flagsTime = DateUtils.FORMAT_SHOW_TIME if (DateFormat.is24HourFormat(context)) { flagsTime = flagsTime or DateUtils.FORMAT_24HOUR } val datetimeString: String if (allDay) { // For multi-day allday events or single-day all-day events that are not // today or tomorrow, use framework formatter. // We need to remove 24hrs because full day events are from the start of a day until the start of the next var adjustedEnd = endMillis - 24 * 60 * 60 * 1000; if (adjustedEnd < startMillis) { adjustedEnd = startMillis; } val f = Formatter(StringBuilder(50), Locale.getDefault()) datetimeString = DateUtils.formatDateRange(context, f, startMillis, adjustedEnd, flagsDate).toString() } else { // For multiday events, shorten day/month names. // Example format: "Fri Apr 6, 5:00pm - Sun, Apr 8, 6:00pm" val flagsDatetime = flagsDate or flagsTime or DateUtils.FORMAT_ABBREV_MONTH or DateUtils.FORMAT_ABBREV_WEEKDAY datetimeString = DateUtils.formatDateRange(context, startMillis, endMillis, flagsDatetime) } return datetimeString } } } override fun onResume() { super.onResume() refresh() } companion object { private val KEY_SYNC_ENTRY = "syncEntry" fun newIntent(context: Context, account: Account, info: CollectionInfo, syncEntry: SyncEntry): Intent { val intent = Intent(context, JournalItemActivity::class.java) intent.putExtra(ViewCollectionActivity.EXTRA_ACCOUNT, account) intent.putExtra(Constants.KEY_COLLECTION_INFO, info) intent.putExtra(KEY_SYNC_ENTRY, syncEntry) return intent } } }
app/src/main/java/com/etesync/syncadapter/ui/JournalItemActivity.kt
2287857323
package de.maibornwolff.codecharta.parser.rawtextparser.metrics import de.maibornwolff.codecharta.parser.rawtextparser.model.FileMetrics import de.maibornwolff.codecharta.parser.rawtextparser.model.toBool import java.io.PrintStream import java.lang.Integer.min class IndentationCounter( private var maxIndentation: Int = 6, private var stderr: PrintStream = System.err, private var verbose: Boolean = false, private var tabWidth: Int = 0 ) : Metric { private val spaceIndentations = MutableList(maxIndentation * 8 + 1) { 0 } private val tabIndentations = MutableList(maxIndentation + 1) { 0 } override val name = "IndentationLevel" override val description = "Number of lines with an indentation level of at least x" // TODO no mixed tab/ space possible at line start? override fun parseLine(line: String) { var tabIndent = line.length - line.trimStart('\t').length var spaceIndent = line.length - line.trimStart(' ').length if (spaceIndent == line.length || tabIndent == line.length) return if (spaceIndent > 0) { spaceIndent = min(spaceIndent, 8 * maxIndentation) spaceIndentations[spaceIndent] = spaceIndentations[spaceIndent] + 1 } else { tabIndent = min(tabIndent, maxIndentation) tabIndentations[tabIndent] = tabIndentations[tabIndent] + 1 } } override fun setParameters(parameters: Map<String, Int>) { maxIndentation = parameters["maxIndentationLevel"] ?: maxIndentation tabWidth = parameters["tabWidth"] ?: tabWidth verbose = parameters["verbose"]?.toBool() ?: verbose } // TODO tabSize - (offset % tabSize) from the current position private fun guessTabWidth(): Int { tabWidth = 1 if (spaceIndentations.sum() == 0) return tabWidth val candidates = 2..8 candidates.forEach { candidate -> var mismatches = 0 for (i in spaceIndentations.indices) { if (i % candidate != 0) { mismatches += spaceIndentations[i] } } if (mismatches == 0) { tabWidth = candidate } } if (verbose) stderr.println("INFO: Assumed tab width to be $tabWidth") return tabWidth } private fun correctMismatchingIndents(tabWidth: Int) { for (i in spaceIndentations.indices) { if (i % tabWidth != 0 && spaceIndentations[i] > 0) { val nextLevel: Int = i / tabWidth + 1 spaceIndentations[nextLevel * tabWidth] = spaceIndentations[nextLevel * tabWidth] + spaceIndentations[i] stderr.println("WARN: Corrected mismatching indentations, moved ${spaceIndentations[i]} lines to indentation level $nextLevel+") spaceIndentations[i] = 0 } } } override fun getValue(): FileMetrics { if (tabWidth == 0) { guessTabWidth() } correctMismatchingIndents(tabWidth) val fileMetrics = FileMetrics() for (i in 0..maxIndentation) { val tabVal = tabIndentations.subList(i, tabIndentations.size).sum() val spaceVal = spaceIndentations.subList(i * tabWidth, spaceIndentations.size).sum() val name = "indentation_level_$i+" fileMetrics.addMetric(name, tabVal + spaceVal) } return fileMetrics } }
analysis/parser/RawTextParser/src/main/kotlin/de/maibornwolff/codecharta/parser/rawtextparser/metrics/IndentationCounter.kt
4099715152
package com.darakeon.dfm.extract import com.darakeon.dfm.R import com.darakeon.dfm.lib.api.entities.extract.Move import com.darakeon.dfm.lib.ui.Adapter class MoveAdapter( activity: ExtractActivity, list: List<Move>, private val canCheck: Boolean, private val edit: (MoveLine) -> Unit, private val delete: (MoveLine) -> Unit, private val check: (MoveLine) -> Unit, private val uncheck: (MoveLine) -> Unit, ) : Adapter<ExtractActivity, Move, MoveLine>(activity, list) { override val lineLayoutId: Int get() = R.layout.move_line override fun populateView(view: MoveLine, position: Int) = view.setMove(list[position], canCheck, edit, delete, check, uncheck) }
android/App/src/main/kotlin/com/darakeon/dfm/extract/MoveAdapter.kt
25523472
package so.lai.example.firstapp import android.support.v7.app.AppCompatActivity class DisplayMessageActivity: AppCompatActivity() { }
FirstApp/app/src/main/java/so/lai/example/firstapp/DisplayMessageActivity.kt
1925276165
package org.rocfish.domain import org.rocfish.IDSpecs import java.net.URL /** * 所有业务模型都属于一个租户,租户分配Licence */ interface Tenant:IDSpecs { fun getBusiness(name:String):AbstractBusiness /** * 创建指定名称的业务对象 */ fun createBusiness(name:String):AbstractBusiness fun business():List<AbstractBusiness> /** * 创建租户的licence授权,租户根据licence决定创建账号的数目/业务数目以及可使用的资源等 */ fun createLicence() /** * 创建租户下的默认账号,并指定账号名称以及登陆标识域,例如:邮箱登陆/手机号登陆等 */ fun createAccount(name:String, vararg loginField: Pair<String, String>):Account /** * 租户可以设定回调域名,所有系统事件钩子都将通过此domain地址,并添加特定参数执行回调 */ var domain:URL /** * 租户第三方应用可以通过access token与租户的所有业务进行交互 */ fun getAccessToken():String }
src/main/kotlin/org/rocfish/domain/Tenant.kt
1899156751
package com.ghstudios.android.data.cursors import android.content.Context import android.database.Cursor import android.database.CursorWrapper import com.ghstudios.android.data.classes.* import com.ghstudios.android.data.DataManager import com.ghstudios.android.data.database.S import com.ghstudios.android.data.util.getInt import com.ghstudios.android.data.util.getLong import com.ghstudios.android.data.util.getString import com.ghstudios.android.mhgendatabase.* import kotlin.math.min class ASBSessionCursor(c: Cursor) : CursorWrapper(c) { fun getASBSession(context: Context): ASBSession? { if (isBeforeFirst || isAfterLast) { return null } val session = ASBSession( id = getLong(S.COLUMN_ASB_SET_ID), name = getString(S.COLUMN_ASB_SET_NAME, ""), rank = Rank.from(getInt(S.COLUMN_ASB_SET_RANK)), hunterType = getInt(S.COLUMN_ASB_SET_HUNTER_TYPE) ) val weaponSlots = getInt(S.COLUMN_ASB_WEAPON_SLOTS) val weaponDecoration1 = getDecorationById(getLong(S.COLUMN_ASB_WEAPON_DECORATION_1_ID)) val weaponDecoration2 = getDecorationById(getLong(S.COLUMN_ASB_WEAPON_DECORATION_2_ID)) val weaponDecoration3 = getDecorationById(getLong(S.COLUMN_ASB_WEAPON_DECORATION_3_ID)) val headId = getLong(S.COLUMN_HEAD_ARMOR_ID) val headArmor = getArmorById(headId) val headDecoration1Id = getLong(S.COLUMN_HEAD_DECORATION_1_ID) val headDecoration2Id = getLong(S.COLUMN_HEAD_DECORATION_2_ID) val headDecoration3Id = getLong(S.COLUMN_HEAD_DECORATION_3_ID) val headDecoration1 = getDecorationById(headDecoration1Id) val headDecoration2 = getDecorationById(headDecoration2Id) val headDecoration3 = getDecorationById(headDecoration3Id) val bodyId = getLong(S.COLUMN_BODY_ARMOR_ID) val bodyArmor = getArmorById(bodyId) val bodyDecoration1Id = getLong(S.COLUMN_BODY_DECORATION_1_ID) val bodyDecoration2Id = getLong(S.COLUMN_BODY_DECORATION_2_ID) val bodyDecoration3Id = getLong(S.COLUMN_BODY_DECORATION_3_ID) val bodyDecoration1 = getDecorationById(bodyDecoration1Id) val bodyDecoration2 = getDecorationById(bodyDecoration2Id) val bodyDecoration3 = getDecorationById(bodyDecoration3Id) val armsId = getLong(S.COLUMN_ARMS_ARMOR_ID) val armsArmor = getArmorById(armsId) val armsDecoration1Id = getLong(S.COLUMN_ARMS_DECORATION_1_ID) val armsDecoration2Id = getLong(S.COLUMN_ARMS_DECORATION_2_ID) val armsDecoration3Id = getLong(S.COLUMN_ARMS_DECORATION_3_ID) val armsDecoration1 = getDecorationById(armsDecoration1Id) val armsDecoration2 = getDecorationById(armsDecoration2Id) val armsDecoration3 = getDecorationById(armsDecoration3Id) val waistId = getLong(S.COLUMN_WAIST_ARMOR_ID) val waistArmor = getArmorById(waistId) val waistDecoration1Id = getLong(S.COLUMN_WAIST_DECORATION_1_ID) val waistDecoration2Id = getLong(S.COLUMN_WAIST_DECORATION_2_ID) val waistDecoration3Id = getLong(S.COLUMN_WAIST_DECORATION_3_ID) val waistDecoration1 = getDecorationById(waistDecoration1Id) val waistDecoration2 = getDecorationById(waistDecoration2Id) val waistDecoration3 = getDecorationById(waistDecoration3Id) val legsId = getLong(S.COLUMN_LEGS_ARMOR_ID) val legsArmor = getArmorById(legsId) val legsDecoration1Id = getLong(S.COLUMN_LEGS_DECORATION_1_ID) val legsDecoration2Id = getLong(S.COLUMN_LEGS_DECORATION_2_ID) val legsDecoration3Id = getLong(S.COLUMN_LEGS_DECORATION_3_ID) val legsDecoration1 = getDecorationById(legsDecoration1Id) val legsDecoration2 = getDecorationById(legsDecoration2Id) val legsDecoration3 = getDecorationById(legsDecoration3Id) val talismanExists = getInt(S.COLUMN_TALISMAN_EXISTS) val talismanSkill1Id = getLong(S.COLUMN_TALISMAN_SKILL_1_ID) val talismanSkill1Points = getInt(S.COLUMN_TALISMAN_SKILL_1_POINTS) val talismanSkill2Id = getLong(S.COLUMN_TALISMAN_SKILL_2_ID) val talismanSkill2Points = getInt(S.COLUMN_TALISMAN_SKILL_2_POINTS) var talismanType = getInt(S.COLUMN_TALISMAN_TYPE) val talismanSlots = getInt(S.COLUMN_TALISMAN_SLOTS) val talismanDecoration1Id = getLong(S.COLUMN_TALISMAN_DECORATION_1_ID) val talismanDecoration2Id = getLong(S.COLUMN_TALISMAN_DECORATION_2_ID) val talismanDecoration3Id = getLong(S.COLUMN_TALISMAN_DECORATION_3_ID) val talismanDecoration1 = getDecorationById(talismanDecoration1Id) val talismanDecoration2 = getDecorationById(talismanDecoration2Id) val talismanDecoration3 = getDecorationById(talismanDecoration3Id) // Set armor pieces session.numWeaponSlots = weaponSlots headArmor?.let { session.setEquipment(ArmorSet.HEAD, it) } bodyArmor?.let { session.setEquipment(ArmorSet.BODY, it) } armsArmor?.let { session.setEquipment(ArmorSet.ARMS, it) } waistArmor?.let { session.setEquipment(ArmorSet.WAIST, it) } legsArmor?.let { session.setEquipment(ArmorSet.LEGS, it) } // Set Weapon decorations weaponDecoration1?.let { session.addDecoration(ArmorSet.WEAPON, it) } weaponDecoration2?.let { session.addDecoration(ArmorSet.WEAPON, it) } weaponDecoration3?.let { session.addDecoration(ArmorSet.WEAPON, it) } if (headDecoration1 != null) { session.addDecoration(ArmorSet.HEAD, headDecoration1) } if (headDecoration2 != null) { session.addDecoration(ArmorSet.HEAD, headDecoration2) } if (headDecoration3 != null) { session.addDecoration(ArmorSet.HEAD, headDecoration3) } if (bodyDecoration1 != null) { session.addDecoration(ArmorSet.BODY, bodyDecoration1) } if (bodyDecoration2 != null) { session.addDecoration(ArmorSet.BODY, bodyDecoration2) } if (bodyDecoration3 != null) { session.addDecoration(ArmorSet.BODY, bodyDecoration3) } if (armsDecoration1 != null) { session.addDecoration(ArmorSet.ARMS, armsDecoration1) } if (armsDecoration2 != null) { session.addDecoration(ArmorSet.ARMS, armsDecoration2) } if (armsDecoration3 != null) { session.addDecoration(ArmorSet.ARMS, armsDecoration3) } if (waistDecoration1 != null) { session.addDecoration(ArmorSet.WAIST, waistDecoration1) } if (waistDecoration2 != null) { session.addDecoration(ArmorSet.WAIST, waistDecoration2) } if (waistDecoration3 != null) { session.addDecoration(ArmorSet.WAIST, waistDecoration3) } if (legsDecoration1 != null) { session.addDecoration(ArmorSet.LEGS, legsDecoration1) } if (legsDecoration2 != null) { session.addDecoration(ArmorSet.LEGS, legsDecoration2) } if (legsDecoration3 != null) { session.addDecoration(ArmorSet.LEGS, legsDecoration3) } if (talismanExists == 1) { val talismanNames = context.resources.getStringArray(R.array.talisman_names) talismanType = min(talismanNames.size - 1, talismanType) val talisman = ASBTalisman(talismanType) val typeName = talismanNames[talismanType] talisman.name = context.getString(R.string.talisman_full_name, typeName) talisman.numSlots = talismanSlots talisman.setFirstSkill(getSkillTreeById(talismanSkill1Id)!!, talismanSkill1Points) if (talismanSkill2Id != -1L) { talisman.setSecondSkill(getSkillTreeById(talismanSkill2Id), talismanSkill2Points) } session.setEquipment(ArmorSet.TALISMAN, talisman) if (talismanDecoration1 != null) { session.addDecoration(ArmorSet.TALISMAN, talismanDecoration1) } if (talismanDecoration2 != null) { session.addDecoration(ArmorSet.TALISMAN, talismanDecoration2) } if (talismanDecoration3 != null) { session.addDecoration(ArmorSet.TALISMAN, talismanDecoration3) } } return session } private fun getArmorById(id: Long): Armor? { return if (id != 0L && id != -1L) { DataManager.get().getArmor(id) } else null } private fun getDecorationById(id: Long): Decoration? { return if (id != 0L && id != -1L) { DataManager.get().getDecoration(id) } else null } private fun getSkillTreeById(id: Long): SkillTree? { return if (id != 0L && id != -1L) { DataManager.get().getSkillTree(id) } else null } }
app/src/main/java/com/ghstudios/android/data/cursors/ASBSessionCursor.kt
757547597
package non_test.fotostrecken_generator val IokaiProject = Project( id = "iokai", title = "Iokai", date = "Fr{\\\"u}hjahr 2017", sections = listOf( Section( title = "Dickdarm", images = listOf( Image("Di1", "Anfang", "Das ist der Anfang."), Image("Di2", "Di2", "rechts"), Image("Di4", "Di4", "Der letzte.") ) ) ) )
src/test/kotlin/non_test/fotostrecken_generator/projects.kt
3972535287
package com.gitlab.daring.fms.common.concurrent import com.gitlab.daring.fms.common.config.getMillis import com.gitlab.daring.fms.common.config.getOpt import com.typesafe.config.Config import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit.MILLISECONDS object ConcurrentUtils { fun newExecutor(c: Config): ThreadPoolExecutor { val size = c.getInt("size") val maxSize = c.getOpt { getInt("maxSize") } ?: size val keepAlive = c.getOpt { getMillis("keepAlive") } ?: 60000 return ThreadPoolExecutor( size, maxSize, keepAlive, MILLISECONDS, LinkedBlockingQueue<Runnable>() ) } }
common/src/main/kotlin/com/gitlab/daring/fms/common/concurrent/ConcurrentUtils.kt
688769833
package de.brlo.hopfen.feature.home import de.brlo.hopfen.feature.data.Listing import de.brlo.hopfen.feature.repository.Repository import io.ashdavies.rx.rxfirebase.ChildEvent import io.ashdavies.rx.rxfirebase.RxFirebaseDatabase import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import javax.inject.Inject internal class ListingsRepository @Inject constructor(private val deserialiser: GsonDeserialiser<Listing>) : Repository<String, Listing> { override fun get(key: String): Single<Listing> { return getInstance(CHILD_LISTINGS, key) .onSingleValueEvent() .map { it.getValue<Listing>(Listing::class.java)!! } } override fun getAll(): Observable<Listing> { return RxFirebaseDatabase.getInstance(CHILD_LISTINGS) .limitToLast(QUERY_LIMIT) .orderByChild(QUERY_ORDER) .onChildEvent(ChildEvent.Type.CHILD_ADDED) .map { deserialiser.deserialise(it.snapshot(), Listing::class.java) } .toObservable() } override fun put(value: Listing, resolver: (Listing) -> String): Completable { return getInstance(CHILD_LISTINGS, value.uuid).setValue(value) } private fun getInstance(vararg args: CharSequence): RxFirebaseDatabase { return RxFirebaseDatabase.getInstance(args.joinToString("/")) } companion object { private const val CHILD_LISTINGS = "listing" private const val QUERY_ORDER = "created" private const val QUERY_LIMIT = 100 } }
feature/src/main/kotlin/de/brlo/hopfen/feature/home/ListingsRepository.kt
1388519558
package com.chrynan.chords.widget import android.content.Context import android.graphics.* import android.os.Parcel import android.os.Parcelable import android.util.AttributeSet import android.view.View import com.chrynan.chords.R import com.chrynan.chords.model.* import com.chrynan.chords.parcel.ChordChartParceler import com.chrynan.chords.parcel.ChordParceler import com.chrynan.chords.util.getTypeface import com.chrynan.chords.util.writeChord import com.chrynan.chords.util.writeChordChart import com.chrynan.chords.view.ChordView import com.chrynan.chords.view.ChordView.Companion.DEFAULT_FIT_TO_HEIGHT import com.chrynan.chords.view.ChordView.Companion.DEFAULT_MUTED_TEXT import com.chrynan.chords.view.ChordView.Companion.DEFAULT_OPEN_TEXT import com.chrynan.chords.view.ChordView.Companion.DEFAULT_SHOW_FINGER_NUMBERS import com.chrynan.chords.view.ChordView.Companion.DEFAULT_SHOW_FRET_NUMBERS import com.chrynan.chords.view.ChordView.Companion.DEFAULT_STRING_LABEL_STATE import kotlin.math.min import kotlin.math.round /* * Copyright 2020 chRyNaN * * 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. */ /** * An Android [View] class to display guitar (or other stringed fretted instruments) chords as a * chart. This class implements the [ChordView] interface and displays a [ChordChart] for a * provided [Chord]. * * @author chRyNaN */ class ChordWidget : View, ChordView { override var chord: Chord? = null set(value) { field = value requestLayout() invalidate() } override var chart: ChordChart = ChordChart.STANDARD_TUNING_GUITAR_CHART set(value) { field = value requestLayout() invalidate() } override var fitToHeight: Boolean = DEFAULT_FIT_TO_HEIGHT set(value) { field = value requestLayout() invalidate() } override var showFretNumbers = DEFAULT_SHOW_FRET_NUMBERS set(value) { field = value requestLayout() invalidate() } override var showFingerNumbers = DEFAULT_SHOW_FINGER_NUMBERS set(value) { field = value invalidate() } override var stringLabelState: StringLabelState = DEFAULT_STRING_LABEL_STATE set(value) { field = value requestLayout() invalidate() } override var mutedStringText: String = DEFAULT_MUTED_TEXT set(value) { field = value invalidate() } override var openStringText: String = DEFAULT_OPEN_TEXT set(value) { field = value invalidate() } override var fretColor = DEFAULT_COLOR set(value) { field = value fretPaint.color = value invalidate() } override var fretLabelTextColor = DEFAULT_TEXT_COLOR set(value) { field = value fretLabelTextPaint.color = value invalidate() } override var stringColor = DEFAULT_COLOR set(value) { field = value stringPaint.color = value invalidate() } override var stringLabelTextColor = DEFAULT_COLOR set(value) { field = value stringLabelTextPaint.color = value invalidate() } override var noteColor = DEFAULT_COLOR set(value) { field = value notePaint.color = value barLinePaint.color = value invalidate() } override var noteLabelTextColor = DEFAULT_TEXT_COLOR set(value) { field = value noteLabelTextPaint.color = value invalidate() } /** * The [Typeface] that is used for the fret label text. This defaults to [Typeface.DEFAULT]. * * @author chRyNaN */ var fretLabelTypeface: Typeface = Typeface.DEFAULT set(value) { field = value fretLabelTextPaint.typeface = value requestLayout() invalidate() } /** * The [Typeface] that is used for the note label text. This defaults to [Typeface.DEFAULT]. * * @author chRyNaN */ var noteLabelTypeface: Typeface = Typeface.DEFAULT set(value) { field = value noteLabelTextPaint.typeface = value requestLayout() invalidate() } /** * The [Typeface] that is used for the string label text. This defaults to [Typeface.DEFAULT]. * * @author chRyNaN */ var stringLabelTypeface: Typeface = Typeface.DEFAULT set(value) { field = value stringLabelTextPaint.typeface = value requestLayout() invalidate() } private val fretPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeCap = Paint.Cap.ROUND } private val fretLabelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER } private val stringPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeCap = Paint.Cap.BUTT } private val stringLabelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER } private val notePaint = Paint(Paint.ANTI_ALIAS_FLAG) private val noteLabelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER } private val barLinePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } private val drawingBounds = RectF() private val chartBounds = RectF() private val stringTopLabelBounds = RectF() private val stringBottomLabelBounds = RectF() private val fretSideLabelBounds = RectF() private val fretCount: Int get() = chart.fretEnd.number - chart.fretStart.number + 1 private val showBottomStringLabels: Boolean get() = stringLabelState != StringLabelState.HIDE && chart.stringLabels.isNotEmpty() private val fretLineRects = mutableListOf<RectF>() private val stringLineRects = mutableListOf<RectF>() private val fretNumberPoints = mutableListOf<PointF>() private val notePositions = mutableListOf<NotePosition>() private val barLinePaths = mutableListOf<BarPosition>() private val stringBottomLabelPositions = mutableListOf<StringPosition>() private val stringTopMarkerPositions = mutableListOf<StringPosition>() private var fretSize = 0f //y value = 0 private var stringDistance = 0f //x value = 0f private var fretMarkerSize = 0f set(value) { field = value fretPaint.strokeWidth = value } private var fretLabelTextSize = 0f set(value) { field = value fretLabelTextPaint.textSize = value } private var stringSize = 0f set(value) { field = value stringPaint.strokeWidth = value barLinePaint.strokeWidth = 2 * value } private var stringLabelTextSize = 0f set(value) { field = value stringLabelTextPaint.textSize = value } private var noteSize = 0f set(value) { field = value notePaint.strokeWidth = value } private var noteLabelTextSize = 0f set(value) { field = value noteLabelTextPaint.textSize = value } constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet? = null) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { if (!isInEditMode) { if (attrs != null) { val a = getContext().theme.obtainStyledAttributes(attrs, R.styleable.ChordWidget, defStyleAttr, 0) try { fitToHeight = a.getBoolean(R.styleable.ChordWidget_fitToHeight, DEFAULT_FIT_TO_HEIGHT) fretColor = a.getColor(R.styleable.ChordWidget_fretColor, DEFAULT_COLOR) stringColor = a.getColor(R.styleable.ChordWidget_stringColor, DEFAULT_COLOR) fretLabelTextColor = a.getColor(R.styleable.ChordWidget_fretLabelTextColor, DEFAULT_COLOR) stringLabelTextColor = a.getColor(R.styleable.ChordWidget_stringLabelTextColor, DEFAULT_COLOR) noteColor = a.getColor(R.styleable.ChordWidget_noteColor, DEFAULT_COLOR) noteLabelTextColor = a.getColor(R.styleable.ChordWidget_noteLabelTextColor, DEFAULT_TEXT_COLOR) mutedStringText = a.getString(R.styleable.ChordWidget_mutedStringText) ?: DEFAULT_MUTED_TEXT openStringText = a.getString(R.styleable.ChordWidget_openStringText) ?: DEFAULT_OPEN_TEXT stringLabelState = when (a.getInt(R.styleable.ChordWidget_stringLabelState, 0)) { 0 -> StringLabelState.SHOW_NUMBER 1 -> StringLabelState.SHOW_LABEL else -> StringLabelState.HIDE } showFingerNumbers = a.getBoolean(R.styleable.ChordWidget_showFingerNumbers, DEFAULT_SHOW_FINGER_NUMBERS) showFretNumbers = a.getBoolean(R.styleable.ChordWidget_showFretNumbers, DEFAULT_SHOW_FRET_NUMBERS) a.getTypeface(context, R.styleable.ChordWidget_fretLabelTypeface)?.let { fretLabelTypeface = it } a.getTypeface(context, R.styleable.ChordWidget_noteLabelTypeface)?.let { noteLabelTypeface = it } a.getTypeface(context, R.styleable.ChordWidget_stringLabelTypeface)?.let { stringLabelTypeface = it } } finally { a.recycle() } } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) calculateSize() calculateBarLinePositions() calculateFretNumberPositions() calculateFretPositions() calculateNotePositions() calculateStringMarkers() calculateStringPositions() } override fun onDraw(canvas: Canvas) { // First draw the strings and fret markers fretLineRects.forEach { canvas.drawLine(it, fretPaint) } stringLineRects.forEach { canvas.drawLine(it, stringPaint) } // Next draw the fret numbers and string markers drawFretNumbers(canvas) drawStringMarkers(canvas) // Finally, draw all the notes and the note text drawBars(canvas) drawNotes(canvas) } override fun onSaveInstanceState(): Parcelable? { val superState = super.onSaveInstanceState() as Parcelable val savedState = SavedState(superState) savedState.chart = chart savedState.chord = chord return savedState } override fun onRestoreInstanceState(state: Parcelable) { if (state is SavedState) { super.onRestoreInstanceState(state.superState) chart = state.chart chord = state.chord } else { super.onRestoreInstanceState(state) } } private fun calculateSize() { val absoluteWidth = measuredWidth - (paddingLeft + paddingRight).toFloat() val absoluteHeight = measuredHeight - (paddingTop + paddingBottom).toFloat() val minSideSize = min(absoluteWidth, absoluteHeight) val actualWidth = if (fitToHeight) minSideSize * (2f / 3f) else absoluteWidth val actualHeight = if (fitToHeight) minSideSize else absoluteHeight // Give some space for the labels val horizontalExtraCount = if (showFretNumbers) 1 else 0 val verticalExtraCount = if (showBottomStringLabels) 2 else 1 // We add 1 to make room for two halves of notes displayed on the first and last strings. Otherwise, they'll be cut-off. noteSize = min((actualWidth / (chart.stringCount + 1 + horizontalExtraCount)), (actualHeight / (fretCount + 1 + verticalExtraCount))) val textSize = noteSize * .75f fretLabelTextSize = textSize stringLabelTextSize = textSize noteLabelTextSize = textSize stringDistance = noteSize stringSize = (stringDistance / chart.stringCount).coerceAtLeast(1f) fretMarkerSize = stringSize fretSize = round((actualHeight - (noteSize * verticalExtraCount) - (fretCount + 1) * fretMarkerSize) / fretCount) val drawingWidth = noteSize * (chart.stringCount + 1 + horizontalExtraCount) val drawingHeight = (fretSize * fretCount) + (noteSize * (1 + verticalExtraCount)) // Center everything drawingBounds.set( (absoluteWidth - drawingWidth) / 2, (absoluteHeight - drawingHeight) / 2, (absoluteWidth - drawingWidth) / 2 + drawingWidth, (absoluteHeight - drawingHeight) / 2 + drawingHeight) // The actual chart bounds chartBounds.set( drawingBounds.left + (noteSize * horizontalExtraCount) + (noteSize * .5f), drawingBounds.top + noteSize, drawingBounds.right - (noteSize * .5f), drawingBounds.bottom - (if (showBottomStringLabels) noteSize else 0f)) // The open/closed labels for the String above the chart stringTopLabelBounds.set( chartBounds.left, drawingBounds.top, chartBounds.right, drawingBounds.top + noteSize) // The number/note labels for the String below the chart stringBottomLabelBounds.set( chartBounds.left, chartBounds.bottom, chartBounds.right, chartBounds.bottom + noteSize) // The fret number labels on the side of the chart fretSideLabelBounds.set( drawingBounds.left, chartBounds.top, drawingBounds.left + noteSize, drawingBounds.bottom) } private fun calculateFretPositions() { fretLineRects.clear() for (i in 0..fretCount) { fretLineRects.add(RectF( chartBounds.left, chartBounds.top + i * fretSize + i * fretMarkerSize, chartBounds.right - stringSize, chartBounds.top + i * fretSize + i * fretMarkerSize)) } } private fun calculateStringPositions() { stringLineRects.clear() for (i in 0 until chart.stringCount) { stringLineRects.add(RectF( chartBounds.left + i * stringDistance + i * stringSize, chartBounds.top, chartBounds.left + i * stringDistance + i * stringSize, chartBounds.top + fretCount * fretSize + fretCount * fretMarkerSize)) } } private fun calculateFretNumberPositions() { fretNumberPoints.clear() for (i in 0..(chart.fretEnd.number - chart.fretStart.number)) { fretNumberPoints.add(PointF( drawingBounds.left + fretSideLabelBounds.width() / 2, getVerticalCenterTextPosition(stringTopLabelBounds.bottom + i * fretMarkerSize + i * fretSize + fretSize / 2, (i + 1).toString(), fretLabelTextPaint))) } } private fun calculateBarLinePositions() { barLinePaths.clear() chord?.bars?.forEach { bar -> if (bar.fret.number in chart.fretStart.number..chart.fretEnd.number && bar.endString.number < chart.stringCount + 1) { val relativeFretNumber = bar.fret.number - (chart.fretStart.number - 1) val left = (chartBounds.left + (chart.stringCount - bar.endString.number) * stringDistance + (chart.stringCount - bar.endString.number) * stringSize) - noteSize / 2 val top = chartBounds.top + (relativeFretNumber * fretSize + relativeFretNumber * fretMarkerSize - fretSize / 2) - (noteSize / 2) val right = (chartBounds.left + (chart.stringCount - bar.startString.number) * stringDistance + (chart.stringCount - bar.startString.number) * stringSize) + (noteSize / 2) val bottom = top + noteSize val text = if (bar.finger === Finger.UNKNOWN) "" else bar.finger.toString() val textX = left + (right - left) / 2 val textY = getVerticalCenterTextPosition(top + (bottom - top) / 2, text, noteLabelTextPaint) barLinePaths.add( BarPosition( text = text, textX = textX, textY = textY, left = left, top = top, right = right, bottom = bottom)) } } } private fun calculateNotePositions() { notePositions.clear() chord?.notes?.forEach { note -> if (note.fret.number in chart.fretStart.number..chart.fretEnd.number && note.string.number < chart.stringCount + 1) { val relativeFretNumber = note.fret.number - (chart.fretStart.number - 1) val startCenterX = chartBounds.left + (chart.stringCount - note.string.number) * stringDistance + (chart.stringCount - note.string.number) * stringSize val startCenterY = chartBounds.top + (relativeFretNumber * fretSize + relativeFretNumber * fretMarkerSize - fretSize / 2) val text = if (note.finger === Finger.UNKNOWN) "" else note.finger.toString() notePositions.add( NotePosition( text = text, circleX = startCenterX, circleY = startCenterY, textX = startCenterX, textY = getVerticalCenterTextPosition(startCenterY, text, noteLabelTextPaint))) } } } private fun calculateStringMarkers() { stringBottomLabelPositions.clear() stringTopMarkerPositions.clear() // Top string mute labels chord?.mutes?.forEach { muted -> if (muted.string.number < chart.stringCount + 1) { val x = chartBounds.left + (chart.stringCount - muted.string.number) * stringDistance + (chart.stringCount - muted.string.number) * stringSize val y = getVerticalCenterTextPosition(drawingBounds.top + stringTopLabelBounds.height() / 2, mutedStringText, stringLabelTextPaint) stringTopMarkerPositions.add( StringPosition( text = mutedStringText, textX = x, textY = y)) } } // Top string open labels chord?.opens?.forEach { open -> if (open.string.number < chart.stringCount + 1) { val x = chartBounds.left + (chart.stringCount - open.string.number) * stringDistance + (chart.stringCount - open.string.number) * stringSize val y = getVerticalCenterTextPosition(drawingBounds.top + stringTopLabelBounds.height() / 2, openStringText, stringLabelTextPaint) stringTopMarkerPositions.add( StringPosition( text = openStringText, textX = x, textY = y)) } } if (showBottomStringLabels) { chart.stringLabels.forEach { stringLabel -> if (stringLabel.string.number < chart.stringCount + 1) { val label = if (stringLabelState == StringLabelState.SHOW_NUMBER) stringLabel.string.toString() else stringLabel.label if (label != null) { val x = chartBounds.left + (chart.stringCount - stringLabel.string.number) * stringDistance + (chart.stringCount - stringLabel.string.number) * stringSize val y = getVerticalCenterTextPosition(chartBounds.bottom + stringBottomLabelBounds.height() / 2, label, stringLabelTextPaint) stringBottomLabelPositions.add( StringPosition( text = label, textX = x, textY = y)) } } } } } private fun drawFretNumbers(canvas: Canvas) { // Fret numbers; check if we are showing them or not if (showFretNumbers) { fretNumberPoints.forEachIndexed { index, point -> canvas.drawText((chart.fretStart.number + index).toString(), point.x, point.y, fretLabelTextPaint) } } } private fun drawStringMarkers(canvas: Canvas) { // Top String markers (open/muted) stringTopMarkerPositions.forEach { canvas.drawText(it.text, it.textX, it.textY, stringLabelTextPaint) } // Bottom String labels (number/note) stringBottomLabelPositions.forEach { canvas.drawText(it.text, it.textX, it.textY, stringLabelTextPaint) } } private fun drawBars(canvas: Canvas) { // Bars barLinePaths.forEach { // Draw Bar canvas.drawRoundRect(it.left, it.top, it.right, it.bottom, (it.bottom - it.top), (it.bottom - it.top), barLinePaint) // Text if (showFingerNumbers) { canvas.drawText(it.text, it.textX, it.textY, noteLabelTextPaint) } } } private fun drawNotes(canvas: Canvas) { //Individual notes notePositions.forEach { canvas.drawCircle(it.circleX, it.circleY, noteSize / 2f, notePaint) if (showFingerNumbers) { canvas.drawText(it.text, it.textX, it.textY, noteLabelTextPaint) } } } private fun getVerticalCenterTextPosition(originalYPosition: Float, text: String?, textPaint: Paint): Float { val bounds = Rect() textPaint.getTextBounds(text, 0, text?.length ?: 0, bounds) return originalYPosition + bounds.height() / 2 } private fun Canvas.drawLine(rectF: RectF, paint: Paint) = drawLine(rectF.left, rectF.top, rectF.right, rectF.bottom, paint) companion object { const val DEFAULT_COLOR = Color.BLACK const val DEFAULT_TEXT_COLOR = Color.WHITE } private class SavedState : BaseSavedState { companion object { @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> { override fun createFromParcel(source: Parcel): SavedState = SavedState(source) override fun newArray(size: Int): Array<SavedState?> = arrayOfNulls(size) } } var chart: ChordChart = ChordChart.STANDARD_TUNING_GUITAR_CHART var chord: Chord? = null constructor(parcelable: Parcelable) : super(parcelable) constructor(parcel: Parcel) : super(parcel) { chart = ChordChartParceler.create(parcel) chord = try { ChordParceler.create(parcel) } catch (throwable: Throwable) { null } } override fun writeToParcel(parcel: Parcel, flags: Int) { super.writeToParcel(parcel, flags) parcel.writeChordChart(chart, flags) chord?.let { parcel.writeChord(it, flags) } } } private data class NotePosition( val text: String, val circleX: Float, val circleY: Float, val textX: Float, val textY: Float ) private data class StringPosition( val text: String, val textX: Float, val textY: Float ) private data class BarPosition( val text: String, val left: Float, val top: Float, val right: Float, val bottom: Float, val textX: Float, val textY: Float ) }
android/src/main/java/com/chrynan/chords/widget/ChordWidget.kt
2927497686