repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
DemonWav/IntelliJBukkitSupport
src/main/kotlin/nbt/lang/NbttFileType.kt
1
549
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang import com.demonwav.mcdev.asset.PlatformAssets import com.intellij.openapi.fileTypes.LanguageFileType object NbttFileType : LanguageFileType(NbttLanguage) { override fun getIcon() = PlatformAssets.MINECRAFT_ICON override fun getName() = "NBTT" override fun getDefaultExtension() = "nbtt" override fun getDescription() = "NBT Text Representation (Don't Use This One)" }
mit
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIRadioButton.kt
1
2521
package com.soywiz.korge.ui import com.soywiz.korge.view.* import com.soywiz.korge.view.ktree.* import com.soywiz.korim.bitmap.* class UIRadioButtonGroup { private var mutableButtons = hashSetOf<UIRadioButton>() val buttons: Set<UIRadioButton> get() = mutableButtons var selectedButton: UIRadioButton? = null internal set(value) { if (field != value) { field?.checked = false field = value } } internal fun addRadio(button: UIRadioButton) { mutableButtons += button if (selectedButton == null) { button.checked = true } } internal fun removeRadio(button: UIRadioButton) { mutableButtons -= button } } inline fun Container.uiRadioButton( width: Double = UI_DEFAULT_WIDTH, height: Double = UI_DEFAULT_HEIGHT, checked: Boolean = false, text: String = "Radio Button", group: UIRadioButtonGroup = UIRadioButtonGroup(), block: @ViewDslMarker UIRadioButton.() -> Unit = {} ): UIRadioButton = UIRadioButton(width, height, checked, group, text).addTo(this).apply(block) open class UIRadioButton( width: Double = UI_DEFAULT_WIDTH, height: Double = UI_DEFAULT_HEIGHT, checked: Boolean = false, group: UIRadioButtonGroup = UIRadioButtonGroup(), text: String = "Radio Button", ) : UIBaseCheckBox<UIRadioButton>(width, height, checked, text) { var group: UIRadioButtonGroup = group set(value) { if (field !== value) { field.removeRadio(this) field = value value.addRadio(this) } } override var checked: Boolean get() = super.checked set(value) { if (super.checked != value) { super.checked = value if (value) group.selectedButton = this } } init { group.addRadio(this) if (checked) { group.selectedButton = this } } override fun onComponentClick() { checked = true } override fun getNinePatch(over: Boolean): NinePatchBmpSlice { return when { over -> radioOver else -> radioNormal } } object Serializer : KTreeSerializerExt<UIRadioButton>("UIRadioButton", UIRadioButton::class, { UIRadioButton() }, { add(UIRadioButton::text) add(UIRadioButton::checked) add(UIRadioButton::width) add(UIRadioButton::height) }) }
apache-2.0
kiruto/kotlin-android-mahjong
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/models/collections/Kantsu.kt
1
3728
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.kotmahjan.models.collections import dev.yuriel.kotmahjan.models.Hai /** * Created by yuriel on 8/13/16. */ /** * 槓子に関するクラスです * 暗槓と明槓の両方を扱います */ class Kantsu(override var identifierTile: Hai?): Mentsu() { /** * 槓子が完成していることを前提にしているため * 槓子であるかのチェックは伴いません。 * @param isOpen 暗槓の場合false, 明槓の場合はtrueを入れて下さい * @param identifierTile どの牌の槓子なのか */ constructor(isOpen: Boolean, identifierTile: Hai): this(identifierTile) { this.isOpen = isOpen this.isMentsu = true } /** * 槓子であるかのチェックも伴います * すべての牌(t1~4)が同じ場合にisMentsuがtrueになります * @param isOpen 暗槓の場合false, 明槓の場合はtrueを入れて下さい * @param tile1 1枚目 * @param tile2 2枚目 * @param tile3 3枚目 * @param tile4 4枚目 */ constructor(isOpen: Boolean, tile1: Hai, tile2: Hai, tile3: Hai, tile4: Hai): this(tile1) { this.isOpen = isOpen this.isMentsu = check(tile1, tile2, tile3, tile4) if (!isMentsu) { identifierTile = null } } override val fu: Int by lazy { var mentsuFu = 8 if (!isOpen) { mentsuFu *= 2 } if (identifierTile?.isYaochu() == true) { mentsuFu *= 2 } mentsuFu } override fun equals(o: Any?): Boolean { if (this === o) return true if (o !is Kantsu) return false if (isMentsu !== o.isMentsu) return false if (isOpen !== o.isOpen) return false return identifierTile === o.identifierTile } override fun hashCode(): Int { var result: Int = if (null != identifierTile) identifierTile!!.hashCode() else 0 result = 31 * result + if (isMentsu) 1 else 0 result = 31 * result + if (isOpen) 1 else 0 return result } companion object { /** * t1~4が同一の牌かを調べます * @param tile1 1枚目 * @param tile2 2枚目 * @param tile3 3枚目 * @param tile4 4枚目 * @return 槓子の場合true 槓子でない場合false */ fun check(tile1: Hai, tile2: Hai, tile3: Hai, tile4: Hai): Boolean { return tile1 sameAs tile2 && tile2 sameAs tile3 && tile3 sameAs tile4 } } }
mit
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/o/katydid/vdom/builders/media/KatydidMediaEmbeddedContentBuilder.kt
1
5008
// // (C) Copyright 2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.vdom.builders.media import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.builders.KatydidEmbeddedContentBuilder import o.katydid.vdom.types.EDirection import o.katydid.vdom.types.ETrackKind import o.katydid.vdom.types.MimeType //--------------------------------------------------------------------------------------------------------------------- /** * Builder DSL to create the contents of a media element. */ interface KatydidMediaEmbeddedContentBuilder<in Msg> : KatydidEmbeddedContentBuilder<Msg> { /** * Adds a `<source>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param media the media descriptor for which the source applies. * @param sizes image sizes between breakpoints. * @param spellcheck whether the element is subject to spell checking. * @param src address of the resource. * @param srcset images to use in different situations (e.g., high-resolution displays, small monitors, etc). * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param type the MIME type of the source. * @param defineAttributes a DSL-style lambda that builds any custom attributes of the new element. */ fun source( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, media: String? = null, sizes: String? = null, spellcheck: Boolean? = null, src: String, srcset: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, type: MimeType? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds a `<track>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param default whether this is the default track to play. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param kind the purpose of this track. * @param label user-visible label for the track. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param src address of the resource. * @param srclang the language of the source. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that builds any custom attributes of the new element. */ fun track( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, default: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, kind: ETrackKind? = null, label: String? = null, lang: String? = null, spellcheck: Boolean? = null, src: String, srclang: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/preferences/types/ListPreferenceDialogFragment.kt
1
1468
package de.saschahlusiak.freebloks.preferences.types import android.app.Dialog import android.content.Context import android.os.Bundle import androidx.preference.ListPreferenceDialogFragmentCompat import androidx.preference.PreferenceDialogFragmentCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder open class ListPreferenceDialogFragment : ListPreferenceDialogFragmentCompat() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // exactly the same as super.onCreateDialog, but uses a MaterialAlertDialogBuilder instead val context: Context? = activity val builder = MaterialAlertDialogBuilder(requireContext()) .setTitle(preference.dialogTitle) .setIcon(preference.dialogIcon) .setPositiveButton(preference.positiveButtonText, this) .setNegativeButton(preference.negativeButtonText, this) val contentView = onCreateDialogView(requireContext()) if (contentView != null) { onBindDialogView(contentView) builder.setView(contentView) } else { builder.setMessage(preference.dialogMessage) } onPrepareDialogBuilder(builder) return builder.create() } fun setKey(key: String): ListPreferenceDialogFragment { if (arguments == null) arguments = Bundle() arguments?.putString(PreferenceDialogFragmentCompat.ARG_KEY, key) return this } }
gpl-2.0
codicius/bioskop-scraper
src/main/kotlin/com/codicius/bioskop/scraper/City.kt
1
124
package com.codicius.bioskop.scraper /** * Created by michel on 10/12/15. */ class City(val id: String, val name: String)
mpl-2.0
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/location/GeoJson.kt
1
987
package ffc.app.location import ffc.api.ApiErrorException import ffc.api.FfcCentral import ffc.app.util.RepoCallback import ffc.entity.Organization import ffc.entity.place.House import me.piruin.geok.geometry.FeatureCollection import retrofit2.dsl.enqueue interface PlaceGeoJson { fun all(callbackDsl: RepoCallback<FeatureCollection<House>>.() -> Unit) } fun placeGeoJson(org: Organization): PlaceGeoJson = ApiPlaceGeoJson(org) private class ApiPlaceGeoJson(val org: Organization) : PlaceGeoJson { val api = FfcCentral().service<PlaceService>() override fun all(callbackDsl: RepoCallback<FeatureCollection<House>>.() -> Unit) { val callback = RepoCallback<FeatureCollection<House>>().apply(callbackDsl) api.listHouseGeoJson(org.id).enqueue { onSuccess { callback.onFound!!.invoke(body()!!) } onError { callback.onFail!!.invoke(ApiErrorException(this)) } onFailure { callback.onFail!!.invoke(it) } } } }
apache-2.0
uchuhimo/kotlin-playground
lang/src/main/kotlin/com/uchuhimo/typeclass/extend/Self.kt
1
176
package com.uchuhimo.typeclass.extend open class Self<out T>(val self: T) inline infix fun <T, Extend : Self<T>> T.extend(provider: T.() -> Extend): Extend = this.provider()
apache-2.0
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/AsyncTaskPreference.kt
1
2889
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.preference import android.content.Context import android.os.AsyncTask import android.os.AsyncTask.Status import android.support.v7.preference.Preference import android.util.AttributeSet import org.mariotaku.chameleon.ChameleonUtils import org.mariotaku.ktextension.dismissDialogFragment import de.vanita5.twittnuker.activity.iface.IBaseActivity import de.vanita5.twittnuker.fragment.ProgressDialogFragment import java.lang.ref.WeakReference abstract class AsyncTaskPreference(context: Context, attrs: AttributeSet? = null) : Preference(context, attrs) { private var task: InternalTask? = null override fun onClick() { if (task?.status != Status.RUNNING) { task = InternalTask(this).apply { execute() } } } protected abstract fun doInBackground() private class InternalTask(preference: AsyncTaskPreference) : AsyncTask<Any, Any, Unit>() { private val preferenceRef = WeakReference<AsyncTaskPreference>(preference) override fun doInBackground(vararg args: Any) { val preference = preferenceRef.get() ?: return preference.doInBackground() } override fun onPostExecute(result: Unit) { val context = preferenceRef.get()?.context ?: return val activity = ChameleonUtils.getActivity(context) as? IBaseActivity<*> ?: return activity.executeAfterFragmentResumed { it.supportFragmentManager.dismissDialogFragment(FRAGMENT_TAG) } } override fun onPreExecute() { val context = preferenceRef.get()?.context ?: return val activity = ChameleonUtils.getActivity(context) as? IBaseActivity<*> ?: return activity.executeAfterFragmentResumed { ProgressDialogFragment.show(it.supportFragmentManager, FRAGMENT_TAG) } } companion object { private const val FRAGMENT_TAG = "task_progress" } } }
gpl-3.0
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/ThemedEditTextPreference.kt
1
1646
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.preference import android.content.Context import android.support.v7.preference.EditTextPreference import android.support.v7.preference.PreferenceFragmentCompat import android.util.AttributeSet import de.vanita5.twittnuker.fragment.ThemedEditTextPreferenceDialogFragmentCompat import de.vanita5.twittnuker.preference.iface.IDialogPreference class ThemedEditTextPreference(context: Context, attrs: AttributeSet? = null) : EditTextPreference(context, attrs), IDialogPreference { override fun displayDialog(fragment: PreferenceFragmentCompat) { val df = ThemedEditTextPreferenceDialogFragmentCompat.newInstance(key) df.setTargetFragment(fragment, 0) df.show(fragment.fragmentManager, key) } }
gpl-3.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/talk/TalkReplyActivity.kt
1
15060
package org.wikipedia.talk import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.TextWatcher import android.view.View import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.core.util.lruCache import androidx.core.view.isVisible import androidx.core.widget.doOnTextChanged import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.BaseActivity import org.wikipedia.analytics.EditFunnel import org.wikipedia.analytics.LoginFunnel import org.wikipedia.analytics.eventplatform.EditAttemptStepEvent import org.wikipedia.auth.AccountUtil import org.wikipedia.databinding.ActivityTalkReplyBinding import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.discussiontools.ThreadItem import org.wikipedia.history.HistoryEntry import org.wikipedia.login.LoginActivity import org.wikipedia.notifications.AnonymousNotificationHelper import org.wikipedia.page.* import org.wikipedia.page.linkpreview.LinkPreviewDialog import org.wikipedia.readinglist.AddToReadingListDialog import org.wikipedia.richtext.RichTextUtil import org.wikipedia.staticdata.TalkAliasData import org.wikipedia.util.* import org.wikipedia.views.UserMentionInputView class TalkReplyActivity : BaseActivity(), LinkPreviewDialog.Callback, UserMentionInputView.Listener { private lateinit var binding: ActivityTalkReplyBinding private lateinit var editFunnel: EditFunnel private lateinit var linkHandler: TalkLinkHandler private lateinit var textWatcher: TextWatcher private val viewModel: TalkReplyViewModel by viewModels { TalkReplyViewModel.Factory(intent.extras!!) } private val bottomSheetPresenter = ExclusiveBottomSheetPresenter() private var userMentionScrolled = false private var savedSuccess = false private val linkMovementMethod = LinkMovementMethodExt { url, title, linkText, x, y -> linkHandler.onUrlClick(url, title, linkText, x, y) } private val requestLogin = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == LoginActivity.RESULT_LOGIN_SUCCESS) { updateEditLicenseText() editFunnel.logLoginSuccess() FeedbackUtil.showMessage(this, R.string.login_success_toast) } else { editFunnel.logLoginFailure() } } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTalkReplyBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.replyToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) title = "" linkHandler = TalkLinkHandler(this) linkHandler.wikiSite = viewModel.pageTitle.wikiSite textWatcher = binding.replySubjectText.doOnTextChanged { _, _, _, _ -> binding.replySubjectLayout.error = null binding.replyInputView.textInputLayout.error = null setSaveButtonEnabled(!binding.replyInputView.editText.text.isNullOrBlank()) } binding.replyInputView.editText.addTextChangedListener(textWatcher) binding.replySaveButton.setOnClickListener { onSaveClicked() } binding.replyInputView.wikiSite = viewModel.pageTitle.wikiSite binding.replyInputView.listener = this editFunnel = EditFunnel(WikipediaApp.instance, viewModel.pageTitle) editFunnel.logStart() EditAttemptStepEvent.logInit(viewModel.pageTitle) if (viewModel.topic != null) { binding.threadItemView.bindItem(viewModel.topic!!, linkMovementMethod, true) binding.threadItemView.isVisible = true } else { binding.threadItemView.isVisible = false } viewModel.postReplyData.observe(this) { if (it is Resource.Success) { savedSuccess = true onSaveSuccess(it.data) } else if (it is Resource.Error) { onSaveError(it.throwable) } } onInitialLoad() } public override fun onDestroy() { if (!savedSuccess && !binding.replyInputView.editText.text.isNullOrBlank() && viewModel.topic != null) { draftReplies.put(viewModel.topic!!.id, binding.replyInputView.editText.text!!) } binding.replySubjectText.removeTextChangedListener(textWatcher) binding.replyInputView.editText.removeTextChangedListener(textWatcher) super.onDestroy() } private fun onInitialLoad() { updateEditLicenseText() setSaveButtonEnabled(false) setToolbarTitle(viewModel.pageTitle) L10nUtil.setConditionalLayoutDirection(binding.talkScrollContainer, viewModel.pageTitle.wikiSite.languageCode) if (viewModel.topic != null) { binding.replyInputView.userNameHints = setOf(viewModel.topic!!.author) } val savedReplyText = if (viewModel.topic == null) null else draftReplies.get(viewModel.topic?.id) if (!savedReplyText.isNullOrEmpty()) { binding.replyInputView.editText.setText(savedReplyText) binding.replyInputView.editText.setSelection(binding.replyInputView.editText.text.toString().length) } binding.progressBar.isVisible = false binding.replySubjectText.setText(intent.getCharSequenceExtra(EXTRA_SUBJECT)) if (intent.hasExtra(EXTRA_BODY) && binding.replyInputView.editText.text.isNullOrEmpty()) { binding.replyInputView.editText.setText(intent.getCharSequenceExtra(EXTRA_BODY)) binding.replyInputView.editText.setSelection(binding.replyInputView.editText.text.toString().length) } editFunnel.logStart() EditAttemptStepEvent.logInit(viewModel.pageTitle) if (viewModel.isNewTopic) { title = getString(R.string.talk_new_topic) binding.replyInputView.textInputLayout.hint = getString(R.string.talk_message_hint) binding.replySubjectLayout.isVisible = true binding.replySubjectLayout.requestFocus() } else { binding.replySubjectLayout.isVisible = false binding.replyInputView.textInputLayout.hint = getString(R.string.talk_reply_hint) binding.talkScrollContainer.fullScroll(View.FOCUS_DOWN) binding.replyInputView.maybePrepopulateUserName(AccountUtil.userName.orEmpty(), viewModel.pageTitle) binding.talkScrollContainer.post { if (!isDestroyed) { binding.replyInputView.editText.requestFocus() DeviceUtil.showSoftKeyboard(binding.replyInputView.editText) binding.talkScrollContainer.postDelayed({ binding.talkScrollContainer.smoothScrollTo(0, binding.talkScrollContainer.height * 4) }, 500) } } } } private fun setToolbarTitle(pageTitle: PageTitle) { binding.toolbarTitle.text = StringUtil.fromHtml( if (viewModel.isNewTopic) pageTitle.namespace.ifEmpty { TalkAliasData.valueFor(pageTitle.wikiSite.languageCode) } + ": " + "<a href='#'>${StringUtil.removeNamespace(pageTitle.displayText)}</a>" else intent.getStringExtra(EXTRA_PARENT_SUBJECT).orEmpty() ).trim().ifEmpty { getString(R.string.talk_no_subject) } binding.toolbarTitle.contentDescription = binding.toolbarTitle.text binding.toolbarTitle.movementMethod = LinkMovementMethodExt { _ -> val entry = HistoryEntry(TalkTopicsActivity.getNonTalkPageTitle(pageTitle), HistoryEntry.SOURCE_TALK_TOPIC) startActivity(PageActivity.newIntentForNewTab(this, entry, entry.title)) } RichTextUtil.removeUnderlinesFromLinks(binding.toolbarTitle) FeedbackUtil.setButtonLongPressToast(binding.toolbarTitle) } internal inner class TalkLinkHandler internal constructor(context: Context) : LinkHandler(context) { private var lastX: Int = 0 private var lastY: Int = 0 fun onUrlClick(url: String, title: String?, linkText: String, x: Int, y: Int) { lastX = x lastY = y super.onUrlClick(url, title, linkText) } override fun onMediaLinkClicked(title: PageTitle) { // TODO } override fun onDiffLinkClicked(title: PageTitle, revisionId: Long) { // TODO } override lateinit var wikiSite: WikiSite override fun onPageLinkClicked(anchor: String, linkText: String) { // TODO } override fun onInternalLinkClicked(title: PageTitle) { UserTalkPopupHelper.show(this@TalkReplyActivity, bottomSheetPresenter, title, false, lastX, lastY, Constants.InvokeSource.TALK_REPLY_ACTIVITY, HistoryEntry.SOURCE_TALK_TOPIC) } } private fun setSaveButtonEnabled(enabled: Boolean) { binding.replySaveButton.isEnabled = enabled binding.replySaveButton.setTextColor(ResourceUtil .getThemedColor(this, if (enabled) R.attr.colorAccent else R.attr.material_theme_de_emphasised_color)) } private fun onSaveClicked() { val subject = binding.replySubjectText.text.toString().trim() val body = binding.replyInputView.editText.getParsedText(viewModel.pageTitle.wikiSite).trim() Intent().let { it.putExtra(EXTRA_SUBJECT, subject) it.putExtra(EXTRA_BODY, body) } editFunnel.logSaveAttempt() EditAttemptStepEvent.logSaveAttempt(viewModel.pageTitle) if (viewModel.isNewTopic && subject.isEmpty()) { binding.replySubjectLayout.error = getString(R.string.talk_subject_empty) binding.replySubjectLayout.requestFocus() return } else if (body.isEmpty()) { binding.replyInputView.textInputLayout.error = getString(R.string.talk_message_empty) binding.replyInputView.textInputLayout.requestFocus() return } binding.progressBar.visibility = View.VISIBLE setSaveButtonEnabled(false) viewModel.postReply(subject, body) } private fun onSaveSuccess(newRevision: Long) { AnonymousNotificationHelper.onEditSubmitted() binding.progressBar.visibility = View.GONE setSaveButtonEnabled(true) editFunnel.logSaved(newRevision) EditAttemptStepEvent.logSaveSuccess(viewModel.pageTitle) Intent().let { it.putExtra(RESULT_NEW_REVISION_ID, newRevision) it.putExtra(EXTRA_SUBJECT, binding.replySubjectText.text) it.putExtra(EXTRA_BODY, binding.replyInputView.editText.text) if (viewModel.topic != null) { it.putExtra(EXTRA_TOPIC_ID, viewModel.topic!!.id) } setResult(RESULT_EDIT_SUCCESS, it) if (viewModel.topic != null) { draftReplies.remove(viewModel.topic?.id) } finish() } } private fun onSaveError(t: Throwable) { editFunnel.logError(t.message) EditAttemptStepEvent.logSaveFailure(viewModel.pageTitle) binding.progressBar.visibility = View.GONE setSaveButtonEnabled(true) FeedbackUtil.showError(this, t) } private fun updateEditLicenseText() { binding.licenseText.text = StringUtil.fromHtml(getString(if (AccountUtil.isLoggedIn) R.string.edit_save_action_license_logged_in else R.string.edit_save_action_license_anon, getString(R.string.terms_of_use_url), getString(R.string.cc_by_sa_3_url))) binding.licenseText.movementMethod = LinkMovementMethodExt { url: String -> if (url == "https://#login") { val loginIntent = LoginActivity.newIntent(this, LoginFunnel.SOURCE_EDIT, editFunnel.sessionToken) requestLogin.launch(loginIntent) } else { UriUtil.handleExternalLink(this, Uri.parse(url)) } } } override fun onLinkPreviewLoadPage(title: PageTitle, entry: HistoryEntry, inNewTab: Boolean) { startActivity(if (inNewTab) PageActivity.newIntentForNewTab(this, entry, title) else PageActivity.newIntentForCurrentTab(this, entry, title, false)) } override fun onLinkPreviewCopyLink(title: PageTitle) { ClipboardUtil.setPlainText(this, text = title.uri) FeedbackUtil.showMessage(this, R.string.address_copied) } override fun onLinkPreviewAddToList(title: PageTitle) { bottomSheetPresenter.show(supportFragmentManager, AddToReadingListDialog.newInstance(title, Constants.InvokeSource.TALK_REPLY_ACTIVITY)) } override fun onLinkPreviewShareLink(title: PageTitle) { ShareUtil.shareText(this, title) } override fun onBackPressed() { setResult(RESULT_BACK_FROM_TOPIC) super.onBackPressed() } override fun onUserMentionListUpdate() { binding.licenseText.isVisible = false binding.talkScrollContainer.post { if (!isDestroyed && !userMentionScrolled) { binding.talkScrollContainer.smoothScrollTo(0, binding.root.height * 4) userMentionScrolled = true } } } override fun onUserMentionComplete() { userMentionScrolled = false binding.licenseText.isVisible = true } companion object { const val EXTRA_PAGE_TITLE = "pageTitle" const val EXTRA_PARENT_SUBJECT = "parentSubject" const val EXTRA_TOPIC = "topic" const val EXTRA_TOPIC_ID = "topicId" const val EXTRA_SUBJECT = "subject" const val EXTRA_BODY = "body" const val RESULT_EDIT_SUCCESS = 1 const val RESULT_BACK_FROM_TOPIC = 2 const val RESULT_NEW_REVISION_ID = "newRevisionId" // TODO: persist in db. But for now, it's fine to store these for the lifetime of the app. val draftReplies = lruCache<String, CharSequence>(10) fun newIntent(context: Context, pageTitle: PageTitle, parentSubject: String?, topic: ThreadItem?, invokeSource: Constants.InvokeSource, undoSubject: CharSequence? = null, undoBody: CharSequence? = null): Intent { return Intent(context, TalkReplyActivity::class.java) .putExtra(EXTRA_PAGE_TITLE, pageTitle) .putExtra(EXTRA_PARENT_SUBJECT, parentSubject) .putExtra(EXTRA_TOPIC, topic) .putExtra(EXTRA_SUBJECT, undoSubject) .putExtra(EXTRA_BODY, undoBody) .putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, invokeSource) } } }
apache-2.0
Dolvic/gw2-api
types/src/main/kotlin/dolvic/gw2/api/masteries/Mastery.kt
1
256
package dolvic.gw2.api.masteries import java.net.URI data class Mastery( val id: Int, val name: String, val requirement: String, val order: Int, val background: URI, val region: MasteryRegion, val levels: List<MasteryLevel> )
mit
deskchanproject/DeskChanJava
src/main/kotlin/info/deskchan/groovy_support/GroovyPlugin.kt
2
3292
package info.deskchan.groovy_support import groovy.lang.Script import info.deskchan.core.* import java.util.* abstract class GroovyPlugin : Script(), Plugin { private var pluginProxy: PluginProxyInterface? = null private val cleanupHandlers = ArrayList<Runnable>() var pluginDirPath: Path? = null get() = pluginProxy!!.pluginDirPath var assetsDirPath: Path? = null get() = pluginProxy!!.assetsDirPath var rootDirPath: Path? = null get() = pluginProxy!!.rootDirPath val dataDirPath: Path get() = pluginProxy!!.dataDirPath val id: String get() = pluginProxy!!.getId() val properties: PluginProperties get() = pluginProxy!!.getProperties() override fun initialize(pluginProxy: PluginProxyInterface): Boolean { this.pluginProxy = pluginProxy try { run() } catch (e: Exception) { pluginProxy.log(e) return false } return true } override fun unload() { for (runnable in cleanupHandlers) { runnable.run() } } fun sendMessage(tag: String, data: Any?) { pluginProxy!!.sendMessage(tag, data) } fun sendMessage(tag: String, data: Any?, responseListener: ResponseListener) { pluginProxy!!.sendMessage(tag, data, responseListener) } fun sendMessage(tag: String, data: Any?, responseListener: ResponseListener, returnListener: ResponseListener) { pluginProxy!!.sendMessage(tag, data, responseListener, returnListener) } fun addMessageListener(tag: String, listener: MessageListener) { pluginProxy!!.addMessageListener(tag, listener) } fun removeMessageListener(tag: String, listener: MessageListener) { pluginProxy!!.removeMessageListener(tag, listener) } fun setTimer(delay: Long, listener: ResponseListener): Int { return pluginProxy!!.setTimer(delay, listener) } fun setTimer(delay: Long, count: Int, listener: ResponseListener): Int { return pluginProxy!!.setTimer(delay, count, listener) } fun cancelTimer(id: Int) { pluginProxy!!.cancelTimer(id) } fun getString(key: String): String { return pluginProxy!!.getString(key) } fun addCleanupHandler(handler: Runnable) { cleanupHandlers.add(handler) } fun setResourceBundle(path: String) { pluginProxy!!.setResourceBundle(pluginDirPath!!.resolve(path).toString()) } fun setConfigField(key: String, value: Any) { pluginProxy!!.setConfigField(key, value) } fun getConfigField(key: String): Any? { return pluginProxy!!.getConfigField(key) } fun log(text: String) { pluginProxy!!.log(text) } fun log(e: Throwable) { pluginProxy!!.log(e) } fun setAlternative(srcTag: String, dstTag: String, priority:Int) { pluginProxy!!.setAlternative(srcTag, dstTag, priority) } fun deleteAlternative(srcTag: String, dstTag: String) { pluginProxy!!.deleteAlternative(srcTag, dstTag) } fun callNextAlternative(sender: String, tag: String, currentAlternative: String, data: Any?) { pluginProxy!!.callNextAlternative(sender, tag, currentAlternative, data) } }
lgpl-3.0
sargunster/PokeKotlin
pokekotlin/src/main/kotlin/me/sargunvohra/lib/pokekotlin/client/PokeApiService.kt
1
12333
package me.sargunvohra.lib.pokekotlin.client import me.sargunvohra.lib.pokekotlin.model.* import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query internal interface PokeApiService { // region Resource Lists // region Berries @GET("berry/") fun getBerryList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("berry-firmness/") fun getBerryFirmnessList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("berry-flavor/") fun getBerryFlavorList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion Berries // region Contests @GET("contest-type/") fun getContestTypeList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("contest-effect/") fun getContestEffectList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<ApiResourceList> @GET("super-contest-effect/") fun getSuperContestEffectList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<ApiResourceList> // endregion Contests // region Encounters @GET("encounter-method/") fun getEncounterMethodList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("encounter-condition/") fun getEncounterConditionList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("encounter-condition-value/") fun getEncounterConditionValueList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion // region Evolution @GET("evolution-chain/") fun getEvolutionChainList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<ApiResourceList> @GET("evolution-trigger/") fun getEvolutionTriggerList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion //region Games @GET("generation/") fun getGenerationList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokedex/") fun getPokedexList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("version/") fun getVersionList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("version-group/") fun getVersionGroupList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion // region Items @GET("item/") fun getItemList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("item-attribute/") fun getItemAttributeList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("item-category/") fun getItemCategoryList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("item-fling-effect/") fun getItemFlingEffectList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("item-pocket/") fun getItemPocketList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion //region Moves @GET("move/") fun getMoveList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("move-ailment/") fun getMoveAilmentList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("move-battle-style/") fun getMoveBattleStyleList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("move-category/") fun getMoveCategoryList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("move-damage-class/") fun getMoveDamageClassList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("move-learn-method/") fun getMoveLearnMethodList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("move-target/") fun getMoveTargetList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion // region Locations @GET("location/") fun getLocationList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("location-area/") fun getLocationAreaList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pal-park-area/") fun getPalParkAreaList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("region/") fun getRegionList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion // region Pokemon @GET("ability/") fun getAbilityList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("characteristic/") fun getCharacteristicList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<ApiResourceList> @GET("egg-group/") fun getEggGroupList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("gender/") fun getGenderList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("growth-rate/") fun getGrowthRateList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("nature/") fun getNatureList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokeathlon-stat/") fun getPokeathlonStatList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokemon/") fun getPokemonList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokemon-color/") fun getPokemonColorList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokemon-form/") fun getPokemonFormList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokemon-habitat/") fun getPokemonHabitatList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokemon-shape/") fun getPokemonShapeList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("pokemon-species/") fun getPokemonSpeciesList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("stat/") fun getStatList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> @GET("type/") fun getTypeList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion // region Utility @GET("language/") fun getLanguageList(@Query("offset") offset: Int, @Query("limit") limit: Int): Call<NamedApiResourceList> // endregion // endregion // region Berries @GET("berry/{id}/") fun getBerry(@Path("id") id: Int): Call<Berry> @GET("berry-firmness/{id}/") fun getBerryFirmness(@Path("id") id: Int): Call<BerryFirmness> @GET("berry-flavor/{id}/") fun getBerryFlavor(@Path("id") id: Int): Call<BerryFlavor> // endregion Berries // region Contests @GET("contest-type/{id}/") fun getContestType(@Path("id") id: Int): Call<ContestType> @GET("contest-effect/{id}/") fun getContestEffect(@Path("id") id: Int): Call<ContestEffect> @GET("super-contest-effect/{id}/") fun getSuperContestEffect(@Path("id") id: Int): Call<SuperContestEffect> // endregion Contests // region Encounters @GET("encounter-method/{id}/") fun getEncounterMethod(@Path("id") id: Int): Call<EncounterMethod> @GET("encounter-condition/{id}/") fun getEncounterCondition(@Path("id") id: Int): Call<EncounterCondition> @GET("encounter-condition-value/{id}/") fun getEncounterConditionValue(@Path("id") id: Int): Call<EncounterConditionValue> // endregion Contests // region Evolution @GET("evolution-chain/{id}/") fun getEvolutionChain(@Path("id") id: Int): Call<EvolutionChain> @GET("evolution-trigger/{id}/") fun getEvolutionTrigger(@Path("id") id: Int): Call<EvolutionTrigger> // endregion Evolution // region Games @GET("generation/{id}/") fun getGeneration(@Path("id") id: Int): Call<Generation> @GET("pokedex/{id}/") fun getPokedex(@Path("id") id: Int): Call<Pokedex> @GET("version/{id}/") fun getVersion(@Path("id") id: Int): Call<Version> @GET("version-group/{id}/") fun getVersionGroup(@Path("id") id: Int): Call<VersionGroup> // endregion Games // region Items @GET("item/{id}/") fun getItem(@Path("id") id: Int): Call<Item> @GET("item-attribute/{id}/") fun getItemAttribute(@Path("id") id: Int): Call<ItemAttribute> @GET("item-category/{id}/") fun getItemCategory(@Path("id") id: Int): Call<ItemCategory> @GET("item-fling-effect/{id}/") fun getItemFlingEffect(@Path("id") id: Int): Call<ItemFlingEffect> @GET("item-pocket/{id}/") fun getItemPocket(@Path("id") id: Int): Call<ItemPocket> // endregion Items // region Moves @GET("move/{id}/") fun getMove(@Path("id") id: Int): Call<Move> @GET("move-ailment/{id}/") fun getMoveAilment(@Path("id") id: Int): Call<MoveAilment> @GET("move-battle-style/{id}/") fun getMoveBattleStyle(@Path("id") id: Int): Call<MoveBattleStyle> @GET("move-category/{id}/") fun getMoveCategory(@Path("id") id: Int): Call<MoveCategory> @GET("move-damage-class/{id}/") fun getMoveDamageClass(@Path("id") id: Int): Call<MoveDamageClass> @GET("move-learn-method/{id}/") fun getMoveLearnMethod(@Path("id") id: Int): Call<MoveLearnMethod> @GET("move-target/{id}/") fun getMoveTarget(@Path("id") id: Int): Call<MoveTarget> // endregion Moves // region Locations @GET("location/{id}/") fun getLocation(@Path("id") id: Int): Call<Location> @GET("location-area/{id}/") fun getLocationArea(@Path("id") id: Int): Call<LocationArea> @GET("pal-park-area/{id}/") fun getPalParkArea(@Path("id") id: Int): Call<PalParkArea> @GET("region/{id}/") fun getRegion(@Path("id") id: Int): Call<Region> // endregion Locations // region Pokemon @GET("ability/{id}/") fun getAbility(@Path("id") id: Int): Call<Ability> @GET("characteristic/{id}/") fun getCharacteristic(@Path("id") id: Int): Call<Characteristic> @GET("egg-group/{id}/") fun getEggGroup(@Path("id") id: Int): Call<EggGroup> @GET("gender/{id}/") fun getGender(@Path("id") id: Int): Call<Gender> @GET("growth-rate/{id}/") fun getGrowthRate(@Path("id") id: Int): Call<GrowthRate> @GET("nature/{id}/") fun getNature(@Path("id") id: Int): Call<Nature> @GET("pokeathlon-stat/{id}/") fun getPokeathlonStat(@Path("id") id: Int): Call<PokeathlonStat> @GET("pokemon/{id}/") fun getPokemon(@Path("id") id: Int): Call<Pokemon> @GET("pokemon/{id}/encounters/") fun getPokemonEncounterList(@Path("id") id: Int): Call<List<LocationAreaEncounter>> @GET("pokemon-color/{id}/") fun getPokemonColor(@Path("id") id: Int): Call<PokemonColor> @GET("pokemon-form/{id}/") fun getPokemonForm(@Path("id") id: Int): Call<PokemonForm> @GET("pokemon-habitat/{id}/") fun getPokemonHabitat(@Path("id") id: Int): Call<PokemonHabitat> @GET("pokemon-shape/{id}/") fun getPokemonShape(@Path("id") id: Int): Call<PokemonShape> @GET("pokemon-species/{id}/") fun getPokemonSpecies(@Path("id") id: Int): Call<PokemonSpecies> @GET("stat/{id}/") fun getStat(@Path("id") id: Int): Call<Stat> @GET("type/{id}/") fun getType(@Path("id") id: Int): Call<Type> // endregion Pokemon // region Utility @GET("language/{id}/") fun getLanguage(@Path("id") id: Int): Call<Language> // endregion Utility }
apache-2.0
kittinunf/Fuel
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/requests/RepeatableBody.kt
1
3166
package com.github.kittinunf.fuel.core.requests import com.github.kittinunf.fuel.core.Body import java.io.ByteArrayInputStream import java.io.InputStream import java.io.OutputStream /** * A Repeatable Body wraps a body and on the first [writeTo] it keeps the bytes in memory so it can be written again. * * Delegation is not possible because the [body] is re-assigned, and the delegation would point to the initial * assignment. */ data class RepeatableBody( var body: Body ) : Body { /** * Writes the body to the [OutputStream]. * * @note callers are responses for closing the [OutputStream]. * @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again. * @note implementations are recommended to buffer the output stream if they can't ensure bulk writing. * * @param outputStream [OutputStream] the stream to write to * @return [Long] the number of bytes written */ override fun writeTo(outputStream: OutputStream): Long { val repeatableBodyStream = ByteArrayInputStream(toByteArray()) return body.writeTo(outputStream) .also { length -> body = DefaultBody.from({ repeatableBodyStream }, { length }) } } /** * Returns the body as a [ByteArray]. * * @note Because the body needs to be read into memory anyway, implementations may choose to make the [Body] * readable once more after calling this method, with the original [InputStream] being closed (and release its * resources). This also means that if an implementation choose to keep it around, `isConsumed` returns false. * * @return the entire body */ override fun toByteArray() = body.toByteArray() /** * Returns the body as an [InputStream]. * * @note callers are responsible for closing the returned stream. * @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again. * * @return the body as input stream */ override fun toStream() = body.toStream() /** * Returns the body emptiness. * @return [Boolean] if true, this body is empty */ override fun isEmpty() = body.isEmpty() /** * Returns if the body is consumed. * @return [Boolean] if true, `writeTo`, `toStream` and `toByteArray` may throw */ override fun isConsumed() = body.isConsumed() /** * Represents this body as a string * @param contentType [String] the type of the content in the body, or null if a guess is necessary * @return [String] the body as a string or a string that represents the body such as (empty) or (consumed) */ override fun asString(contentType: String?) = body.asString(contentType) /** * Returns the length of the body in bytes * @return [Long?] the length in bytes, null if it is unknown */ override val length = body.length /** * Makes the body repeatable by e.g. loading its contents into memory * @return [RepeatableBody] the body to be repeated */ override fun asRepeatable(): RepeatableBody = this }
mit
TeamWizardry/LibrarianLib
modules/foundation/src/test/kotlin/com/teamwizardry/librarianlib/foundation/testmod/customtypes/client/TestTileEntityRenderer.kt
1
2640
package com.teamwizardry.librarianlib.foundation.testmod.customtypes.client import com.mojang.blaze3d.matrix.MatrixStack import com.teamwizardry.librarianlib.core.util.Client import com.teamwizardry.librarianlib.core.util.loc import com.teamwizardry.librarianlib.foundation.testmod.customtypes.TestTileEntity import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.renderer.RenderType import net.minecraft.client.renderer.tileentity.TileEntityRenderer import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher class TestTileEntityRenderer(rendererDispatcherIn: TileEntityRendererDispatcher) : TileEntityRenderer<TestTileEntity>(rendererDispatcherIn) { override fun render( tileEntityIn: TestTileEntity, partialTicks: Float, matrixStackIn: MatrixStack, bufferIn: VertexConsumerProvider, combinedLightIn: Int, combinedOverlayIn: Int ) { val texture = Client.getBlockAtlasSprite(loc("block/dirt")) val builder = texture.wrapBuffer(bufferIn.getBuffer(RenderType.getCutout())) builder.pos(matrixStackIn.last.matrix, 0, tileEntityIn.lastFallDistance + 1, 0).color(1f, 1f, 1f, 1f) builder.tex(0f, 0f).lightmap(combinedLightIn).normal(0f, 1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 1, tileEntityIn.lastFallDistance + 1, 0).color(1f, 1f, 1f, 1f) builder.tex(1f, 0f).lightmap(combinedLightIn).normal(0f, 1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 1, tileEntityIn.lastFallDistance + 1, 1).color(1f, 1f, 1f, 1f) builder.tex(1f, 1f).lightmap(combinedLightIn).normal(0f, 1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 0, tileEntityIn.lastFallDistance + 1, 1).color(1f, 1f, 1f, 1f) builder.tex(0f, 1f).lightmap(combinedLightIn).normal(0f, 1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 0, tileEntityIn.lastFallDistance + 1, 1).color(1f, 1f, 1f, 1f) builder.tex(0f, 1f).lightmap(combinedLightIn).normal(0f, -1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 1, tileEntityIn.lastFallDistance + 1, 1).color(1f, 1f, 1f, 1f) builder.tex(1f, 1f).lightmap(combinedLightIn).normal(0f, -1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 1, tileEntityIn.lastFallDistance + 1, 0).color(1f, 1f, 1f, 1f) builder.tex(1f, 0f).lightmap(combinedLightIn).normal(0f, -1f, 0f).endVertex() builder.pos(matrixStackIn.last.matrix, 0, tileEntityIn.lastFallDistance + 1, 0).color(1f, 1f, 1f, 1f) builder.tex(0f, 0f).lightmap(combinedLightIn).normal(0f, -1f, 0f).endVertex() } }
lgpl-3.0
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/util/InstallUtils.kt
4
309
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.util @Suppress("unused") sealed class DownloadResult<out T> { class Ok<T>(val value: T) : DownloadResult<T>() class Err(val error: String) : DownloadResult<Nothing>() }
mit
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/extractFunction/ExtractFunctionParameterTablePanel.kt
3
3254
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.extractFunction import com.intellij.refactoring.util.AbstractParameterTablePanel import com.intellij.refactoring.util.AbstractVariableData import com.intellij.ui.BooleanTableCellEditor import com.intellij.ui.BooleanTableCellRenderer import com.intellij.util.ui.ColumnInfo class ParameterDataHolder(val parameter: Parameter, val onChange: () -> Unit) : AbstractVariableData() { fun changeName(name: String) { parameter.name = name onChange() } fun changeMutability(mutable: Boolean) { parameter.isMutable = mutable onChange() } } class ChooseColumn : ColumnInfo<ParameterDataHolder, Boolean>(null) { override fun valueOf(item: ParameterDataHolder): Boolean = item.parameter.isSelected override fun setValue(item: ParameterDataHolder, value: Boolean) { item.parameter.isSelected = value } override fun getColumnClass(): Class<*> = Boolean::class.java override fun isCellEditable(item: ParameterDataHolder): Boolean = true } class NameColumn(private val nameValidator: (String) -> Boolean) : ColumnInfo<ParameterDataHolder, String>("Name") { override fun valueOf(item: ParameterDataHolder): String = item.parameter.name override fun setValue(item: ParameterDataHolder, value: String) { if (nameValidator(value)) { item.changeName(value) } } override fun isCellEditable(item: ParameterDataHolder): Boolean = true } class TypeColumn : ColumnInfo<ParameterDataHolder, String>("Type") { override fun valueOf(item: ParameterDataHolder): String = item.parameter.type?.toString() ?: "_" } class MutabilityColumn : ColumnInfo<ParameterDataHolder, Boolean>("Mutable") { override fun valueOf(item: ParameterDataHolder): Boolean = item.parameter.isMutable override fun setValue(item: ParameterDataHolder, value: Boolean) { item.changeMutability(value) } override fun isCellEditable(item: ParameterDataHolder): Boolean = true override fun getColumnClass(): Class<*> = Boolean::class.java } class ExtractFunctionParameterTablePanel( nameValidator: (String) -> Boolean, private val config: RsExtractFunctionConfig, private val onChange: () -> Unit ) : AbstractParameterTablePanel<ParameterDataHolder>( ChooseColumn(), NameColumn(nameValidator), TypeColumn(), MutabilityColumn() ) { init { myTable.setDefaultRenderer(Boolean::class.java, BooleanTableCellRenderer()) myTable.setDefaultEditor(Boolean::class.java, BooleanTableCellEditor()) myTable.columnModel.getColumn(0).preferredWidth = WIDTH myTable.columnModel.getColumn(0).maxWidth = WIDTH init( config.parameters.map { ParameterDataHolder(it, ::updateSignature) }.toTypedArray() ) } override fun doEnterAction() {} override fun doCancelAction() {} override fun updateSignature() { config.parameters = variableData.map { it.parameter } onChange() } companion object { private const val WIDTH = 40 } }
mit
satamas/fortran-plugin
src/test/kotlin/org/jetbrains/fortran/ide/inspections/FortranNonstandardKindInspectionTest.kt
1
1261
package org.jetbrains.fortran.ide.inspections import org.junit.Test class FortranNonstandardKindInspectionTest() : FortranInspectionsBaseTestCase(FortranNonstandardKindInspection()) { @Test fun testReal8() = checkFixByText( "Nonstandard Kind Selector fix", """program prog1 real<warning descr="Nonstandard Kind Selector">*8<caret></warning> :: a end """, """program prog1 real(kind=8) :: a end """, true) @Test fun testComplex16() = checkFixByText("Nonstandard Kind Selector fix","""program prog1 complex<warning descr="Nonstandard Kind Selector">*16<caret></warning> :: a end """, """program prog1 complex(kind=8) :: a end """, true) @Test fun testRealN() = checkFixByText("Nonstandard Kind Selector fix","""program prog1 real<warning descr="Nonstandard Kind Selector">*N<caret></warning> :: a end """, """program prog1 real(kind=N) :: a end """, true) @Test fun testComplexN() = checkFixByText("Nonstandard Kind Selector fix","""program prog1 complex<warning descr="Nonstandard Kind Selector">*N<caret></warning> :: a end """, """program prog1 complex(kind=(N)/2) :: a end """, true) }
apache-2.0
google/dokka
core/src/main/kotlin/Formats/PackageListService.kt
2
2456
package org.jetbrains.dokka import com.google.inject.Inject interface PackageListService { fun formatPackageList(module: DocumentationModule): String } class DefaultPackageListService @Inject constructor( val generator: NodeLocationAwareGenerator, val formatService: FormatService ) : PackageListService { override fun formatPackageList(module: DocumentationModule): String { val packages = mutableSetOf<String>() val nonStandardLocations = mutableMapOf<String, String>() fun visit(node: DocumentationNode, relocated: Boolean = false) { val nodeKind = node.kind when (nodeKind) { NodeKind.Package -> { packages.add(node.qualifiedName()) node.members.forEach { visit(it) } } NodeKind.Signature -> { if (relocated) nonStandardLocations[node.name] = generator.relativePathToLocation(module, node.owner!!) } NodeKind.ExternalClass -> { node.members.forEach { visit(it, relocated = true) } } NodeKind.GroupNode -> { //only children of top-level GN records interesting for us, since link to top-level ones should point to GN node.members.forEach { it.members.forEach { visit(it, relocated = true) } } //record signature of GN as signature of type alias and class merged to GN, so link to it should point to GN node.detailOrNull(NodeKind.Signature)?.let { visit(it, relocated = true) } } else -> { if (nodeKind in NodeKind.classLike || nodeKind in NodeKind.memberLike) { node.details(NodeKind.Signature).forEach { visit(it, relocated) } node.members.forEach { visit(it, relocated) } } } } } module.members.forEach { visit(it) } return buildString { appendln("\$dokka.linkExtension:${formatService.linkExtension}") nonStandardLocations.map { (signature, location) -> "\$dokka.location:$signature\u001f$location" } .sorted().joinTo(this, separator = "\n", postfix = "\n") packages.sorted().joinTo(this, separator = "\n", postfix = "\n") } } }
apache-2.0
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/studyroom/model/StudyRoom.kt
1
1984
package de.tum.`in`.tumcampusapp.component.ui.studyroom.model import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import android.arch.persistence.room.RoomWarnings import com.google.gson.annotations.SerializedName import org.joda.time.DateTime /** * Representation of a study room. */ @Entity(tableName = "study_rooms") @SuppressWarnings(RoomWarnings.DEFAULT_CONSTRUCTOR) data class StudyRoom( @PrimaryKey @SerializedName("room_id") var id: Int = -1, @SerializedName("room_code") var code: String = "", @SerializedName("room_name") var name: String = "", @ColumnInfo(name = "building_name") @SerializedName("building_name") var buildingName: String = "", @ColumnInfo(name = "group_id") @SerializedName("group_id") var studyRoomGroup: Int = -1, @ColumnInfo(name = "occupied_until") @SerializedName("occupied_until") var occupiedUntil: DateTime? = null, @ColumnInfo(name = "free_until") @SerializedName("free_until") var freeUntil: DateTime? = null ) : Comparable<StudyRoom> { override fun compareTo(other: StudyRoom): Int { // We use the following sorting order: // 1. Rooms that are currently free and don't have a reservation coming up (freeUntil == null) // 2. Rooms that are currently free but have a reservation coming up (sorted descending by // the amount of free time remaining) // 3. Rooms that are currently occupied but will be free soon (sorted ascending by the // amount of occupied time remaining) // 4. The remaining rooms return compareBy<StudyRoom> { it.freeUntil?.millis?.times(-1) } .thenBy { it.occupiedUntil } .thenBy { it.name } .compare(this, other) } override fun toString() = code }
gpl-3.0
arcuri82/testing_security_development_enterprise_systems
advanced/exercise-solutions/card-game/part-02/cards-dto/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/cards/dto/CardDto.kt
1
621
package org.tsdes.advanced.exercises.cardgame.cards.dto import io.swagger.annotations.ApiModelProperty class CardDto( @get:ApiModelProperty("The id of the card") var cardId : String? = null, @get:ApiModelProperty("The name of this card") var name : String? = null, @get:ApiModelProperty("A description of the card effects") var description: String? = null, @get:ApiModelProperty("The rarity of the card") var rarity: Rarity? = null, @get:ApiModelProperty("The id of the image associated with this card") var imageId: String? = null )
lgpl-3.0
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/Recreatable.kt
2
455
package nl.rsdt.japp.jotial import android.os.Bundle /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 31-7-2016 * Defines a interface for classes that can be recreated. */ interface Recreatable { /** * Gets invoked on the Activity's onCreate(). */ fun onCreate(savedInstanceState: Bundle?) /** * Gets invoked when the state should be saved. */ fun onSaveInstanceState(saveInstanceState: Bundle?) }
apache-2.0
androidx/androidx
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/ProgressSemanticsSamples.kt
3
1558
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.progressSemantics import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Sampled @Composable fun DeterminateProgressSemanticsSample() { val progress = 0.5f // emulate progress from some state Box( Modifier .progressSemantics(progress) .size((progress * 100).dp, 4.dp) .background(color = Color.Cyan) ) } @Sampled @Composable fun IndeterminateProgressSemanticsSample() { Box(Modifier.progressSemantics().background(color = Color.Cyan)) { Text("Operation is on progress") } }
apache-2.0
stoyicker/dinger
data/src/main/kotlin/data/tinder/recommendation/RecommendationPhoto_ProcessedFileDao.kt
1
413
package data.tinder.recommendation import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy @Dao internal interface RecommendationPhoto_ProcessedFileDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertPhoto_ProcessedFile( bond: RecommendationUserPhotoEntity_RecommendationUserPhotoProcessedFileEntity) }
mit
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/inspections/ElmLocalInspection.kt
1
1864
package org.elm.ide.inspections import com.intellij.codeInsight.intention.PriorityAction import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.elm.lang.core.psi.ElmPsiElement abstract class ElmLocalInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) if (element is ElmPsiElement) { visitElement(element, holder, isOnTheFly) } } } abstract fun visitElement(element: ElmPsiElement, holder: ProblemsHolder, isOnTheFly: Boolean) } /** * A [LocalQuickFix] base class that takes care of some of the boilerplate * * Note: [LocalQuickFix] implementations should never store a reference to a [PsiElement], since the * PSI may change between the time that they're created and called, causing the elements to be * invalid or leak memory. * * If you really need a reference to an element other than the one this fix is shown on, you can implement * [LocalQuickFixOnPsiElement], which holds a weak reference to an element. */ abstract class NamedQuickFix( private val fixName: String, private val fixPriority: PriorityAction.Priority = PriorityAction.Priority.NORMAL ) : LocalQuickFix, PriorityAction { override fun getName(): String = fixName override fun getFamilyName(): String = name override fun getPriority(): PriorityAction.Priority = fixPriority final override fun applyFix(project: Project, descriptor: ProblemDescriptor) { this.applyFix(descriptor.psiElement ?: return, project) } abstract fun applyFix(element: PsiElement, project: Project) }
mit
oleksiyp/mockk
mockk/jvm/src/test/kotlin/io/mockk/jvm/JvmAnyValueGeneratorTest.kt
1
80
package io.mockk.jvm class JvmAnyValueGeneratorTest { // TODO more tests }
apache-2.0
noemus/kotlin-eclipse
kotlin-eclipse-ui-test/testData/completion/relevance/byCamelCaseLocal.kt
1
138
val SomeVal4 = 4 val someVal1 = 1 val SomeVal3 = 3 val someVal2 = 2 fun test() { Some<caret> } // ORDER: SomeVal3 // ORDER: SomeVal4
apache-2.0
danwallach/CalWatch
app/src/main/kotlin/org/dwallach/calwatch2/Constants.kt
1
883
/* * CalWatch / CalWatch2 * Copyright © 2014-2022 by Dan S. Wallach * Home page: http://www.cs.rice.edu/~dwallach/calwatch/ * Licensing: http://www.cs.rice.edu/~dwallach/calwatch/licensing.html */ package org.dwallach.calwatch2 import org.dwallach.complications.ComplicationLocation.BOTTOM import org.dwallach.complications.ComplicationLocation.RIGHT import org.dwallach.complications.ComplicationLocation.TOP object Constants { const val PREFS_KEY = "org.dwallach.calwatch2.prefs" const val DATA_KEY = "org.dwallach.calwatch2.data" const val SETTINGS_PATH = "/settings" const val DEFAULT_WATCHFACE = ClockState.FACE_TOOL const val DEFAULT_SHOW_SECONDS = true const val DEFAULT_SHOW_DAY_DATE = true const val POWER_WARN_LOW_LEVEL = 0.33f const val POWER_WARN_CRITICAL_LEVEL = 0.1f val COMPLICATION_LOCATIONS = listOf(RIGHT, TOP, BOTTOM) }
gpl-3.0
vitorsalgado/android-boilerplate
utils/src/test/kotlin/br/com/vitorsalgado/example/utils/RxUtils.kt
1
862
package br.com.vitorsalgado.example.utils import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class RxUtils { class ImmediateSchedulersRule : TestRule { override fun apply(base: Statement, description: Description): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() } try { base.evaluate() } finally { RxJavaPlugins.reset() } } } } } }
apache-2.0
wordpress-mobile/AztecEditor-Android
aztec/src/test/kotlin/org/wordpress/aztec/AztecParserTest.kt
1
51581
@file:Suppress("DEPRECATION") package org.wordpress.aztec import android.test.AndroidTestCase import android.text.SpannableString import android.text.SpannableStringBuilder import androidx.test.core.app.ApplicationProvider import org.junit.Assert import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.robolectric.ParameterizedRobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config /** * Tests for [AztecParser]. */ @RunWith(ParameterizedRobolectricTestRunner::class) @Config(sdk = [23]) class AztecParserTest(alignmentRendering: AlignmentRendering) : AndroidTestCase() { private var mParser = AztecParser(alignmentRendering) private val HTML_BOLD = "<b>Bold</b><br><br>" private val HTML_LIST_ORDERED = "<ol><li>Ordered</li></ol>" private val HTML_LIST_ORDERED_WITH_EMPTY_ITEM = "<ol><li>Ordered 1</li><li></li><li>Ordered 2</li></ol>" private val HTML_LIST_ORDERED_WITH_QUOTE = "<ol><li><blockquote>Ordered Quote</blockquote></li></ol>" private val HTML_LIST_ORDERED_WITH_WHITE_SPACE = "<ol><li>Ordered<br></br></li></ol>" private val HTML_LIST_UNORDERED = "<ul><li>Unordered</li></ul>" private val HTML_LIST_UNORDERED_WITH_EMPTY_ITEM = "<ul><li>Unordered 1</li><li></li><li>Unordered 2</li></ul>" private val HTML_LIST_UNORDERED_WITH_QUOTE = "<ul><li><blockquote>Unordered Quote</blockquote></li></ul>" private val HTML_LIST_UNORDERED_WITH_WHITE_SPACE = "<ul><li>Unordered<br></br></li></ul>" private val HTML_COMMENT = "<!--Comment--><br><br>" private val HTML_HEADING_ALL = "<h1>Heading 1</h1><br><br><h2>Heading 2</h2><br><br><h3>Heading 3</h3><br><br><h4>Heading 4</h4><br><br><h5>Heading 5</h5><br><br><h6>Heading 6</h6><br><br>" private val HTML_HEADING_ONE = "<h1>Heading 1</h1>" private val HTML_ITALIC = "<i>Italic</i><br><br>" private val HTML_LINK = "<a href=\"https://github.com/wordpress-mobile/WordPress-Aztec-Android\">Link</a>" private val HTML_MORE = "<!--more-->" private val HTML_PAGE = "<!--nextpage-->" private val HTML_QUOTE = "<blockquote>Quote</blockquote>" private val HTML_QUOTE_EMPTY = "<blockquote></blockquote>" private val HTML_QUOTE_WITH_LIST_ORDERED = "<blockquote><ol><li>Ordered</li></ol></blockquote>" private val HTML_QUOTE_WITH_LIST_UNORDERED = "<blockquote><ul><li>Unordered</li></ul></blockquote>" private val HTML_QUOTE_WITH_WHITE_SPACE = "<blockquote>Quote<br><br></br></blockquote>" private val HTML_STRIKETHROUGH = "<s>Strikethrough</s>" // <s> or <strike> or <del> private val HTML_UNDERLINE = "<u>Underline</u><br><br>" private val HTML_UNKNOWN = "<iframe class=\"classic\">Menu</iframe><br><br>" private val HTML_COMMENT_INSIDE_UNKNOWN = "<unknown><!--more--></unknown>" private val HTML_NESTED_MIXED = "<span></span>" + "<div class=\"first\">" + "<div class=\"second\">" + "<div class=\"third\">" + "Div<br><span><b>b</b></span><br>Hidden" + "</div>" + "<div class=\"fourth\"></div>" + "<div class=\"fifth\"></div>" + "</div>" + "<span class=\"second last\"></span>" + "<span></span><div><div><div><span></span></div></div></div><div></div>" + "</div>" + "<br><br>" private val HTML_NESTED_EMPTY_END = "1<span></span><div><div><div><span></span>a</div><div></div><div></div></div><span></span></div>" private val HTML_NESTED_EMPTY_START = "<span></span><div><div><div><span></span></div><div></div></div><span></span></div>1" private val HTML_NESTED_EMPTY = "<span></span><div><div><div><span></span></div></div></div><div></div>" private val HTML_NESTED_WITH_TEXT = "<div>1<div>2<div>3<span>4</span>5</div>6</div>7</div>" private val HTML_NESTED_INTERLEAVING = "<div><div><div><span></span><div></div><span></span></div></div></div><br>" + "<div><span>1</span><br><div>2</div>3<span></span><br>4</div><br><br>5<br><br><div></div>" private val HTML_NESTED_INLINE = "<u><i><b>Nested</b></i></u>" private val HTML_HIDDEN_WITH_NO_TEXT = "<br><br><div></div><br><br>" private val HTML_EMOJI = "\uD83D\uDC4D❤" // Thumbsup + heart private val HTML_NON_LATIN_TEXT = "测试一个" private val SPAN_BOLD = "Bold\n\n" private val SPAN_LIST_ORDERED = "Ordered\n\n" private val SPAN_LIST_UNORDERED = "Unordered\n\n" private val SPAN_COMMENT = "Comment\n\n" private val SPAN_HEADING = "Heading 1\n\nHeading 2\n\nHeading 3\n\nHeading 4\n\nHeading 5\n\nHeading 6\n\n" private val SPAN_ITALIC = "Italic\n\n" private val SPAN_LINK = "Link\n\n" private val SPAN_MORE = "more\n\n" private val SPAN_PAGE = "page\n\n" private val SPAN_QUOTE = "Quote\n\n" private val SPAN_STRIKETHROUGH = "Strikethrough\n\n" private val SPAN_UNDERLINE = "Underline\n\n" private val SPAN_UNKNOWN = "\uFFFC\n\n" companion object { @JvmStatic @ParameterizedRobolectricTestRunner.Parameters(name = "Testing parser with AlignmentRendering.{0}") fun data(): Collection<Array<AlignmentRendering>> { return listOf( arrayOf(AlignmentRendering.SPAN_LEVEL), arrayOf(AlignmentRendering.VIEW_LEVEL) ) } } /** * Initialize variables. */ @Before fun init() { context = ApplicationProvider.getApplicationContext() } /** * Parse all text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlAll_isEqual() { val input = HTML_HEADING_ALL + HTML_BOLD + HTML_ITALIC + HTML_UNDERLINE + HTML_STRIKETHROUGH + HTML_LIST_ORDERED + HTML_LIST_ORDERED_WITH_EMPTY_ITEM + HTML_LIST_ORDERED_WITH_QUOTE + HTML_LIST_UNORDERED + HTML_LIST_UNORDERED_WITH_EMPTY_ITEM + HTML_LIST_UNORDERED_WITH_QUOTE + HTML_QUOTE + HTML_LINK + HTML_UNKNOWN + HTML_QUOTE_WITH_LIST_ORDERED + HTML_QUOTE_WITH_LIST_UNORDERED + HTML_QUOTE_EMPTY + HTML_COMMENT + HTML_NESTED_MIXED + HTML_NESTED_EMPTY_END + HTML_NESTED_EMPTY_START + HTML_NESTED_EMPTY + HTML_NESTED_WITH_TEXT + HTML_NESTED_INTERLEAVING + HTML_EMOJI + HTML_NON_LATIN_TEXT val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse bold text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlBold_isEqual() { val input = HTML_BOLD val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse unordered list text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnordered_isEqual() { val input = HTML_LIST_UNORDERED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse unordered list with quote from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnorderedWithQuote_isEqual() { val input = HTML_LIST_UNORDERED_WITH_QUOTE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse unordered list with quote surrounded by text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnorderedWithQuoteSurroundedByText_isEqual() { val input = "One" + HTML_LIST_UNORDERED_WITH_QUOTE + "Two" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse unordered list with white space text from HTML to span to HTML. If input without white space and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnorderedWhiteSpace_isEqual() { val input = HTML_LIST_UNORDERED_WITH_WHITE_SPACE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(HTML_LIST_UNORDERED, output) } /** * Parse ordered list text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrdered_isEqual() { val input = HTML_LIST_ORDERED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse ordered list with quote from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedWithQuote_isEqual() { val input = HTML_LIST_ORDERED_WITH_QUOTE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse ordered list with quote surrounded by text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedWithQuoteSurroundedByText_isEqual() { val input = "One" + HTML_LIST_ORDERED_WITH_QUOTE + "Two" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse ordered list with white space text from HTML to span to HTML. If input without white space and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedWhiteSpace_isEqual() { val input = HTML_LIST_ORDERED_WITH_WHITE_SPACE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(HTML_LIST_ORDERED, output) } /** * Parse ordered list surrounded text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedSurroundedByText_isEqual() { val input = "1" + HTML_LIST_ORDERED + "2" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse ordered list surrounded text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedSurroundedByNewlineAndText_isEqual() { val input = "1<br>$HTML_LIST_ORDERED<br>2" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse ordered lists with text between from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListsWithTextBetween_isEqual() { val input = HTML_LIST_ORDERED + "1" + HTML_LIST_ORDERED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse block elements with preceding newline from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlLinebreakFollowedByBlock_isEqual() { var input: String var output: String var span: SpannableString input = "<br>$HTML_HEADING_ONE" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) Assert.assertEquals("\nHeading 1", span.toString()) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "Text<br>$HTML_HEADING_ONE" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "<br>$HTML_QUOTE" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) Assert.assertEquals("\nQuote", span.toString()) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "Text<br>$HTML_QUOTE" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "<br>$HTML_LIST_ORDERED" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) Assert.assertEquals("\nOrdered", span.toString()) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "Text<br>$HTML_LIST_ORDERED" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "<br>$HTML_LIST_UNORDERED" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) Assert.assertEquals("\nUnordered", span.toString()) output = mParser.toHtml(span) Assert.assertEquals(input, output) input = "Text<br>$HTML_LIST_UNORDERED" span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse comment text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlComment_isEqual() { val input = HTML_COMMENT val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse heading text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlHeading_isEqual() { val input = HTML_HEADING_ALL val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse italic text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlItalic_isEqual() { val input = HTML_ITALIC val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse link text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlLink_isEqual() { val input = HTML_LINK val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse more comment text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlMore_isEqual() { val input = HTML_MORE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse page comment text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlPage_isEqual() { val input = HTML_PAGE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse quote text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlQuote_isEqual() { val input = HTML_QUOTE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse empty quote text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlQuoteEmpty_isEqual() { val input = HTML_QUOTE_EMPTY val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse quote text with white space from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlQuoteWithWhiteSpace_isEqual() { val input = HTML_QUOTE_WITH_WHITE_SPACE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(HTML_QUOTE, output) } /** * Parse quote with ordered list from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlQuoteWithListOrdered_isEqual() { val input = HTML_QUOTE_WITH_LIST_ORDERED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse quote with unordered list from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlQuoteWithListUnordered_isEqual() { val input = HTML_QUOTE_WITH_LIST_UNORDERED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse strikethrough text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlStrikethrough_isEqual() { val input = HTML_STRIKETHROUGH val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse underline text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlUnderline_isEqual() { val input = HTML_UNDERLINE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse unknown text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlUnknown_isEqual() { val input = HTML_UNKNOWN val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse nested blocks text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedMixed_isEqual() { val input = HTML_NESTED_MIXED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse nested blocks text from HTML to span to HTML twice with the same spannable string * instance. If input and output are equal with the same length and corresponding characters, * [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedMixedTwice_isEqual() { val input = HTML_NESTED_MIXED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) Assert.assertEquals(input, mParser.toHtml(span)) Assert.assertEquals(input, mParser.toHtml(span)) } /** * Parse empty nested blocks text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedEmpty_isEqual() { val input = HTML_NESTED_EMPTY val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse empty nested blocks at the end from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedEmptyEnd_isEqual() { val input = HTML_NESTED_EMPTY_END val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse empty nested blocks at the beginning from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedEmptyStart_isEqual() { val input = HTML_NESTED_EMPTY_START val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse non-empty nested blocks text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedNonEmpty_isEqual() { val input = HTML_NESTED_WITH_TEXT val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse interleaving nested blocks text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedInterleaving_isEqual() { val input = HTML_NESTED_INTERLEAVING val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse hidden HTML with no text from HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHiddenHtmlWithNoTextToSpanToHtmlNestedInterleaving_isEqual() { val input = HTML_HIDDEN_WITH_NO_TEXT val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun preserveListListUnorderedWithEmptyListItem() { val input = HTML_LIST_UNORDERED_WITH_EMPTY_ITEM val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun preserveListOrderedWithEmptyListItem() { val input = HTML_LIST_ORDERED_WITH_EMPTY_ITEM val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse all text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanAll_isEqual() { val input = SpannableString( SPAN_HEADING + SPAN_BOLD + SPAN_ITALIC + SPAN_UNDERLINE + SPAN_STRIKETHROUGH + SPAN_LIST_UNORDERED + SPAN_QUOTE + SPAN_LINK + SPAN_UNKNOWN + SPAN_COMMENT ) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse bold text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanBold_isEqual() { val input = SpannableString(SPAN_BOLD) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse ordered list text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanListOrdered_isEqual() { val input = SpannableString(SPAN_LIST_ORDERED) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse unordered list text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanListUnordered_isEqual() { val input = SpannableString(SPAN_LIST_UNORDERED) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse comment text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanComment_isEqual() { val input = SpannableString(SPAN_COMMENT) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse heading text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanHeading_isEqual() { val input = SpannableString(SPAN_HEADING) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse italic text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanItalic_isEqual() { val input = SpannableString(SPAN_ITALIC) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse link text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanLink_isEqual() { val input = SpannableString(SPAN_LINK) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse more comment text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanMore_isEqual() { val input = SpannableString(SPAN_MORE) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse page comment text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanPage_isEqual() { val input = SpannableString(SPAN_PAGE) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse quote text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanQuote_isEqual() { val input = SpannableString(SPAN_QUOTE) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse strikethrough text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanStrikethrough_isEqual() { val input = SpannableString(SPAN_STRIKETHROUGH) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse underline text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanUnderline_isEqual() { val input = SpannableString(SPAN_UNDERLINE) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse unknown text from span to HTML to span. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseSpanToHtmlToSpanUnknown_isEqual() { val input = SpannableString(SPAN_UNKNOWN) val html = mParser.toHtml(input) val output = mParser.fromHtml(html, RuntimeEnvironment.application.applicationContext) Assert.assertEquals(input, output) } /** * Parse comment tag nested inside unknown HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlCommentInsideUnknown_isEqual() { val input = HTML_COMMENT_INSIDE_UNKNOWN val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse single heading HTML to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlSingleHeading_isEqual() { val input = HTML_HEADING_ONE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse HTML of heading surrounded by text to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlSingleHeadingSurroundedByText_isEqual() { val input = "1" + HTML_HEADING_ONE + "1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse HTML of heading surrounded by list to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlHeadingSurroundedByList_isEqual() { val input = HTML_LIST_ORDERED + HTML_HEADING_ONE + HTML_LIST_ORDERED val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse HTML of heading surrounded by quote to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlHeadingSurroundedByQuote_isEqual() { val input = HTML_QUOTE + HTML_HEADING_ONE + HTML_QUOTE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse HTML of heading surrounded by quote to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlLineBreakBetweenHeadings_isEqual() { val input = HTML_HEADING_ONE + "<br>" + HTML_HEADING_ONE val span = SpannableStringBuilder(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse HTML of nested inline text style to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlNestedInlineStyles_isEqual() { val input = HTML_NESTED_INLINE val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedWithTrailingEmptyItem_isEqual() { val input = "<ol><li>Ordered item</li><li></li></ol>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnorderedWithLinebreak_isEqual() { val input = "<ul><li>a</li></ul><br>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListOrderedWithTrailingEmptyItemAndLinebreak_isEqual() { val input = "<ol><li>Ordered item</li><li></li></ol><br>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnorderedFollowedByLinebreak_isEqual() { val input = "<ul><li>Ordered item</li><li>b</li></ul><br>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListUnorderedFollowedByUnknwonHtml_isEqual() { val input = HTML_LIST_UNORDERED + HTML_UNKNOWN val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Parse HTML of header with single character surrounded by other headers to span to HTML. If input and output are equal with * the same length and corresponding characters, [AztecParser] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlSingleCharHeaderSurroundedByHeaders_isEqual() { val input = "<h1>Heading 1</h1><h2>2</h2><h3>Heading 3</h3>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlOrderedListWithTrailingEmptyItemAnd2Linebreaks_isEqual() { val input = "<ol><li>Ordered item</li><li></li></ol><br><br>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlUnorderedListFollowedBy2Linebreaks_isEqual() { val input = "<ul><li>Ordered item</li><li>b</li></ul><br><br>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListWithEmptyItemFollowedByText_isEqual() { val input = "<ol><li>Ordered item</li><li></li></ol>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListWithNonEmptyItemsFollowedByText_isEqual() { val input = "<ol><li>Ordered item</li><li>a</li></ol>1" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlBrAfterHeadings_isEqual() { val input = "<h1>h1</h1><br><h2>h2</h2><br><h3>h3</h3><br>" val span = SpannableStringBuilder(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlBrAfterHeadings2_isEqual() { val input = "<ol><li><ul><li>supernesting</li></ul></li></ol><br>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Currently, this html <p>Hello There!<br></p> after being parsed to span and back to html will become * <p>Hello There!</p>. * This is not a bug, this is how we originally implemented the function that cleans the HTML input * in AztecParser->tidy method. * * Since we're using this editor in Gutenberg Mobile project, where the selection could be sent from * the JS side to the native, we needed to take in consideration this behavior of Aztec in GB-mobile, * and modify the logic that does set the selection accordingly. * * This test just checks that the underlying parser is working as expected. */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlBrBeforePara_isNotEqual() { val input = "<p>Hello There!<br></p>" val expectedOutput = "<p>Hello There!</p>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(expectedOutput, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlBrBeforePara2_isNotEqual() { val input = "<p>Hello There!<br><br><br><br></p>" val expectedOutput = "<p>Hello There!</p>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(expectedOutput, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlMixedContentInListItem_isEqual() { val input = "<ul><li>some text<blockquote>Quote</blockquote>some text</li></ul>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlProperVisualNewlineSync_isEqual() { val input = "<blockquote>Hello</blockquote><u>Bye</u><blockquote>Hello</blockquote>End" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Ignore("Until this issue is fixed: https://github.com/wordpress-mobile/AztecEditor-Android/issues/434") @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlListInDiv_isEqual() { val input = "<div>" + HTML_LIST_UNORDERED + "</div>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Ignore("Until this issue is fixed: https://github.com/wordpress-mobile/AztecEditor-Android/issues/434") @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlBrBeforeAndAfterDiv_isEqual() { val input = "<br><div><br></div>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } /** * Currently, this html <b>bold <i>italic</i> bold</b> after being parsed to span and back to html will become * <b>bold </b><b><i>italic</i></b><b> bold</b>. * This is not a bug, this is how Google originally implemented the parsing inside Html.java. * https://github.com/wordpress-mobile/AztecEditor-Android/issues/136 * * This test just checks that the underlying parser is working as expected. */ @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlMixedBoldAndItalic_isNotEqual() { val input = "<b>bold <i>italic</i> bold</b>" val inputAfterParser = "<b>bold </b><b><i>italic</i></b><b> bold</b>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(output, inputAfterParser) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlParagraphInsideHiddenSpan_isEqual() { val input = "<p>a</p><div><p>b</p></div><p>c</p>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(input, output) } @Test @Throws(Exception::class) fun parseHtmlToSpanToHtmlParagraphWithMultipleWhitespace_isNotEqual() { val input = "<p> Hello There!</p>" val inputAfterParser = "<p>Hello There!</p>" val span = SpannableString(mParser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = mParser.toHtml(span) Assert.assertEquals(output, inputAfterParser) } }
mpl-2.0
adgvcxz/Diycode
app/src/main/java/com/adgvcxz/diycode/util/AppBlockCanaryContext.kt
1
3745
package com.adgvcxz.diycode.util import com.github.moduth.blockcanary.BlockCanaryContext import java.io.File import java.util.* /** * zhaowei * Created by zhaowei on 2017/2/14. */ class AppBlockCanaryContext: BlockCanaryContext() { /** * Implement in your project. * @return Qualifier which can specify this installation, like version + flavor. */ override fun provideQualifier(): String { return "unknown" } /** * Implement in your project. * @return user id */ override fun provideUid(): String { return "uid" } /** * Network type * @return [String] like 2G, 3G, 4G, wifi, etc. */ override fun provideNetworkType(): String { return "unknown" } /** * Config monitor duration, after this time BlockCanary will stop, use * with `BlockCanary`'s isMonitorDurationEnd * @return monitor last duration (in hour) */ override fun provideMonitorDuration(): Int { return -1 } /** * Config block threshold (in millis), dispatch over this duration is regarded as a BLOCK. You may set it * from performance of device. * @return threshold in mills */ override fun provideBlockThreshold(): Int { return 1000 } /** * Thread stack dump interval, use when block happens, BlockCanary will dump on main thread * stack according to current sample cycle. * * * Because the implementation mechanism of Looper, real dump interval would be longer than * the period specified here (especially when cpu is busier). * * @return dump interval (in millis) */ override fun provideDumpInterval(): Int { return provideBlockThreshold() } /** * Path to save log, like "/blockcanary/", will save to sdcard if can. * @return path of log files */ override fun providePath(): String { return "/blockcanary/" } /** * If need notification to notice block. * @return true if need, else if not need. */ override fun displayNotification(): Boolean { return true } /** * Implement in your project, bundle files into a zip file. * @param src files before compress * * * @param dest files compressed * * * @return true if compression is successful */ override fun zip(src: Array<File>?, dest: File?): Boolean { return false } /** * Implement in your project, bundled log files. * @param zippedFile zipped file */ override fun upload(zippedFile: File?) { throw UnsupportedOperationException() } /** * Packages that developer concern, by default it uses process name, * put high priority one in pre-order. * @return null if simply concern only package with process name. */ override fun concernPackages(): List<String>? { return null } /** * Filter stack without any in concern package, used with @{code concernPackages}. * @return true if filter, false it not. */ override fun filterNonConcernStack(): Boolean { return false } /** * Provide white list, entry in white list will not be shown in ui list. * @return return null if you don't need white-list filter. */ override fun provideWhiteList(): List<String> { val whiteList = LinkedList<String>() whiteList.add("org.chromium") return whiteList } /** * Whether to delete files whose stack is in white list, used with white-list. * @return true if delete, false it not. */ override fun deleteFilesInWhiteList(): Boolean { return true } }
apache-2.0
world-federation-of-advertisers/panel-exchange-client
src/test/kotlin/org/wfanet/panelmatch/common/beam/WriteShardedDataTest.kt
1
2470
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.common.beam import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import com.google.protobuf.stringValue import java.io.File import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.storage.StorageClient import org.wfanet.measurement.storage.filesystem.FileSystemStorageClient import org.wfanet.panelmatch.common.ShardedFileName import org.wfanet.panelmatch.common.beam.testing.BeamTestBase import org.wfanet.panelmatch.common.storage.StorageFactory import org.wfanet.panelmatch.common.testing.runBlockingTest @RunWith(JUnit4::class) class WriteShardedDataTest : BeamTestBase() { @get:Rule val temporaryFolder = TemporaryFolder() @Test fun assignToShardReturnsNonNegativeValueForIntMinValue() { val shardCount = 10 val item = object { override fun hashCode(): Int = Int.MIN_VALUE } val shard = item.assignToShard(shardCount) assertThat(shard).isAtLeast(0) assertThat(shard).isLessThan(shardCount) } @Test fun addsAllFilesInFileSpec() = runBlockingTest { val shardedFileName = ShardedFileName("foo-*-of-10") val rootPath = temporaryFolder.root.absolutePath val storageFactory = object : StorageFactory { override fun build(): StorageClient { return FileSystemStorageClient(File(rootPath)) } } val input = pcollectionOf("Input", stringValue { value = "some-input" }) input.apply(WriteShardedData(shardedFileName.spec, storageFactory)) pipeline.run() val client = storageFactory.build() for (filename in shardedFileName.fileNames) { assertWithMessage("Shard $filename").that(client.getBlob(filename)).isNotNull() } } }
apache-2.0
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/users/dto/UsersCareer.kt
1
2396
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.users.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import kotlin.Int import kotlin.String /** * @param cityId - City ID * @param cityName - City name * @param company - Company name * @param countryId - Country ID * @param from - From year * @param groupId - Community ID * @param id - Career ID * @param position - Position * @param until - Till year */ data class UsersCareer( @SerializedName("city_id") val cityId: Int? = null, @SerializedName("city_name") val cityName: String? = null, @SerializedName("company") val company: String? = null, @SerializedName("country_id") val countryId: Int? = null, @SerializedName("from") val from: Int? = null, @SerializedName("group_id") val groupId: UserId? = null, @SerializedName("id") val id: Int? = null, @SerializedName("position") val position: String? = null, @SerializedName("until") val until: Int? = null )
mit
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/parser/ParsedDataTypes.kt
1
9404
package org.jetbrains.haskell.debugger.parser import java.util.ArrayList import org.json.simple.JSONObject import java.io.File /** * This file contains data types for holding parsed information * * @author Habibullin Marat */ public open class ParseResult public class BreakpointCommandResult(public val breakpointNumber: Int, public val position: HsFilePosition) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as BreakpointCommandResult return breakpointNumber == othCasted.breakpointNumber && position.equals(othCasted.position) } override fun hashCode(): Int { val prime = 31; var result = 1; result = prime * result + breakpointNumber result = prime * result + position.hashCode() return result } } public class HsFilePosition(public val filePath: String, public val rawStartLine: Int, public val rawStartSymbol: Int, public val rawEndLine: Int, public val rawEndSymbol: Int) : ParseResult() { // zero based start line number public val normalizedStartLine: Int = rawStartLine - 1 public val normalizedStartSymbol: Int = rawStartSymbol // zero based end line number public val normalizedEndLine: Int = rawEndLine - 1 // ghci returns value for end symbol that is less for 1 than idea uses. so normalizedEndSymbol contains corrected one public val normalizedEndSymbol: Int = rawEndSymbol + 1 public val simplePath: String = filePath.substring(if (filePath.contains("/")) filePath.lastIndexOf('/') + 1 else 0) public fun spanToString(): String { if (rawStartLine == rawEndLine) { if (rawStartSymbol == rawEndSymbol) { return "$rawStartLine:$rawStartSymbol" } else { return "$rawStartLine:$rawStartSymbol-$rawEndSymbol" } } else { return "($rawStartLine,$rawStartSymbol)-($rawEndLine,$rawEndSymbol)" } } public fun getFileName(): String = File(filePath).getName() override fun toString(): String = "${getFileName()}:${spanToString()}" override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as HsFilePosition return filePath.equals(othCasted.filePath) && rawStartLine == othCasted.rawStartLine && rawEndLine == othCasted.rawEndLine && rawStartSymbol == othCasted.rawStartSymbol && rawEndSymbol == othCasted.rawEndSymbol } override fun hashCode(): Int { val prime = 31; var result = 1; result = prime * result + filePath.hashCode() result = prime * result + rawStartLine result = prime * result + rawEndLine result = prime * result + rawStartSymbol result = prime * result + rawEndSymbol return result } } public class BreakInfo(public val breakIndex: Int, public val srcSpan: HsFilePosition) : ParseResult() public class BreakInfoList(public val list: ArrayList<BreakInfo>) : ParseResult() public class ExceptionResult(public val message: String) : ParseResult() //public class CallInfo(public val index: Int, public val function: String, public val position: FilePosition): ParseResult() //public class HistoryResult(public val list: ArrayList<CallInfo>) : ParseResult() public class LocalBinding(var name: String?, var typeName: String?, var value: String?) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as LocalBinding return name == othCasted.name && typeName == othCasted.typeName && value == othCasted.value } override fun hashCode(): Int { val prime = 31; var result = 1; result = prime * result + (name?.hashCode() ?: 0) result = prime * result + (typeName?.hashCode() ?: 0) result = prime * result + (value?.hashCode() ?: 0) return result } } public class LocalBindingList(public val list: ArrayList<LocalBinding>) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as LocalBindingList var bindingsAreEq = true if (list.size() != othCasted.list.size()) { bindingsAreEq = false } else { for (i in 0..list.size() - 1) { if (list.get(i) != othCasted.list.get(i)) { bindingsAreEq = false break } } } return bindingsAreEq } } public open class HsStackFrameInfo(val filePosition: HsFilePosition?, var bindings: ArrayList<LocalBinding>?, val functionName: String?) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as HsStackFrameInfo var bindingsAreEq = true if (bindings != null && othCasted.bindings != null && bindings!!.size() != othCasted.bindings!!.size()) { bindingsAreEq = false } else { for (i in 0..bindings!!.size() - 1) { if (bindings!!.get(i) != othCasted.bindings!!.get(i)) { bindingsAreEq = false break } } } return bindingsAreEq && filePosition == othCasted.filePosition && functionName == othCasted.functionName } } public class HsHistoryFrameInfo(public val index: Int, public val function: String?, public val filePosition: HsFilePosition?) : ParseResult() { override fun toString(): String { return if (function != null) "$function : $filePosition" else filePosition.toString() } override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as HsHistoryFrameInfo return index == othCasted.index && function == othCasted.function && filePosition == othCasted.filePosition } override fun hashCode(): Int { val prime = 31; var result = 1; result = prime * result + index result = prime * result + (function?.hashCode() ?: 0) result = prime * result + (filePosition?.hashCode() ?: 0) return result } } public class ExpressionType(public val expression: String, public val expressionType: String) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as ExpressionType return expression == othCasted.expression && expressionType == othCasted.expressionType } override fun hashCode(): Int { val prime = 31; var result = 1; result = prime * result + expression.hashCode() result = prime * result + expressionType.hashCode() return result } } public class EvalResult(public val expressionType: String, public val expressionValue: String) : ParseResult() public class ShowOutput(public val output: String) : ParseResult() public class MoveHistResult(public val filePosition: HsFilePosition?, public val bindingList: LocalBindingList) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as MoveHistResult return filePosition == othCasted.filePosition && bindingList == othCasted.bindingList } } public class HistoryResult(public val frames: ArrayList<HsHistoryFrameInfo>, public val full: Boolean) : ParseResult() { override fun equals(other: Any?): Boolean { if (other identityEquals this) return true if (other == null || other.javaClass != this.javaClass) return false val othCasted = other as HistoryResult var framesAreEq = true if (frames.size() != othCasted.frames.size()) { framesAreEq = false } else { for (i in 0..frames.size() - 1) { if (frames.get(i) != othCasted.frames.get(i)) { framesAreEq = false break } } } return framesAreEq && full == othCasted.full } } public class JSONResult(public val json: JSONObject) : ParseResult()
apache-2.0
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/utils/response/ResponseBuilder.kt
1
3549
package xyz.gnarbot.gnar.utils.response import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.requests.RestAction import org.apache.commons.lang3.exception.ExceptionUtils import xyz.gnarbot.gnar.utils.EmbedProxy import xyz.gnarbot.gnar.utils.Utils import java.awt.Color import javax.annotation.CheckReturnValue open class ResponseBuilder(private val channel: MessageChannel) { /** * Quick-reply to a message. * * @param text The text to send. * @return The Message created by this function. */ open fun text(text: String): RestAction<Message> { return channel.sendMessage(text) } /** * Send a standard info message. * * @param msg The text to send. * @return The Message created by this function. */ open fun info(msg: String): RestAction<Message> { return embed { desc { msg } }.action() } /** * Send a standard error message. * * @param msg The text to send. * @return The Message created by this function. */ open fun error(msg: String): RestAction<Message> { return embed { title { "Error" } desc { msg } color { Color.RED } }.action() } /** * Send a standard exception message. * * @return The Message created by this function. */ open fun exception(exception: Exception): RestAction<Message> { if (exception.toString().contains("decoding")) { return embed { title { "Exception" } desc { buildString { append("```\n") append(exception.toString()) append("```\n") val link = Utils.hasteBin(ExceptionUtils.getStackTrace(exception)) if (link != null) { append("[Full stack trace.](").append("Probably a music error tbh").append(')') } else { append("HasteBin down.") } } } color { Color.RED } }.action() } return embed { title { "Exception" } desc { buildString { append("For some reason this track causes errors, ignore this.") } } color { Color.RED } }.action() } /** * Creates an EmbedBuilder to be used to creates an embed to send. */ open fun embed(): ResponseEmbedBuilder = embed(null) /** * Creates an EmbedBuilder to be used to creates an embed to send. * * @param title Title of the embed. */ open fun embed(title: String?): ResponseEmbedBuilder = ResponseEmbedBuilder().apply { title { title } } /** * Creates an EmbedBuilder to be used to creates an embed to send. * This builder can use [ResponseEmbedBuilder.action] to quickly send the built embed. * * @param title Title of the embed. */ inline fun embed(title: String? = null, value: ResponseEmbedBuilder.() -> Unit): ResponseEmbedBuilder { return embed(title).apply(value) } inner class ResponseEmbedBuilder : EmbedProxy<ResponseEmbedBuilder>() { @CheckReturnValue fun action(): RestAction<Message> { return channel.sendMessage(build()) } } }
mit
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/account/dto/AccountPushConversations.kt
1
1759
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.account.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.collections.List /** * @param count - Items count * @param items */ data class AccountPushConversations( @SerializedName("count") val count: Int? = null, @SerializedName("items") val items: List<AccountPushConversationsItem>? = null )
mit
why168/AndroidProjects
KotlinLearning/app/src/main/java/com/github/why168/kotlinlearn/Constants.kt
1
795
package com.github.why168.kotlinlearn /** * * * @author Edwin.Wu * @version 2018/2/23 上午11:31 * @since JDK1.8 */ class Constants { companion object { const val BASE_URL = "http://baobab.kaiyanapp.com/api/" const val ERROR_NETWORK_1: String = " 网络不给力 " const val ERROR_NETWORK_2: String = "网络异常,请检查你的网络!" const val HTTP_STATUS_0: Int = 0 const val HTTP_STATUS_1: Int = 1 const val HTTP_STATUS_2: Int = 2 const val HTTP_STATUS_3: Int = 3 const val HTTP_STATUS_4: Int = 4 const val HTTP_STATUS_5: Int = 5 const val HTTP_STATUS_6: Int = 6 const val HTTP_STATUS_7: Int = 7 const val HTTP_STATUS_8: Int = 8 const val HTTP_STATUS_9: Int = 9 } }
mit
ZieIony/Carbon
samples/src/main/java/tk/zielony/carbonsamples/component/AvatarTextRatingSubtextDateListItemActivity.kt
1
4165
package tk.zielony.carbonsamples.component import android.graphics.drawable.Drawable import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import carbon.component.AvatarTextRatingSubtextDateRow import carbon.component.DefaultAvatarTextRatingSubtextDateItem import carbon.component.DefaultHeaderItem import carbon.component.PaddedHeaderRow import carbon.recycler.RowListAdapter import carbon.recycler.ViewItemDecoration import kotlinx.android.synthetic.main.activity_listcomponent.* import tk.zielony.carbonsamples.R import tk.zielony.carbonsamples.SampleAnnotation import tk.zielony.carbonsamples.ThemedActivity import tk.zielony.randomdata.RandomData import tk.zielony.randomdata.Target import tk.zielony.randomdata.common.DateGenerator import tk.zielony.randomdata.common.IntegerGenerator import tk.zielony.randomdata.common.TextGenerator import tk.zielony.randomdata.person.DrawableAvatarGenerator import tk.zielony.randomdata.person.StringNameGenerator import tk.zielony.randomdata.transformer.DateToStringTransformer import java.io.Serializable @SampleAnnotation(layoutId = R.layout.activity_listcomponent, titleId = R.string.avatarTextRatingSubtextDateListItemActivity_title) class AvatarTextRatingSubtextDateListItemActivity : ThemedActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() val randomData = RandomData().apply { addGenerator(Drawable::class.java, DrawableAvatarGenerator(this@AvatarTextRatingSubtextDateListItemActivity)) addGenerator(String::class.java, StringNameGenerator().withMatcher { f: Target -> f.name == "text" && f.declaringClass == DefaultAvatarTextRatingSubtextDateItem::class.java }) addGenerator(Int::class.java, IntegerGenerator(0, 5).withMatcher { f: Target -> f.name == "rating" }) addGenerator(String::class.java, TextGenerator().withMatcher { f: Target -> f.name == "subtext" }) addGenerator(String::class.java, DateGenerator().withTransformer(DateToStringTransformer()).withMatcher { f: Target -> f.name == "date" }) } val adapter = RowListAdapter<Serializable>().apply { putFactory(DefaultAvatarTextRatingSubtextDateItem::class.java, { AvatarTextRatingSubtextDateRow(it) }) putFactory(DefaultHeaderItem::class.java, { PaddedHeaderRow(it) }) } adapter.items = listOf( DefaultHeaderItem("Header"), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), DefaultHeaderItem("Header"), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), DefaultHeaderItem("Header"), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), DefaultHeaderItem("Header"), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java), randomData.generate(DefaultAvatarTextRatingSubtextDateItem::class.java)) recycler.layoutManager = LinearLayoutManager(this) recycler.adapter = adapter val paddingItemDecoration = ViewItemDecoration(this, R.layout.carbon_row_padding) paddingItemDecoration.setDrawBefore { it == 0 } paddingItemDecoration.setDrawAfter { it == adapter.itemCount - 1 } recycler.addItemDecoration(paddingItemDecoration) } }
apache-2.0
JavaEden/Orchid
plugins/OrchidForms/src/main/kotlin/com/eden/orchid/forms/model/FormFieldList.kt
2
1407
package com.eden.orchid.forms.model import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.theme.components.ModularPageList import java.util.function.Function import javax.inject.Provider import javax.inject.Inject class FormFieldList : ModularPageList<FormFieldList, FormField>(Function { getFieldInputTypes(it) }) { private var extraFields = mutableMapOf<String, Boolean>() override fun getItemClass(): Class<FormField> { return FormField::class.java } fun addExtraField(extraFieldKey: String, fieldName: String, fieldValue: String) { if(!extraFields.containsKey(extraFieldKey)) { add(mapOf( "type" to "hidden", "key" to fieldName, "value" to fieldValue, "order" to Integer.MAX_VALUE )) extraFields[extraFieldKey] = true } } companion object { fun getFieldInputTypes(context: OrchidContext): Map<String, Class<FormField>> { val fieldTypes = HashMap<String, Class<FormField>>() val itemTypes = context.resolveSet(FormField::class.java) for (itemType in itemTypes) { for (itemTypeAtKey in itemType.inputTypes) { fieldTypes[itemTypeAtKey] = itemType.javaClass } } return fieldTypes } } }
lgpl-3.0
Jire/Arrowhead
src/main/kotlin/org/jire/arrowhead/ProcessBy.kt
1
1849
/* * Copyright 2016 Thomas Nappo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("ProcessBy") package org.jire.arrowhead import com.sun.jna.Platform import com.sun.jna.platform.win32.WinNT import org.jire.arrowhead.linux.LinuxProcess import org.jire.arrowhead.windows.Windows import java.util.* /** * Attempts to open a process of the specified process ID. * * @param processID The ID of the process to open. */ @JvmOverloads fun processByID(processID: Int, accessFlags: Int = WinNT.PROCESS_ALL_ACCESS): Process? = when { Platform.isWindows() || Platform.isWindowsCE() -> Windows.openProcess(processID, accessFlags) Platform.isLinux() -> LinuxProcess(processID) else -> null } /** * Attempts to open a process of the specified process name. * * @param processName The name of the process to open. */ @JvmOverloads fun processByName(processName: String, accessFlags: Int = WinNT.PROCESS_ALL_ACCESS): Process? = when { Platform.isWindows() || Platform.isWindowsCE() -> Windows.openProcess(processName, accessFlags) Platform.isLinux() -> { val search = Runtime.getRuntime().exec(arrayOf("bash", "-c", "ps -A | grep -m1 \"$processName\" | awk '{print $1}'")) val scanner = Scanner(search.inputStream) val processID = scanner.nextInt() scanner.close() processByID(processID) } else -> null }
apache-2.0
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/recycling_glass/DetermineRecyclingGlass.kt
1
1620
package de.westnordost.streetcomplete.quests.recycling_glass import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.quest.AllCountriesExcept import de.westnordost.streetcomplete.quests.recycling_glass.RecyclingGlass.* class DetermineRecyclingGlass : OsmFilterQuestType<RecyclingGlass>() { override val elementFilter = """ nodes with amenity = recycling and recycling_type = container and recycling:glass = yes and !recycling:glass_bottles """ override val commitMessage = "Determine whether any glass or just glass bottles can be recycled here" override val wikiLink = "Key:recycling" override val icon = R.drawable.ic_quest_recycling_glass // see isUsuallyAnyGlassRecycleableInContainers.yml override val enabledInCountries = AllCountriesExcept("CZ") override val isDeleteElementEnabled = true override fun getTitle(tags: Map<String, String>) = R.string.quest_recycling_glass_title override fun createForm() = DetermineRecyclingGlassForm() override fun applyAnswerTo(answer: RecyclingGlass, changes: StringMapChangesBuilder) { when(answer) { ANY -> { // to mark that it has been checked changes.add("recycling:glass_bottles", "yes") } BOTTLES -> { changes.add("recycling:glass_bottles", "yes") changes.modify("recycling:glass", "no") } } } }
gpl-3.0
wagnermarques/somewritings
android/aula_sobre_activity/projeto/ProjSobreActivity/app/src/test/java/com/example/wagner/projsobreactivity/ExampleUnitTest.kt
1
361
package com.example.wagner.projsobreactivity import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
gpl-3.0
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryBoundarySpaceDeclPsiImpl.kt
1
934
/* * Copyright (C) 2016 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryBoundarySpaceDecl class XQueryBoundarySpaceDeclPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryBoundarySpaceDecl
apache-2.0
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/debug/frame/QueryResultNamedValue.kt
1
1303
/* * Copyright (C) 2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.processor.debug.frame import com.intellij.xdebugger.frame.XNamedValue import com.intellij.xdebugger.frame.XValueNode import com.intellij.xdebugger.frame.XValuePlace import uk.co.reecedunn.intellij.plugin.processor.debug.frame.presentation.QueryValuePresentation import uk.co.reecedunn.intellij.plugin.processor.query.QueryResult class QueryResultNamedValue(name: String, private val result: QueryResult) : XNamedValue(name) { override fun computePresentation(node: XValueNode, place: XValuePlace) { val presentation = QueryValuePresentation.forValue(result.value.toString(), result.type) node.setPresentation(null, presentation, false) } }
apache-2.0
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogCustomizationSetContent.kt
1
1648
package com.habitrpg.android.habitica.ui.views.shops import android.content.Context import android.widget.TextView import com.google.android.flexbox.FlexboxLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.DialogPurchaseCustomizationsetBinding import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.common.habitica.extensions.dpToPx import com.habitrpg.common.habitica.extensions.layoutInflater import com.habitrpg.common.habitica.extensions.loadImage import com.habitrpg.common.habitica.views.PixelArtView class PurchaseDialogCustomizationSetContent(context: Context) : PurchaseDialogContent(context) { val binding = DialogPurchaseCustomizationsetBinding.inflate(context.layoutInflater, this) override val imageView: PixelArtView get() = PixelArtView(context) override val titleTextView: TextView get() = binding.titleTextView override fun setItem(item: ShopItem) { titleTextView.text = item.text binding.imageViewWrapper.removeAllViews() item.setImageNames.forEach { val imageView = PixelArtView(context) imageView.setBackgroundResource(R.drawable.layout_rounded_bg_window) imageView.loadImage(it) imageView.layoutParams = FlexboxLayout.LayoutParams(76.dpToPx(context), 76.dpToPx(context)) binding.imageViewWrapper.addView(imageView) } if (item.key == "facialHair") { binding.notesTextView.text = context.getString(R.string.facial_hair_notes) } else { binding.notesTextView.text = item.notes } } }
gpl-3.0
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/comment/CommentsPresenter.kt
1
12408
package org.stepik.android.presentation.comment import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.rxkotlin.Singles import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.PublishSubject import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import ru.nobird.android.domain.rx.emptyOnErrorStub import org.stepik.android.domain.comment.interactor.CommentInteractor import org.stepik.android.domain.comment.interactor.ComposeCommentInteractor import org.stepik.android.domain.comment.model.CommentsData import org.stepik.android.domain.discussion_proxy.interactor.DiscussionProxyInteractor import org.stepik.android.domain.discussion_proxy.model.DiscussionOrder import org.stepik.android.domain.profile.interactor.ProfileGuestInteractor import org.stepik.android.model.Step import org.stepik.android.model.Submission import org.stepik.android.model.comments.Comment import org.stepik.android.model.comments.DiscussionProxy import org.stepik.android.model.comments.Vote import org.stepik.android.presentation.base.PresenterBase import org.stepik.android.presentation.comment.mapper.CommentsStateMapper import org.stepik.android.presentation.comment.model.CommentItem import org.stepik.android.view.injection.step.StepDiscussionBus import ru.nobird.android.core.model.PaginationDirection import javax.inject.Inject class CommentsPresenter @Inject constructor( private val commentInteractor: CommentInteractor, private val composeCommentInteractor: ComposeCommentInteractor, private val discussionProxyInteractor: DiscussionProxyInteractor, private val profileGuestInteractor: ProfileGuestInteractor, private val commentsStateMapper: CommentsStateMapper, @StepDiscussionBus private val stepDiscussionSubject: PublishSubject<Long>, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<CommentsView>() { private var state: CommentsView.State = CommentsView.State.Idle set(value) { field = value view?.setState(value) } override fun attachView(view: CommentsView) { super.attachView(view) view.setState(state) } /** * Data initialization variants */ fun onDiscussion(discussionProxyId: String, discussionId: Long?, forceUpdate: Boolean = false) { if (state != CommentsView.State.Idle && !((state == CommentsView.State.NetworkError || state is CommentsView.State.DiscussionLoaded) && forceUpdate) ) { return } val discussionOrderSource = (state as? CommentsView.State.DiscussionLoaded) ?.discussionOrder ?.let { Single.just(it) } ?: discussionProxyInteractor.getDiscussionOrder() compositeDisposable.clear() state = CommentsView.State.Loading compositeDisposable += Singles .zip( profileGuestInteractor.isGuest(), discussionProxyInteractor.getDiscussionProxy(discussionProxyId), discussionOrderSource ) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { (isGuest, discussionProxy, discussionOrder) -> fetchComments(isGuest, discussionProxy, discussionOrder, discussionId) }, onError = { state = CommentsView.State.NetworkError } ) } private fun fetchComments( isGuest: Boolean, discussionProxy: DiscussionProxy, discussionOrder: DiscussionOrder, discussionId: Long?, keepCachedComments: Boolean = false ) { if (discussionProxy.discussions.isEmpty()) { state = CommentsView.State.DiscussionLoaded(isGuest, discussionProxy, discussionOrder, discussionId, CommentsView.CommentsState.EmptyComments) } else { val cachedComments: List<CommentItem.Data> = ((state as? CommentsView.State.DiscussionLoaded) ?.commentsState as? CommentsView.CommentsState.Loaded) ?.commentDataItems ?.takeIf { keepCachedComments } ?: emptyList() val newState = CommentsView.State.DiscussionLoaded(isGuest, discussionProxy, discussionOrder, discussionId, CommentsView.CommentsState.Loading) state = newState compositeDisposable += commentInteractor .getComments(discussionProxy, discussionOrder, discussionId, cachedComments) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = newState.copy(commentsState = CommentsView.CommentsState.Loaded(it, commentsStateMapper.mapCommentDataItemsToRawItems(it))) if (discussionId != null) { view?.focusDiscussion(discussionId) } }, onError = { state = CommentsView.State.NetworkError } ) } } /** * Discussion ordering */ fun changeDiscussionOrder(discussionOrder: DiscussionOrder) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return compositeDisposable += discussionProxyInteractor .saveDiscussionOrder(discussionOrder) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy(onError = emptyOnErrorStub) fetchComments(oldState.isGuest, oldState.discussionProxy, discussionOrder, oldState.discussionId, keepCachedComments = true) } /** * Load more logic in both directions */ fun onLoadMore(direction: PaginationDirection) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return val commentDataItems = commentsState.commentDataItems val lastCommentId = when (direction) { PaginationDirection.PREV -> commentDataItems .takeIf { it.hasPrev } .takeIf { commentsState.commentItems.first() !is CommentItem.Placeholder } ?.first() ?.id ?: return PaginationDirection.NEXT -> commentDataItems .takeIf { it.hasNext } .takeIf { commentsState.commentItems.last() !is CommentItem.Placeholder } ?.last { it.comment.parent == null } ?.id ?: return } state = oldState.copy(commentsState = commentsStateMapper.mapToLoadMoreState(commentsState, direction)) compositeDisposable += commentInteractor .getMoreComments(oldState.discussionProxy, oldState.discussionOrder, direction, lastCommentId) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = commentsStateMapper.mapFromLoadMoreToSuccess(state, it, direction) }, onError = { state = commentsStateMapper.mapFromLoadMoreToError(state, direction); view?.showNetworkError() } ) } /** * Load more comments logic */ fun onLoadMoreReplies(loadMoreReplies: CommentItem.LoadMoreReplies) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return state = oldState.copy(commentsState = commentsStateMapper.mapToLoadMoreRepliesState(commentsState, loadMoreReplies)) compositeDisposable += commentInteractor .getMoreReplies(loadMoreReplies.parentComment, loadMoreReplies.lastCommentId) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = commentsStateMapper.mapFromLoadMoreRepliesToSuccess(state, it, loadMoreReplies) }, onError = { state = commentsStateMapper.mapFromLoadMoreRepliesToError(state, loadMoreReplies); view?.showNetworkError() } ) } /** * Vote logic * * if [voteValue] is equal to current value new value will be null */ fun onChangeVote(commentDataItem: CommentItem.Data, voteValue: Vote.Value) { if (commentDataItem.voteStatus !is CommentItem.Data.VoteStatus.Resolved || commentDataItem.comment.actions?.vote != true) { return } val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return val newVote = commentDataItem.voteStatus.vote .copy(value = voteValue.takeIf { it != commentDataItem.voteStatus.vote.value }) state = oldState.copy(commentsState = commentsStateMapper.mapToVotePending(commentsState, commentDataItem)) compositeDisposable += commentInteractor .changeCommentVote(commentDataItem.id, newVote) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = commentsStateMapper.mapFromVotePendingToSuccess(state, it) }, onError = { state = commentsStateMapper.mapFromVotePendingToError(state, commentDataItem.voteStatus.vote); view?.showNetworkError() } ) } fun onComposeCommentClicked(step: Step, parent: Long? = null, comment: Comment? = null, submission: Submission? = null) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return if (oldState.isGuest) { view?.showAuthRequired() } else { view?.showCommentComposeDialog(step, parent, comment, submission) } } /** * Edit logic */ fun onCommentCreated(commentsData: CommentsData) { val commentDataItem = commentInteractor .mapCommentsDataToCommentItem(commentsData) ?: return state = if (commentDataItem.comment.parent != null) { commentsStateMapper.insertCommentReply(state, commentDataItem) } else { stepDiscussionSubject.onNext(commentDataItem.comment.target) commentsStateMapper.insertComment(state, commentDataItem) } view?.focusDiscussion(commentDataItem.id) } fun onCommentUpdated(commentsData: CommentsData) { val commentDataItem = commentInteractor .mapCommentsDataToCommentItem(commentsData) ?: return state = commentsStateMapper.mapFromVotePendingToSuccess(state, commentDataItem) } fun removeComment(commentId: Long) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return val commentDataItem = commentsState.commentDataItems.find { it.id == commentId } ?: return state = oldState.copy(commentsState = commentsStateMapper.mapToRemovePending(commentsState, commentDataItem)) compositeDisposable += composeCommentInteractor .removeComment(commentDataItem.id) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .doOnComplete { if (commentDataItem.comment.parent == null) { stepDiscussionSubject.onNext(commentDataItem.comment.target) } } .subscribeBy( onComplete = { state = commentsStateMapper.mapFromRemovePendingToSuccess(state, commentId) }, onError = { state = commentsStateMapper.mapFromRemovePendingToError(state, commentDataItem); view?.showNetworkError() } ) } }
apache-2.0
robfletcher/orca
orca-sql/src/main/kotlin/com/netflix/spinnaker/orca/sql/pipeline/persistence/ExecutionMapper.kt
3
3114
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.sql.pipeline.persistence import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import java.sql.ResultSet import org.jooq.DSLContext import org.slf4j.LoggerFactory /** * Converts a SQL [ResultSet] into an Execution. * * When retrieving an Execution from SQL, we lazily load its stages on-demand * in this mapper as well. */ class ExecutionMapper( private val mapper: ObjectMapper, private val stageBatchSize: Int ) { private val log = LoggerFactory.getLogger(javaClass) fun map(rs: ResultSet, context: DSLContext): Collection<PipelineExecution> { val results = mutableListOf<PipelineExecution>() val executionMap = mutableMapOf<String, PipelineExecution>() val legacyMap = mutableMapOf<String, String>() while (rs.next()) { mapper.readValue<PipelineExecution>(rs.getString("body")) .also { execution -> results.add(execution) execution.partition = rs.getString("partition") if (rs.getString("id") != execution.id) { // Map legacyId executions to their current ULID legacyMap[execution.id] = rs.getString("id") executionMap[rs.getString("id")] = execution } else { executionMap[execution.id] = execution } } } if (results.isNotEmpty()) { val type = results[0].type results.chunked(stageBatchSize) { executions -> val executionIds: List<String> = executions.map { if (legacyMap.containsKey(it.id)) { legacyMap[it.id]!! } else { it.id } } context.selectExecutionStages(type, executionIds).let { stageResultSet -> while (stageResultSet.next()) { mapStage(stageResultSet, executionMap) } } executions.forEach { execution -> execution.stages.sortBy { it.refId } } } } return results } private fun mapStage(rs: ResultSet, executions: Map<String, PipelineExecution>) { val executionId = rs.getString("execution_id") executions.getValue(executionId) .stages .add( mapper.readValue<StageExecution>(rs.getString("body")) .apply { execution = executions.getValue(executionId) } ) } }
apache-2.0
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/coroutines/suspendDefaultImpl.kt
2
588
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.startCoroutine import kotlin.coroutines.experimental.intrinsics.* interface TestInterface { suspend fun toInt(): Int = suspendCoroutineOrReturn { x -> x.resume(56) COROUTINE_SUSPENDED } } class TestClass2 : TestInterface { } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var result = -1 builder { result = TestClass2().toInt() } if (result != 56) return "fail 1: $result" return "OK" }
apache-2.0
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/increment/postfixNullableClassIncrement.kt
3
221
class MyClass operator fun MyClass?.inc(): MyClass? = null public fun box() : String { var i : MyClass? i = MyClass() val j = i++ return if (j is MyClass && null == i) "OK" else "fail i = $i j = $j" }
apache-2.0
anrelic/Anci-OSS
logging/src/main/kotlin/su/jfdev/anci/logging/CatchingUtil.kt
1
2023
package su.jfdev.anci.logging import su.jfdev.anci.logging.LogLevel.* infix inline fun <R> Logger.unchecked(block: () -> R): R? = unchecked(ERROR, block) infix inline fun <R> Logger.exception(block: () -> R): R? = exception(ERROR, block) infix inline fun <R> Logger.throwable(block: () -> R): R? = throwable(ERROR, block) inline fun <R> Logger.unchecked(level: LogLevel, block: () -> R): R? = catching<R, RuntimeException>(level, block) inline fun <R> Logger.exception(level: LogLevel, block: () -> R): R? = catching<R, Exception>(level, block) inline fun <R> Logger.throwable(level: LogLevel, block: () -> R): R? = catching<R, Throwable>(level, block) inline fun <R, reified T: Throwable> Logger.catching(level: LogLevel, block: () -> R): R? { doOrCatch<T>(level, { return block() }) { return null } error("should exit by doOrCatch") } infix inline fun Logger.unchecked(block: () -> Unit): Unit = catch<RuntimeException>(block) infix inline fun Logger.exception(block: () -> Unit): Unit = catch<Exception>(block) infix inline fun Logger.throwable(block: () -> Unit): Unit = catch<Throwable>(block) inline fun Logger.unchecked(level: LogLevel, block: () -> Unit): Unit = catch<RuntimeException>(level, block) inline fun Logger.exception(level: LogLevel, block: () -> Unit): Unit = catch<Exception>(level, block) inline fun Logger.throwable(level: LogLevel, block: () -> Unit): Unit = catch<Throwable>(level, block) infix inline fun <reified T: Throwable> Logger.catch(block: () -> Unit): Unit = catch<T>(ERROR, block) inline fun <reified T: Throwable> Logger.catch(level: LogLevel, block: () -> Unit): Unit = doOrCatch<T>(level, block) { } inline fun <reified T: Throwable> Logger.doOrCatch(level: LogLevel, block: () -> Unit, or: () -> Unit) = tryCatch<T>(block) { log(level, it) or() } inline fun <reified T: Throwable> tryCatch(`try`: () -> Unit, catch: (T) -> Unit) = try { `try`() } catch (e: Throwable) { when (e) { is T -> catch(e) else -> throw e } }
mit
Bios-Marcel/ServerBrowser
src/test/kotlin/com/msc/serverbrowser/util/basic/StringUtilityTest.kt
1
1370
package com.msc.serverbrowser.util.basic import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test /** * @author Marcel * @since 21.09.2017 */ class StringUtilityTest { @Test fun testStringToBoolean() { assertTrue(StringUtility.stringToBoolean("true")) assertTrue(StringUtility.stringToBoolean("1")) assertTrue(StringUtility.stringToBoolean("True")) assertTrue(StringUtility.stringToBoolean("TRUE")) assertFalse(StringUtility.stringToBoolean(null)) assertFalse(StringUtility.stringToBoolean("0")) assertFalse(StringUtility.stringToBoolean("1 ")) assertFalse(StringUtility.stringToBoolean(" 1")) assertFalse(StringUtility.stringToBoolean("Kauderwelsch")) assertFalse(StringUtility.stringToBoolean("")) assertFalse(StringUtility.stringToBoolean("false")) } @Test fun testFixUrl() { assertEquals("https://google.com", StringUtility.fixUrlIfNecessary("https://google.com")) assertEquals("http://google.com", StringUtility.fixUrlIfNecessary("http://google.com")) assertEquals("http://google.com", StringUtility.fixUrlIfNecessary("google.com")) assertEquals("http://", StringUtility.fixUrlIfNecessary("")) assertThrows(NullPointerException::class.java) { StringUtility.fixUrlIfNecessary(null) } } }
mpl-2.0
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/autotune/data/PreppedGlucose.kt
1
4184
package info.nightscout.androidaps.plugins.general.autotune.data import info.nightscout.androidaps.utils.DateUtil import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.* class PreppedGlucose { var crData: List<CRDatum> = ArrayList() var csfGlucoseData: List<BGDatum> = ArrayList() var isfGlucoseData: List<BGDatum> = ArrayList() var basalGlucoseData: List<BGDatum> = ArrayList() var diaDeviations: List<DiaDeviation> = ArrayList() var peakDeviations: List<PeakDeviation> = ArrayList() var from: Long = 0 lateinit var dateUtil: DateUtil // to generate same king of json string than oref0-autotune-prep override fun toString(): String { return toString(0) } constructor(from: Long, crData: List<CRDatum>, csfGlucoseData: List<BGDatum>, isfGlucoseData: List<BGDatum>, basalGlucoseData: List<BGDatum>, dateUtil: DateUtil) { this.from = from this.crData = crData this.csfGlucoseData = csfGlucoseData this.isfGlucoseData = isfGlucoseData this.basalGlucoseData = basalGlucoseData this.dateUtil = dateUtil } constructor(json: JSONObject?, dateUtil: DateUtil) { if (json == null) return this.dateUtil = dateUtil crData = ArrayList() csfGlucoseData = ArrayList() isfGlucoseData = ArrayList() basalGlucoseData = ArrayList() try { crData = JsonCRDataToList(json.getJSONArray("CRData")) csfGlucoseData = JsonGlucoseDataToList(json.getJSONArray("CSFGlucoseData")) isfGlucoseData = JsonGlucoseDataToList(json.getJSONArray("ISFGlucoseData")) basalGlucoseData = JsonGlucoseDataToList(json.getJSONArray("basalGlucoseData")) } catch (e: JSONException) { } } private fun JsonGlucoseDataToList(array: JSONArray): List<BGDatum> { val bgData: MutableList<BGDatum> = ArrayList() for (index in 0 until array.length()) { try { val o = array.getJSONObject(index) bgData.add(BGDatum(o, dateUtil)) } catch (e: Exception) { } } return bgData } private fun JsonCRDataToList(array: JSONArray): List<CRDatum> { val crData: MutableList<CRDatum> = ArrayList() for (index in 0 until array.length()) { try { val o = array.getJSONObject(index) crData.add(CRDatum(o, dateUtil)) } catch (e: Exception) { } } return crData } fun toString(indent: Int): String { var jsonString = "" val json = JSONObject() try { val crjson = JSONArray() for (crd in crData) { crjson.put(crd.toJSON()) } val csfjson = JSONArray() for (bgd in csfGlucoseData) { csfjson.put(bgd.toJSON(true)) } val isfjson = JSONArray() for (bgd in isfGlucoseData) { isfjson.put(bgd.toJSON(false)) } val basaljson = JSONArray() for (bgd in basalGlucoseData) { basaljson.put(bgd.toJSON(false)) } val diajson = JSONArray() val peakjson = JSONArray() if (diaDeviations.size > 0 || peakDeviations.size > 0) { for (diad in diaDeviations) { diajson.put(diad.toJSON()) } for (peakd in peakDeviations) { peakjson.put(peakd.toJSON()) } } json.put("CRData", crjson) json.put("CSFGlucoseData", csfjson) json.put("ISFGlucoseData", isfjson) json.put("basalGlucoseData", basaljson) if (diaDeviations.size > 0 || peakDeviations.size > 0) { json.put("diaDeviations", diajson) json.put("peakDeviations", peakjson) } jsonString = if (indent != 0) json.toString(indent) else json.toString() } catch (e: JSONException) { } return jsonString } }
agpl-3.0
Heiner1/AndroidAPS
omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/info/AttachPodViewModel.kt
1
255
package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.viewmodel.ViewModelBase abstract class AttachPodViewModel : ViewModelBase()
agpl-3.0
Adventech/sabbath-school-android-2
common/lessons-data/src/main/java/app/ss/lessons/data/api/SSLessonsApi.kt
1
3124
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.lessons.data.api import app.ss.lessons.data.model.api.request.UploadPdfAnnotationsRequest import app.ss.models.PdfAnnotations import app.ss.models.SSLessonInfo import app.ss.models.SSRead import app.ss.models.SSReadComments import app.ss.models.SSReadHighlights import okhttp3.ResponseBody import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Url interface SSLessonsApi { @GET("api/v2/{lang}/quarterlies/{quarterlyId}/lessons/{lessonId}/index.json") suspend fun getLessonInfo( @Path("lang") language: String, @Path("quarterlyId") quarterlyId: String, @Path("lessonId") lessonId: String ): Response<SSLessonInfo> @GET suspend fun getDayRead(@Url fullPath: String): Response<SSRead> @GET("api/v2/annotations/{lessonIndex}/{pdfId}") suspend fun getPdfAnnotations( @Path("lessonIndex") lessonIndex: String, @Path("pdfId") pdfId: String ): Response<List<PdfAnnotations>> @POST("api/v2/annotations/{lessonIndex}/{pdfId}") suspend fun uploadAnnotations( @Path("lessonIndex") lessonIndex: String, @Path("pdfId") pdfId: String, @Body request: UploadPdfAnnotationsRequest ): Response<ResponseBody> @GET("api/v2/comments/{readIndex}") suspend fun getComments( @Path("readIndex") readIndex: String ): Response<SSReadComments> @POST("api/v2/comments") suspend fun uploadComments( @Body comments: SSReadComments ): Response<ResponseBody> @GET("api/v2/highlights/{readIndex}") suspend fun getHighlights( @Path("readIndex") readIndex: String ): Response<SSReadHighlights> @POST("api/v2/highlights") suspend fun uploadHighlights( @Body highlights: SSReadHighlights ): Response<ResponseBody> @GET suspend fun readerArtifact( @Url url: String ): Response<ResponseBody> }
mit
realm/realm-java
realm/realm-library/src/androidTest/kotlin/io/realm/entities/embedded/EmbeddedSimpleListParentWithoutPrimaryKey.kt
1
1040
/* * Copyright 2020 Realm 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 io.realm.entities.embedded import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import java.util.* // Top-level object describing a simple embedded objects structure consisting of only a // list of embedded objects. open class EmbeddedSimpleListParentWithoutPrimaryKey(var _id: String = UUID.randomUUID().toString()) : RealmObject() { var children: RealmList<EmbeddedSimpleChild> = RealmList() }
apache-2.0
myoffe/kotlin-koans
test/ii_collections/_13_Introduction.kt
1
296
package ii_collections import ii_collections.data.customers import ii_collections.data.shop import org.junit.Assert.assertEquals import org.junit.Test class _13_Introduction { @Test fun testSetOfCustomers() { assertEquals(shop.getSetOfCustomers(), customers.values.toSet()) } }
mit
elsiff/MoreFish
src/main/kotlin/me/elsiff/morefish/configuration/loader/PrizeMapLoader.kt
1
1023
package me.elsiff.morefish.configuration.loader import me.elsiff.morefish.configuration.ConfigurationValueAccessor import me.elsiff.morefish.configuration.translated import me.elsiff.morefish.fishing.competition.Prize /** * Created by elsiff on 2019-01-20. */ class PrizeMapLoader : CustomLoader<Map<IntRange, Prize>> { override fun loadFrom(section: ConfigurationValueAccessor, path: String): Map<IntRange, Prize> { return section[path].children.map { val range = intRangeFrom(it.name) val commands = it.strings("commands").translated() range to Prize(commands) }.toMap() } private fun intRangeFrom(string: String): IntRange { val tokens = string.split("~") val start = tokens[0].toInt() val end = if (tokens.size > 1) { if (tokens[1].isEmpty()) Int.MAX_VALUE else tokens[1].toInt() } else { start } return IntRange(start, end) } }
mit
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt
2
2770
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.util import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPrimaryConstructor import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.ifEmpty inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType( factory: (T) -> KotlinQuickFixAction<T>? ) = psiElement.getNonStrictParentOfType<T>()?.let(factory) fun createIntentionFactory( factory: (Diagnostic) -> IntentionAction? ) = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = factory(diagnostic) } fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? { val modifierList = this.modifierList ?: return null val psiFactory = KtPsiFactory(this) val constructor = if (valueParameterList == null) { psiFactory.createPrimaryConstructor("constructor()") } else { psiFactory.createConstructorKeyword() } return addAfter(constructor, modifierList) } fun getDataFlowAwareTypes( expression: KtExpression, bindingContext: BindingContext = expression.analyze(), originalType: KotlinType? = bindingContext.getType(expression) ): Collection<KotlinType> { if (originalType == null) return emptyList() val dataFlowInfo = bindingContext.getDataFlowInfoAfter(expression) val dataFlowValueFactory = expression.getResolutionFacade().dataFlowValueFactory val expressionType = bindingContext.getType(expression) ?: return listOf(originalType) val dataFlowValue = dataFlowValueFactory.createDataFlowValue( expression, expressionType, bindingContext, expression.getResolutionFacade().moduleDescriptor ) return dataFlowInfo.getCollectedTypes(dataFlowValue, expression.languageVersionSettings).ifEmpty { listOf(originalType) } }
apache-2.0
Maccimo/intellij-community
plugins/kotlin/base/util/src/org/jetbrains/kotlin/util/CollectionUtils.kt
2
601
// 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.util import java.util.* inline fun <T, R> Collection<T>.mapAll(transform: (T) -> R?): List<R>? { val result = ArrayList<R>(this.size) for (item in this) { result += transform(item) ?: return null } return result } fun <K, V> merge(vararg maps: Map<K, V>?): Map<K, V> { val result = mutableMapOf<K, V>() for (map in maps) { if (map != null) { result.putAll(map) } } return result }
apache-2.0
lcmatrix/betting-game
src/main/kotlin/de/bettinggame/infrastructure/WebConfig.kt
1
3824
package de.bettinggame.infrastructure import de.bettinggame.domain.UserRepository import de.bettinggame.domain.UserStatus import org.springframework.context.MessageSource import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.CacheControl import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.builders.WebSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.userdetails.User.withUsername import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import java.util.concurrent.TimeUnit @Configuration class WebConfig : WebMvcConfigurer { override fun addResourceHandlers(registry: ResourceHandlerRegistry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/") .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS)) } @Bean fun messageKeyPrinter(messageSource: MessageSource): MessageKeyPrinter { return MessageKeyPrinter(messageSource) } @Bean fun multilingualPrinter(): MultilingualPrinter { return MultilingualPrinter() } } @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) class WebSecurityConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity?) { http?.authorizeRequests() ?.antMatchers("/", "/static/**", "/favicon.ico", "/register*", "/groups*")?.permitAll() ?.antMatchers("/admin/**")?.hasAuthority("ADMIN") ?.and() ?.formLogin() ?.loginPage("/login") ?.failureForwardUrl("/error") ?.successForwardUrl("/") ?.permitAll() ?.and() ?.logout() ?.logoutSuccessUrl("/") ?.deleteCookies("JSESSIONID") ?.permitAll() } override fun configure(web: WebSecurity?) { web?.ignoring()?.antMatchers("/static/**") } @Bean fun passwordEncoder(): PasswordEncoder { return BCryptPasswordEncoder() } @Bean fun userDetailService(userRepository: UserRepository): CustomUserDetailService { return CustomUserDetailService(userRepository) } } class CustomUserDetailService(private val userRepository: UserRepository) : UserDetailsService { override fun loadUserByUsername(userOrEMail: String?): UserDetails { val user = userRepository.findByUsernameOrEmail(userOrEMail, userOrEMail) ?: throw UsernameNotFoundException("User $userOrEMail not found") return withUsername(user.identifier) .password(user.password) .disabled(user.status != UserStatus.ACTIVE) .accountLocked(user.status == UserStatus.LOCKED) .authorities(AuthorityUtils.createAuthorityList(user.role.name)) .build() } }
apache-2.0
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/action/motion/updown/MotionArrowDownActionTest.kt
1
15901
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ @file:Suppress("RemoveCurlyBracesFromTemplate") package org.jetbrains.plugins.ideavim.action.motion.updown import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt import org.jetbrains.plugins.ideavim.OptionValueType import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimOptionDefault import org.jetbrains.plugins.ideavim.VimOptionDefaultAll import org.jetbrains.plugins.ideavim.VimOptionTestCase import org.jetbrains.plugins.ideavim.VimOptionTestConfiguration import org.jetbrains.plugins.ideavim.VimTestOption class MotionArrowDownActionTest : VimOptionTestCase(OptionConstants.keymodelName, OptionConstants.virtualeditName) { @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionDefaultAll fun `test visual default options`() { doTest( listOf("v", "<Down>"), """ A Discovery I found it in a legendary land all ${c}rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land all ${s}rocks and lavender and tufted grass, wher${c}e${se} it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.VISUAL, VimStateMachine.SubMode.VISUAL_CHARACTER ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption( OptionConstants.keymodelName, OptionValueType.STRING, OptionConstants.keymodel_stopsel ) ) @VimOptionDefault(OptionConstants.virtualeditName) fun `test visual stopsel`() { doTest( listOf("v", "<Down>"), """ A Discovery I found it in a legendary land all ${c}rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, wher${c}e it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption( OptionConstants.keymodelName, OptionValueType.STRING, OptionConstants.keymodel_stopselect ) ) @VimOptionDefault(OptionConstants.virtualeditName) fun `test visual stopselect`() { doTest( listOf("v", "<Down>"), """ A Discovery I found it in a legendary land all ${c}rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land all ${s}rocks and lavender and tufted grass, wher${c}e${se} it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.VISUAL, VimStateMachine.SubMode.VISUAL_CHARACTER ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption( OptionConstants.keymodelName, OptionValueType.STRING, OptionConstants.keymodel_stopvisual ) ) @VimOptionDefault(OptionConstants.virtualeditName) fun `test visual stopvisual`() { doTest( listOf("v", "<Down>"), """ A Discovery I found it in a legendary land all ${c}rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, wher${c}e it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption( OptionConstants.keymodelName, OptionValueType.STRING, OptionConstants.keymodel_stopvisual ) ) @VimOptionDefault(OptionConstants.virtualeditName) fun `test visual stopvisual multicaret`() { doTest( listOf("v", "<Down>"), """ A Discovery I found it in a legendary land all ${c}rocks and lavender and tufted grass, where it was ${c}settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, wher${c}e it was settled on some sodden sand hard by the t${c}orrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration(VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, "")) @VimOptionDefault(OptionConstants.virtualeditName) fun `test char select stopsel`() { doTest( listOf("gh", "<Down>"), """ A Discovery I found it in a legendary land all ${c}rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land all ${s}rocks and lavender and tufted grass, where${c}${se} it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.SELECT, VimStateMachine.SubMode.VISUAL_CHARACTER ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test virtual edit down to shorter line`() { doTest( listOf("<Down>"), """ class MyClass ${c}{ } """.trimIndent(), """ class MyClass { }${c} """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test virtual edit down to shorter line after dollar`() { doTest( listOf("$", "<Down>"), """ class ${c}MyClass { } """.trimIndent(), """ class MyClass { ${c}} """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } // Once you press '$', then any up or down actions stay on the end of the current line. // Any non up/down action breaks this. private val start = """ what ${c}a long line I am yet I am short Lo and behold, I am the longest yet nope. """.trimIndent() @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar`() { // Arrow keys doTest( listOf("$", "<Down>"), start, """ what a long line I am yet I am shor${c}t Lo and behold, I am the longest yet nope. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar1`() { doTest( listOf("$", "<Down>", "<Down>"), start, """ what a long line I am yet I am short Lo and behold, I am the longest ye${c}t nope. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar2`() { doTest( listOf("$", "<Down>", "<Down>", "<Down>"), start, """ what a long line I am yet I am short Lo and behold, I am the longest yet nope${c}. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar3`() { doTest( listOf("$", "<Down>", "<Down>", "<Down>", "<Up>"), start, """ what a long line I am yet I am short Lo and behold, I am the longest ye${c}t nope. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar4`() { // j k keys doTest( listOf("$", "j"), start, """ what a long line I am yet I am shor${c}t Lo and behold, I am the longest yet nope. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar5`() { doTest( listOf("$", "j", "j"), start, """ what a long line I am yet I am short Lo and behold, I am the longest ye${c}t nope. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar6`() { doTest( listOf("$", "j", "j", "j"), start, """ what a long line I am yet I am short Lo and behold, I am the longest yet nope${c}. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption(OptionConstants.keymodelName, OptionValueType.STRING, ""), VimTestOption(OptionConstants.virtualeditName, OptionValueType.STRING, OptionConstants.virtualedit_onemore) ) fun `test up and down after dollar7`() { doTest( listOf("$", "j", "j", "j", "k"), start, """ what a long line I am yet I am short Lo and behold, I am the longest ye${c}t nope. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption( OptionConstants.keymodelName, OptionValueType.STRING, OptionConstants.keymodel_stopselect ) ) @VimOptionDefault(OptionConstants.virtualeditName) fun `test char select simple move`() { doTest( listOf("gH", "<Down>"), """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land ${c}all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionTestConfiguration( VimTestOption( OptionConstants.keymodelName, OptionValueType.STRING, OptionConstants.keymodel_stopselect ) ) @VimOptionDefault(OptionConstants.virtualeditName) fun `test select multiple carets`() { doTest( listOf("gH", "<Down>"), """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by ${c}the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary land ${c}all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by ${c}the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.OPTION) @VimOptionDefaultAll fun `test arrow down in insert mode scrolls caret at scrolloff`() { VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolljumpName, VimInt(10)) VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolloffName, VimInt(5)) configureByPages(5) setPositionAndScroll(0, 29) typeText(injector.parser.parseKeys("i" + "<Down>")) assertPosition(30, 0) assertVisibleArea(10, 44) } }
mit
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/newapi/IjVimInjector.kt
1
8720
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.newapi import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.api.EngineEditorHelper import com.maddyhome.idea.vim.api.ExEntryPanel import com.maddyhome.idea.vim.api.ExecutionContextManager import com.maddyhome.idea.vim.api.NativeActionManager import com.maddyhome.idea.vim.api.SystemInfoService import com.maddyhome.idea.vim.api.VimActionExecutor import com.maddyhome.idea.vim.api.VimApplication import com.maddyhome.idea.vim.api.VimChangeGroup import com.maddyhome.idea.vim.api.VimClipboardManager import com.maddyhome.idea.vim.api.VimCommandGroup import com.maddyhome.idea.vim.api.VimDigraphGroup import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditorGroup import com.maddyhome.idea.vim.api.VimEnabler import com.maddyhome.idea.vim.api.VimExOutputPanel import com.maddyhome.idea.vim.api.VimExOutputPanelService import com.maddyhome.idea.vim.api.VimExtensionRegistrator import com.maddyhome.idea.vim.api.VimFile import com.maddyhome.idea.vim.api.VimInjectorBase import com.maddyhome.idea.vim.api.VimKeyGroup import com.maddyhome.idea.vim.api.VimLookupManager import com.maddyhome.idea.vim.api.VimMessages import com.maddyhome.idea.vim.api.VimMotionGroup import com.maddyhome.idea.vim.api.VimProcessGroup import com.maddyhome.idea.vim.api.VimRegexpService import com.maddyhome.idea.vim.api.VimSearchGroup import com.maddyhome.idea.vim.api.VimSearchHelper import com.maddyhome.idea.vim.api.VimStatistics import com.maddyhome.idea.vim.api.VimStorageService import com.maddyhome.idea.vim.api.VimStringParser import com.maddyhome.idea.vim.api.VimTemplateManager import com.maddyhome.idea.vim.api.VimVisualMotionGroup import com.maddyhome.idea.vim.api.VimrcFileState import com.maddyhome.idea.vim.api.VimscriptExecutor import com.maddyhome.idea.vim.api.VimscriptFunctionService import com.maddyhome.idea.vim.api.VimscriptParser import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.common.VimMachine import com.maddyhome.idea.vim.diagnostic.VimLogger import com.maddyhome.idea.vim.ex.ExOutputModel import com.maddyhome.idea.vim.extension.VimExtensionRegistrar import com.maddyhome.idea.vim.group.CommandGroup import com.maddyhome.idea.vim.group.EditorGroup import com.maddyhome.idea.vim.group.FileGroup import com.maddyhome.idea.vim.group.HistoryGroup import com.maddyhome.idea.vim.group.MacroGroup import com.maddyhome.idea.vim.group.MarkGroup import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.group.SearchGroup import com.maddyhome.idea.vim.group.TabService import com.maddyhome.idea.vim.group.VimWindowGroup import com.maddyhome.idea.vim.group.WindowGroup import com.maddyhome.idea.vim.group.copy.PutGroup import com.maddyhome.idea.vim.helper.CommandLineHelper import com.maddyhome.idea.vim.helper.IjActionExecutor import com.maddyhome.idea.vim.helper.IjEditorHelper import com.maddyhome.idea.vim.helper.IjVimStringParser import com.maddyhome.idea.vim.helper.UndoRedoHelper import com.maddyhome.idea.vim.helper.VimCommandLineHelper import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.history.VimHistory import com.maddyhome.idea.vim.macro.VimMacro import com.maddyhome.idea.vim.mark.VimMarkGroup import com.maddyhome.idea.vim.put.VimPut import com.maddyhome.idea.vim.register.VimRegisterGroup import com.maddyhome.idea.vim.ui.VimRcFileState import com.maddyhome.idea.vim.undo.VimUndoRedo import com.maddyhome.idea.vim.vimscript.Executor import com.maddyhome.idea.vim.vimscript.services.FunctionStorage import com.maddyhome.idea.vim.vimscript.services.OptionService import com.maddyhome.idea.vim.vimscript.services.PatternService import com.maddyhome.idea.vim.vimscript.services.VariableService import com.maddyhome.idea.vim.yank.VimYankGroup import com.maddyhome.idea.vim.yank.YankGroupBase class IjVimInjector : VimInjectorBase() { override fun <T : Any> getLogger(clazz: Class<T>): VimLogger = IjVimLogger(Logger.getInstance(clazz::class.java)) override val actionExecutor: VimActionExecutor get() = service<IjActionExecutor>() override val exEntryPanel: ExEntryPanel get() = service<IjExEntryPanel>() override val exOutputPanel: VimExOutputPanelService get() = object : VimExOutputPanelService { override fun getPanel(editor: VimEditor): VimExOutputPanel { return ExOutputModel.getInstance(editor.ij) } } override val historyGroup: VimHistory get() = service<HistoryGroup>() override val extensionRegistrator: VimExtensionRegistrator get() = VimExtensionRegistrar override val tabService: TabService get() = service() override val regexpService: VimRegexpService get() = PatternService override val clipboardManager: VimClipboardManager get() = service<IjClipboardManager>() override val searchHelper: VimSearchHelper get() = service<IjVimSearchHelper>() override val motion: VimMotionGroup get() = service<MotionGroup>() override val lookupManager: VimLookupManager get() = service<IjVimLookupManager>() override val templateManager: VimTemplateManager get() = service<IjTemplateManager>() override val searchGroup: VimSearchGroup get() = service<SearchGroup>() override val put: VimPut get() = service<PutGroup>() override val window: VimWindowGroup get() = service<WindowGroup>() override val yank: VimYankGroup get() = service<YankGroupBase>() override val file: VimFile get() = service<FileGroup>() override val macro: VimMacro get() = service<MacroGroup>() override val undo: VimUndoRedo get() = service<UndoRedoHelper>() override val commandLineHelper: VimCommandLineHelper get() = service<CommandLineHelper>() override val nativeActionManager: NativeActionManager get() = service<IjNativeActionManager>() override val messages: VimMessages get() = service<IjVimMessages>() override val registerGroup: VimRegisterGroup get() = service() override val registerGroupIfCreated: VimRegisterGroup? get() = serviceIfCreated() override val changeGroup: VimChangeGroup get() = service() override val processGroup: VimProcessGroup get() = service() override val keyGroup: VimKeyGroup get() = service() override val markGroup: VimMarkGroup get() = service<MarkGroup>() override val application: VimApplication get() = service<IjVimApplication>() override val executionContextManager: ExecutionContextManager get() = service<IjExecutionContextManager>() override val vimMachine: VimMachine get() = service<VimMachineImpl>() override val enabler: VimEnabler get() = service<IjVimEnabler>() override val digraphGroup: VimDigraphGroup get() = service() override val visualMotionGroup: VimVisualMotionGroup get() = service() override val statisticsService: VimStatistics get() = service() override val commandGroup: VimCommandGroup get() = service<CommandGroup>() override val functionService: VimscriptFunctionService get() = FunctionStorage override val variableService: VariableService get() = service() override val vimrcFileState: VimrcFileState get() = VimRcFileState override val vimscriptExecutor: VimscriptExecutor get() = service<Executor>() override val vimscriptParser: VimscriptParser get() = com.maddyhome.idea.vim.vimscript.parser.VimscriptParser override val optionService: OptionService get() = service() override val parser: VimStringParser get() = service<IjVimStringParser>() override val systemInfoService: SystemInfoService get() = service() override val vimStorageService: VimStorageService get() = service() override fun commandStateFor(editor: VimEditor): VimStateMachine { var res = editor.ij.vimStateMachine if (res == null) { res = VimStateMachine(editor) editor.ij.vimStateMachine = res } return res } override fun commandStateFor(editor: Any): VimStateMachine { return when (editor) { is VimEditor -> this.commandStateFor(editor) is Editor -> this.commandStateFor(IjVimEditor(editor)) else -> error("Unexpected type: $editor") } } override val engineEditorHelper: EngineEditorHelper get() = service<IjEditorHelper>() override val editorGroup: VimEditorGroup get() = service<EditorGroup>() }
mit
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/widgets/MaterialTextViewWithNumerals.kt
1
644
package org.wordpress.android.widgets import android.content.Context import android.util.AttributeSet import com.google.android.material.textview.MaterialTextView import org.wordpress.android.util.extensions.enforceWesternArabicNumerals /** * MaterialTextView which enforces Western Arabic numerals. */ class MaterialTextViewWithNumerals @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : MaterialTextView(context, attrs, defStyleAttr) { override fun setText(text: CharSequence?, type: BufferType?) { super.setText(text?.enforceWesternArabicNumerals(), type) } }
gpl-2.0
qoncept/TensorKotlin
src/jp/co/qoncept/tensorkotlin/Shape.kt
1
681
package jp.co.qoncept.tensorkotlin import java.util.* class Shape(vararg dimensions: Int) { val dimensions: IntArray = dimensions.clone() val volume: Int get() = dimensions.fold(1) { a, x -> a * x } override fun equals(other: Any?): Boolean { if (other !is Shape) { return false } return dimensions.size == other.dimensions.size && zipFold(dimensions, other.dimensions, true) { result, a, b -> if (!result) { return false } a == b } } override fun hashCode(): Int { return dimensions.hashCode() } override fun toString(): String { return Arrays.toString(dimensions) } }
mit
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/repl/completion/definedClassMember.kt
13
82
>> class MyClass { fun f() {} fun g() {} } -- MyClass(). // EXIST: f // EXIST: g
apache-2.0
google/flatbuffers
kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt
6
27376
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package com.google.flatbuffers.kotlin public class FlexBuffersBuilder( public val buffer: ReadWriteBuffer, private val shareFlag: Int = SHARE_KEYS ) { public constructor(initialCapacity: Int = 1024, shareFlag: Int = SHARE_KEYS) : this(ArrayReadWriteBuffer(initialCapacity), shareFlag) private val stringValuePool: HashMap<String, Value> = HashMap() private val stringKeyPool: HashMap<String, Int> = HashMap() private val stack: MutableList<Value> = mutableListOf() private var finished: Boolean = false /** * Reset the FlexBuffersBuilder by purging all data that it holds. Buffer might * keep its capacity after a reset. */ public fun clear() { buffer.clear() stringValuePool.clear() stringKeyPool.clear() stack.clear() finished = false } /** * Finish writing the message into the buffer. After that no other element must * be inserted into the buffer. Also, you must call this function before start using the * FlexBuffer message * @return [ReadBuffer] containing the FlexBuffer message */ public fun finish(): ReadBuffer { // If you hit this assert, you likely have objects that were never included // in a parent. You need to have exactly one root to finish a buffer. // Check your Start/End calls are matched, and all objects are inside // some other object. if (stack.size != 1) error("There is must be only on object as root. Current ${stack.size}.") // Write root value. val byteWidth = align(stack[0].elemWidth(buffer.writePosition, 0)) writeAny(stack[0], byteWidth) // Write root type. buffer.put(stack[0].storedPackedType()) // Write root size. Normally determined by parent, but root has no parent :) buffer.put(byteWidth.value.toByte()) this.finished = true return buffer // TODO: make a read-only shallow copy } /** * Insert a single [Boolean] into the buffer * @param value true or false */ public fun put(value: Boolean): Unit = run { this[null] = value } /** * Insert a null reference into the buffer. A key must be present if element is inserted into a map. */ public fun putNull(key: String? = null): Unit = run { stack.add(Value(T_NULL, putKey(key), W_8, 0UL)) } /** * Insert a single [Boolean] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Boolean): Unit = run { stack.add(Value(T_BOOL, putKey(key), W_8, if (value) 1UL else 0UL)) } /** * Insert a single [Byte] into the buffer */ public fun put(value: Byte): Unit = set(null, value.toLong()) /** * Insert a single [Byte] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Byte): Unit = set(key, value.toLong()) /** * Insert a single [Short] into the buffer. */ public fun put(value: Short): Unit = set(null, value.toLong()) /** * Insert a single [Short] into the buffer. A key must be present if element is inserted into a map. */ public inline operator fun set(key: String? = null, value: Short): Unit = set(key, value.toLong()) /** * Insert a single [Int] into the buffer. */ public fun put(value: Int): Unit = set(null, value.toLong()) /** * Insert a single [Int] into the buffer. A key must be present if element is inserted into a map. */ public inline operator fun set(key: String? = null, value: Int): Unit = set(key, value.toLong()) /** * Insert a single [Long] into the buffer. */ public fun put(value: Long): Unit = set(null, value) /** * Insert a single [Long] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Long): Unit = run { stack.add(Value(T_INT, putKey(key), value.toULong().widthInUBits(), value.toULong())) } /** * Insert a single [UByte] into the buffer */ public fun put(value: UByte): Unit = set(null, value.toULong()) /** * Insert a single [UByte] into the buffer. A key must be present if element is inserted into a map. */ public inline operator fun set(key: String? = null, value: UByte): Unit = set(key, value.toULong()) /** * Insert a single [UShort] into the buffer. */ public fun put(value: UShort): Unit = set(null, value.toULong()) /** * Insert a single [UShort] into the buffer. A key must be present if element is inserted into a map. */ private inline operator fun set(key: String? = null, value: UShort): Unit = set(key, value.toULong()) /** * Insert a single [UInt] into the buffer. */ public fun put(value: UInt): Unit = set(null, value.toULong()) /** * Insert a single [UInt] into the buffer. A key must be present if element is inserted into a map. */ private inline operator fun set(key: String? = null, value: UInt): Unit = set(key, value.toULong()) /** * Insert a single [ULong] into the buffer. */ public fun put(value: ULong): Unit = set(null, value) /** * Insert a single [ULong] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: ULong): Unit = run { stack.add(Value(T_UINT, putKey(key), value.widthInUBits(), value)) } /** * Insert a single [Float] into the buffer. */ public fun put(value: Float): Unit = run { this[null] = value } /** * Insert a single [Float] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Float): Unit = run { stack.add(Value(T_FLOAT, putKey(key), W_32, dValue = value.toDouble())) } /** * Insert a single [Double] into the buffer. */ public fun put(value: Double): Unit = run { this[null] = value } /** * Insert a single [Double] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Double): Unit = run { stack.add(Value(T_FLOAT, putKey(key), W_64, dValue = value)) } /** * Insert a single [String] into the buffer. */ public fun put(value: String): Int = set(null, value) /** * Insert a single [String] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: String): Int { val iKey = putKey(key) val holder = if (shareFlag and SHARE_STRINGS != 0) { stringValuePool.getOrPut(value) { writeString(iKey, value).also { stringValuePool[value] = it } }.copy(key = iKey) } else { writeString(iKey, value) } stack.add(holder) return holder.iValue.toInt() } /** * Adds a [ByteArray] into the message as a [Blob]. * @param value byte array * @return position in buffer as the start of byte array */ public fun put(value: ByteArray): Int = set(null, value) /** * Adds a [ByteArray] into the message as a [Blob]. A key must be present if element is inserted into a map. * @param value byte array * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: ByteArray): Int { val element = writeBlob(putKey(key), value, T_BLOB, false) stack.add(element) return element.iValue.toInt() } /** * Adds a [IntArray] into the message as a typed vector of fixed size. * @param value [IntArray] * @return position in buffer as the start of byte array */ public fun put(value: IntArray): Int = set(null, value) /** * Adds a [IntArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [IntArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: IntArray): Int = setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } /** * Adds a [ShortArray] into the message as a typed vector of fixed size. * @param value [ShortArray] * @return position in buffer as the start of byte array */ public fun put(value: ShortArray): Int = set(null, value) /** * Adds a [ShortArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [ShortArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: ShortArray): Int = setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } /** * Adds a [LongArray] into the message as a typed vector of fixed size. * @param value [LongArray] * @return position in buffer as the start of byte array */ public fun put(value: LongArray): Int = set(null, value) /** * Adds a [LongArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [LongArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: LongArray): Int = setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } /** * Adds a [FloatArray] into the message as a typed vector of fixed size. * @param value [FloatArray] * @return position in buffer as the start of byte array */ public fun put(value: FloatArray): Int = set(null, value) /** * Adds a [FloatArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [FloatArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: FloatArray): Int = setTypedVector(key, value.size, T_VECTOR_FLOAT, W_32) { writeFloatArray(value) } /** * Adds a [DoubleArray] into the message as a typed vector of fixed size. * @param value [DoubleArray] * @return position in buffer as the start of byte array */ public fun put(value: DoubleArray): Int = set(null, value) /** * Adds a [DoubleArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [DoubleArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: DoubleArray): Int = setTypedVector(key, value.size, T_VECTOR_FLOAT, W_64) { writeFloatArray(value) } /** * Adds a [UByteArray] into the message as a typed vector of fixed size. * @param value [UByteArray] * @return position in buffer as the start of byte array */ public fun put(value: UByteArray): Int = set(null, value) /** * Adds a [UByteArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [UByteArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: UByteArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Adds a [UShortArray] into the message as a typed vector of fixed size. * @param value [UShortArray] * @return position in buffer as the start of byte array */ public fun put(value: UShortArray): Int = set(null, value) /** * Adds a [UShortArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [UShortArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: UShortArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Adds a [UIntArray] into the message as a typed vector of fixed size. * @param value [UIntArray] * @return position in buffer as the start of byte array */ public fun put(value: UIntArray): Int = set(null, value) /** * Adds a [UIntArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [UIntArray] * @return position in buffer as the start of byte array */ public fun set(key: String? = null, value: UIntArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Adds a [ULongArray] into the message as a typed vector of fixed size. * @param value [ULongArray] * @return position in buffer as the start of byte array */ public fun put(value: ULongArray): Int = set(null, value) /** * Adds a [ULongArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [ULongArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: ULongArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Creates a new vector will all elements inserted in [block]. * @param block where elements will be inserted * @return position in buffer as the start of byte array */ public inline fun putVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startVector() this.block() return endVector(pos) } /** * Creates a new typed vector will all elements inserted in [block]. * @param block where elements will be inserted * @return position in buffer as the start of byte array */ public inline fun putTypedVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startVector() this.block() return endTypedVector(pos) } /** * Helper function to return position for starting a new vector. */ public fun startVector(): Int = stack.size /** * Finishes a vector element. The initial position of the vector must be passed * @param position position at the start of the vector */ public fun endVector(position: Int): Int = endVector(null, position) /** * Finishes a vector element. The initial position of the vector must be passed * @param position position at the start of the vector */ public fun endVector(key: String? = null, position: Int): Int = endAnyVector(position) { createVector(putKey(key), position, stack.size - position) } /** * Finishes a typed vector element. The initial position of the vector must be passed * @param position position at the start of the vector */ public fun endTypedVector(position: Int): Int = endTypedVector(position, null) /** * Helper function to return position for starting a new vector. */ public fun startMap(): Int = stack.size /** * Creates a new map will all elements inserted in [block]. * @param block where elements will be inserted * @return position in buffer as the start of byte array */ public inline fun putMap(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startMap() this.block() return endMap(pos, key) } /** * Finishes a map, but writing the information in the buffer * @param key key used to store element in map * @return Reference to the map */ public fun endMap(start: Int, key: String? = null): Int { stack.subList(start, stack.size).sortWith(keyComparator) val length = stack.size - start val keys = createKeyVector(start, length) val vec = putMap(putKey(key), start, length, keys) // Remove temp elements and return map. while (stack.size > start) { stack.removeAt(stack.size - 1) } stack.add(vec) return vec.iValue.toInt() } private inline fun setTypedVector( key: String? = null, length: Int, vecType: FlexBufferType, bitWidth: BitWidth, crossinline writeBlock: (ByteWidth) -> Unit ): Int { val keyPos = putKey(key) val byteWidth = align(bitWidth) // Write vector. First the keys width/offset if available, and size. // write the size writeInt(length, byteWidth) // Then the actual data. val vloc: Int = buffer.writePosition writeBlock(byteWidth) stack.add(Value(vecType, keyPos, bitWidth, vloc.toULong())) return vloc } private inline fun setTypedVec(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startVector() this.block() return endTypedVector(pos, key) } public fun endTypedVector(position: Int, key: String? = null): Int = endAnyVector(position) { createTypedVector(putKey(key), position, stack.size - position) } private inline fun endAnyVector(start: Int, crossinline creationBlock: () -> Value): Int { val vec = creationBlock() // Remove temp elements and return vector. while (stack.size > start) { stack.removeLast() } stack.add(vec) return vec.iValue.toInt() } private inline fun putKey(key: String? = null): Int { if (key == null) return -1 return if ((shareFlag and SHARE_KEYS) != 0) { stringKeyPool.getOrPut(key) { val pos: Int = buffer.writePosition buffer.put(key) buffer.put(ZeroByte) pos } } else { val pos: Int = buffer.writePosition buffer.put(key) buffer.put(ZeroByte) pos } } private fun writeAny(toWrite: Value, byteWidth: ByteWidth) = when (toWrite.type) { T_NULL, T_BOOL, T_INT, T_UINT -> writeInt(toWrite.iValue, byteWidth) T_FLOAT -> writeDouble(toWrite.dValue, byteWidth) else -> writeOffset(toWrite.iValue.toInt(), byteWidth) } private fun writeString(key: Int, s: String): Value { val size = Utf8.encodedLength(s) val bitWidth = size.toULong().widthInUBits() val byteWidth = align(bitWidth) writeInt(size, byteWidth) val sloc: Int = buffer.writePosition if (size > 0) buffer.put(s, size) buffer.put(ZeroByte) return Value(T_STRING, key, bitWidth, sloc.toULong()) } private fun writeDouble(toWrite: Double, byteWidth: ByteWidth): Unit = when (byteWidth.value) { 4 -> buffer.put(toWrite.toFloat()) 8 -> buffer.put(toWrite) else -> Unit } private fun writeOffset(toWrite: Int, byteWidth: ByteWidth) { val relativeOffset = (buffer.writePosition - toWrite) if (byteWidth.value != 8 && relativeOffset >= 1L shl byteWidth.value * 8) error("invalid offset $relativeOffset, writer pos ${buffer.writePosition}") writeInt(relativeOffset, byteWidth) } private inline fun writeBlob(key: Int, blob: ByteArray, type: FlexBufferType, trailing: Boolean): Value { val bitWidth = blob.size.toULong().widthInUBits() val byteWidth = align(bitWidth) writeInt(blob.size, byteWidth) val sloc: Int = buffer.writePosition buffer.put(blob, 0, blob.size) if (trailing) { buffer.put(ZeroByte) } return Value(type, key, bitWidth, sloc.toULong()) } private fun writeIntArray(value: IntArray, byteWidth: ByteWidth) = writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } private fun writeIntArray(value: ShortArray, byteWidth: ByteWidth) = writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } private fun writeIntArray(value: LongArray, byteWidth: ByteWidth) = writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } private fun writeFloatArray(value: FloatArray) { val byteWidth = Float.SIZE_BYTES // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting // the right size on the spot buffer.requestCapacity(buffer.writePosition + (value.size * byteWidth)) value.forEach { buffer.put(it) } } private fun writeFloatArray(value: DoubleArray) { val byteWidth = Double.SIZE_BYTES // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting // the right size on the spot buffer.requestCapacity(buffer.writePosition + (value.size * byteWidth)) value.forEach { buffer.put(it) } } private inline fun writeIntegerArray( start: Int, size: Int, byteWidth: ByteWidth, crossinline valueBlock: (Int) -> ULong ) { // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting // the right size on the spot buffer.requestCapacity(buffer.writePosition + (size * byteWidth)) return when (byteWidth.value) { 1 -> for (i in start until start + size) { buffer.put(valueBlock(i).toUByte()) } 2 -> for (i in start until start + size) { buffer.put(valueBlock(i).toUShort()) } 4 -> for (i in start until start + size) { buffer.put(valueBlock(i).toUInt()) } 8 -> for (i in start until start + size) { buffer.put(valueBlock(i)) } else -> Unit } } private fun writeInt(value: Int, byteWidth: ByteWidth) = when (byteWidth.value) { 1 -> buffer.put(value.toUByte()) 2 -> buffer.put(value.toUShort()) 4 -> buffer.put(value.toUInt()) 8 -> buffer.put(value.toULong()) else -> Unit } private fun writeInt(value: ULong, byteWidth: ByteWidth) = when (byteWidth.value) { 1 -> buffer.put(value.toUByte()) 2 -> buffer.put(value.toUShort()) 4 -> buffer.put(value.toUInt()) 8 -> buffer.put(value) else -> Unit } // Align to prepare for writing a scalar with a certain size. // returns the amounts of bytes needed to be written. private fun align(alignment: BitWidth): ByteWidth { val byteWidth = 1 shl alignment.value var padBytes = paddingBytes(buffer.writePosition, byteWidth) while (padBytes-- != 0) { buffer.put(ZeroByte) } return ByteWidth(byteWidth) } private fun calculateKeyVectorBitWidth(start: Int, length: Int): BitWidth { val bitWidth = length.toULong().widthInUBits() var width = bitWidth val prefixElems = 1 // Check bit widths and types for all elements. for (i in start until stack.size) { val elemWidth = elemWidth(T_KEY, W_8, stack[i].key.toLong(), buffer.writePosition, i + prefixElems) width = width.max(elemWidth) } return width } private fun createKeyVector(start: Int, length: Int): Value { // Figure out smallest bit width we can store this vector with. val bitWidth = calculateKeyVectorBitWidth(start, length) val byteWidth = align(bitWidth) // Write vector. First the keys width/offset if available, and size. writeInt(length, byteWidth) // Then the actual data. val vloc = buffer.writePosition.toULong() for (i in start until stack.size) { val pos = stack[i].key if (pos == -1) error("invalid position $pos for key") writeOffset(stack[i].key, byteWidth) } // Then the types. return Value(T_VECTOR_KEY, -1, bitWidth, vloc) } private inline fun createVector(key: Int, start: Int, length: Int, keys: Value? = null): Value { return createAnyVector(key, start, length, T_VECTOR, keys) { // add types since we are not creating a typed vector. for (i in start until stack.size) { buffer.put(stack[i].storedPackedType(it)) } } } private fun putMap(key: Int, start: Int, length: Int, keys: Value? = null): Value { return createAnyVector(key, start, length, T_MAP, keys) { // add types since we are not creating a typed vector. for (i in start until stack.size) { buffer.put(stack[i].storedPackedType(it)) } } } private inline fun createTypedVector(key: Int, start: Int, length: Int, keys: Value? = null): Value { // We assume the callers of this method guarantees all elements are of the same type. val elementType: FlexBufferType = stack[start].type for (i in start + 1 until length) { if (elementType != stack[i].type) error("TypedVector does not support array of different element types") } if (!elementType.isTypedVectorElementType()) error("TypedVector does not support this element type") return createAnyVector(key, start, length, elementType.toTypedVector(), keys) } private inline fun createAnyVector( key: Int, start: Int, length: Int, type: FlexBufferType, keys: Value? = null, crossinline typeBlock: (BitWidth) -> Unit = {} ): Value { // Figure out smallest bit width we can store this vector with. var bitWidth = W_8.max(length.toULong().widthInUBits()) var prefixElems = 1 if (keys != null) { // If this vector is part of a map, we will pre-fix an offset to the keys // to this vector. bitWidth = bitWidth.max(keys.elemWidth(buffer.writePosition, 0)) prefixElems += 2 } // Check bit widths and types for all elements. for (i in start until stack.size) { val elemWidth = stack[i].elemWidth(buffer.writePosition, i + prefixElems) bitWidth = bitWidth.max(elemWidth) } val byteWidth = align(bitWidth) // Write vector. First the keys width/offset if available, and size. if (keys != null) { writeOffset(keys.iValue.toInt(), byteWidth) writeInt(1 shl keys.minBitWidth.value, byteWidth) } // write the size writeInt(length, byteWidth) // Then the actual data. val vloc: Int = buffer.writePosition for (i in start until stack.size) { writeAny(stack[i], byteWidth) } // Optionally you can introduce the types for non-typed vector typeBlock(bitWidth) return Value(type, key, bitWidth, vloc.toULong()) } // A lambda to sort map keys internal val keyComparator = object : Comparator<Value> { override fun compare(a: Value, b: Value): Int { var ia: Int = a.key var io: Int = b.key var c1: Byte var c2: Byte do { c1 = buffer[ia] c2 = buffer[io] if (c1.toInt() == 0) return c1 - c2 ia++ io++ } while (c1 == c2) return c1 - c2 } } public companion object { /** * No keys or strings will be shared */ public const val SHARE_NONE: Int = 0 /** * Keys will be shared between elements. Identical keys will only be serialized once, thus possibly saving space. * But serialization performance might be slower and consumes more memory. */ public const val SHARE_KEYS: Int = 1 /** * Strings will be shared between elements. Identical strings will only be serialized once, thus possibly saving space. * But serialization performance might be slower and consumes more memory. This is ideal if you expect many repeated * strings on the message. */ public const val SHARE_STRINGS: Int = 2 /** * Strings and keys will be shared between elements. */ public const val SHARE_KEYS_AND_STRINGS: Int = 3 } }
apache-2.0
SkyTreasure/Kotlin-Firebase-Group-Chat
app/src/main/java/io/skytreasure/kotlingroupchat/MainActivity.kt
1
3790
package io.skytreasure.kotlingroupchat import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* import android.view.View import android.widget.Toast import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import io.skytreasure.kotlingroupchat.chat.MyChatManager import io.skytreasure.kotlingroupchat.chat.ui.CreateGroupActivity import io.skytreasure.kotlingroupchat.chat.ui.OneOnOneChat import io.skytreasure.kotlingroupchat.chat.ui.ViewGroupsActivity import io.skytreasure.kotlingroupchat.common.constants.DataConstants import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.sCurrentUser import io.skytreasure.kotlingroupchat.common.constants.NetworkConstants import io.skytreasure.kotlingroupchat.common.controller.NotifyMeInterface import io.skytreasure.kotlingroupchat.common.util.SharedPrefManager import com.google.firebase.database.DatabaseError import android.databinding.adapters.NumberPickerBindingAdapter.setValue import android.util.Log import com.google.firebase.database.DataSnapshot import com.google.firebase.database.ValueEventListener import com.google.firebase.iid.FirebaseInstanceId class MainActivity : AppCompatActivity(), View.OnClickListener { var onlineRef: DatabaseReference? = null var currentUserRef: DatabaseReference? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) MyChatManager.setmContext(this@MainActivity) sCurrentUser = SharedPrefManager.getInstance(this@MainActivity).savedUserModel btn_creategroup.setOnClickListener(this) btn_showgroup.setOnClickListener(this) btn_oneonone.setOnClickListener(this) btn_logout.setOnClickListener(this) MyChatManager.setOnlinePresence() MyChatManager.updateFCMTokenAndDeviceId(this@MainActivity, FirebaseInstanceId.getInstance().token!!) MyChatManager.fetchAllUserInformation() MyChatManager.fetchMyGroups(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { var i = 0 for (group in DataConstants.sGroupMap!!) { if (group.value.members.containsKey(sCurrentUser?.uid!!)) { i += group.value.members.get(sCurrentUser?.uid)?.unread_group_count!! } } tv_notification_count.text = "Total Notification Count :" + i } }, NetworkConstants.FETCH_GROUPS, sCurrentUser, false) } override fun onClick(v: View?) { when (v?.id) { R.id.btn_creategroup -> { val intent = Intent(this@MainActivity, CreateGroupActivity::class.java) startActivity(intent) } R.id.btn_showgroup -> { val intent = Intent(this@MainActivity, ViewGroupsActivity::class.java) startActivity(intent) } R.id.btn_oneonone -> { val intent = Intent(this@MainActivity, OneOnOneChat::class.java) startActivity(intent) } R.id.btn_logout -> { MyChatManager.logout(this@MainActivity) } } } override fun onDestroy() { MyChatManager.goOffline(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { Toast.makeText(this@MainActivity, "You are offline now", Toast.LENGTH_SHORT).show() } }, sCurrentUser, NetworkConstants.GO_OFFLINE) super.onDestroy() } }
mit
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PlaceholderImpl.kt
7
1414
// 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.ui.dsl.builder.impl import com.intellij.ui.dsl.builder.Placeholder import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal internal class PlaceholderImpl(parent: RowImpl) : PlaceholderBaseImpl<Placeholder>(parent), Placeholder { override fun horizontalAlign(horizontalAlign: HorizontalAlign): Placeholder { super.horizontalAlign(horizontalAlign) return this } override fun verticalAlign(verticalAlign: VerticalAlign): Placeholder { super.verticalAlign(verticalAlign) return this } override fun resizableColumn(): Placeholder { super.resizableColumn() return this } override fun gap(rightGap: RightGap): Placeholder { super.gap(rightGap) return this } override fun enabled(isEnabled: Boolean): Placeholder { super.enabled(isEnabled) return this } override fun visible(isVisible: Boolean): Placeholder { super.visible(isVisible) return this } override fun customize(customGaps: Gaps): Placeholder { super.customize(customGaps) return this } }
apache-2.0
Major-/Vicis
modern/src/main/kotlin/rs/emulate/modern/codec/bundle/Bundle.kt
1
4552
package rs.emulate.modern.codec.bundle import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import rs.emulate.modern.codec.Archive import rs.emulate.modern.codec.Archive.Companion.readArchive import rs.emulate.modern.codec.Container import rs.emulate.modern.codec.Container.Companion.readContainer import rs.emulate.modern.codec.ReferenceTable import rs.emulate.modern.codec.ReferenceTable.Companion.readRefTable import java.io.FileNotFoundException import java.util.* class Bundle(private val referenceTable: ReferenceTable = ReferenceTable()) { private val entries = TreeMap<Int, ByteBuf>() private var dirtyReferenceTable = false val capacity: Int get() = referenceTable.capacity val listFiles: List<Int> get() = referenceTable.entryIds private fun createArchive(entry: ReferenceTable.Entry): BundleArchive { val archive = Archive() return BundleArchive(this, archive, entry) } fun createArchive(name: String): BundleArchive { val entry = referenceTable.createEntry() entry.setName(name) return createArchive(entry) } fun createArchive(file: Int): BundleArchive { val entry = referenceTable.createEntry(file) return createArchive(entry) } private fun openArchive(entry: ReferenceTable.Entry): BundleArchive { val archive = read(entry).readArchive(entry) return BundleArchive(this, archive, entry) } fun openArchive(name: String): BundleArchive { return openArchive(referenceTable.getEntry(name) ?: throw FileNotFoundException()) } fun openArchive(file: Int): BundleArchive { return openArchive(referenceTable.getEntry(file) ?: throw FileNotFoundException()) } fun flushArchive(entry: ReferenceTable.Entry, archive: Archive) { entry.bumpVersion() write(entry, archive.write()) dirtyReferenceTable = true } operator fun contains(file: Int) = referenceTable.containsEntry(file) operator fun contains(name: String) = referenceTable.containsEntry(name) fun read(file: Int): ByteBuf { return read(referenceTable.getEntry(file) ?: throw FileNotFoundException()) } fun read(name: String): ByteBuf { return read(referenceTable.getEntry(name) ?: throw FileNotFoundException()) } private fun read(entry: ReferenceTable.Entry): ByteBuf { return requireNotNull(entries[entry.id]) { "Entry in ReferenceTable but not in Bundle" } } fun write(file: Int, buf: ByteBuf) { val entry = referenceTable.getEntry(file) if (entry != null) { entry.bumpVersion() write(entry, buf) } else { val newEntry = referenceTable.createEntry(file) write(newEntry, buf) } dirtyReferenceTable = true } fun write(name: String, buf: ByteBuf) { val entry = referenceTable.getEntry(name) if (entry != null) { entry.bumpVersion() write(entry, buf) } else { val newEntry = referenceTable.createEntry() newEntry.setName(name) write(newEntry, buf) } dirtyReferenceTable = true } private fun write(entry: ReferenceTable.Entry, buf: ByteBuf) { entries[entry.id] = buf } fun remove(file: Int) { referenceTable.getEntry(file) ?: throw FileNotFoundException() entries.remove(file) referenceTable.removeEntry(file) dirtyReferenceTable = true } fun remove(name: String) { val entry = referenceTable.getEntry(name) ?: throw FileNotFoundException() val file = entry.id entries.remove(file) referenceTable.removeEntry(file) dirtyReferenceTable = true } fun write(): ByteBuf { if (dirtyReferenceTable) { dirtyReferenceTable = false referenceTable.bumpVersion() } val buf = Unpooled.compositeBuffer() buf.addComponent(true, Container.pack(referenceTable.write())) for (entry in entries.values) { buf.addComponent(true, Container.pack(entry)) } return buf.asReadOnly() } companion object { fun ByteBuf.readBundle(): Bundle { val table = readContainer().buffer.readRefTable() val bundle = Bundle(table) for (id in table.entryIds) { bundle.entries[id] = readContainer().buffer } return bundle } } }
isc
android/nowinandroid
feature/bookmarks/src/test/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksViewModelTest.kt
1
3715
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.feature.bookmarks import com.google.samples.apps.nowinandroid.core.domain.GetSaveableNewsResourcesStreamUseCase import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources import com.google.samples.apps.nowinandroid.core.testing.repository.TestNewsRepository import com.google.samples.apps.nowinandroid.core.testing.repository.TestUserDataRepository import com.google.samples.apps.nowinandroid.core.testing.util.MainDispatcherRule import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Loading import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Success import kotlin.test.assertEquals import kotlin.test.assertIs import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test /** * To learn more about how this test handles Flows created with stateIn, see * https://developer.android.com/kotlin/flow/test#statein */ class BookmarksViewModelTest { @get:Rule val dispatcherRule = MainDispatcherRule() private val userDataRepository = TestUserDataRepository() private val newsRepository = TestNewsRepository() private val getSaveableNewsResourcesStreamUseCase = GetSaveableNewsResourcesStreamUseCase( newsRepository = newsRepository, userDataRepository = userDataRepository ) private lateinit var viewModel: BookmarksViewModel @Before fun setup() { viewModel = BookmarksViewModel( userDataRepository = userDataRepository, getSaveableNewsResourcesStream = getSaveableNewsResourcesStreamUseCase ) } @Test fun stateIsInitiallyLoading() = runTest { assertEquals(Loading, viewModel.feedUiState.value) } @Test fun oneBookmark_showsInFeed() = runTest { val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.feedUiState.collect() } newsRepository.sendNewsResources(previewNewsResources) userDataRepository.updateNewsResourceBookmark(previewNewsResources[0].id, true) val item = viewModel.feedUiState.value assertIs<Success>(item) assertEquals(item.feed.size, 1) collectJob.cancel() } @Test fun oneBookmark_whenRemoving_removesFromFeed() = runTest { val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.feedUiState.collect() } // Set the news resources to be used by this test newsRepository.sendNewsResources(previewNewsResources) // Start with the resource saved userDataRepository.updateNewsResourceBookmark(previewNewsResources[0].id, true) // Use viewModel to remove saved resource viewModel.removeFromSavedResources(previewNewsResources[0].id) // Verify list of saved resources is now empty val item = viewModel.feedUiState.value assertIs<Success>(item) assertEquals(item.feed.size, 0) collectJob.cancel() } }
apache-2.0
ianhanniballake/ContractionTimer
mobile/src/main/java/com/ianhanniballake/contractiontimer/ui/AboutActivity.kt
1
1538
package com.ianhanniballake.contractiontimer.ui import android.content.pm.ActivityInfo import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.ianhanniballake.contractiontimer.BuildConfig import com.ianhanniballake.contractiontimer.R /** * About screen for the application. Shows as a dialog on large devices */ class AboutActivity : AppCompatActivity() { companion object { private const val TAG = "AboutActivity" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) val version = findViewById<TextView>(R.id.version) version.text = getString(R.string.version, BuildConfig.VERSION_NAME) } override fun onStart() { super.onStart() supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onResume() { super.onResume() val preferences = PreferenceManager.getDefaultSharedPreferences(this) val isLockPortrait = preferences.getBoolean(Preferences.LOCK_PORTRAIT_PREFERENCE_KEY, resources.getBoolean(R.bool.pref_lock_portrait_default)) if (BuildConfig.DEBUG) Log.d(TAG, "Lock Portrait: $isLockPortrait") requestedOrientation = if (isLockPortrait) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_SENSOR } }
bsd-3-clause
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/BookmarkNode.kt
2
4172
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.ui.tree import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkGroup import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmark.ui.BookmarksView import com.intellij.ide.projectView.PresentationData import com.intellij.ide.projectView.ProjectViewNode import com.intellij.ide.projectView.ProjectViewSettings.Immutable.DEFAULT import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.presentation.FilePresentationService import com.intellij.ui.BackgroundSupplier import com.intellij.ui.IconManager import com.intellij.ui.SimpleTextAttributes import javax.swing.Icon abstract class BookmarkNode<B : Bookmark>(project: Project, bookmark: B) : BackgroundSupplier, ProjectViewNode<B>(project, bookmark, DEFAULT) { val bookmarksView: BookmarksView? get() = parentRootNode?.value private val bookmarkType get() = bookmarksManager?.getType(value) val bookmarkDescription get() = bookmarkGroup?.getDescription(value)?.ifBlank { null } var bookmarkGroup: BookmarkGroup? = null override fun canRepresent(element: Any?) = virtualFile?.equals(element) ?: false override fun contains(file: VirtualFile) = virtualFile?.let { VfsUtil.isAncestor(it, file, true) } ?: false override fun canNavigate() = value.canNavigate() override fun canNavigateToSource() = value.canNavigateToSource() override fun navigate(requestFocus: Boolean) = value.navigate(requestFocus) override fun computeBackgroundColor() = FilePresentationService.getFileBackgroundColor(project, virtualFile) override fun getElementBackground(row: Int) = presentation.background protected fun wrapIcon(icon: Icon?): Icon { val type = bookmarkType ?: BookmarkType.DEFAULT return when { icon == null -> type.icon type == BookmarkType.DEFAULT -> icon else -> IconManager.getInstance().createRowIcon(type.icon, icon) } } override fun update(presentation: PresentationData) { val file = virtualFile ?: return presentation.setIcon(wrapIcon(findFileIcon())) addTextTo(presentation, file) } protected fun addTextTo(presentation: PresentationData, file: VirtualFile, line: Int = 0) { val name = file.presentableName val location = file.parent?.let { getRelativePath(it) } addTextTo(presentation, name, location, line) } protected fun addTextTo(presentation: PresentationData, name: @NlsSafe String, location: @NlsSafe String? = null, line: Int = 0) { val description = bookmarkDescription if (description == null) { presentation.presentableText = name // configure speed search presentation.addText(name, SimpleTextAttributes.REGULAR_ATTRIBUTES) if (line > 0) presentation.addText(" :$line", SimpleTextAttributes.GRAYED_ATTRIBUTES) location?.let { presentation.addText(" $it", SimpleTextAttributes.GRAYED_ATTRIBUTES) } } else { presentation.presentableText = "$description $name" // configure speed search presentation.addText("$description ", SimpleTextAttributes.REGULAR_ATTRIBUTES) presentation.addText(name, SimpleTextAttributes.GRAYED_ATTRIBUTES) if (line > 0) presentation.addText(" :$line", SimpleTextAttributes.GRAYED_ATTRIBUTES) location?.let { presentation.addText(" ($it)", SimpleTextAttributes.GRAYED_ATTRIBUTES) } } } private fun getRelativePath(file: VirtualFile): @NlsSafe String? { val project = project ?: return null if (project.isDisposed) return null val index = ProjectFileIndex.getInstance(project) index.getModuleForFile(file, false) ?: return computeExternalLocation(file) var root = file while (true) { val parent = root.parent ?: break index.getModuleForFile(parent, false) ?: break root = parent } return if (file == root) null else VfsUtil.getRelativePath(file, root) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinArrayVariable.kt
4
1157
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl import com.intellij.debugger.streams.trace.dsl.ArrayVariable import com.intellij.debugger.streams.trace.dsl.Expression import com.intellij.debugger.streams.trace.dsl.VariableDeclaration import com.intellij.debugger.streams.trace.dsl.impl.TextExpression import com.intellij.debugger.streams.trace.dsl.impl.VariableImpl import com.intellij.debugger.streams.trace.impl.handler.type.ArrayType class KotlinArrayVariable(override val type: ArrayType, override val name: String) : VariableImpl(type, name), ArrayVariable { override fun get(index: Expression): Expression = TextExpression("$name[${index.toCode()}]!!") override operator fun set(index: Expression, value: Expression): Expression = TextExpression("$name[${index.toCode()}] = ${value.toCode()}") override fun defaultDeclaration(size: Expression): VariableDeclaration = KotlinVariableDeclaration(this, false, type.sizedDeclaration(size.toCode())) }
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/selfMembersNoReflection.kt
7
1260
package ceMembers fun main(args: Array<String>) { A().test() } class A { public fun publicFun(): Int = 1 public val publicVal: Int = 2 protected fun protectedFun(): Int = 3 protected val protectedVal: Int = 4 @JvmField protected val protectedField: Int = 5 private fun privateFun() = 6 private val privateVal = 7 fun test() { //Breakpoint! val a = 1 } } fun <T> block(block: () -> T): T { return block() } // Working as intended on EE-IR: No support for disabling reflective access // REFLECTION_PATCHING: false // EXPRESSION: block { publicFun() } // RESULT: 1: I // EXPRESSION: block { publicVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { protectedFun() } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { protectedVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { protectedField } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { privateFun() } // RESULT: Method threw 'java.lang.VerifyError' exception. // EXPRESSION: block { privateVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception.
apache-2.0
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/main/kotlin/entities/OneToOneChildFetchEntity.kt
1
529
package entities import com.onyx.persistence.IManagedEntity import com.onyx.persistence.annotations.* import com.onyx.persistence.annotations.values.RelationshipType /** * Created by timothy.osborn on 11/15/14. */ @Entity class OneToOneChildFetchEntity : AbstractInheritedAttributes(), IManagedEntity { @Attribute @Identifier var id: String? = null @Relationship(type = RelationshipType.ONE_TO_ONE, inverseClass = OneToOneFetchEntity::class, inverse = "child") var parent: OneToOneFetchEntity? = null }
agpl-3.0
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslTestAction/OthersPanel.kt
8
1373
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.ui.uiDslTestAction import com.intellij.openapi.ui.Messages import com.intellij.ui.dsl.builder.COLUMNS_LARGE import com.intellij.ui.dsl.builder.columns import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.builder.text import org.jetbrains.annotations.ApiStatus import javax.swing.JEditorPane @Suppress("DialogTitleCapitalization") @ApiStatus.Internal internal class OthersPanel { val panel = panel { group("DslLabel text update") { lateinit var dslText: JEditorPane row { dslText = text("Initial text with a <a href='link'>link</a>", action = { Messages.showMessageDialog("Link '${it.description}' is clicked", "Message", null) }) .component } row { val textField = textField() .text("New text with <a href='another link'>another link</a><br>Second line") .columns(COLUMNS_LARGE) .component button("Update") { dslText.text = textField.text } } } group("Size groups") { row { button("Button", {}).widthGroup("group1") button("A very long button", {}).widthGroup("group1") }.rowComment("Buttons with the same widthGroup") } } }
apache-2.0
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/util/livedata/LiveDataExtensions.kt
4
226
package org.thoughtcrime.securesms.util.livedata import androidx.lifecycle.LiveData fun <T, R> LiveData<T>.distinctUntilChanged(selector: (T) -> R): LiveData<T> { return LiveDataUtil.distinctUntilChanged(this, selector) }
gpl-3.0
pdvrieze/kotlinsql
sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/dml/Insert.kt
1
885
/* * Copyright (c) 2021. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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.github.pdvrieze.kotlinsql.dml interface Insert : UpdatingStatement { val batch: List<InsertValues> fun toSQL(): String }
apache-2.0
pdvrieze/kotlinsql
sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/ddl/columns/LengthCharColumn.kt
1
1149
/* * Copyright (c) 2021. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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.github.pdvrieze.kotlinsql.ddl.columns import io.github.pdvrieze.kotlinsql.ddl.Table interface LengthCharColumn<S: LengthCharColumnType<S>>: ICharColumn<S, LengthCharColumn<S>>, ILengthColumn<String, S, LengthCharColumn<S>> { override fun copyConfiguration(newName:String?, owner: Table): LengthCharColumnConfiguration<S> }
apache-2.0
bgogetap/KotlinWeather
app/src/main/kotlin/com/cultureoftech/kotlinweather/main/MainComponent.kt
1
291
package com.cultureoftech.kotlinweather.main import com.cultureoftech.kotlinweather.dagger.ForMain import dagger.Subcomponent /** * Created by bgogetap on 2/19/16. */ @ForMain @Subcomponent(modules = arrayOf(MainModule::class)) interface MainComponent { fun inject(view: MainView) }
apache-2.0
DarrenAtherton49/droid-community-app
app/src/main/kotlin/com/darrenatherton/droidcommunity/common/threading/RxIoExecutor.kt
1
309
package com.darrenatherton.droidcommunity.common.threading import rx.Scheduler import rx.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @Singleton class RxIoExecutor @Inject constructor() : IoExecutor { override val scheduler: Scheduler get() = Schedulers.io() }
mit
daviddenton/k2
src/test/kotlin/Runners.kt
1
4507
import io.github.daviddenton.k2.Filter import io.github.daviddenton.k2.Service import io.github.daviddenton.k2.Service.Companion.mk import io.github.daviddenton.k2.Svc import io.github.daviddenton.k2.contract.* import io.github.daviddenton.k2.contract.ContentType.Companion.APPLICATION_FORM_URLENCODED import io.github.daviddenton.k2.contract.ContentType.Companion.APPLICATION_XML import io.github.daviddenton.k2.formats.Argo import io.github.daviddenton.k2.formats.Argo.Json import io.github.daviddenton.k2.formats.Argo.Json.asJson import io.github.daviddenton.k2.formats.Argo.Json.obj import io.github.daviddenton.k2.formats.Argo.Response import io.github.daviddenton.k2.http.Method import io.github.daviddenton.k2.http.Method.Get import io.github.daviddenton.k2.http.Request import io.github.daviddenton.k2.http.Root import io.github.daviddenton.k2.module.render.RouteModule import java.time.LocalDate data class Bob(val value: String) data class DateWrapper(val value: LocalDate) fun main(args: Array<String>) { fun servicesAndFilters() { println("filters") val asInt = Filter.mk { req: String, svc: Service<Int, Int> -> svc(req.toInt()).toString() } val tripleResult = Filter.mk { req: Int, svc: Service<Int, Int> -> svc(req) * 3 } println((asInt.andThen(tripleResult).andThen(Service.const(123)))("321")) } fun routes() { println("routes") val bob = Path.of(Parameter.string().map(::Bob, Bob::value).single("bob")) val json = Path.of(Argo.parameter.single("bob")) val query = Query.required(Argo.parameter.single("bob")) fun svc(string: Bob): Svc = Service.const(Response(200).build()) val serverRoute = Route("bob") .producing(APPLICATION_FORM_URLENCODED) .consuming(APPLICATION_XML) .body(Body.of(Body.string(ContentType.TEXT_HTML))) .taking(query) / "bob" / bob at Get bind ::svc val clientRoute = Route("bob2") / "bob" / bob at Get bindClient mk { r: Request -> Response(200).withContent(Json.array(Json.string(r.uri))).build() } val a = RouteModule(Root) .withRoute(serverRoute).toService() println(a(Request(Get, "/asd"))) } fun parameters() { println("parameters") val date: NamedParameter<DateWrapper, DateWrapper> = Parameter.localDate().map(::DateWrapper).single("date") val dates: NamedParameter<DateWrapper, Iterable<DateWrapper>> = Parameter.localDate().map(::DateWrapper).multi("dates") val dateWOpt: DateWrapper? = Query.optional(date).from(Request(Get, "http://location/index?date=2012-10-02", "")) val dateWListOpt: Iterable<DateWrapper>? = Query.optional(dates).from(Request(Get, "http://location/index?dates=2012-10-02", "")) val dateW: DateWrapper = Query.required(date).from(Request(Get, "http://location/index?date=2012-10-02", "")) val dateWList: Iterable<DateWrapper> = Query.required(dates).from(Request(Get, "http://location/index?dates=2012-10-02", "")) println(Query.optional(date).extract(Request(Get, "http://location/index", ""))) println(Query.optional(dates).extract(Request(Get, "http://location/index", ""))) println(Query.required(date).extract(Request(Get, "http://location/index?date=2012-10-02", ""))) println(Query.required(dates).extract(Request(Get, "http://location/index?dates=2012-10-02", ""))) } fun bodies() { println("bodies") val field1 = FormField.required(Parameter.string().map(::Bob, Bob::value).multi("bob")) val field2 = FormField.required(Parameter.boolean().single("sue")) val form = Body.of(Form.mk(field1, field2)).from(Request(Method.Post, "http://location/index", "bob=hello&bob=hello2&sue=true")) println("${field1.named.name}=${form[field1]}") println("${field2.named.name}=${form[field2]}") Form(field1.of(listOf<Bob>()), field2.of(true)) println(Body.of(Form.mk(field1, field2)).extract(Request(Method.Post, "http://location/index", "bob=hello&bob=hello2"))) val body = Body.of(Argo.body.map({ Bob(it.getStringValue("name")) }) { obj("name" to it.value.asJson()) }) println(body.from(Request(Get, "http://location/index?bob=foo&bob=fo2", """{"name":"bobby"}"""))) } fun formats() { println("formats") println(obj("name" to Json.string("hello"))) } servicesAndFilters() formats() routes() parameters() bodies() }
apache-2.0
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/OAuth.kt
2
362
package eu.kanade.tachiyomi.data.track.kitsu import kotlinx.serialization.Serializable @Serializable data class OAuth( val access_token: String, val token_type: String, val created_at: Long, val expires_in: Long, val refresh_token: String? ) { fun isExpired() = (System.currentTimeMillis() / 1000) > (created_at + expires_in - 3600) }
apache-2.0
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/commons/CollectionsExtensions.kt
1
1285
/* * Copyright 2021 Michael Rozumyanskiy * * 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.michaelrocks.grip.commons import java.util.Collections import java.util.SortedMap import java.util.SortedSet internal fun <T> Collection<T>.immutable(): Collection<T> = Collections.unmodifiableCollection(this) internal fun <T> List<T>.immutable(): List<T> = Collections.unmodifiableList(this) internal fun <K, V> Map<K, V>.immutable(): Map<K, V> = Collections.unmodifiableMap(this) internal fun <T> Set<T>.immutable(): Set<T> = Collections.unmodifiableSet(this) internal fun <K, V> SortedMap<K, V>.immutable(): SortedMap<K, V> = Collections.unmodifiableSortedMap(this) internal fun <T> SortedSet<T>.immutable(): SortedSet<T> = Collections.unmodifiableSortedSet(this)
apache-2.0
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/MethodsResult.kt
1
1909
/* * Copyright 2021 Michael Rozumyanskiy * * 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.michaelrocks.grip import io.michaelrocks.grip.commons.LazyMap import io.michaelrocks.grip.mirrors.ClassMirror import io.michaelrocks.grip.mirrors.MethodMirror import io.michaelrocks.grip.mirrors.Type interface MethodsResult : Map<Type.Object, List<MethodMirror>> { val types: Set<Type.Object> get() = keys fun containsType(type: Type.Object) = containsKey(type) class Builder { private val methods = LazyMap<Type.Object, List<MethodMirror>>() fun addMethods(classMirror: ClassMirror, methodMirrors: Iterable<MethodMirror>) = apply { val oldMethods = methods.put(classMirror.type, methodMirrors.toList()) require(oldMethods == null) { "Methods for class ${classMirror.type} have already been added" } } fun build(): MethodsResult = ImmutableMethodsResult(this) private class ImmutableMethodsResult( builder: Builder ) : MethodsResult, Map<Type.Object, List<MethodMirror>> by builder.methods.detachImmutableCopy() } } internal inline fun buildMethodsResult(body: MethodsResult.Builder.() -> Unit) = MethodsResult.Builder().run { body() build() } val Map.Entry<Type.Object, List<MethodMirror>>.type: Type.Object get() = key val Map.Entry<Type.Object, List<MethodMirror>>.methods: List<MethodMirror> get() = value
apache-2.0
jovr/imgui
core/src/main/kotlin/imgui/internal/sections/Multi-select support.kt
2
226
package imgui.internal.sections //----------------------------------------------------------------------------- // [SECTION] Multi-select support //-----------------------------------------------------------------------------
mit
KDE/kdeconnect-android
src/org/kde/kdeconnect/UserInterface/About/ApplicationAboutData.kt
1
2910
/* * SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ package org.kde.kdeconnect.UserInterface.About import android.content.Context import org.kde.kdeconnect_tp.BuildConfig import org.kde.kdeconnect_tp.R /** * Add authors and credits here */ fun getApplicationAboutData(context: Context): AboutData { val aboutData = AboutData(context.getString(R.string.kde_connect), R.string.app_description, R.drawable.icon, BuildConfig.VERSION_NAME, context.getString(R.string.copyright_statement), context.getString(R.string.report_bug_url), context.getString(R.string.website_url), context.getString(R.string.source_code_url), context.getString(R.string.donate_url), R.string.everyone_else) aboutData.authors += AboutPerson("Albert Vaca Cintora", R.string.maintainer_and_developer, "[email protected]") aboutData.authors += AboutPerson("Aleix Pol", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Inoki Shaw", R.string.apple_support, "[email protected]") aboutData.authors += AboutPerson("Matthijs Tijink", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Nicolas Fella", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Philip Cohn-Cort", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Piyush Aggarwal", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Simon Redman", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Erik Duisters", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Isira Seneviratne", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Vineet Garg", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Anjani Kumar", R.string.bug_fixes_and_general_improvements, "[email protected]") aboutData.authors += AboutPerson("Samoilenko Yuri", R.string.samoilenko_yuri_task, "[email protected]") aboutData.authors += AboutPerson("Aniket Kumar", R.string.aniket_kumar_task, "[email protected]") aboutData.authors += AboutPerson("Àlex Fiestas", R.string.alex_fiestas_task, "[email protected]") aboutData.authors += AboutPerson("Daniel Tang", R.string.bug_fixes_and_general_improvements, "[email protected]") aboutData.authors += AboutPerson("Maxim Leshchenko", R.string.maxim_leshchenko_task, "[email protected]") aboutData.authors += AboutPerson("Holger Kaelberer", R.string.holger_kaelberer_task, "[email protected]") aboutData.authors += AboutPerson("Saikrishna Arcot", R.string.saikrishna_arcot_task, "[email protected]") return aboutData }
gpl-2.0
google/ground-android
ground/src/main/java/com/google/android/ground/persistence/local/LocalDatabaseModule.kt
1
1393
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.persistence.local import android.content.Context import androidx.room.Room import com.google.android.ground.Config import com.google.android.ground.persistence.local.room.LocalDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object LocalDatabaseModule { @Provides @Singleton fun localDatabase(@ApplicationContext context: Context): LocalDatabase { return Room.databaseBuilder(context, LocalDatabase::class.java, Config.DB_NAME) .fallbackToDestructiveMigration() // TODO(#128): Disable before official release. .build() } }
apache-2.0
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/database/Table.kt
1
994
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.database @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Table(val name: String, val id: String = "id")
gpl-3.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/addJvmNameAnnotation/extension3.kt
4
173
// "Add '@JvmName' annotation" "true" // WITH_STDLIB interface Bar<T, U> fun Bar<Int, Double>.bar() = this fun <caret>Bar<Int, Bar<Long, Bar<Double, String>>>.bar() = this
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/stubs/AnnotationsOnPrimaryCtr.kt
13
56
class A @[Deprecated] private @[Override Deprecated] ()
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/completion/tests/testData/handlers/basic/override/ValInConstructorParameter3.kt
8
145
// FIR_IDENTICAL // FIR_COMPARISON interface I { val p: Int } class CCCC(over<caret>val x: Int) : I // ELEMENT_TEXT: "override val p: Int"
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinUsageInfo.kt
6
1846
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.util.descendantsOfType import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.NotNullablePsiCopyableUserDataProperty abstract class KotlinUsageInfo<T : PsiElement> : UsageInfo { constructor(element: T) : super(element) constructor(reference: PsiReference) : super(reference) @Suppress("UNCHECKED_CAST") override fun getElement() = super.getElement() as T? open fun preprocessUsage() {} abstract fun processUsage(changeInfo: KotlinChangeInfo, element: T, allUsages: Array<out UsageInfo>): Boolean protected fun <T: KtElement> T.asMarkedForShortening(): T = apply { isMarked = true } protected fun KtElement.flushElementsForShorteningToWaitList(options: ShortenReferences.Options = ShortenReferences.Options.ALL_ENABLED) { for (element in descendantsOfType<KtElement>()) { if (element.isMarked) { element.isMarked = false element.addToShorteningWaitSet(options) } } } companion object { private var KtElement.isMarked: Boolean by NotNullablePsiCopyableUserDataProperty( key = Key.create("MARKER_FOR_SHORTENING"), defaultValue = false, ) } }
apache-2.0
dkandalov/katas
kotlin/src/katas/kotlin/leetcode/remove_duplicates_from_array/RemoveDuplicatesFromSortedArray.kt
1
1863
package katas.kotlin.leetcode.remove_duplicates_from_array import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ */ class RemoveDuplicatesFromSortedArrayTests { @Test fun `remove the duplicates in-place such that each element appear only once`() { intArrayOf().removeDuplicatesToList() shouldEqual emptyList() intArrayOf(1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1, 1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1, 1, 1).removeDuplicatesToList() shouldEqual listOf(1) intArrayOf(1, 2).removeDuplicatesToList() shouldEqual listOf(1, 2) intArrayOf(1, 1, 2).removeDuplicatesToList() shouldEqual listOf(1, 2) intArrayOf(1, 2, 2).removeDuplicatesToList() shouldEqual listOf(1, 2) intArrayOf(1, 2, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 1, 2, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 2, 2, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 2, 3, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(1, 1, 2, 2, 3, 3).removeDuplicatesToList() shouldEqual listOf(1, 2, 3) intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4).removeDuplicatesToList() shouldEqual listOf(0, 1, 2, 3, 4) } } private fun IntArray.removeDuplicatesToList(): List<Int> { val newSize = removeDuplicates() return toList().take(newSize) } private fun IntArray.removeDuplicates(): Int { if (size <= 1) return size var i = 0 var j = 1 while (j < size) { if (this[i] != this[j]) { if (i + 1 != j) this[i + 1] = this[j] i++ } j++ } return i + 1 }
unlicense
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/formatter/modifierList/funAnnotationBeforeAnnotation.after.kt
13
27
@annot @foo fun foo() { }
apache-2.0
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipActionProvider.kt
5
5756
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl import com.intellij.codeInsight.daemon.impl.tooltips.TooltipActionProvider import com.intellij.codeInsight.intention.AbstractEmptyIntentionAction import com.intellij.codeInsight.intention.CustomizableIntentionAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInsight.intention.impl.CachedIntentions import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.internal.statistic.service.fus.collectors.TooltipActionsLogger import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.TooltipAction import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.xml.util.XmlStringUtil import java.awt.event.InputEvent import java.util.* class DaemonTooltipActionProvider : TooltipActionProvider { override fun getTooltipAction(info: HighlightInfo, editor: Editor, psiFile: PsiFile): TooltipAction? { val intention = extractMostPriorityFixFromHighlightInfo(info, editor, psiFile) ?: return null return wrapIntentionToTooltipAction(intention, info, editor) } } /** * Tooltip link-action that proxies its execution to intention action with text [myActionText] * @param myFixText is a text to show in tooltip * @param myActionText is a text to search for in intentions' actions */ class DaemonTooltipAction(@NlsActions.ActionText private val myFixText: String, @NlsContexts.Command private val myActionText: String, private val myActualOffset: Int) : TooltipAction { override fun getText(): String { return myFixText } override fun execute(editor: Editor, inputEvent: InputEvent?) { val project = editor.project ?: return TooltipActionsLogger.logExecute(project, inputEvent) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return val intentions = ShowIntentionsPass.getAvailableFixes(editor, psiFile, -1, myActualOffset) for (descriptor in intentions) { val action = descriptor.action if (action.text == myActionText) { //unfortunately it is very common case when quick fixes/refactorings use caret position editor.caretModel.moveToOffset(myActualOffset) ShowIntentionActionsHandler.chooseActionAndInvoke(psiFile, editor, action, myActionText) return } } } override fun showAllActions(editor: Editor) { editor.caretModel.moveToOffset(myActualOffset) val project = editor.project ?: return TooltipActionsLogger.showAllEvent.log(project) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return ShowIntentionActionsHandler().invoke(project, editor, psiFile) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val info = other as DaemonTooltipAction? return myActualOffset == info!!.myActualOffset && myFixText == info.myFixText } override fun hashCode(): Int { return Objects.hash(myFixText, myActualOffset) } } fun extractMostPriorityFixFromHighlightInfo(highlightInfo: HighlightInfo, editor: Editor, psiFile: PsiFile): IntentionAction? { ApplicationManager.getApplication().assertReadAccessAllowed() val fixes = mutableListOf<HighlightInfo.IntentionActionDescriptor>() val quickFixActionMarkers = highlightInfo.quickFixActionRanges if (quickFixActionMarkers.isNullOrEmpty()) return null fixes.addAll(quickFixActionMarkers.map { it.first }.toList()) val intentionsInfo = ShowIntentionsPass.IntentionsInfo() ShowIntentionsPass.fillIntentionsInfoForHighlightInfo(highlightInfo, intentionsInfo, fixes) intentionsInfo.filterActions(psiFile) return getFirstAvailableAction(psiFile, editor, intentionsInfo) } fun getFirstAvailableAction(psiFile: PsiFile, editor: Editor, intentionsInfo: ShowIntentionsPass.IntentionsInfo): IntentionAction? { val project = psiFile.project //sort the actions val cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFile, editor, intentionsInfo) val allActions = cachedIntentions.allActions if (allActions.isEmpty()) return null allActions.forEach { val action = IntentionActionDelegate.unwrap(it.action) if (action !is AbstractEmptyIntentionAction && action.isAvailable(project, editor, psiFile)) { val text = it.text //we cannot properly render html inside the fix button fixes with html text if (!XmlStringUtil.isWrappedInHtml(text)) { return action } } } return null } fun wrapIntentionToTooltipAction(intention: IntentionAction, info: HighlightInfo, editor: Editor): TooltipAction { val editorOffset = editor.caretModel.offset val text = (intention as? CustomizableIntentionAction)?.tooltipText ?: intention.text if ((info.actualStartOffset .. info.actualEndOffset).contains(editorOffset)) { //try to avoid caret movements return DaemonTooltipAction(text, intention.text, editorOffset) } val pair = info.quickFixActionMarkers?.find { it.first?.action == intention } val offset = if (pair?.second?.isValid == true) pair.second.startOffset else info.actualStartOffset return DaemonTooltipAction(text, intention.text, offset) }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/completion/tests/testData/handlers/multifile/KT12077-2.kt
13
47
package other annotation class SomeAnnotation
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/hierarchy/kotlin/get/K/K.kt
10
55
open class K { open var prop<caret>erty: Int = 42 }
apache-2.0
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/table/FavMute.kt
1
2779
package jp.juggler.subwaytooter.table import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import jp.juggler.subwaytooter.api.entity.Acct import jp.juggler.subwaytooter.global.appDatabase import jp.juggler.util.LogCategory import jp.juggler.util.TableCompanion object FavMute : TableCompanion { private val log = LogCategory("FavMute") override val table = "fav_mute" const val COL_ID = "_id" const val COL_ACCT = "acct" override fun onDBCreate(db: SQLiteDatabase) { log.d("onDBCreate!") db.execSQL( """create table if not exists $table ($COL_ID INTEGER PRIMARY KEY ,$COL_ACCT text not null )""".trimIndent() ) db.execSQL("create unique index if not exists ${table}_acct on $table($COL_ACCT)") } override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (oldVersion < 22 && newVersion >= 22) { onDBCreate(db) } } fun save(acct: Acct?) { acct ?: return try { val cv = ContentValues() cv.put(COL_ACCT, acct.ascii) appDatabase.replace(table, null, cv) } catch (ex: Throwable) { log.e(ex, "save failed.") } } fun delete(acct: Acct) { try { appDatabase.delete(table, "$COL_ACCT=?", arrayOf(acct.ascii)) } catch (ex: Throwable) { log.e(ex, "delete failed.") } } fun createCursor(): Cursor { return appDatabase.query(table, null, null, null, null, null, "$COL_ACCT asc") } val acctSet: HashSet<Acct> get() = HashSet<Acct>().also { dst -> try { appDatabase.query(table, null, null, null, null, null, null) .use { cursor -> val idx_name = cursor.getColumnIndex(COL_ACCT) while (cursor.moveToNext()) { val s = cursor.getString(idx_name) dst.add(Acct.parse(s)) } } } catch (ex: Throwable) { log.trace(ex) } } fun contains(acct: Acct): Boolean { var found = false try { appDatabase.query(table, null, "$COL_ACCT=?", arrayOf(acct.ascii), null, null, null) .use { cursor -> while (cursor.moveToNext()) { found = true } } } catch (ex: Throwable) { log.trace(ex) } return found } }
apache-2.0