content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
public object `$$Anko$Factories$RecyclerviewV7ViewGroup` { public val RECYCLER_VIEW = { ctx: Context -> _RecyclerView(ctx) } } public inline fun ViewManager.recyclerView(): android.support.v7.widget.RecyclerView = recyclerView({}) public inline fun ViewManager.recyclerView(init: _RecyclerView.() -> Unit): android.support.v7.widget.RecyclerView { return ankoView(`$$Anko$Factories$RecyclerviewV7ViewGroup`.RECYCLER_VIEW) { init() } } public inline fun Context.recyclerView(): android.support.v7.widget.RecyclerView = recyclerView({}) public inline fun Context.recyclerView(init: _RecyclerView.() -> Unit): android.support.v7.widget.RecyclerView { return ankoView(`$$Anko$Factories$RecyclerviewV7ViewGroup`.RECYCLER_VIEW) { init() } } public inline fun Activity.recyclerView(): android.support.v7.widget.RecyclerView = recyclerView({}) public inline fun Activity.recyclerView(init: _RecyclerView.() -> Unit): android.support.v7.widget.RecyclerView { return ankoView(`$$Anko$Factories$RecyclerviewV7ViewGroup`.RECYCLER_VIEW) { init() } }
dsl/testData/functional/recyclerview-v7/ViewTest.kt
2736629610
package yuku.alkitab.base.verses import android.graphics.Rect import android.graphics.drawable.Drawable import yuku.alkitab.model.Version import yuku.alkitab.util.IntArrayList interface VersesController { enum class VerseSelectionMode { none, multiple, singleClick } abstract class SelectedVersesListener { open fun onSomeVersesSelected(verses_1: IntArrayList) {} open fun onNoVersesSelected() {} open fun onVerseSingleClick(verse_1: Int) {} } abstract class AttributeListener { open fun onBookmarkAttributeClick(version: Version, versionId: String, ari: Int) {} open fun onNoteAttributeClick(version: Version, versionId: String, ari: Int) {} open fun onProgressMarkAttributeClick(version: Version, versionId: String, preset_id: Int) {} open fun onHasMapsAttributeClick(version: Version, versionId: String, ari: Int) {} } abstract class VerseScrollListener { open fun onVerseScroll(isPericope: Boolean, verse_1: Int, prop: Float) {} open fun onScrollToTop() {} } abstract class PinDropListener { open fun onPinDropped(presetId: Int, ari: Int) {} } sealed class PressResult { object Left : PressResult() object Right : PressResult() class Consumed(val targetVerse_1: Int) : PressResult() object Nop : PressResult() } // # field ctor /** * Name of this [VersesController] for debugging. */ val name: String var versesDataModel: VersesDataModel var versesUiModel: VersesUiModel var versesListeners: VersesListeners fun uncheckAllVerses(callSelectedVersesListener: Boolean) fun checkVerses(verses_1: IntArrayList, callSelectedVersesListener: Boolean) /** * Returns a list of checked verse_1 in ascending order. * Old name: getSelectedVerses_1 */ fun getCheckedVerses_1(): IntArrayList fun scrollToTop() /** * This is different from the other [scrollToVerse] in that if the requested * verse has a pericope header, this will scroll to the top of the pericope header, * not to the top of the verse. */ fun scrollToVerse(verse_1: Int) /** * This is different from the other [scrollToVerse] in that if the requested * verse has a pericope header, this will scroll to the verse, ignoring the pericope header. */ fun scrollToVerse(verse_1: Int, prop: Float) /** * Returns 0 if the scroll position can't be determined (e.g. the view has 0 height). * Old name: getVerseBasedOnScroll */ fun getVerse_1BasedOnScroll(): Int fun pageDown(): PressResult fun pageUp(): PressResult fun verseDown(): PressResult fun verseUp(): PressResult fun setViewVisibility(visibility: Int) fun setViewPadding(padding: Rect) fun setViewScrollbarThumb(thumb: Drawable) /** * Set the layout params of the view that is represented by this controller. */ fun setViewLayoutSize(width: Int, height: Int) fun callAttentionForVerse(verse_1: Int) fun setEmptyMessage(message: CharSequence?, textColor: Int) }
Alkitab/src/main/java/yuku/alkitab/base/verses/VersesController.kt
584287467
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.css.styles import i.katydid.css.styles.KatydidStyleImpl //--------------------------------------------------------------------------------------------------------------------- /** * Interface to a style - one or more CSS properties with values. */ interface KatydidStyle { /** The individual properties making up this style. */ val properties: List<String> /** Funky side-effecting getter actually sets the previously set property to be !important. */ val important: Unit /** True if this style has at least one property. */ val isNotEmpty: Boolean //// /** Copies all the properties from the given [style]. (Similar to CSS @import.) */ fun include(style: KatydidStyle) /** Adds a given property with key [key] and value "inherit". */ fun inherit(key: String) /** Sets a property with 1-4 values [top], [right], [bottom], [left] for the CSS box model. */ fun <T> setBoxProperty(key: String, top: T, right: T = top, bottom: T = top, left: T = right) /** Sets a property of the style with given [key] and [value]. */ fun setProperty(key: String, value: String) /** Sets an [x]/[y] or horizontal/vertical two-value property with given [key]. */ fun <T> setXyProperty(key: String, x: T, y: T = x) /** Sets a property where the value is to become a quoted string. */ fun setStringProperty(key: String, value: String) /** * Converts this style to CSS with [indent] spaces at the beginning of each line and [whitespace] between * successive lines. */ fun toCssString(indent: String = "", whitespace: String = "\n"): String } //--------------------------------------------------------------------------------------------------------------------- /** * Builds a new style object. * @param build the callback that fills in the CSS properties. */ fun makeStyle( build: KatydidStyle.() -> Unit ): KatydidStyle { val result = KatydidStyleImpl() result.build() return result } //---------------------------------------------------------------------------------------------------------------------
Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/KatydidStyle.kt
3059585413
package api.item import api.predef.* import io.luna.util.Rational /** * A model representing the primary [lootTable] receiver. * * @author lare96 */ class LootTableReceiver { /** * The items to initialize the loot table with. */ val items = mutableListOf<LootTableItem>() /** * Creates a set of [LootTableItem]s with [chance]. */ fun rarity(chance: Rational, func: RarityReceiver.() -> Unit) = func(RarityReceiver(this, chance, false)) /** * Create the loot table! */ fun toLootTable() = LootTable(items) }
plugins/api/item/LootTableReceiver.kt
2465724308
package de.saschahlusiak.freebloks.network import de.saschahlusiak.freebloks.model.GameStateException interface MessageHandler { /** * Process a single message */ @Throws(ProtocolException::class, GameStateException::class) fun handleMessage(message: Message) }
game/src/main/java/de/saschahlusiak/freebloks/network/MessageHandler.kt
1045255096
package com.tamsiree.rxdemo.adapter import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import com.tamsiree.rxdemo.fragment.FragmentPage /** * @ClassName PagerAdapter * @Description TODO * @Author tamsiree * @Date 20-3-14 下午1:23 * @Version 1.0 */ internal class AdapterFP(fm: FragmentManager?) : FragmentPagerAdapter(fm!!) { override fun getCount(): Int { return 5 } override fun getItem(position: Int): Fragment { return FragmentPage.newInstance(position + 1, position == count - 1) } override fun getPageTitle(position: Int): CharSequence { return "Page $position" } }
RxDemo/src/main/java/com/tamsiree/rxdemo/adapter/AdapterFP.kt
808038841
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.data.api import com.github.panpf.sketch.sample.model.PexelsCurated import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface PexelsService { @GET("v1/curated") suspend fun curated(@Query("page") pageIndex: Int, @Query("per_page") size: Int): Response<PexelsCurated> }
sample/src/main/java/com/github/panpf/sketch/sample/data/api/PexelsService.kt
3165180678
package com.tamsiree.rxkit import android.content.Context import android.util.Log import com.tamsiree.rxkit.RxDataTool.Companion.isNullString import com.tamsiree.rxkit.RxFileTool.Companion.rootPath import java.io.* import java.text.SimpleDateFormat import java.util.* /** * @author tamsiree * @date 2016/1/24 */ object TLog { private val LOG_FORMAT = SimpleDateFormat("yyyy年MM月dd日_HH点mm分ss秒") // 日志的输出格式 private val FILE_SUFFIX = SimpleDateFormat("HH点mm分ss秒") // 日志文件格式 private val FILE_DIR = SimpleDateFormat("yyyy年MM月dd日") // 日志文件格式 // 日志文件总开关 private var LOG_SWITCH = true // 日志写入文件开关 private var LOG_TO_FILE = true //崩溃日志写入文件开关 private var LOG_CRASH_FILE = true private const val LOG_TAG = "TLog" // 默认的tag private const val LOG_TYPE = 'v' // 输入日志类型,v代表输出所有信息,w则只输出警告... private const val LOG_SAVE_DAYS = 7 // sd卡中日志文件的最多保存天数 private var LOG_FILE_PATH // 日志文件保存路径 : String? = null private var LOG_FILE_NAME // 日志文件保存名称 : String? = null @JvmStatic fun init(context: Context) { // 在Application中初始化 LOG_FILE_PATH = rootPath!!.path + File.separator + context.packageName + File.separator + "Log" LOG_FILE_NAME = "TLog_" } fun switchLog(switch: Boolean) { this.LOG_SWITCH = switch } fun switch2File(switch: Boolean) { this.LOG_TO_FILE = switch } fun switchCrashFile(switch: Boolean) { this.LOG_CRASH_FILE = switch } /**************************** * Warn */ @JvmStatic fun w(msg: Any): File { return w(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun w(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'w') } /*************************** * Error */ @JvmStatic fun e(msg: Any): File { return e(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun e(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'e') } /*************************** * Debug */ @JvmStatic fun d(msg: Any): File { return d(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun d(tag: String, msg: Any?, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'd') } /**************************** * Info */ @JvmStatic fun i(msg: Any): File { return i(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun i(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'i') } /************************** * Verbose */ @JvmStatic fun v(msg: Any): File { return v(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun v(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'v') } /** * 根据tag, msg和等级,输出日志 * * @param tag * @param msg * @param level */ private fun log(tag: String, msg: String, tr: Throwable?, level: Char): File { var logFile = File("") if (LOG_SWITCH) { if ('e' == level && ('e' == LOG_TYPE || 'v' == LOG_TYPE)) { // 输出错误信息 Log.e(tag, msg, tr) } else if ('w' == level && ('w' == LOG_TYPE || 'v' == LOG_TYPE)) { Log.w(tag, msg, tr) } else if ('d' == level && ('d' == LOG_TYPE || 'v' == LOG_TYPE)) { Log.d(tag, msg, tr) } else if ('i' == level && ('d' == LOG_TYPE || 'v' == LOG_TYPE)) { Log.i(tag, msg, tr) } else { Log.v(tag, msg, tr) } if (LOG_TO_FILE || (LOG_CRASH_FILE && ('e' == level || 'e' == LOG_TYPE))) { var content = "" if (!isNullString(msg)) { content += msg } if (tr != null) { content += "\n" content += Log.getStackTraceString(tr) } logFile = log2File(level.toString(), tag, content) } } return logFile } /** * 打开日志文件并写入日志 * * @return */ @Synchronized private fun log2File(mylogtype: String, tag: String, text: String): File { val nowtime = Date() val date = FILE_SUFFIX.format(nowtime) val dateLogContent = """ Date:${LOG_FORMAT.format(nowtime)} LogType:$mylogtype Tag:$tag Content: $text """.trimIndent() // 日志输出格式 val path = LOG_FILE_PATH + File.separator + FILE_DIR.format(nowtime) val destDir = File(path) if (!destDir.exists()) { destDir.mkdirs() } val file = File(path, "$LOG_FILE_NAME$date.txt") try { if (!file.exists()) { file.createNewFile() } val filerWriter = FileWriter(file, true) val bufWriter = BufferedWriter(filerWriter) bufWriter.write(dateLogContent) bufWriter.newLine() bufWriter.close() filerWriter.close() } catch (e: IOException) { e.printStackTrace() } return file } /** * 删除指定的日志文件 */ @JvmStatic fun delAllLogFile() { // 删除日志文件 // String needDelFiel = FILE_SUFFIX.format(getDateBefore()); RxFileTool.deleteDir(LOG_FILE_PATH) } /** * 得到LOG_SAVE_DAYS天前的日期 * * @return */ private val dateBefore: Date private get() { val nowtime = Date() val now = Calendar.getInstance() now.time = nowtime now[Calendar.DATE] = now[Calendar.DATE] - LOG_SAVE_DAYS return now.time } @JvmStatic fun saveLogFile(message: String) { val fileDir = File(rootPath.toString() + File.separator + RxTool.getContext().packageName) if (!fileDir.exists()) { fileDir.mkdirs() } val file = File(fileDir, RxTimeTool.getCurrentDateTime("yyyyMMdd") + ".txt") try { if (file.exists()) { val ps = PrintStream(FileOutputStream(file, true)) ps.append(""" ${RxTimeTool.getCurrentDateTime("\n\n\nyyyy-MM-dd HH:mm:ss")} $message """.trimIndent()) // 往文件里写入字符串 } else { val ps = PrintStream(FileOutputStream(file)) file.createNewFile() ps.println(""" ${RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm:ss")} $message """.trimIndent()) // 往文件里写入字符串 } } catch (e: IOException) { e.printStackTrace() } } }
RxKit/src/main/java/com/tamsiree/rxkit/TLog.kt
1945875436
package chat.rocket.android.chatdetails.ui import DrawableHelper import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import chat.rocket.android.R import chat.rocket.android.chatdetails.domain.ChatDetails import chat.rocket.android.chatdetails.presentation.ChatDetailsPresenter import chat.rocket.android.chatdetails.presentation.ChatDetailsView import chat.rocket.android.chatdetails.viewmodel.ChatDetailsViewModel import chat.rocket.android.chatdetails.viewmodel.ChatDetailsViewModelFactory import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.server.domain.CurrentServerRepository import chat.rocket.android.server.domain.GetSettingsInteractor import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import chat.rocket.android.widget.DividerItemDecoration import chat.rocket.common.model.RoomType import chat.rocket.common.model.roomTypeOf import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_chat_details.* import javax.inject.Inject fun newInstance( chatRoomId: String, chatRoomType: String, isSubscribed: Boolean, isFavorite: Boolean, disableMenu: Boolean ): ChatDetailsFragment { return ChatDetailsFragment().apply { arguments = Bundle(5).apply { putString(BUNDLE_CHAT_ROOM_ID, chatRoomId) putString(BUNDLE_CHAT_ROOM_TYPE, chatRoomType) putBoolean(BUNDLE_IS_SUBSCRIBED, isSubscribed) putBoolean(BUNDLE_IS_FAVORITE, isFavorite) putBoolean(BUNDLE_DISABLE_MENU, disableMenu) } } } internal const val TAG_CHAT_DETAILS_FRAGMENT = "ChatDetailsFragment" internal const val MENU_ACTION_FAVORITE_REMOVE_FAVORITE = 1 internal const val MENU_ACTION_VIDEO_CALL = 2 private const val BUNDLE_CHAT_ROOM_ID = "BUNDLE_CHAT_ROOM_ID" private const val BUNDLE_CHAT_ROOM_TYPE = "BUNDLE_CHAT_ROOM_TYPE" private const val BUNDLE_IS_SUBSCRIBED = "BUNDLE_IS_SUBSCRIBED" private const val BUNDLE_IS_FAVORITE = "BUNDLE_IS_FAVORITE" private const val BUNDLE_DISABLE_MENU = "BUNDLE_DISABLE_MENU" class ChatDetailsFragment : Fragment(), ChatDetailsView { @Inject lateinit var presenter: ChatDetailsPresenter @Inject lateinit var factory: ChatDetailsViewModelFactory @Inject lateinit var serverUrl: CurrentServerRepository @Inject lateinit var settings: GetSettingsInteractor private var adapter: ChatDetailsAdapter? = null private lateinit var viewModel: ChatDetailsViewModel internal lateinit var chatRoomId: String internal lateinit var chatRoomType: String private var isSubscribed: Boolean = true internal var isFavorite: Boolean = false private var disableMenu: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "") chatRoomType = getString(BUNDLE_CHAT_ROOM_TYPE, "") isSubscribed = getBoolean(BUNDLE_IS_SUBSCRIBED) isFavorite = getBoolean(BUNDLE_IS_FAVORITE) disableMenu = getBoolean(BUNDLE_DISABLE_MENU) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_chat_details) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProviders.of(this, factory).get(ChatDetailsViewModel::class.java) setupOptions() setupToolbar() getDetails() } override fun onPrepareOptionsMenu(menu: Menu) { menu.clear() setupMenu(menu) super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { setOnMenuItemClickListener(item) return true } override fun showFavoriteIcon(isFavorite: Boolean) { this.isFavorite = isFavorite activity?.invalidateOptionsMenu() } override fun displayDetails(room: ChatDetails) { ui { val text = room.name name.text = text bindImage(chatRoomType) content_topic.text = if (room.topic.isNullOrEmpty()) getString(R.string.msg_no_topic) else room.topic content_announcement.text = if (room.announcement.isNullOrEmpty()) getString(R.string.msg_no_announcement) else room.announcement content_description.text = if (room.description.isNullOrEmpty()) getString(R.string.msg_no_description) else room.description } } override fun showGenericErrorMessage() = showMessage(R.string.msg_generic_error) override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } private fun addOptions(adapter: ChatDetailsAdapter?) { adapter?.let { if (!disableMenu) { it.addOption(getString(R.string.title_files), R.drawable.ic_files_24dp) { presenter.toFiles(chatRoomId) } } if (chatRoomType != RoomType.DIRECT_MESSAGE && !disableMenu) { it.addOption(getString(R.string.msg_mentions), R.drawable.ic_at_black_20dp) { presenter.toMentions(chatRoomId) } it.addOption( getString(R.string.title_members), R.drawable.ic_people_outline_black_24dp ) { presenter.toMembers(chatRoomId) } } it.addOption( getString(R.string.title_favorite_messages), R.drawable.ic_star_border_white_24dp ) { presenter.toFavorites(chatRoomId) } it.addOption( getString(R.string.title_pinned_messages), R.drawable.ic_action_message_pin_24dp ) { presenter.toPinned(chatRoomId) } } } private fun bindImage(chatRoomType: String) { val drawable = when (roomTypeOf(chatRoomType)) { is RoomType.Channel -> { DrawableHelper.getDrawableFromId(R.drawable.ic_hashtag_black_12dp, context!!) } is RoomType.PrivateGroup -> { DrawableHelper.getDrawableFromId(R.drawable.ic_lock_black_12_dp, context!!) } else -> null } drawable?.let { val wrappedDrawable = DrawableHelper.wrapDrawable(it) val mutableDrawable = wrappedDrawable.mutate() DrawableHelper.tintDrawable(mutableDrawable, context!!, R.color.colorPrimary) DrawableHelper.compoundStartDrawable(name, mutableDrawable) } } private fun getDetails() { if (isSubscribed) viewModel.getDetails(chatRoomId).observe(viewLifecycleOwner, Observer { details -> displayDetails(details) }) else presenter.getDetails(chatRoomId, chatRoomType) } private fun setupOptions() { ui { if (options.adapter == null) { adapter = ChatDetailsAdapter() options.adapter = adapter with(options) { layoutManager = LinearLayoutManager(it) addItemDecoration( DividerItemDecoration( it, resources.getDimensionPixelSize(R.dimen.divider_item_decorator_bound_start), resources.getDimensionPixelSize(R.dimen.divider_item_decorator_bound_end) ) ) itemAnimator = DefaultItemAnimator() isNestedScrollingEnabled = false } } addOptions(adapter) } } private fun setupToolbar() { with((activity as ChatRoomActivity)) { hideExpandMoreForToolbar() setupToolbarTitle(getString(R.string.title_channel_details)) } } }
app/src/main/java/chat/rocket/android/chatdetails/ui/ChatDetailsFragment.kt
2572344089
package com.sapuseven.untis.models.untis import kotlinx.serialization.Serializable @Serializable data class UntisMessengerSettings( val serverUrl: String, val organizationId: String )
app/src/main/java/com/sapuseven/untis/models/untis/UntisMessengerSettings.kt
3611515166
/* * 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.fragment import android.app.Dialog import android.content.DialogInterface import android.graphics.Color import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import me.uucky.colorpicker.ColorPickerDialog import de.vanita5.twittnuker.Constants.* import de.vanita5.twittnuker.R import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.onShow import de.vanita5.twittnuker.fragment.iface.IDialogFragmentCallback class ColorPickerDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener { private var mController: ColorPickerDialog.Controller? = null override fun onCancel(dialog: DialogInterface?) { super.onCancel(dialog) val a = activity if (a is Callback) { a.onCancelled() } } override fun onClick(dialog: DialogInterface, which: Int) { val a = activity if (a !is Callback || mController == null) return when (which) { DialogInterface.BUTTON_POSITIVE -> { val color = mController!!.color a.onColorSelected(color) } DialogInterface.BUTTON_NEUTRAL -> { a.onColorCleared() } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val color: Int val args = arguments if (savedInstanceState != null) { color = savedInstanceState.getInt(EXTRA_COLOR, Color.WHITE) } else { color = args.getInt(EXTRA_COLOR, Color.WHITE) } val activity = activity val builder = AlertDialog.Builder(activity) builder.setView(me.uucky.colorpicker.R.layout.cp__dialog_color_picker) builder.setPositiveButton(android.R.string.ok, this) if (args.getBoolean(EXTRA_CLEAR_BUTTON, false)) { builder.setNeutralButton(R.string.action_clear, this) } builder.setNegativeButton(android.R.string.cancel, this) val dialog = builder.create() dialog.onShow { it.applyTheme() mController = ColorPickerDialog.Controller(it.context, it.window.decorView) val showAlphaSlider = args.getBoolean(EXTRA_ALPHA_SLIDER, true) for (presetColor in PRESET_COLORS) { mController!!.addColor(ContextCompat.getColor(context, presetColor)) } mController!!.setAlphaEnabled(showAlphaSlider) mController!!.setInitialColor(color) } return dialog } override fun onDismiss(dialog: DialogInterface?) { super.onDismiss(dialog) val a = activity if (a is Callback) { a.onDismissed() } } override fun onSaveInstanceState(outState: Bundle?) { if (mController != null) { outState!!.putInt(EXTRA_COLOR, mController!!.color) } super.onSaveInstanceState(outState) } interface Callback : IDialogFragmentCallback { fun onColorCleared() fun onColorSelected(color: Int) } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/ColorPickerDialogFragment.kt
2359961428
/* * Copyright 2017 RedRoma, 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 tech.aroma.data.sql.serializers import org.springframework.jdbc.core.JdbcOperations import tech.aroma.data.sql.DatabaseSerializer import tech.aroma.data.sql.serializers.Columns.Activity import tech.aroma.thrift.events.Event import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.arguments.assertions.* import tech.sirwellington.alchemy.thrift.ThriftObjects import java.sql.ResultSet /** * * @author SirWellington */ internal class EventSerializer : DatabaseSerializer<Event> { override fun save(event: Event, statement: String, database: JdbcOperations) { checkThat(event.eventId).isA(validUUID()) checkThat(statement).isA(nonEmptyString()) } override fun deserialize(row: ResultSet): Event { var event = Event() val serializedEvent = row.getString(Activity.SERIALIZED_EVENT) if (serializedEvent != null) { event = ThriftObjects.fromJson(event, serializedEvent) } return event } }
src/main/java/tech/aroma/data/sql/serializers/EventSerializer.kt
1911254647
package com.stripe.android.ui.core.elements import android.content.Context import androidx.annotation.RestrictTo import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine /** * This is the element that represent the collection of all the card details: * card number, expiration date, and CVC. */ internal class CardDetailsElement( identifier: IdentifierSpec, context: Context, initialValues: Map<IdentifierSpec, String?>, viewOnlyFields: Set<IdentifierSpec> = emptySet(), val controller: CardDetailsController = CardDetailsController( context, initialValues, viewOnlyFields.contains(IdentifierSpec.CardNumber) ) ) : SectionMultiFieldElement(identifier) { val isCardScanEnabled = controller.numberElement.controller.cardScanEnabled override fun sectionFieldErrorController(): SectionFieldErrorController = controller override fun setRawValue(rawValuesMap: Map<IdentifierSpec, String?>) { // Nothing from formFragmentArguments to populate } override fun getTextFieldIdentifiers(): Flow<List<IdentifierSpec>> = MutableStateFlow( listOf( controller.numberElement.identifier, controller.expirationDateElement.identifier, controller.cvcElement.identifier ) ) override fun getFormFieldValueFlow() = combine( controller.numberElement.controller.formFieldValue, controller.cvcElement.controller.formFieldValue, controller.expirationDateElement.controller.formFieldValue, controller.numberElement.controller.cardBrandFlow ) { number, cvc, expirationDate, brand -> listOf( controller.numberElement.identifier to number, controller.cvcElement.identifier to cvc, IdentifierSpec.CardBrand to FormFieldEntry(brand.code, true) ) + createExpiryDateFormFieldValues(expirationDate).toList() } } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun createExpiryDateFormFieldValues( entry: FormFieldEntry ): Map<IdentifierSpec, FormFieldEntry> { var month = -1 var year = -1 entry.value?.let { date -> val newString = convertTo4DigitDate(date) if (newString.length == 4) { month = requireNotNull(newString.take(2).toIntOrNull()) year = requireNotNull(newString.takeLast(2).toIntOrNull()) + 2000 } } val monthEntry = entry.copy( value = month.toString().padStart(length = 2, padChar = '0') ) val yearEntry = entry.copy( value = year.toString() ) return mapOf( IdentifierSpec.CardExpMonth to monthEntry, IdentifierSpec.CardExpYear to yearEntry ) }
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CardDetailsElement.kt
1850615258
package com.stripe.android.identity import com.stripe.android.identity.networking.VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE_JSON_STRING import com.stripe.android.identity.networking.VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE_JSON_STRING import com.stripe.android.identity.networking.models.Requirement import com.stripe.android.identity.networking.models.VerificationPage import com.stripe.android.identity.networking.models.VerificationPageData import com.stripe.android.identity.networking.models.VerificationPageDataRequirements import kotlinx.serialization.json.Json internal const val ERROR_BODY = "errorBody" internal const val ERROR_BUTTON_TEXT = "error button text" internal const val ERROR_TITLE = "errorTitle" internal val CORRECT_WITH_SUBMITTED_FAILURE_VERIFICATION_PAGE_DATA = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList() ), status = VerificationPageData.Status.VERIFIED, submitted = false ) internal val CORRECT_WITH_SUBMITTED_SUCCESS_VERIFICATION_PAGE_DATA = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList() ), status = VerificationPageData.Status.VERIFIED, submitted = true ) internal val VERIFICATION_PAGE_DATA_MISSING_BACK = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList(), missings = listOf(Requirement.IDDOCUMENTBACK) ), status = VerificationPageData.Status.REQUIRESINPUT, submitted = false ) internal val VERIFICATION_PAGE_DATA_NOT_MISSING_BACK = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList(), missings = emptyList() ), status = VerificationPageData.Status.REQUIRESINPUT, submitted = false ) internal val VERIFICATION_PAGE_DATA_MISSING_SELFIE = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList(), missings = listOf(Requirement.FACE) ), status = VerificationPageData.Status.REQUIRESINPUT, submitted = false ) internal val json: Json = Json { ignoreUnknownKeys = true isLenient = true encodeDefaults = true } internal val SUCCESS_VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE: VerificationPage = json.decodeFromString( VerificationPage.serializer(), VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE_JSON_STRING ) internal val SUCCESS_VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE: VerificationPage = json.decodeFromString( VerificationPage.serializer(), VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE_JSON_STRING )
identity/src/test/java/com/stripe/android/identity/TestFixtures.kt
1472210184
package com.stripe.android.camera.image import android.graphics.Color import android.graphics.Rect import android.util.Size import androidx.core.graphics.drawable.toBitmap import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.stripe.android.camera.framework.image.crop import com.stripe.android.camera.framework.image.cropWithFill import com.stripe.android.camera.framework.image.scale import com.stripe.android.camera.framework.image.size import com.stripe.android.camera.framework.image.zoom import com.stripe.android.camera.framework.util.centerOn import com.stripe.android.camera.framework.util.toRect import com.stripe.android.camera.test.R import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class ImageTest { private val testResources = InstrumentationRegistry.getInstrumentation().context.resources @Test @SmallTest fun bitmap_scale_isCorrect() { // read in a sample bitmap file val bitmap = testResources.getDrawable(R.drawable.ocr_card_numbers, null).toBitmap() assertNotNull(bitmap) // Make sure a non-empty image is read. assertNotEquals(0, bitmap.width, "Bitmap width is 0") assertNotEquals(0, bitmap.height, "Bitmap height is 0") // scale the bitmap val scaledBitmap = bitmap.scale(Size(bitmap.width / 5, bitmap.height / 5)) // check the expected sizes of the images assertEquals( Size(bitmap.width / 5, bitmap.height / 5), Size(scaledBitmap.width, scaledBitmap.height), "Scaled image is the wrong size" ) // check each pixel of the images var encounteredNonZeroPixel = false for (x in 0 until scaledBitmap.width) { for (y in 0 until scaledBitmap.height) { encounteredNonZeroPixel = encounteredNonZeroPixel || scaledBitmap.getPixel(x, y) != 0 } } assertTrue(encounteredNonZeroPixel, "Pixels were all zero") } @Test @SmallTest fun bitmap_crop_isCorrect() { val bitmap = testResources.getDrawable(R.drawable.ocr_card_numbers, null).toBitmap() assertNotNull(bitmap) // Make sure a non-empty image is read. assertNotEquals(0, bitmap.width, "Bitmap width is 0") assertNotEquals(0, bitmap.height, "Bitmap height is 0") // crop the bitmap val croppedBitmap = bitmap.crop( Rect( bitmap.width / 4, bitmap.height / 4, bitmap.width * 3 / 4, bitmap.height * 3 / 4 ) ) // check the expected sizes of the images assertEquals( Size( bitmap.width * 3 / 4 - bitmap.width / 4, bitmap.height * 3 / 4 - bitmap.height / 4 ), Size(croppedBitmap.width, croppedBitmap.height), "Cropped image is the wrong size" ) // check each pixel of the images var encounteredNonZeroPixel = false for (x in 0 until croppedBitmap.width) { for (y in 0 until croppedBitmap.height) { val croppedPixel = croppedBitmap.getPixel(x, y) val originalPixel = bitmap.getPixel(x + bitmap.width / 4, y + bitmap.height / 4) assertEquals(originalPixel, croppedPixel, "Difference at pixel $x, $y") encounteredNonZeroPixel = encounteredNonZeroPixel || croppedPixel != 0 } } assertTrue(encounteredNonZeroPixel, "Pixels were all zero") } @Test @SmallTest fun bitmap_cropWithFill_isCorrect() { val bitmap = testResources.getDrawable(R.drawable.ocr_card_numbers, null).toBitmap() assertNotNull(bitmap) // Make sure a non-empty image is read. assertNotEquals(0, bitmap.width, "Bitmap width is 0") assertNotEquals(0, bitmap.height, "Bitmap height is 0") val cropRegion = Rect( -100, -100, bitmap.width + 100, bitmap.height + 100 ) // crop the bitmap val croppedBitmap = bitmap.cropWithFill( cropRegion ) // check the expected sizes of the images assertEquals( Size( bitmap.width + 200, bitmap.height + 200 ), Size(croppedBitmap.width, croppedBitmap.height), "Cropped image is the wrong size" ) for (y in 0 until croppedBitmap.height) { for (x in 0 until croppedBitmap.width) { if ( x < 100 || x > croppedBitmap.width - 100 || y < 100 || y > croppedBitmap.height - 100 ) { val croppedPixel = croppedBitmap.getPixel(x, y) assertEquals(Color.GRAY, croppedPixel, "Pixel $x, $y not gray") } } } // check each pixel of the images var encounteredNonZeroPixel = false for (x in 0 until bitmap.width) { for (y in 0 until bitmap.height) { val croppedPixel = croppedBitmap.getPixel(x + 100, y + 100) val originalPixel = bitmap.getPixel(x, y) assertEquals(originalPixel, croppedPixel, "Difference at pixel $x, $y") encounteredNonZeroPixel = encounteredNonZeroPixel || croppedPixel != 0 } } assertTrue(encounteredNonZeroPixel, "Pixels were all zero") } @Test @SmallTest fun zoom_isCorrect() { val bitmap = testResources.getDrawable(R.drawable.ocr_card_numbers, null).toBitmap() assertNotNull(bitmap) // Make sure a non-empty image is read. assertNotEquals(0, bitmap.width, "Bitmap width is 0") assertNotEquals(0, bitmap.height, "Bitmap height is 0") // zoom the bitmap val zoomedBitmap = bitmap.zoom( originalRegion = Size(224, 224).centerOn(bitmap.size().toRect()), newRegion = Rect(112, 112, 336, 336), newImageSize = Size(448, 448) ) // check the expected sizes of the images assertEquals( Size(448, 448), Size(zoomedBitmap.width, zoomedBitmap.height), "Zoomed image is the wrong size" ) // check each pixel of the images var encounteredNonZeroPixel = false for (x in 0 until zoomedBitmap.width) { for (y in 0 until zoomedBitmap.height) { val zoomedPixel = zoomedBitmap.getPixel(x, y) encounteredNonZeroPixel = encounteredNonZeroPixel || zoomedPixel != 0 } } assertTrue(encounteredNonZeroPixel, "Pixels were all zero") } }
camera-core/src/androidTest/java/com/stripe/android/camera/image/ImageTest.kt
1511959830
package com.ivantrogrlic.leaguestats.splash import com.hannesdorfmann.mosby3.mvp.MvpView /** * Created by ivanTrogrlic on 16/07/2017. */ interface SplashView : MvpView { fun showServerChoiceDialog(choiceArray: Array<CharSequence>) fun animateLogo() fun goToMainScreen() }
app/src/main/java/com/ivantrogrlic/leaguestats/splash/SplashView.kt
1456636493
package com.stripe.android.ui.core.elements import androidx.annotation.RestrictTo import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class SameAsShippingElement( override val identifier: IdentifierSpec, override val controller: SameAsShippingController ) : SectionSingleFieldElement(identifier) { override val shouldRenderOutsideCard: Boolean get() = true override fun getFormFieldValueFlow(): Flow<List<Pair<IdentifierSpec, FormFieldEntry>>> { return controller.formFieldValue.map { listOf( identifier to it ) } } override fun setRawValue(rawValuesMap: Map<IdentifierSpec, String?>) { rawValuesMap[identifier]?.let { controller.onRawValueChange(it) } } }
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/SameAsShippingElement.kt
509574901
package dwallet.u8 import dwallet.core.bitcoin.protocol.structures.* import dwallet.core.extensions.* import org.junit.Assert.* import org.junit.Test /** * Created by unsignedint8 on 8/21/17. */ class MerkleBlockTests { @Test fun testMerkleBlock() { val raw = "000000203110b9caef379f0131f8a7b490316625d7f53308fb47ac352e2e3803180000005dcad525acc0d9cc4fc483e999ddd0ff01b9d5c7583958b84524adcd670996750511fb58ffff7f2008f50eb901000000015dcad525acc0d9cc4fc483e999ddd0ff01b9d5c7583958b84524adcd670996750100".hexToByteArray() val b = MerkleBlock.fromBytes(raw) assertEquals("0000001803382e2e35ac47fb0833f5d725663190b4a7f831019f37efcab91031", b.preBlockHash) assertEquals(1, b.totalTxs) assertArrayEquals(arrayOf(0.toByte()), b.flags.toTypedArray()) assertEquals(raw.toHexString(), b.toBytes().toHexString()) println(b.hash) } @Test fun testMerkleBlock2() { val raw = "000000207f026bea3f187657d0da0165b5122484cb91b292f00cf76323617bc841c8f26997e9e1dc840597b09b0718c1e116e5073f2c3c0b3120e5d8c4585918942d481c35209959ffff7f20020000001500000015e998e96c234906c36554da9a65c89d3ad2f7465011bb5c0861bd4baf401b15aa8c0e129c7a25c70fe3743ca211360b78a014ce586c111e0bf3d2d1ee2bb2d76f2dcf64125fd10ecaafbc86712404c93cf424c2ec11ddd9d0b20a878e6bb6ec1e11b1693a38fff4dbd27162a6d3ecc36f196cd10fe4b00f07885cdbe2f65cb2ecff5091a2af58399b82af4bc3eac89dbf892113949c4c3527e62e098c6427d2d17e36d66a75e278f5dbd626293a25501599edef09d39678abd72d7a8ae989a3d5a238c93c61f322e53c9b8016f6871fd44fad5fe303cb68e4bbd667abc8f38f1e21df783456fb0218f56277ecda58293e380714f72c82ad58e7c6960973dc88ee4321e4d948a7760584c2c27ce16d8845a778563fee74828774ca9e323ca4c0fac33ace425b352babe3b44abeab7115d8d405753d6d144c04ec1666b6dd2f2fe7c78946387fabd470392078079423f8129015e20a49463e60302e872ea2a0dcf667fb551aadd906cc72e00232f818697cd6ad9e6cd934024cb6831dff9bc53e84d0604b75b6535ad9db1da5441d62e85e64bc4a0daef663d62bcb37e9a7676c225b8a2b900f84ec0ab057b3aaf64ceb8149e8b0baa9fe19758135543b15cf7d2a2bde61d37725a0f4bbe47d7468df286fbcdf353c17e95bb4ac6024219a7ad97959996671d568ca3724b5a2b39aa82970137033979bc8407085207aeae3081932b177835c43c0bf7399f2c9d4753f7017069d7eedd190babaeee03e7021a5374d8427d50f76af03f137a0a71a7c88a90a2dca9cba8994942f4b1797a06b648c7c5469d69f770c6ef4fafdd7d9ebf7cecb30f9115393397f8445fb9da95cd7e6dfb84efabf1687bba6b5e106d560c4a25029c556123c970cfdf50351abfebaf5b32a05e3197b56082e3ea102c91184511c3a8d4154d154b0c05b122d84f7dc6d9806dfffffffff0f".hexToByteArray() val b = MerkleBlock.fromBytes(raw) assertEquals("69f2c841c87b612363f70cf092b291cb842412b56501dad05776183fea6b027f", b.preBlockHash) assertEquals(21, b.totalTxs) assertArrayEquals(arrayOf(0xdf.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0x0f.toByte()), b.flags.toTypedArray()) assertEquals(raw.toHexString(), b.toBytes().toHexString()) println(b.hash) } @Test fun testMerkleBlock3() { val raw = "00000020fc0485f19747fa25a4c2620a017daddf2dd80040f2bc4e45c3b578db3198fe6438461f7e3a8a8356ac53c80ff99c6e088fade188cefc0c9fdb01443f9b6fe5a6d4b1dc58ffff7f2000000000010000000138461f7e3a8a8356ac53c80ff99c6e088fade188cefc0c9fdb01443f9b6fe5a60100" val b = MerkleBlock.fromBytes(raw.hexToByteArray()) assertEquals("01e97e5a81d8f81044fb861f4487f55dd86041f210f843c31c24455590c57b6b", b.hash) } }
android/lib/src/test/java/dWallet/u8/MerkleBlockTests.kt
1226673330
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Purchase a product action information. * * @param purchase The interaction for purchasing a product. */ @JsonClass(generateAdapter = true) data class ProductInteractions( @Json(name = "purchase") val purchase: PurchaseInteraction? = null )
models/src/main/java/com/vimeo/networking2/ProductInteractions.kt
27598850
package com.vimeo.modelgenerator import org.gradle.api.Project /** * Extension object that is used to configure the [GenerateModelsPlugin]. */ open class GenerateModelsExtension(private val project: Project) { /** * A file path to the base models that will be use to generate new models. */ open var inputPath: String? = null /** * The specific type of models that will be generated. */ open var typeGenerated: ModelType? = null } /** * The supported types of models that can be generated. */ enum class ModelType { /** * Generates models that support [java.io.Serializable]. */ SERIALIZABLE, /** * Generates models that support [android.os.Parcelable]. */ PARCELABLE }
model-generator/plugin/src/main/java/com/vimeo/modelgenerator/GenerateModelsExtension.kt
342132728
package org.hexworks.mixite.core.api import org.hexworks.cobalt.datatypes.Maybe import org.hexworks.mixite.core.api.contract.SatelliteData /** * Supports advanced operations on a [HexagonalGrid]. * Operations supported: * * * Calculating distance between 2 [Hexagon]s. * * Calculating movement range from a [Hexagon] using an arbitrary distance. * * *Not implemented yet, but are on the roadmap:* * * * Calculating movement range with obstacles * * Calculating field of view * * Path finding between two [Hexagon]s (using obstacles) * */ interface HexagonalGridCalculator<T : SatelliteData> { /** * Calculates the distance (in hexagons) between two [Hexagon] objects on the grid. * * @param hex0 hex 0 * @param hex1 hex 1 * * @return distance */ fun calculateDistanceBetween(hex0: Hexagon<T>, hex1: Hexagon<T>): Int /** * Returns all [Hexagon]s which are within `distance` (inclusive) from the [Hexagon]. * * @param hexagon [Hexagon] * @param distance distance * * @return [Hexagon]s within distance (inclusive) */ fun calculateMovementRangeFrom(hexagon: Hexagon<T>, distance: Int): Set<Hexagon<T>> /** * Returns the Hexagon on the grid which is at the point resulted by rotating the `targetHex`'s * coordinates around the `originalHex` by `rotationDirection` degrees. * * @param originalHex center hex * @param targetHex hex to rotate * @param rotationDirection direction of the rotation * * @return result */ fun rotateHexagon(originalHex: Hexagon<T>, targetHex: Hexagon<T>, rotationDirection: RotationDirection): Maybe<Hexagon<T>> /** * Returns the [Set] of [Hexagon]s which are `radius` distance * from `centerHexagon`. * * @param centerHexagon center * @param radius radius * * @return Set of hexagons or empty set if not applicable */ fun calculateRingFrom(centerHexagon: Hexagon<T>, radius: Int): Set<Hexagon<T>> /** * Returns a [List] of [Hexagon]s which must be traversed in the * given order to go from the `from` Hexagon to the `to` Hexagon. * * @param from starting hexagon * @param to target hexagon * * @return List of hexagons containing the line */ fun drawLine(from: Hexagon<T>, to: Hexagon<T>): List<Hexagon<T>> /** * Returns true if the `from` [Hexagon] is visible from the `to` Hexagon. * * @param from the Hexagon that we are testing the visibility from * @param to the Hexagon from which we are testing the visibility to * * @return true if hexagon is visible, false otherwise */ fun isVisible(from: Hexagon<T>, to: Hexagon<T>): Boolean }
mixite.core/src/commonMain/kotlin/org/hexworks/mixite/core/api/HexagonalGridCalculator.kt
1395242808
package abi44_0_0.expo.modules.notifications.service.delegates import android.app.NotificationManager import android.content.Context import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Parcel import android.provider.Settings import android.service.notification.StatusBarNotification import android.util.Log import android.util.Pair import androidx.core.app.NotificationManagerCompat import expo.modules.notifications.notifications.enums.NotificationPriority import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationBehavior import expo.modules.notifications.notifications.model.NotificationContent import expo.modules.notifications.notifications.model.NotificationRequest import abi44_0_0.expo.modules.notifications.notifications.presentation.builders.CategoryAwareNotificationBuilder import abi44_0_0.expo.modules.notifications.notifications.presentation.builders.ExpoNotificationBuilder import abi44_0_0.expo.modules.notifications.service.interfaces.PresentationDelegate import org.json.JSONException import org.json.JSONObject import java.util.* open class ExpoPresentationDelegate( protected val context: Context ) : PresentationDelegate { companion object { protected const val ANDROID_NOTIFICATION_ID = 0 protected const val INTERNAL_IDENTIFIER_SCHEME = "expo-notifications" protected const val INTERNAL_IDENTIFIER_AUTHORITY = "foreign_notifications" protected const val INTERNAL_IDENTIFIER_TAG_KEY = "tag" protected const val INTERNAL_IDENTIFIER_ID_KEY = "id" /** * Tries to parse given identifier as an internal foreign notification identifier * created by us in [getInternalIdentifierKey]. * * @param identifier String identifier of the notification * @return Pair of (notification tag, notification id), if the identifier could be parsed. null otherwise. */ fun parseNotificationIdentifier(identifier: String): Pair<String?, Int>? { try { val parsedIdentifier = Uri.parse(identifier) if (INTERNAL_IDENTIFIER_SCHEME == parsedIdentifier.scheme && INTERNAL_IDENTIFIER_AUTHORITY == parsedIdentifier.authority) { val tag = parsedIdentifier.getQueryParameter(INTERNAL_IDENTIFIER_TAG_KEY) val id = parsedIdentifier.getQueryParameter(INTERNAL_IDENTIFIER_ID_KEY)!!.toInt() return Pair(tag, id) } } catch (e: NullPointerException) { Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e) } catch (e: NumberFormatException) { Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e) } catch (e: UnsupportedOperationException) { Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e) } return null } /** * Creates an identifier for given [StatusBarNotification]. It's supposed to be parsable * by [parseNotificationIdentifier]. * * @param notification Notification to be identified * @return String identifier */ protected fun getInternalIdentifierKey(notification: StatusBarNotification): String { return with(Uri.parse("$INTERNAL_IDENTIFIER_SCHEME://$INTERNAL_IDENTIFIER_AUTHORITY").buildUpon()) { notification.tag?.let { this.appendQueryParameter(INTERNAL_IDENTIFIER_TAG_KEY, it) } this.appendQueryParameter(INTERNAL_IDENTIFIER_ID_KEY, notification.id.toString()) this.toString() } } } /** * Callback called to present the system UI for a notification. * * If the notification behavior is set to not show any alert, * we (may) play a sound, but then bail out early. You cannot * set badge count without showing a notification. */ override fun presentNotification(notification: Notification, behavior: NotificationBehavior?) { if (behavior != null && !behavior.shouldShowAlert()) { if (behavior.shouldPlaySound()) { RingtoneManager.getRingtone( context, notification.notificationRequest.content.sound ?: Settings.System.DEFAULT_NOTIFICATION_URI ).play() } return } NotificationManagerCompat.from(context).notify( notification.notificationRequest.identifier, getNotifyId(notification.notificationRequest), createNotification(notification, behavior) ) } protected open fun getNotifyId(request: NotificationRequest?): Int { return ANDROID_NOTIFICATION_ID } /** * Callback called to fetch a collection of currently displayed notifications. * * **Note:** This feature is only supported on Android 23+. * * @return A collection of currently displayed notifications. */ override fun getAllPresentedNotifications(): Collection<Notification> { // getActiveNotifications() is not supported on platforms below Android 23 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return emptyList() } val notificationManager = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) return notificationManager.activeNotifications.mapNotNull { getNotification(it) } } override fun dismissNotifications(identifiers: Collection<String>) { identifiers.forEach { identifier -> val foreignNotification = parseNotificationIdentifier(identifier) if (foreignNotification != null) { // Foreign notification identified by us NotificationManagerCompat.from(context).cancel(foreignNotification.first, foreignNotification.second) } else { // If the notification exists, let's assume it's ours, we have no reason to believe otherwise val existingNotification = this.getAllPresentedNotifications().find { it.notificationRequest.identifier == identifier } NotificationManagerCompat.from(context).cancel(identifier, getNotifyId(existingNotification?.notificationRequest)) } } } override fun dismissAllNotifications() = NotificationManagerCompat.from(context).cancelAll() protected open fun createNotification(notification: Notification, notificationBehavior: NotificationBehavior?): android.app.Notification = CategoryAwareNotificationBuilder(context, SharedPreferencesNotificationCategoriesStore(context)).also { it.setNotification(notification) it.setAllowedBehavior(notificationBehavior) }.build() protected open fun getNotification(statusBarNotification: StatusBarNotification): Notification? { val notification = statusBarNotification.notification notification.extras.getByteArray(ExpoNotificationBuilder.EXTRAS_MARSHALLED_NOTIFICATION_REQUEST_KEY)?.let { try { with(Parcel.obtain()) { this.unmarshall(it, 0, it.size) this.setDataPosition(0) val request: NotificationRequest = NotificationRequest.CREATOR.createFromParcel(this) this.recycle() val notificationDate = Date(statusBarNotification.postTime) return Notification(request, notificationDate) } } catch (e: Exception) { // Let's catch all the exceptions -- there's nothing we can do here // and we'd rather return an array with a single, naively reconstructed notification // than throw an exception and return none. val message = "Could not have unmarshalled NotificationRequest from (${statusBarNotification.tag}, ${statusBarNotification.id})." Log.e("expo-notifications", message) } } // We weren't able to reconstruct the notification from our data, which means // it's either not our notification or we couldn't have unmarshaled it from // the byte array. Let's do what we can. val content = NotificationContent.Builder() .setTitle(notification.extras.getString(android.app.Notification.EXTRA_TITLE)) .setText(notification.extras.getString(android.app.Notification.EXTRA_TEXT)) .setSubtitle(notification.extras.getString(android.app.Notification.EXTRA_SUB_TEXT)) // using deprecated field .setPriority(NotificationPriority.fromNativeValue(notification.priority)) // using deprecated field .setVibrationPattern(notification.vibrate) // using deprecated field .setSound(notification.sound) .setAutoDismiss(notification.flags and android.app.Notification.FLAG_AUTO_CANCEL != 0) .setSticky(notification.flags and android.app.Notification.FLAG_ONGOING_EVENT != 0) .setBody(fromBundle(notification.extras)) .build() val request = NotificationRequest(getInternalIdentifierKey(statusBarNotification), content, null) return Notification(request, Date(statusBarNotification.postTime)) } protected open fun fromBundle(bundle: Bundle): JSONObject { return JSONObject().also { json -> for (key in bundle.keySet()) { try { json.put(key, JSONObject.wrap(bundle[key])) } catch (e: JSONException) { // can't do anything about it apart from logging it Log.d("expo-notifications", "Error encountered while serializing Android notification extras: " + key + " -> " + bundle[key], e) } } } } }
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/notifications/service/delegates/ExpoPresentationDelegate.kt
3078589827
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml.completion import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.psi.codeStyle.MinusculeMatcher import com.intellij.psi.codeStyle.NameUtil class CargoDependenciesPrefixMatcher(prefix: String): PrefixMatcher(prefix) { private val normalizedPrefix: String = normalize(prefix) private val minusculeMatcher: MinusculeMatcher = NameUtil.buildMatcher(normalizedPrefix).withSeparators("_").build() override fun prefixMatches(name: String): Boolean { val normalizedName = normalize(name) return minusculeMatcher.matches(normalizedName) } override fun cloneWithPrefix(prefix: String): PrefixMatcher = CargoDependenciesPrefixMatcher(prefix) private fun normalize(string: String) = string.replace('-', '_') }
toml/src/main/kotlin/org/rust/toml/completion/CargoDependenciesPrefixMatcher.kt
3365939144
package solutions.day21 import solutions.AbstractDayTest class Day21Test: AbstractDayTest(Day21()) { override fun getPart1Data(): List<TestData> = listOf( TestData(listOf("../.. => ##./##./.##", "#./.. => .../.#./##.", "##/.. => .../.##/#.#", ".#/#. => ##./#../#..", "##/#. => .##/#.#/#..", "##/## => ..#/.#./.##", ".../.../... => #.../.##./...#/#...", "#../.../... => ...#/..../..#./..##", ".#./.../... => ..../.##./###./....", "##./.../... => ###./#.##/..#./..#.", "#.#/.../... => #.../.#../#..#/..#.", "###/.../... => ..##/.##./#.../....", ".#./#../... => #.##/..../..../#.##", "##./#../... => .#.#/.#.#/##../.#..", "..#/#../... => .###/####/.###/##..", "#.#/#../... => ..../.#.#/..../####", ".##/#../... => .##./##.#/.###/#..#", "###/#../... => ####/...#/###./.###", ".../.#./... => ..##/#..#/###./###.", "#../.#./... => ###./..##/.#.#/.#.#", ".#./.#./... => ..#./..#./##.#/##..", "##./.#./... => #..#/###./..#./#.#.", "#.#/.#./... => .###/#.../.#.#/.##.", "###/.#./... => #.##/##../#.#./...#", ".#./##./... => #.##/#.##/#.##/.###", "##./##./... => ..##/#..#/.###/....", "..#/##./... => #..#/.##./##../####", "#.#/##./... => ###./###./..##/..##", ".##/##./... => ###./##.#/.##./###.", "###/##./... => ##../#..#/##../....", ".../#.#/... => ##.#/..#./..##/##..", "#../#.#/... => #..#/.###/.#../#.#.", ".#./#.#/... => ####/#.##/.###/###.", "##./#.#/... => #.../####/...#/.#.#", "#.#/#.#/... => ...#/.#.#/#..#/#.##", "###/#.#/... => ###./#.##/##.#/..##", ".../###/... => ..../##.#/.#../..##", "#../###/... => ####/..##/.##./.###", ".#./###/... => #.#./#.#./#.../#..#", "##./###/... => #..#/..##/#.##/#.#.", "#.#/###/... => .##./##.#/.#../####", "###/###/... => ####/##.#/.#../#.#.", "..#/.../#.. => #..#/#.##/.###/.###", "#.#/.../#.. => .##./#.../.#.#/....", ".##/.../#.. => .#.#/.#.#/##../####", "###/.../#.. => .#.#/.##./####/##.#", ".##/#../#.. => .###/.###/.###/#...", "###/#../#.. => ..##/#.../#.#./..#.", "..#/.#./#.. => #.#./##../##../####", "#.#/.#./#.. => ..../..##/#..#/..#.", ".##/.#./#.. => #.##/#..#/##.#/.##.", "###/.#./#.. => ...#/#.../#.#./.#..", ".##/##./#.. => .##./#..#/.##./...#", "###/##./#.. => ##.#/##.#/.##./...#", "#../..#/#.. => ##../..#./..#./#.#.", ".#./..#/#.. => #.#./##../#..#/#.##", "##./..#/#.. => #.##/###./###./.#.#", "#.#/..#/#.. => ..../...#/...#/#..#", ".##/..#/#.. => #..#/#.#./..##/.##.", "###/..#/#.. => ##../.#.#/.#../#.#.", "#../#.#/#.. => ####/.##./.##./.##.", ".#./#.#/#.. => ...#/.##./..#./.##.", "##./#.#/#.. => .#.#/.##./..#./.#.#", "..#/#.#/#.. => .#../##.#/##../#...", "#.#/#.#/#.. => .#.#/..#./#.../##..", ".##/#.#/#.. => ..#./#.#./###./#...", "###/#.#/#.. => ..../#.#./..##/##.#", "#../.##/#.. => .##./##../.#../..##", ".#./.##/#.. => ##../#.#./#.../####", "##./.##/#.. => ###./###./#.#./..##", "#.#/.##/#.. => ...#/#..#/..#./###.", ".##/.##/#.. => ..##/####/..../#.##", "###/.##/#.. => .#.#/#.../.##./#...", "#../###/#.. => ..#./.#.#/#..#/.##.", ".#./###/#.. => ####/..../####/#.##", "##./###/#.. => .###/..../#.#./####", "..#/###/#.. => ###./#.#./.#.#/#...", "#.#/###/#.. => #.#./#.#./..##/.##.", ".##/###/#.. => #.##/.###/.##./#.##", "###/###/#.. => #..#/.#../.#../.##.", ".#./#.#/.#. => .#../.##./##../..##", "##./#.#/.#. => .##./#.##/...#/#.#.", "#.#/#.#/.#. => ##.#/###./#.#./..#.", "###/#.#/.#. => ..../##../.###/###.", ".#./###/.#. => .#.#/.###/..../#..#", "##./###/.#. => #.../..#./#..#/.#..", "#.#/###/.#. => .#../##.#/##.#/.###", "###/###/.#. => #..#/.#.#/#.#./..#.", "#.#/..#/##. => .#../.###/...#/#.##", "###/..#/##. => ...#/...#/..##/...#", ".##/#.#/##. => #.#./###./.##./####", "###/#.#/##. => #.#./...#/...#/....", "#.#/.##/##. => ###./#.../##.#/..#.", "###/.##/##. => .#../#.../.###/.#..", ".##/###/##. => #.../..#./..#./.###", "###/###/##. => .#../.#../####/###.", "#.#/.../#.# => ##.#/##../...#/##.#", "###/.../#.# => ###./###./#..#/###.", "###/#../#.# => .###/..#./.#../#...", "#.#/.#./#.# => ##.#/.##./.#.#/##.#", "###/.#./#.# => ...#/...#/#.##/.##.", "###/##./#.# => #.../##../#.../....", "#.#/#.#/#.# => ####/.#../..##/..##", "###/#.#/#.# => ##../####/#.##/..##", "#.#/###/#.# => ##../..../..../####", "###/###/#.# => .#../.#.#/.###/.#.#", "###/#.#/### => ##../####/###./...#", "###/###/### => ###./#..#/##../.##."), "144") ) override fun getPart2Data(): List<TestData> = listOf( TestData(listOf("../.. => ##./##./.##", "#./.. => .../.#./##.", "##/.. => .../.##/#.#", ".#/#. => ##./#../#..", "##/#. => .##/#.#/#..", "##/## => ..#/.#./.##", ".../.../... => #.../.##./...#/#...", "#../.../... => ...#/..../..#./..##", ".#./.../... => ..../.##./###./....", "##./.../... => ###./#.##/..#./..#.", "#.#/.../... => #.../.#../#..#/..#.", "###/.../... => ..##/.##./#.../....", ".#./#../... => #.##/..../..../#.##", "##./#../... => .#.#/.#.#/##../.#..", "..#/#../... => .###/####/.###/##..", "#.#/#../... => ..../.#.#/..../####", ".##/#../... => .##./##.#/.###/#..#", "###/#../... => ####/...#/###./.###", ".../.#./... => ..##/#..#/###./###.", "#../.#./... => ###./..##/.#.#/.#.#", ".#./.#./... => ..#./..#./##.#/##..", "##./.#./... => #..#/###./..#./#.#.", "#.#/.#./... => .###/#.../.#.#/.##.", "###/.#./... => #.##/##../#.#./...#", ".#./##./... => #.##/#.##/#.##/.###", "##./##./... => ..##/#..#/.###/....", "..#/##./... => #..#/.##./##../####", "#.#/##./... => ###./###./..##/..##", ".##/##./... => ###./##.#/.##./###.", "###/##./... => ##../#..#/##../....", ".../#.#/... => ##.#/..#./..##/##..", "#../#.#/... => #..#/.###/.#../#.#.", ".#./#.#/... => ####/#.##/.###/###.", "##./#.#/... => #.../####/...#/.#.#", "#.#/#.#/... => ...#/.#.#/#..#/#.##", "###/#.#/... => ###./#.##/##.#/..##", ".../###/... => ..../##.#/.#../..##", "#../###/... => ####/..##/.##./.###", ".#./###/... => #.#./#.#./#.../#..#", "##./###/... => #..#/..##/#.##/#.#.", "#.#/###/... => .##./##.#/.#../####", "###/###/... => ####/##.#/.#../#.#.", "..#/.../#.. => #..#/#.##/.###/.###", "#.#/.../#.. => .##./#.../.#.#/....", ".##/.../#.. => .#.#/.#.#/##../####", "###/.../#.. => .#.#/.##./####/##.#", ".##/#../#.. => .###/.###/.###/#...", "###/#../#.. => ..##/#.../#.#./..#.", "..#/.#./#.. => #.#./##../##../####", "#.#/.#./#.. => ..../..##/#..#/..#.", ".##/.#./#.. => #.##/#..#/##.#/.##.", "###/.#./#.. => ...#/#.../#.#./.#..", ".##/##./#.. => .##./#..#/.##./...#", "###/##./#.. => ##.#/##.#/.##./...#", "#../..#/#.. => ##../..#./..#./#.#.", ".#./..#/#.. => #.#./##../#..#/#.##", "##./..#/#.. => #.##/###./###./.#.#", "#.#/..#/#.. => ..../...#/...#/#..#", ".##/..#/#.. => #..#/#.#./..##/.##.", "###/..#/#.. => ##../.#.#/.#../#.#.", "#../#.#/#.. => ####/.##./.##./.##.", ".#./#.#/#.. => ...#/.##./..#./.##.", "##./#.#/#.. => .#.#/.##./..#./.#.#", "..#/#.#/#.. => .#../##.#/##../#...", "#.#/#.#/#.. => .#.#/..#./#.../##..", ".##/#.#/#.. => ..#./#.#./###./#...", "###/#.#/#.. => ..../#.#./..##/##.#", "#../.##/#.. => .##./##../.#../..##", ".#./.##/#.. => ##../#.#./#.../####", "##./.##/#.. => ###./###./#.#./..##", "#.#/.##/#.. => ...#/#..#/..#./###.", ".##/.##/#.. => ..##/####/..../#.##", "###/.##/#.. => .#.#/#.../.##./#...", "#../###/#.. => ..#./.#.#/#..#/.##.", ".#./###/#.. => ####/..../####/#.##", "##./###/#.. => .###/..../#.#./####", "..#/###/#.. => ###./#.#./.#.#/#...", "#.#/###/#.. => #.#./#.#./..##/.##.", ".##/###/#.. => #.##/.###/.##./#.##", "###/###/#.. => #..#/.#../.#../.##.", ".#./#.#/.#. => .#../.##./##../..##", "##./#.#/.#. => .##./#.##/...#/#.#.", "#.#/#.#/.#. => ##.#/###./#.#./..#.", "###/#.#/.#. => ..../##../.###/###.", ".#./###/.#. => .#.#/.###/..../#..#", "##./###/.#. => #.../..#./#..#/.#..", "#.#/###/.#. => .#../##.#/##.#/.###", "###/###/.#. => #..#/.#.#/#.#./..#.", "#.#/..#/##. => .#../.###/...#/#.##", "###/..#/##. => ...#/...#/..##/...#", ".##/#.#/##. => #.#./###./.##./####", "###/#.#/##. => #.#./...#/...#/....", "#.#/.##/##. => ###./#.../##.#/..#.", "###/.##/##. => .#../#.../.###/.#..", ".##/###/##. => #.../..#./..#./.###", "###/###/##. => .#../.#../####/###.", "#.#/.../#.# => ##.#/##../...#/##.#", "###/.../#.# => ###./###./#..#/###.", "###/#../#.# => .###/..#./.#../#...", "#.#/.#./#.# => ##.#/.##./.#.#/##.#", "###/.#./#.# => ...#/...#/#.##/.##.", "###/##./#.# => #.../##../#.../....", "#.#/#.#/#.# => ####/.#../..##/..##", "###/#.#/#.# => ##../####/#.##/..##", "#.#/###/#.# => ##../..../..../####", "###/###/#.# => .#../.#.#/.###/.#.#", "###/#.#/### => ##../####/###./...#", "###/###/### => ###./#..#/##../.##."), "2169301") ) }
src/test/kotlin/solutions/day21/Day21Test.kt
929974503
package de.tum.`in`.tumcampusapp.api.tumonline import de.tum.`in`.tumcampusapp.api.tumonline.model.AccessToken import de.tum.`in`.tumcampusapp.api.tumonline.model.TokenConfirmation import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CreateEventResponse import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.DeleteEventResponse import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.EventsResponse import de.tum.`in`.tumcampusapp.component.tumui.grades.model.ExamList import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LectureAppointmentsResponse import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LectureDetailsResponse import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LecturesResponse import de.tum.`in`.tumcampusapp.component.tumui.person.model.Employee import de.tum.`in`.tumcampusapp.component.tumui.person.model.IdentitySet import de.tum.`in`.tumcampusapp.component.tumui.person.model.PersonList import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.model.TuitionList import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Query interface TUMOnlineAPIService { @GET("wbservicesbasic.kalender") fun getCalendar( @Query("pMonateVor") start: Int, @Query("pMonateNach") end: Int, @Header("Cache-Control") cacheControl: String ): Call<EventsResponse> @GET("wbservicesbasic.terminCreate") fun createCalendarEvent( @Query("pTitel") title: String, @Query("pAnmerkung") description: String, @Query("pVon") start: String, @Query("pBis") end: String, @Query("pTerminNr") eventId: String? = null ): Call<CreateEventResponse> @GET("wbservicesbasic.terminDelete") fun deleteCalendarEvent( @Query("pTerminNr") eventId: String ): Call<DeleteEventResponse> @GET("wbservicesbasic.studienbeitragsstatus") fun getTuitionFeesStatus( @Header("Cache-Control") cacheControl: String ): Call<TuitionList> @GET("wbservicesbasic.veranstaltungenEigene") fun getPersonalLectures( @Header("Cache-Control") cacheControl: String ): Call<LecturesResponse> @GET("wbservicesbasic.veranstaltungenDetails") fun getLectureDetails( @Query("pLVNr") id: String, @Header("Cache-Control") cacheControl: String ): Call<LectureDetailsResponse> @GET("wbservicesbasic.veranstaltungenTermine") fun getLectureAppointments( @Query("pLVNr") id: String, @Header("Cache-Control") cacheControl: String ): Call<LectureAppointmentsResponse> @GET("wbservicesbasic.veranstaltungenSuche") fun searchLectures( @Query("pSuche") query: String ): Call<LecturesResponse> @GET("wbservicesbasic.personenDetails") fun getPersonDetails( @Query("pIdentNr") id: String, @Header("Cache-Control") cacheControl: String ): Call<Employee> @GET("wbservicesbasic.personenSuche") fun searchPerson( @Query("pSuche") query: String ): Call<PersonList> @GET("wbservicesbasic.noten") fun getGrades( @Header("Cache-Control") cacheControl: String ): Call<ExamList> @GET("wbservicesbasic.requestToken") fun requestToken( @Query("pUsername") username: String, @Query("pTokenName") tokenName: String ): Call<AccessToken> @GET("wbservicesbasic.id") fun getIdentity(): Call<IdentitySet> @GET("wbservicesbasic.secretUpload") fun uploadSecret( @Query("pToken") token: String, @Query("pSecret") secret: String ): Call<TokenConfirmation> }
app/src/main/java/de/tum/in/tumcampusapp/api/tumonline/TUMOnlineAPIService.kt
788898093
package org.jetbrains.dokka import com.google.inject.Inject import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.JavaConstantExpressionEvaluator import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtModifierListOwner import java.io.File fun getSignature(element: PsiElement?) = when(element) { is PsiPackage -> element.qualifiedName is PsiClass -> element.qualifiedName is PsiField -> element.containingClass!!.qualifiedName + "$" + element.name is PsiMethod -> element.containingClass!!.qualifiedName + "$" + element.name + "(" + element.parameterList.parameters.map { it.type.typeSignature() }.joinToString(",") + ")" else -> null } private fun PsiType.typeSignature(): String = when(this) { is PsiArrayType -> "Array((${componentType.typeSignature()}))" is PsiPrimitiveType -> "kotlin." + canonicalText.capitalize() else -> mapTypeName(this) } private fun mapTypeName(psiType: PsiType): String = when (psiType) { is PsiPrimitiveType -> psiType.canonicalText is PsiClassType -> psiType.resolve()?.qualifiedName ?: psiType.className is PsiEllipsisType -> mapTypeName(psiType.componentType) is PsiArrayType -> "kotlin.Array" else -> psiType.canonicalText } interface JavaDocumentationBuilder { fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map<String, Content>) } class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { private val options: DocumentationOptions private val refGraph: NodeReferenceGraph private val docParser: JavaDocumentationParser @Inject constructor( options: DocumentationOptions, refGraph: NodeReferenceGraph, logger: DokkaLogger, signatureProvider: ElementSignatureProvider, externalDocumentationLinkResolver: ExternalDocumentationLinkResolver ) { this.options = options this.refGraph = refGraph this.docParser = JavadocParser(refGraph, logger, signatureProvider, externalDocumentationLinkResolver) } constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { this.options = options this.refGraph = refGraph this.docParser = docParser } override fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map<String, Content>) { if (skipFile(file) || file.classes.all { skipElement(it) }) { return } val packageNode = findOrCreatePackageNode(module, file.packageName, emptyMap(), refGraph) appendClasses(packageNode, file.classes) } fun appendClasses(packageNode: DocumentationNode, classes: Array<PsiClass>) { packageNode.appendChildren(classes) { build() } } fun register(element: PsiElement, node: DocumentationNode) { val signature = getSignature(element) if (signature != null) { refGraph.register(signature, node) } } fun link(node: DocumentationNode, element: PsiElement?) { val qualifiedName = getSignature(element) if (qualifiedName != null) { refGraph.link(node, qualifiedName, RefKind.Link) } } fun link(element: PsiElement?, node: DocumentationNode, kind: RefKind) { val qualifiedName = getSignature(element) if (qualifiedName != null) { refGraph.link(qualifiedName, node, kind) } } fun nodeForElement(element: PsiNamedElement, kind: NodeKind, name: String = element.name ?: "<anonymous>"): DocumentationNode { val (docComment, deprecatedContent, attrs, apiLevel, deprecatedLevel, artifactId, attribute) = docParser.parseDocumentation(element) val node = DocumentationNode(name, docComment, kind) if (element is PsiModifierListOwner) { node.appendModifiers(element) val modifierList = element.modifierList if (modifierList != null) { modifierList.annotations.filter { !ignoreAnnotation(it) }.forEach { val annotation = it.build() node.append(annotation, if (it.qualifiedName == "java.lang.Deprecated") RefKind.Deprecation else RefKind.Annotation) } } } if (deprecatedContent != null) { val deprecationNode = DocumentationNode("", deprecatedContent, NodeKind.Modifier) node.append(deprecationNode, RefKind.Deprecation) } if (element is PsiDocCommentOwner && element.isDeprecated && node.deprecation == null) { val deprecationNode = DocumentationNode("", Content.of(ContentText("Deprecated")), NodeKind.Modifier) node.append(deprecationNode, RefKind.Deprecation) } apiLevel?.let { node.append(it, RefKind.Detail) } deprecatedLevel?.let { node.append(it, RefKind.Detail) } artifactId?.let { node.append(it, RefKind.Detail) } attrs.forEach { refGraph.link(node, it, RefKind.Detail) refGraph.link(it, node, RefKind.Owner) } attribute?.let { val attrName = node.qualifiedName() refGraph.register("Attr:$attrName", attribute) } return node } fun ignoreAnnotation(annotation: PsiAnnotation) = when(annotation.qualifiedName) { "java.lang.SuppressWarnings" -> true else -> false } fun <T : Any> DocumentationNode.appendChildren(elements: Array<T>, kind: RefKind = RefKind.Member, buildFn: T.() -> DocumentationNode) { elements.forEach { if (!skipElement(it)) { append(it.buildFn(), kind) } } } private fun skipFile(javaFile: PsiJavaFile): Boolean = options.effectivePackageOptions(javaFile.packageName).suppress private fun skipElement(element: Any) = skipElementByVisibility(element) || hasSuppressDocTag(element) || hasHideAnnotation(element) || skipElementBySuppressedFiles(element) private fun skipElementByVisibility(element: Any): Boolean = element is PsiModifierListOwner && element !is PsiParameter && !(options.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && (element.hasModifierProperty(PsiModifier.PRIVATE) || element.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || element.isInternal()) private fun skipElementBySuppressedFiles(element: Any): Boolean = element is PsiElement && File(element.containingFile.virtualFile.path).absoluteFile in options.suppressedFiles private fun PsiElement.isInternal(): Boolean { val ktElement = (this as? KtLightElement<*, *>)?.kotlinOrigin ?: return false return (ktElement as? KtModifierListOwner)?.hasModifier(KtTokens.INTERNAL_KEYWORD) ?: false } fun <T : Any> DocumentationNode.appendMembers(elements: Array<T>, buildFn: T.() -> DocumentationNode) = appendChildren(elements, RefKind.Member, buildFn) fun <T : Any> DocumentationNode.appendDetails(elements: Array<T>, buildFn: T.() -> DocumentationNode) = appendChildren(elements, RefKind.Detail, buildFn) fun PsiClass.build(): DocumentationNode { val kind = when { isInterface -> NodeKind.Interface isEnum -> NodeKind.Enum isAnnotationType -> NodeKind.AnnotationClass isException() -> NodeKind.Exception else -> NodeKind.Class } val node = nodeForElement(this, kind) superTypes.filter { !ignoreSupertype(it) }.forEach { node.appendType(it, NodeKind.Supertype) val superClass = it.resolve() if (superClass != null) { link(superClass, node, RefKind.Inheritor) } } node.appendDetails(typeParameters) { build() } node.appendMembers(methods) { build() } node.appendMembers(fields) { build() } node.appendMembers(innerClasses) { build() } register(this, node) return node } fun PsiClass.isException() = InheritanceUtil.isInheritor(this, "java.lang.Throwable") fun ignoreSupertype(psiType: PsiClassType): Boolean = false // psiType.isClass("java.lang.Enum") || psiType.isClass("java.lang.Object") fun PsiClassType.isClass(qName: String): Boolean { val shortName = qName.substringAfterLast('.') if (className == shortName) { val psiClass = resolve() return psiClass?.qualifiedName == qName } return false } fun PsiField.build(): DocumentationNode { val node = nodeForElement(this, nodeKind()) node.appendType(type) node.appendConstantValueIfAny(this) register(this, node) return node } private fun DocumentationNode.appendConstantValueIfAny(field: PsiField) { val modifierList = field.modifierList ?: return val initializer = field.initializer ?: return if (modifierList.hasExplicitModifier(PsiModifier.FINAL) && modifierList.hasExplicitModifier(PsiModifier.STATIC)) { val value = JavaConstantExpressionEvaluator.computeConstantExpression(initializer, false) ?: return val text = when(value) { is String -> "\"${StringUtil.escapeStringCharacters(value)}\"" else -> value.toString() } append(DocumentationNode(text, Content.Empty, NodeKind.Value), RefKind.Detail) } } private fun PsiField.nodeKind(): NodeKind = when { this is PsiEnumConstant -> NodeKind.EnumItem else -> NodeKind.Field } fun PsiMethod.build(): DocumentationNode { val node = nodeForElement(this, nodeKind(), if (isConstructor) "<init>" else name) if (!isConstructor) { node.appendType(returnType) } node.appendDetails(parameterList.parameters) { build() } node.appendDetails(typeParameters) { build() } register(this, node) return node } private fun PsiMethod.nodeKind(): NodeKind = when { isConstructor -> NodeKind.Constructor else -> NodeKind.Function } fun PsiParameter.build(): DocumentationNode { val node = nodeForElement(this, NodeKind.Parameter) node.appendType(type) if (type is PsiEllipsisType) { node.appendTextNode("vararg", NodeKind.Modifier, RefKind.Detail) } return node } fun PsiTypeParameter.build(): DocumentationNode { val node = nodeForElement(this, NodeKind.TypeParameter) extendsListTypes.forEach { node.appendType(it, NodeKind.UpperBound) } implementsListTypes.forEach { node.appendType(it, NodeKind.UpperBound) } return node } fun DocumentationNode.appendModifiers(element: PsiModifierListOwner) { val modifierList = element.modifierList ?: return PsiModifier.MODIFIERS.forEach { if (modifierList.hasExplicitModifier(it)) { appendTextNode(it, NodeKind.Modifier) } } } fun DocumentationNode.appendType(psiType: PsiType?, kind: NodeKind = NodeKind.Type) { if (psiType == null) { return } append(psiType.build(kind), RefKind.Detail) } fun PsiType.build(kind: NodeKind = NodeKind.Type): DocumentationNode { val name = mapTypeName(this) val node = DocumentationNode(name, Content.Empty, kind) if (this is PsiClassType) { node.appendDetails(parameters) { build(NodeKind.Type) } link(node, resolve()) } if (this is PsiArrayType && this !is PsiEllipsisType) { node.append(componentType.build(NodeKind.Type), RefKind.Detail) } return node } fun PsiAnnotation.build(): DocumentationNode { val node = DocumentationNode(nameReferenceElement?.text ?: "<?>", Content.Empty, NodeKind.Annotation) parameterList.attributes.forEach { val parameter = DocumentationNode(it.name ?: "value", Content.Empty, NodeKind.Parameter) val value = it.value if (value != null) { val valueText = (value as? PsiLiteralExpression)?.value as? String ?: value.text val valueNode = DocumentationNode(valueText, Content.Empty, NodeKind.Value) parameter.append(valueNode, RefKind.Detail) } node.append(parameter, RefKind.Detail) } return node } } fun hasSuppressDocTag(element: Any?): Boolean { val declaration = (element as? KtLightDeclaration<*, *>)?.kotlinOrigin as? KtDeclaration ?: return false return PsiTreeUtil.findChildrenOfType(declaration.docComment, KDocTag::class.java).any { it.knownTag == KDocKnownTag.SUPPRESS } } /** * Determines if the @hide annotation is present in a Javadoc comment. * * @param element a doc element to analyze for the presence of @hide * * @return true if @hide is present, otherwise false * * Note: this does not process @hide annotations in KDoc. For KDoc, use the @suppress tag instead, which is processed * by [hasSuppressDocTag]. */ fun hasHideAnnotation(element: Any?): Boolean { return element is PsiDocCommentOwner && element.docComment?.run { findTagByName("hide") != null } ?: false }
core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt
3727449874
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.tooling import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.DashPathEffect import android.graphics.Paint import android.os.Bundle import android.util.AttributeSet import android.util.Log import android.widget.FrameLayout import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedDispatcherOwner import androidx.activity.compose.LocalActivityResultRegistryOwner import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.activity.result.ActivityResultRegistry import androidx.activity.result.ActivityResultRegistryOwner import androidx.activity.result.contract.ActivityResultContract import androidx.annotation.VisibleForTesting import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.SideEffect import androidx.compose.runtime.currentComposer import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalFontFamilyResolver import androidx.compose.ui.platform.LocalFontLoader import androidx.compose.ui.platform.ViewRootForTest import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.tooling.animation.AnimateXAsStateComposeAnimation import androidx.compose.ui.tooling.animation.AnimationSearch import androidx.compose.ui.tooling.animation.PreviewAnimationClock import androidx.compose.ui.tooling.animation.UnsupportedComposeAnimation import androidx.compose.ui.tooling.data.Group import androidx.compose.ui.tooling.data.SourceLocation import androidx.compose.ui.tooling.data.UiToolingDataApi import androidx.compose.ui.tooling.data.asTree import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.compose.ui.unit.IntRect import androidx.core.app.ActivityOptionsCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.ViewTreeLifecycleOwner import androidx.lifecycle.ViewTreeViewModelStoreOwner import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryController import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner import java.lang.reflect.Method private const val TOOLS_NS_URI = "http://schemas.android.com/tools" private const val DESIGN_INFO_METHOD = "getDesignInfo" private const val REMEMBER = "remember" private val emptyContent: @Composable () -> Unit = @Composable {} /** * Class containing the minimum information needed by the Preview to map components to the * source code and render boundaries. * * @suppress */ @OptIn(UiToolingDataApi::class) data class ViewInfo( val fileName: String, val lineNumber: Int, val bounds: IntRect, val location: SourceLocation?, val children: List<ViewInfo> ) { fun hasBounds(): Boolean = bounds.bottom != 0 && bounds.right != 0 fun allChildren(): List<ViewInfo> = children + children.flatMap { it.allChildren() } override fun toString(): String = """($fileName:$lineNumber, |bounds=(top=${bounds.top}, left=${bounds.left}, |location=${location?.let { "(${it.offset}L${it.length}" } ?: "<none>"} |bottom=${bounds.bottom}, right=${bounds.right}), |childrenCount=${children.size})""".trimMargin() } /** * View adapter that renders a `@Composable`. The `@Composable` is found by * reading the `tools:composableName` attribute that contains the FQN. Additional attributes can * be used to customize the behaviour of this view: * - `tools:parameterProviderClass`: FQN of the [PreviewParameterProvider] to be instantiated by * the [ComposeViewAdapter] that will be used as source for the `@Composable` parameters. * - `tools:parameterProviderIndex`: The index within the [PreviewParameterProvider] of the * value to be used in this particular instance. * - `tools:paintBounds`: If true, the component boundaries will be painted. This is only meant * for debugging purposes. * - `tools:printViewInfos`: If true, the [ComposeViewAdapter] will log the tree of [ViewInfo] * to logcat for debugging. * - `tools:animationClockStartTime`: When set, a [PreviewAnimationClock] will control the * animations in the [ComposeViewAdapter] context. * * @suppress */ @Suppress("unused") @OptIn(UiToolingDataApi::class) internal class ComposeViewAdapter : FrameLayout { private val TAG = "ComposeViewAdapter" /** * [ComposeView] that will contain the [Composable] to preview. */ private val composeView = ComposeView(context) /** * When enabled, generate and cache [ViewInfo] tree that can be inspected by the Preview * to map components to source code. */ private var debugViewInfos = false /** * When enabled, paint the boundaries generated by layout nodes. */ private var debugPaintBounds = false internal var viewInfos: List<ViewInfo> = emptyList() internal var designInfoList: List<String> = emptyList() private val slotTableRecord = CompositionDataRecord.create() /** * Simple function name of the Composable being previewed. */ private var composableName = "" /** * Whether the current Composable has animations. */ private var hasAnimations = false /** * Saved exception from the last composition. Since we can not handle the exception during the * composition, we save it and throw it during onLayout, this allows Studio to catch it and * display it to the user. */ private val delayedException = ThreadSafeException() /** * The [Composable] to be rendered in the preview. It is initialized when this adapter * is initialized. */ private var previewComposition: @Composable () -> Unit = {} // Note: the constant emptyContent below instead of a literal {} works around // https://youtrack.jetbrains.com/issue/KT-17467, which causes the compiler to emit classes // named `content` and `Content` (from the Content method's composable update scope) // which causes compilation problems on case-insensitive filesystems. @Suppress("RemoveExplicitTypeArguments") private val content = mutableStateOf<@Composable () -> Unit>(emptyContent) /** * When true, the composition will be immediately invalidated after being drawn. This will * force it to be recomposed on the next render. This is useful for live literals so the * whole composition happens again on the next render. */ private var forceCompositionInvalidation = false /** * When true, the adapter will try to look objects that support the call * [DESIGN_INFO_METHOD] within the slot table and populate [designInfoList]. Used to * support rendering in Studio. */ private var lookForDesignInfoProviders = false /** * An additional [String] argument that will be passed to objects that support the * [DESIGN_INFO_METHOD] call. Meant to be used by studio to as a way to request additional * information from the Preview. */ private var designInfoProvidersArgument: String = "" /** * Callback invoked when onDraw has been called. */ private var onDraw = {} private val debugBoundsPaint = Paint().apply { pathEffect = DashPathEffect(floatArrayOf(5f, 10f, 15f, 20f), 0f) style = Paint.Style.STROKE color = Color.Red.toArgb() } private var composition: Composition? = null constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(attrs) } private fun walkTable(viewInfo: ViewInfo, indent: Int = 0) { Log.d(TAG, ("| ".repeat(indent)) + "|-$viewInfo") viewInfo.children.forEach { walkTable(it, indent + 1) } } private val Group.fileName: String get() = location?.sourceFile ?: "" private val Group.lineNumber: Int get() = location?.lineNumber ?: -1 /** * Returns true if this [Group] has no source position information */ private fun Group.hasNullSourcePosition(): Boolean = fileName.isEmpty() && lineNumber == -1 /** * Returns true if this [Group] has no source position information and no children */ private fun Group.isNullGroup(): Boolean = hasNullSourcePosition() && children.isEmpty() private fun Group.toViewInfo(): ViewInfo { if (children.size == 1 && hasNullSourcePosition()) { // There is no useful information in this intermediate node, remove. return children.single().toViewInfo() } val childrenViewInfo = children .filter { !it.isNullGroup() } .map { it.toViewInfo() } // TODO: Use group names instead of indexing once it's supported return ViewInfo( location?.sourceFile ?: "", location?.lineNumber ?: -1, box, location, childrenViewInfo ) } /** * Processes the recorded slot table and re-generates the [viewInfos] attribute. */ private fun processViewInfos() { viewInfos = slotTableRecord.store.map { it.asTree() }.map { it.toViewInfo() }.toList() if (debugViewInfos) { viewInfos.forEach { walkTable(it) } } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) // If there was a pending exception then throw it here since Studio will catch it and show // it to the user. delayedException.throwIfPresent() processViewInfos() if (composableName.isNotEmpty()) { findAndTrackAnimations() if (lookForDesignInfoProviders) { findDesignInfoProviders() } } } override fun onAttachedToWindow() { ViewTreeLifecycleOwner.set(composeView.rootView, FakeSavedStateRegistryOwner) super.onAttachedToWindow() } /** * Finds all animations defined in the Compose tree where the root is the * `@Composable` being previewed. We only return animations defined in the user code, i.e. * the ones we've got source information for. */ @Suppress("UNCHECKED_CAST") private fun findAndTrackAnimations() { val slotTrees = slotTableRecord.store.map { it.asTree() } val transitionSearch = AnimationSearch.TransitionSearch { clock.trackTransition(it) } val animatedContentSearch = AnimationSearch.AnimatedContentSearch { clock.trackAnimatedContent(it) } val animatedVisibilitySearch = AnimationSearch.AnimatedVisibilitySearch { clock.trackAnimatedVisibility(it, ::requestLayout) } fun animateXAsStateSearch() = if (AnimateXAsStateComposeAnimation.apiAvailable) setOf(AnimationSearch.AnimateXAsStateSearch { clock.trackAnimateXAsState(it) }) else emptyList() // All supported animations. fun supportedSearch() = setOf( transitionSearch, animatedVisibilitySearch, ) + animateXAsStateSearch() fun unsupportedSearch() = if (UnsupportedComposeAnimation.apiAvailable) setOf( animatedContentSearch, AnimationSearch.AnimateContentSizeSearch { clock.trackAnimateContentSize(it) }, AnimationSearch.TargetBasedSearch { clock.trackTargetBasedAnimations(it) }, AnimationSearch.DecaySearch { clock.trackDecayAnimations(it) }, AnimationSearch.InfiniteTransitionSearch { clock.trackInfiniteTransition(it) } ) else emptyList() // All supported animations val supportedSearch = supportedSearch() // Animations to track in PreviewAnimationClock. val setToTrack = supportedSearch + unsupportedSearch() // Animations to search. animatedContentSearch is included even if it's not going to be // tracked as it should be excluded from transitionSearch. val setToSearch = setToTrack + setOf(animatedContentSearch) // Check all the slot tables, since some animations might not be present in the same // table as the one containing the `@Composable` being previewed, e.g. when they're // defined using sub-composition. slotTrees.forEach { tree -> val groupsWithLocation = tree.findAll { it.location != null } setToSearch.forEach { it.addAnimations(groupsWithLocation) } // Remove all AnimatedVisibility parent transitions from the transitions list, // otherwise we'd duplicate them in the Android Studio Animation Preview because we // will track them separately. transitionSearch.animations.removeAll(animatedVisibilitySearch.animations) // Remove all AnimatedContent parent transitions from the transitions list, so we can // ignore these animations while support is not added to Animation Preview. transitionSearch.animations.removeAll(animatedContentSearch.animations) } // If non of supported animations are detected, unsupported animations should not be // available either. hasAnimations = supportedSearch.any { it.hasAnimations() } // Make the `PreviewAnimationClock` track all the transitions found. if (::clock.isInitialized && hasAnimations) { setToTrack.forEach { it.track() } } } /** * Find all data objects within the slotTree that can invoke '[DESIGN_INFO_METHOD]', and store * their result in [designInfoList]. */ private fun findDesignInfoProviders() { val slotTrees = slotTableRecord.store.map { it.asTree() } designInfoList = slotTrees.flatMap { rootGroup -> rootGroup.findAll { group -> (group.name != REMEMBER && group.hasDesignInfo()) || group.children.any { child -> child.name == REMEMBER && child.hasDesignInfo() } }.mapNotNull { group -> // Get the DesignInfoProviders from the group or one of its children group.getDesignInfoOrNull(group.box) ?: group.children.firstNotNullOfOrNull { it.getDesignInfoOrNull(group.box) } } } } private fun Group.hasDesignInfo(): Boolean = data.any { it?.getDesignInfoMethodOrNull() != null } private fun Group.getDesignInfoOrNull(box: IntRect): String? = data.firstNotNullOfOrNull { it?.invokeGetDesignInfo(box.left, box.right) } /** * Check if the object supports the method call for [DESIGN_INFO_METHOD], which is expected * to take two Integer arguments for coordinates and a String for additional encoded * arguments that may be provided from Studio. */ private fun Any.getDesignInfoMethodOrNull(): Method? { return try { javaClass.getDeclaredMethod( DESIGN_INFO_METHOD, Integer.TYPE, Integer.TYPE, String::class.java ) } catch (e: NoSuchMethodException) { null } } @Suppress("BanUncheckedReflection") private fun Any.invokeGetDesignInfo(x: Int, y: Int): String? { return this.getDesignInfoMethodOrNull()?.let { designInfoMethod -> try { // Workaround for unchecked Method.invoke val result = designInfoMethod.invoke( this, x, y, designInfoProvidersArgument ) (result as String).ifEmpty { null } } catch (e: Exception) { null } } } private fun invalidateComposition() { // Invalidate the full composition by setting it to empty and back to the actual value content.value = {} content.value = previewComposition // Invalidate the state of the view so it gets redrawn invalidate() } override fun dispatchDraw(canvas: Canvas?) { super.dispatchDraw(canvas) if (forceCompositionInvalidation) invalidateComposition() onDraw() if (!debugPaintBounds) { return } viewInfos .flatMap { listOf(it) + it.allChildren() } .forEach { if (it.hasBounds()) { canvas?.apply { val pxBounds = android.graphics.Rect( it.bounds.left, it.bounds.top, it.bounds.right, it.bounds.bottom ) drawRect(pxBounds, debugBoundsPaint) } } } } /** * Clock that controls the animations defined in the context of this [ComposeViewAdapter]. * * @suppress */ @VisibleForTesting internal lateinit var clock: PreviewAnimationClock /** * Wraps a given [Preview] method an does any necessary setup. */ @Composable private fun WrapPreview(content: @Composable () -> Unit) { // We need to replace the FontResourceLoader to avoid using ResourcesCompat. // ResourcesCompat can not load fonts within Layoutlib and, since Layoutlib always runs // the latest version, we do not need it. @Suppress("DEPRECATION") CompositionLocalProvider( LocalFontLoader provides LayoutlibFontResourceLoader(context), LocalFontFamilyResolver provides createFontFamilyResolver(context), LocalOnBackPressedDispatcherOwner provides FakeOnBackPressedDispatcherOwner, LocalActivityResultRegistryOwner provides FakeActivityResultRegistryOwner, ) { Inspectable(slotTableRecord, content) } } /** * Initializes the adapter and populates it with the given [Preview] composable. * @param className name of the class containing the preview function * @param methodName `@Preview` method name * @param parameterProvider [Class] for the [PreviewParameterProvider] to be used as * parameter input for this call. If null, no parameters will be passed to the composable. * @param parameterProviderIndex when [parameterProvider] is not null, this index will * reference the element in the [Sequence] to be used as parameter. * @param debugPaintBounds if true, the view will paint the boundaries around the layout * elements. * @param debugViewInfos if true, it will generate the [ViewInfo] structures and will log it. * @param animationClockStartTime if positive, [clock] will be defined and will control the * animations defined in the context of the `@Composable` being previewed. * @param forceCompositionInvalidation if true, the composition will be invalidated on every * draw, forcing it to recompose on next render. * @param lookForDesignInfoProviders if true, it will try to populate [designInfoList]. * @param designInfoProvidersArgument String to use as an argument when populating * [designInfoList]. * @param onCommit callback invoked after every commit of the preview composable. * @param onDraw callback invoked after every draw of the adapter. Only for test use. */ @Suppress("DEPRECATION") @OptIn(ExperimentalComposeUiApi::class) @VisibleForTesting internal fun init( className: String, methodName: String, parameterProvider: Class<out PreviewParameterProvider<*>>? = null, parameterProviderIndex: Int = 0, debugPaintBounds: Boolean = false, debugViewInfos: Boolean = false, animationClockStartTime: Long = -1, forceCompositionInvalidation: Boolean = false, lookForDesignInfoProviders: Boolean = false, designInfoProvidersArgument: String? = null, onCommit: () -> Unit = {}, onDraw: () -> Unit = {} ) { this.debugPaintBounds = debugPaintBounds this.debugViewInfos = debugViewInfos this.composableName = methodName this.forceCompositionInvalidation = forceCompositionInvalidation this.lookForDesignInfoProviders = lookForDesignInfoProviders this.designInfoProvidersArgument = designInfoProvidersArgument ?: "" this.onDraw = onDraw previewComposition = @Composable { SideEffect(onCommit) WrapPreview { val composer = currentComposer // We need to delay the reflection instantiation of the class until we are in the // composable to ensure all the right initialization has happened and the Composable // class loads correctly. val composable = { try { ComposableInvoker.invokeComposable( className, methodName, composer, *getPreviewProviderParameters(parameterProvider, parameterProviderIndex) ) } catch (t: Throwable) { // If there is an exception, store it for later but do not catch it so // compose can handle it and dispose correctly. var exception: Throwable = t // Find the root cause and use that for the delayedException. while (exception is ReflectiveOperationException) { exception = exception.cause ?: break } delayedException.set(exception) throw t } } if (animationClockStartTime >= 0) { // When animation inspection is enabled, i.e. when a valid (non-negative) // `animationClockStartTime` is passed, set the Preview Animation Clock. This // clock will control the animations defined in this `ComposeViewAdapter` // from Android Studio. clock = PreviewAnimationClock { // Invalidate the descendants of this ComposeViewAdapter's only grandchild // (an AndroidOwner) when setting the clock time to make sure the Compose // Preview will animate when the states are read inside the draw scope. val composeView = getChildAt(0) as ComposeView (composeView.getChildAt(0) as? ViewRootForTest) ?.invalidateDescendants() // Send pending apply notifications to ensure the animation duration will // be read in the correct frame. Snapshot.sendApplyNotifications() } } composable() } } composeView.setContent(previewComposition) invalidate() } /** * Disposes the Compose elements allocated during [init] */ internal fun dispose() { composeView.disposeComposition() if (::clock.isInitialized) { clock.dispose() } FakeSavedStateRegistryOwner.lifecycleRegistry.currentState = Lifecycle.State.DESTROYED FakeViewModelStoreOwner.viewModelStore.clear() } /** * Returns whether this `@Composable` has animations. This allows Android Studio to decide if * the Animation Inspector icon should be displayed for this preview. The reason for using a * method instead of the property directly is we use Java reflection to call it from Android * Studio, and to find the property we'd need to filter the method names using `contains` * instead of `equals`. * * @suppress */ fun hasAnimations() = hasAnimations private fun init(attrs: AttributeSet) { // ComposeView and lifecycle initialization ViewTreeLifecycleOwner.set(this, FakeSavedStateRegistryOwner) setViewTreeSavedStateRegistryOwner(FakeSavedStateRegistryOwner) ViewTreeViewModelStoreOwner.set(this, FakeViewModelStoreOwner) addView(composeView) val composableName = attrs.getAttributeValue(TOOLS_NS_URI, "composableName") ?: return val className = composableName.substringBeforeLast('.') val methodName = composableName.substringAfterLast('.') val parameterProviderIndex = attrs.getAttributeIntValue( TOOLS_NS_URI, "parameterProviderIndex", 0 ) val parameterProviderClass = attrs.getAttributeValue(TOOLS_NS_URI, "parameterProviderClass") ?.asPreviewProviderClass() val animationClockStartTime = try { attrs.getAttributeValue(TOOLS_NS_URI, "animationClockStartTime").toLong() } catch (e: Exception) { -1L } val forceCompositionInvalidation = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "forceCompositionInvalidation", false ) init( className = className, methodName = methodName, parameterProvider = parameterProviderClass, parameterProviderIndex = parameterProviderIndex, debugPaintBounds = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "paintBounds", debugPaintBounds ), debugViewInfos = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "printViewInfos", debugViewInfos ), animationClockStartTime = animationClockStartTime, forceCompositionInvalidation = forceCompositionInvalidation, lookForDesignInfoProviders = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "findDesignInfoProviders", lookForDesignInfoProviders ), designInfoProvidersArgument = attrs.getAttributeValue( TOOLS_NS_URI, "designInfoProvidersArgument" ) ) } @SuppressLint("VisibleForTests") private val FakeSavedStateRegistryOwner = object : SavedStateRegistryOwner { val lifecycleRegistry = LifecycleRegistry.createUnsafe(this) private val controller = SavedStateRegistryController.create(this).apply { performRestore(Bundle()) } init { lifecycleRegistry.currentState = Lifecycle.State.RESUMED } override val savedStateRegistry: SavedStateRegistry get() = controller.savedStateRegistry override fun getLifecycle(): Lifecycle = lifecycleRegistry } private val FakeViewModelStoreOwner = object : ViewModelStoreOwner { private val viewModelStore = ViewModelStore() override fun getViewModelStore() = viewModelStore } private val FakeOnBackPressedDispatcherOwner = object : OnBackPressedDispatcherOwner { private val onBackPressedDispatcher = OnBackPressedDispatcher() override fun getOnBackPressedDispatcher() = onBackPressedDispatcher override fun getLifecycle() = FakeSavedStateRegistryOwner.lifecycleRegistry } private val FakeActivityResultRegistryOwner = object : ActivityResultRegistryOwner { private val activityResultRegistry = object : ActivityResultRegistry() { override fun <I : Any?, O : Any?> onLaunch( requestCode: Int, contract: ActivityResultContract<I, O>, input: I, options: ActivityOptionsCompat? ) { throw IllegalStateException("Calling launch() is not supported in Preview") } } override fun getActivityResultRegistry(): ActivityResultRegistry = activityResultRegistry } }
compose/ui/ui-tooling/src/androidMain/kotlin/androidx/compose/ui/tooling/ComposeViewAdapter.kt
3672318649
package com.github.willjgriff.ethereumwallet.ethereum.icap import com.github.willjgriff.ethereumwallet.ethereum.icap.BaseConverter import org.amshove.kluent.shouldEqual import org.junit.Test /** * Created by Will on 01/03/2017. */ class BaseConverterTest { private val subject = BaseConverter() @Test fun base16ToBase36_returnsExpectedValue() { val expectedNumber = "P2J0C65CFU410SM2IXXO687WQO2HMJV".toLowerCase() val actualNumber = subject.base16ToBase36("D69F2FF2893C73B5eF4959a2ce85Ab1B1d35CE6B") actualNumber shouldEqual expectedNumber } @Test fun base16ToBase36_returnsExpectedValue2() { val expectedNumber = "38O073KYGTWWZN0F2WZ0R8PX5ZPPZS".toLowerCase() val actualNumber = subject.base16ToBase36("c5496aee77c1ba1f0854206a26dda82a81d6d8") actualNumber shouldEqual expectedNumber } @Test fun base36ToBase16_returnsExpectedValue() { val expectedNumber = "D69F2FF2893C73B5eF4959a2ce85Ab1B1d35CE6B".toLowerCase() val actualNumber = subject.base36ToBase16("P2J0C65CFU410SM2IXXO687WQO2HMJV") actualNumber shouldEqual expectedNumber } @Test fun base36ToBase16_returnsExpectedValue2() { val expectedNumber = "c5496aee77c1ba1f0854206a26dda82a81d6d8".toLowerCase() val actualNumber = subject.base36ToBase16("38O073KYGTWWZN0F2WZ0R8PX5ZPPZS") actualNumber shouldEqual expectedNumber } @Test fun base36ToInteger_returnsExpectedIntegerString() { val expectedInteger = "25219012651215304102822218333324687322624217221931" val actualInteger = subject.base36ToInteger("P2J0C65CFU410SM2IXXO687WQO2HMJV") actualInteger shouldEqual expectedInteger } @Test fun base36ToInteger_returnsExpectedIntegerString2() { val expectedInteger = "38240732034162932323523015232350278253353525253528" val actualInteger = subject.base36ToInteger("38O073KYGTWWZN0F2WZ0R8PX5ZPPZS") actualInteger shouldEqual expectedInteger } }
app/src/test/kotlin/com/github/willjgriff/ethereumwallet/ethereum/icap/BaseConverterTest.kt
1984280615
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.commands.sc import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.commands.ResponseBuilder import com.demonwav.statcraft.querydsl.QDamageDealt import com.demonwav.statcraft.querydsl.QPlayers import org.bukkit.command.CommandSender import java.sql.Connection class SCDamageDealt(plugin: StatCraft) : SCTemplate(plugin) { init { plugin.baseCommand.registerCommand("damagedealt", this) } override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.damagedealt") override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String { val id = getId(name) ?: return ResponseBuilder.build(plugin) { playerName { name } statName { "Damage Dealt" } stats["Total"] = "0" } val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError val d = QDamageDealt.damageDealt val total = query.from(d).where(d.id.eq(id)).uniqueResult(d.amount.sum()) ?: 0 return ResponseBuilder.build(plugin) { playerName { name } statName { "Damage Dealt" } stats["Total"] = df.format(total) } } override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String { val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError val d = QDamageDealt.damageDealt val p = QPlayers.players val list = query .from(d) .innerJoin(p) .on(d.id.eq(p.id)) .groupBy(p.name) .orderBy(d.amount.sum().desc()) .limit(num) .list(p.name, d.amount.sum()) return topListResponse("Damage Dealt", list) } }
src/main/kotlin/com/demonwav/statcraft/commands/sc/SCDamageDealt.kt
415536159
package com.github.willjgriff.ethereumwallet.ethereum.transaction.transactions import com.github.willjgriff.ethereumwallet.ethereum.transactions.BlocksSearchedLogger import com.github.willjgriff.ethereumwallet.ethereum.transactions.model.BlockRange import com.github.willjgriff.ethereumwallet.ethereum.transactions.storage.TransactionsStorage import com.nhaarman.mockito_kotlin.atLeastOnce import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.amshove.kluent.shouldEqual import org.junit.Test /** * Created by williamgriffiths on 23/04/2017. */ class BlocksSearchedLoggerTest { val mockBlocksSearchedStorage = mock<TransactionsStorage> { on { getBlocksSearched() } doReturn listOf<BlockRange>() } val subject: BlocksSearchedLogger = BlocksSearchedLogger(mockBlocksSearchedStorage) @Test fun addingSearchedBlocksAreAddedToList() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(8) } verify(mockBlocksSearchedStorage, atLeastOnce()).storeBlocksSearched(listOf(BlockRange(10, 8))) } @Test fun addingSeparatedSearchedBlocksCreatesMultipleRanges() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(8) blockSearched(15) blockSearched(14) blockSearched(13) } verify(mockBlocksSearchedStorage, atLeastOnce()).storeBlocksSearched(listOf(BlockRange(10, 8), BlockRange(15, 13))) } @Test fun addingTheSameBlockManyTimesIncludesBlockRangeOnce() { subject.apply { blockSearched(10) blockSearched(10) blockSearched(10) } verify(mockBlocksSearchedStorage, atLeastOnce()).storeBlocksSearched(listOf(BlockRange(10, 10))) } @Test fun addingBlocksInAscendingOrderCreatesExpectedBlockRanges() { subject.apply { blockSearched(10) blockSearched(11) blockSearched(12) } verify(mockBlocksSearchedStorage, atLeastOnce()).storeBlocksSearched(listOf(BlockRange(10, 10), BlockRange(11, 11), BlockRange(12, 12))) } @Test fun addingBlocksInRandomOrderStillAddsToExpectedBlockRanges() { subject.apply { blockSearched(10) blockSearched(20) blockSearched(11) blockSearched(19) blockSearched(10) blockSearched(11) } verify(mockBlocksSearchedStorage, atLeastOnce()).storeBlocksSearched(listOf(BlockRange(10, 10), BlockRange(20, 19), BlockRange(11, 11))) } // @Test // fun addingBlocksSearchDoesntCreateLowerGreterThanUpper() { // subject.apply { // blockSearched(10) // blockSearched(12) // } // val expectedList = listOf(BlockRange(10, 10), BlockRange(12, 12)) // verify(mockBlocksSearchedStorage, atLeastOnce()).storeBlocksSearched(expectedList) // } @Test fun searchBlocksAreCorrectWhenNoBlocksHaveBeenSearched() { val searchBlocks = subject.getBlocksToSearchFromTopBlock(15, 5) searchBlocks shouldEqual listOf(BlockRange(15, 11)) } @Test fun searchBlocksAreCorrectWhenBlocksToSearchIsTheSameAsTopBlock() { val searchBlocks = subject.getBlocksToSearchFromTopBlock(5, 5) searchBlocks shouldEqual listOf(BlockRange(5, 1)) } @Test fun searchBlocksAreCorrectWhenBlocksToSearchIsLargerThanTopBlock() { val searchBlocks = subject.getBlocksToSearchFromTopBlock(5, 6) searchBlocks shouldEqual listOf(BlockRange(5, 0)) } @Test fun searchBlocksAreCorrectWhenBlocksToSearchIsLargerThanBlocksAvailable() { val searchBlocks = subject.getBlocksToSearchFromTopBlock(5, 7) searchBlocks shouldEqual listOf(BlockRange(5, 0)) } @Test fun blocksSearchedArentInBlocksToSearchResponse() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(8) } val searchBlocks = subject.getBlocksToSearchFromTopBlock(12, 5) searchBlocks shouldEqual listOf(BlockRange(12, 11), BlockRange(7, 5)) } @Test fun multipleBlockRangesSearchedArentInBlocksToSearchReponse() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(13) blockSearched(12) } val searchBlocks = subject.getBlocksToSearchFromTopBlock(15, 5) searchBlocks shouldEqual listOf(BlockRange(15, 14), BlockRange(11, 11), BlockRange(8, 7)) } @Test fun manyMultipleBlockRangesSearchedArentInBlocksToSearchResponse() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(12) blockSearched(15) blockSearched(14) } val searchBlocks = subject.getBlocksToSearchFromTopBlock(16, 5) searchBlocks shouldEqual listOf(BlockRange(16, 16), BlockRange(13, 13), BlockRange(11, 11), BlockRange(8, 7)) } @Test fun manyMultipleBlockRangesSearchedArentInBlocksToSearchResponse2() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(12) blockSearched(15) blockSearched(14) blockSearched(20) blockSearched(19) blockSearched(18) } val searchBlocks = subject.getBlocksToSearchFromTopBlock(23, 10) searchBlocks shouldEqual listOf(BlockRange(23, 21), BlockRange(17, 16), BlockRange(13, 13), BlockRange(11, 11), BlockRange(8, 6)) } @Test fun returnsCorrectRangeWhenStartingFromBlockLowerThanInCurrentlySearchedRanges() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(8) } val searchBlocks = subject.getBlocksToSearchFromTopBlock(6, 3) searchBlocks shouldEqual listOf(BlockRange(6, 4)) } @Test fun doesntReturnNegativeBlockRangeWithMultipleRanges() { subject.apply { blockSearched(10) blockSearched(9) blockSearched(8) blockSearched(15) blockSearched(14) } val searchBlocks = subject.getBlocksToSearchFromTopBlock(9, 3) searchBlocks shouldEqual listOf(BlockRange(7, 5)) } }
app/src/test/kotlin/com/github/willjgriff/ethereumwallet/ethereum/transaction/transactions/BlocksSearchedLoggerTest.kt
3685277693
fun test() { fun some(a: Int, b: Int) {} some(<caret>12, 3) }
kotlin-eclipse-ui-test/testData/format/autoIndent/newLineInParameters1.kt
3186893065
import kotlinx.serialization.Serializable @Serializable data class ShoppingListItem(val desc: String, val priority: Int) { val id: Int = desc.hashCode() companion object { const val path = "/getShoppingList" } }
samples/dev.jeka.samples.kotlin-multiplatform/src/main/kotlin-common/ShoppingListItem.kt
2564064254
/* * Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.net.social import android.text.Spannable import android.text.SpannableString import android.text.Spanned import org.andstatus.app.data.TextMediaType import org.andstatus.app.util.MyHtml import org.andstatus.app.util.MyUrlSpan import java.util.* import java.util.function.Function import java.util.stream.Stream object SpanUtil { private const val MIN_SPAN_LENGTH = 3 private const val MIN_HASHTAG_LENGTH = 2 val EMPTY = SpannableString.valueOf("") fun regionsOf(spannable: Spanned): MutableList<Region> { return Stream.concat( Arrays.stream(spannable.getSpans(0, spannable.length, Any::class.java)) .map { span: Any -> Region(spannable, span) }, Stream.of(Region(spannable, spannable.length, spannable.length + 1))) .sorted() .reduce( ArrayList(), { xs: ArrayList<Region>, region: Region -> val prevRegion = Region(spannable, if (xs.size == 0) 0 else xs.get(xs.size - 1).end, region.start) if (prevRegion.isValid()) xs.add(prevRegion) if (region.isValid()) xs.add(region) xs }, { xs1: ArrayList<Region>, xs2: ArrayList<Region> -> xs1.addAll(xs2) xs1 }) } fun textToSpannable(text: String?, mediaType: TextMediaType, audience: Audience): Spannable { return if (text.isNullOrEmpty()) EMPTY else spansModifier(audience).apply(MyUrlSpan.toSpannable( if (mediaType == TextMediaType.PLAIN) text else MyHtml.prepareForView(text), mediaType, true)) } fun spansModifier(audience: Audience): Function<Spannable, Spannable> { return Function { spannable: Spannable -> regionsOf(spannable).forEach(modifySpansInRegion(spannable, audience)) spannable } } private fun modifySpansInRegion(spannable: Spannable, audience: Audience): ((Region) -> Unit) = fun(region: Region) { if (region.start >= spannable.length || region.end > spannable.length) return val text = spannable.subSequence(region.start, region.end).toString() if (mentionAdded(spannable, audience, region, text)) return hashTagAdded(spannable, audience, region, text) } private fun mentionAdded(spannable: Spannable, audience: Audience, region: Region, text: String): Boolean { if (audience.hasNonSpecial() && text.contains("@")) { val upperText = text.toUpperCase() val mentionedByAtWebfingerID = audience.getNonSpecialActors().stream() .filter { actor: Actor -> actor.isWebFingerIdValid() && upperText.contains("@" + actor.getWebFingerId().toUpperCase()) }.findAny().orElse(Actor.EMPTY) if (mentionedByAtWebfingerID.nonEmpty) { return notesByActorSpanAdded(spannable, audience, region, "@" + mentionedByAtWebfingerID.getWebFingerId(), mentionedByAtWebfingerID) } else { val mentionedByWebfingerID = audience.getNonSpecialActors().stream() .filter { actor: Actor -> actor.isWebFingerIdValid() && upperText.contains(actor.getWebFingerId().toUpperCase()) }.findAny().orElse(Actor.EMPTY) if (mentionedByWebfingerID.nonEmpty) { return notesByActorSpanAdded(spannable, audience, region, mentionedByWebfingerID.getWebFingerId(), mentionedByWebfingerID) } else { val mentionedByUsername = audience.getNonSpecialActors().stream() .filter { actor: Actor -> actor.isUsernameValid() && upperText.contains("@" + actor.getUsername().toUpperCase()) }.findAny().orElse(Actor.EMPTY) if (mentionedByUsername.nonEmpty) { return notesByActorSpanAdded(spannable, audience, region, "@" + mentionedByUsername.getUsername(), mentionedByUsername) } } } } return false } private fun notesByActorSpanAdded(spannable: Spannable, audience: Audience, region: Region, stringFound: String, actor: Actor): Boolean { return spanAdded(spannable, audience, region, stringFound, MyUrlSpan.Data(Optional.of(actor), Optional.empty(), Optional.empty())) } private fun spanAdded(spannable: Spannable, audience: Audience, region: Region, stringFound: String, spanData: MyUrlSpan.Data): Boolean { if (region.urlSpan.isPresent()) { spannable.removeSpan(region.urlSpan.get()) spannable.setSpan(MyUrlSpan(spanData), region.start, region.end, 0) } else if (region.otherSpan.isPresent()) { spannable.removeSpan(region.otherSpan.get()) spannable.setSpan(MyUrlSpan(spanData), region.start, region.end, 0) } else { val indInRegion = getIndInRegion(spannable, region, stringFound) if (indInRegion < 0) return false val start2 = region.start + indInRegion val start3 = start2 + stringFound.length if (start3 > region.end + 1) return false spannable.setSpan(MyUrlSpan(spanData), start2, Math.min(start3, region.end), 0) if (indInRegion >= MIN_SPAN_LENGTH) { modifySpansInRegion(spannable, audience).invoke( Region(spannable, region.start, start2) ) } if (start3 + MIN_SPAN_LENGTH <= region.end) { modifySpansInRegion(spannable, audience).invoke( Region(spannable, start3, region.end) ) } } return true } /** Case insensitive search */ private fun getIndInRegion(spannable: Spannable, region: Region, stringFound: String): Int { val substr1 = spannable.subSequence(region.start, region.end).toString() val indInRegion = substr1.indexOf(stringFound) if (indInRegion >= 0) return indInRegion val foundUpper = stringFound.toUpperCase() var ind = 0 do { val ind2 = substr1.substring(ind).toUpperCase().indexOf(foundUpper) if (ind2 >= 0) return ind2 + ind ind++ } while (ind + stringFound.length < substr1.length) return -1 } /** As https://www.hashtags.org/definition/ shows, hashtags may have numbers only, * and may contain one symbol only */ private fun hashTagAdded(spannable: Spannable, audience: Audience, region: Region, text: String): Boolean { var indStart = 0 var hashTag: String do { val indTag = text.indexOf('#', indStart) if (indTag < 0) return false hashTag = hashTagAt(text, indTag) indStart = indTag + 1 } while (hashTag.length < MIN_HASHTAG_LENGTH) return spanAdded(spannable, audience, region, hashTag, MyUrlSpan.Data(Optional.empty(), Optional.of(hashTag), Optional.empty())) } private fun hashTagAt(text: String, indStart: Int): String { if (indStart + 1 >= text.length || text.get(indStart) != '#' || !Character.isLetterOrDigit(text.get(indStart + 1)) || indStart > 0 && Character.isLetterOrDigit(text.get(indStart - 1))) { return "" } var ind = indStart + 2 while (ind < text.length) { val c = text.get(ind) if (!Character.isLetterOrDigit(c) && c != '_') break ind++ } return text.substring(indStart, ind) } class Region : Comparable<Region> { val start: Int val end: Int val text: CharSequence? val urlSpan: Optional<MyUrlSpan> val otherSpan: Optional<Any> constructor(spannable: Spanned, span: Any) { val spanStart = spannable.getSpanStart(span) // Sometimes "@" is not included in the span start = if (spanStart > 0 && "@#".indexOf(spannable.get(spanStart)) < 0 && "@#".indexOf(spannable.get(spanStart - 1)) >= 0) spanStart - 1 else spanStart if (MyUrlSpan::class.java.isAssignableFrom(span.javaClass)) { urlSpan = Optional.of(span as MyUrlSpan) otherSpan = Optional.empty() } else { urlSpan = Optional.empty() otherSpan = Optional.of(span) } end = spannable.getSpanEnd(span) text = spannable.subSequence(start, end) } constructor(spannable: Spanned, start: Int, end: Int) { this.start = start this.end = end urlSpan = Optional.empty() otherSpan = Optional.empty() text = if (start < end && spannable.length >= end) spannable.subSequence(start, end) else "" } override operator fun compareTo(other: Region): Int { return Integer.compare(start, other.start) } override fun toString(): String { return "Region{" + start + "-" + end + " '" + text + "'" + urlSpan.map { s: MyUrlSpan? -> ", $s" }.orElse("") + otherSpan.map { s: Any? -> ", otherSpan" }.orElse("") + '}' } fun isValid(): Boolean { return urlSpan.isPresent() || otherSpan.isPresent() || end - start >= MIN_SPAN_LENGTH } } }
app/src/main/kotlin/org/andstatus/app/net/social/SpanUtil.kt
2951216522
/* * Copyright (C) 2021 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.util import org.andstatus.app.context.ExecutionMode import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.TestSuite import org.apache.geode.test.junit.IgnoreCondition import org.junit.runner.Description /** * @author [email protected] */ open class IsExecutionMode(private val executionMode: ExecutionMode) : IgnoreCondition { override fun evaluate(testCaseDescription: Description?): Boolean { TestSuite.initialize(this) MyLog.i(this, "Execution mode: " + MyContextHolder.myContextHolder.executionMode) return true // MyContextHolder.myContextHolder.executionMode == executionMode } } class IsTravisTest: IsExecutionMode(ExecutionMode.TRAVIS_TEST)
app/src/androidTest/kotlin/org/andstatus/app/util/IsExecutionMode.kt
2481789675
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent.blemessagestream import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.companionprotos.OperationProto.OperationType import com.google.android.libraries.car.trustagent.blemessagestream.version2.BluetoothMessageStreamV2 import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.mock import kotlin.test.assertFailsWith import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MessageStreamTest { private val mockBluetothManager: BluetoothConnectionManager = mock() private lateinit var stream: BluetoothMessageStreamV2 @Before fun setUp() { stream = BluetoothMessageStreamV2(mockBluetothManager, isCompressionEnabled = false) } @Test fun testCompressData_canNotCompress_returnsNull() { val payload = ByteArray(1) val compressed = MessageStream.compressData(payload) assertThat(compressed).isNull() } @Test fun testCompressData_canCompress_returnsSmallerData() { val payload = ByteArray(1000) val compressed = MessageStream.compressData(payload) assertThat(payload.size).isGreaterThan(compressed?.size) } @Test fun testCompressDecompress() { val size = 1000 val payload = ByteArray(size) val compressed = MessageStream.compressData(payload) val decompressed = MessageStream.decompressData(compressed!!, size) assertThat(decompressed!!.contentEquals(payload)).isTrue() } @Test fun testDecompressData_originalSizeIsZero_returnsOriginal() { val payload = ByteArray(10) val decompressed = MessageStream.decompressData(payload, originalSize = 0) assertThat(decompressed).isEqualTo(payload) } @Test fun testToEncrypted_payloadNotEncrypted_throwsException() { val message = StreamMessage( ByteArray(1), OperationType.CLIENT_MESSAGE, isPayloadEncrypted = false, originalMessageSize = 0, recipient = null ) assertFailsWith<IllegalStateException> { // We cannot create a mocked instance of interface here, // likely because the extension methods live in the scope provided by the concrete class. with(stream) { message.toEncrypted() } } } @Test fun testToDecrypted_payloadNotEncrypted_throwsException() { val message = StreamMessage( ByteArray(1), OperationType.CLIENT_MESSAGE, isPayloadEncrypted = false, originalMessageSize = 0, recipient = null ) assertFailsWith<IllegalStateException> { with(stream) { message.toDecrypted() } } } }
trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/blemessagestream/MessageStreamTest.kt
421306526
package org.ccci.gto.android.common.db import android.annotation.SuppressLint import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import org.ccci.gto.android.common.db.AbstractDao.Companion.bindValues @SuppressLint("SupportAnnotationUsage") data class Query<T : Any> private constructor( @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val table: Table<T>, internal val isDistinct: Boolean = false, @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val joins: List<Join<T, *>> = emptyList(), internal val projection: List<String>? = null, @VisibleForTesting internal val where: Expression? = null, internal val orderBy: String? = null, internal val groupBy: List<Expression.Field> = emptyList(), private val having: Expression? = null, private val limit: Int? = null, private val offset: Int? = null ) { companion object { @JvmStatic fun <T : Any> select(type: Class<T>) = Query(table = Table.forClass(type)) @JvmStatic fun <T : Any> select(table: Table<T>) = Query(table = table) inline fun <reified T : Any> select() = select(T::class.java) } @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val allTables get() = sequenceOf(table) + joins.flatMap { it.allTables } fun distinct(isDistinct: Boolean) = copy(isDistinct = isDistinct) fun join(vararg joins: Join<T, *>) = copy(joins = this.joins + joins) fun joins(vararg joins: Join<T, *>) = copy(joins = joins.toList()) fun projection(vararg projection: String) = copy(projection = projection.toList().takeUnless { it.isEmpty() }) fun where(where: Expression?) = copy(where = where) fun where(where: String?, vararg args: Any) = where(where, *bindValues(*args)) fun where(where: String?, vararg args: String) = where(where?.let { Expression.raw(it, args) }) fun andWhere(expr: Expression) = copy(where = where?.and(expr) ?: expr) fun orderBy(orderBy: String?): Query<T> = copy(orderBy = orderBy) fun groupBy(vararg groupBy: Expression.Field) = copy(groupBy = groupBy.toList()) fun having(having: Expression?) = copy(having = having) fun limit(limit: Int?) = copy(limit = limit) fun offset(offset: Int?) = copy(offset = offset) internal fun buildSqlFrom(dao: AbstractDao) = QueryComponent(table.sqlTable(dao)) + joins.joinToQueryComponent { it.getSql(dao) } internal fun buildSqlWhere(dao: AbstractDao) = where?.buildSql(dao) internal fun buildSqlHaving(dao: AbstractDao) = having?.buildSql(dao) internal val sqlLimit get() = when { // // XXX: not supported by Android // // "{limit} OFFSET {offset}" syntax // limit != null && offset != null -> "$limit OFFSET $offset" // "{offset},{limit}" syntax limit != null && offset != null -> "$offset, $limit" limit != null -> "$limit" else -> null } }
gto-support-db/src/main/java/org/ccci/gto/android/common/db/Query.kt
2741288242
package com.commonsense.android.kotlin.base.compat import com.commonsense.android.kotlin.test.* import org.junit.* import org.junit.jupiter.api.Test /** * Created by Kasper Tvede on 20-05-2018. * Purpose: */ internal class SSLContextProtocolsTest { @Test fun createContext() { SSLContextProtocols.TLSv12.createContext().assertNotNull("tls1.2 should exist in jvm") SSLContextProtocols.TLSv11.createContext().assertNotNull("tls1.1 should exist in jvm") } @Test fun testalgorithmName() { SSLContextProtocols.SSL.algorithmName.contains("ssl", false) SSLContextProtocols.SSLv2.algorithmName.contains("ssl", false) SSLContextProtocols.SSLv3.algorithmName.contains("ssl", false) SSLContextProtocols.TLS.algorithmName.contains("tls", false) SSLContextProtocols.TLSv11.algorithmName.contains("tls", false) SSLContextProtocols.TLSv12.algorithmName.contains("tls", false) } @Test fun createSocketFactory() { SSLContextProtocols.TLSv12.createSocketFactory().assertNotNull("tls1.2 should exist in jvm") SSLContextProtocols.TLSv11.createSocketFactory().assertNotNull("tls1.1 should exist in jvm") } @Ignore @Test fun getAlgorithmName() { } }
base/src/test/kotlin/com/commonsense/android/kotlin/base/compat/SSLContextProtocolsTest.kt
2501673109
package me.echeung.moemoekyun.adapter import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import me.echeung.moemoekyun.R import me.echeung.moemoekyun.client.auth.AuthUtil import me.echeung.moemoekyun.client.model.Song import me.echeung.moemoekyun.databinding.SongDetailsBinding import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.ext.openUrl import org.koin.core.KoinComponent import org.koin.core.inject class SongDetailAdapter( private val activity: Activity, songs: List<Song> ) : ArrayAdapter<Song>(activity, 0, songs), KoinComponent { private val authUtil: AuthUtil by inject() private val songActionsUtil: SongActionsUtil by inject() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val inflater = LayoutInflater.from(context) val binding: SongDetailsBinding var view = convertView if (view == null) { binding = DataBindingUtil.inflate(inflater, R.layout.song_details, parent, false) view = binding.root view.tag = binding } else { binding = view.tag as SongDetailsBinding } val song = getItem(position) ?: return binding.root binding.song = song binding.isAuthenticated = authUtil.isAuthenticated binding.isFavorite = song.favorite binding.requestBtn.setOnClickListener { songActionsUtil.request(activity, song) } binding.favoriteBtn.setOnClickListener { songActionsUtil.toggleFavorite(activity, song) song.favorite = !song.favorite binding.isFavorite = song.favorite } binding.albumArt.setOnLongClickListener { val albumArtUrl = song.albumArtUrl ?: return@setOnLongClickListener false context.openUrl(albumArtUrl) true } binding.root.setOnLongClickListener { songActionsUtil.copyToClipboard(context, song) true } return binding.root } }
app/src/main/java/me/echeung/moemoekyun/adapter/SongDetailAdapter.kt
822734323
package org.wordpress.aztec.plugins.visual2html import android.annotation.SuppressLint import android.text.style.CharacterStyle import org.wordpress.aztec.plugins.IAztecPlugin /** * An interface for processing inline spans during visual-to-HTML. */ @SuppressLint("NewApi") interface IInlineSpanHandler : IAztecPlugin { /** * Determines, whether the content of a span (text, if any) should be parsed/rendered by [org.wordpress.aztec.AztecParser] * * @return true if content should be parsed, false otherwise. */ fun shouldParseContent(): Boolean { return true } /** * Determines, whether the plugin can handle a particular [span] type. * * This method is called by [org.wordpress.aztec.AztecParser] during span-to-HTML parsing. * * @return true for compatible spans, false otherwise. */ fun canHandleSpan(span: CharacterStyle): Boolean /** * A plugin handler used by [org.wordpress.aztec.AztecParser] during span-to-HTML parsing. * * This method is called when the beginning of a compatible span is encountered. * * @param html the resulting HTML string output. * @param span the encountered span. */ fun handleSpanStart(html: StringBuilder, span: CharacterStyle) /** * A plugin handler used by [org.wordpress.aztec.AztecParser] during span-to-HTML parsing. * * This method is called when the ending of a compatible span is encountered. * * @param html the resulting HTML string output. * @param span the encountered span. */ fun handleSpanEnd(html: StringBuilder, span: CharacterStyle) }
aztec/src/main/kotlin/org/wordpress/aztec/plugins/visual2html/IInlineSpanHandler.kt
3967941464
package ru.fantlab.android.helper import android.app.Activity import android.content.* import androidx.core.app.ShareCompat import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import es.dmoral.toasty.Toasty import ru.fantlab.android.App import ru.fantlab.android.R object ActivityHelper { fun getActivity(content: Context?): Activity? { return when (content) { null -> null is Activity -> content is ContextWrapper -> getActivity(content.baseContext) else -> null } } fun getVisibleFragment(manager: FragmentManager): Fragment? { val fragments = manager.fragments if (fragments != null && !fragments.isEmpty()) { fragments .filter { it != null && it.isVisible } .forEach { return it } } return null } fun shareUrl(context: Context, url: String) { val activity = getActivity(context) ?: throw IllegalArgumentException("Context given is not an instance of activity ${context.javaClass.name}") try { ShareCompat.IntentBuilder.from(activity) .setChooserTitle(context.getString(R.string.share)) .setType("text/plain") .setText(url) .startChooser() } catch (e: ActivityNotFoundException) { Toasty.error(App.instance, e.message!!, Toast.LENGTH_LONG).show() } } fun copyToClipboard(context: Context, uri: String) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText(context.getString(R.string.app_name), uri) clipboard.primaryClip = clip Toasty.success(App.instance, context.getString(R.string.success_copied)).show() } }
app/src/main/kotlin/ru/fantlab/android/helper/ActivityHelper.kt
3426411251
package ru.fantlab.android.data.dao.response import com.github.kittinunf.fuel.core.ResponseDeserializable import com.google.gson.JsonParser import ru.fantlab.android.data.dao.model.AuthorInList import ru.fantlab.android.provider.rest.DataManager data class AuthorsResponse( val authors: ArrayList<AuthorInList> ) { class Deserializer : ResponseDeserializable<AuthorsResponse> { private val authors: ArrayList<AuthorInList> = arrayListOf() override fun deserialize(content: String): AuthorsResponse { val jsonObject = JsonParser().parse(content).asJsonObject val array = jsonObject.getAsJsonArray("list") array.map { authors.add(DataManager.gson.fromJson(it, AuthorInList::class.java)) } return AuthorsResponse(authors) } } }
app/src/main/kotlin/ru/fantlab/android/data/dao/response/AuthorsResponse.kt
3591770404
package eu.kanade.tachiyomi.extension.en.twentyfourhmanga import eu.kanade.tachiyomi.multisrc.madara.Madara import eu.kanade.tachiyomi.annotations.Nsfw import java.text.SimpleDateFormat import java.util.Locale @Nsfw class TwentyFourhManga : Madara("24hManga", "https://24hmanga.com", "en", dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.US)) { }
multisrc/overrides/madara/twentyfourhmanga/src/TwentyFourhManga.kt
1719016513
package eu.kanade.tachiyomi.multisrc.mangadventure import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.util.Log import kotlin.system.exitProcess /** * Springboard that accepts `{baseUrl}/reader/{slug}` * intents and redirects them to the main Tachiyomi process. */ class MangAdventureActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent?.data?.pathSegments?.takeIf { it.size > 1 }?.let { try { startActivity( Intent().apply { action = "eu.kanade.tachiyomi.SEARCH" putExtra("query", MangAdventure.SLUG_QUERY + it[1]) putExtra("filter", packageName) } ) } catch (ex: ActivityNotFoundException) { Log.e("MangAdventureActivity", ex.message, ex) } } ?: Log.e( "MangAdventureActivity", "Failed to parse URI from intent: $intent" ) finish() exitProcess(0) } }
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangadventure/MangAdventureActivity.kt
230833824
package eu.kanade.tachiyomi.extension.es.tmohentai import android.app.Application import android.content.SharedPreferences import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get @Nsfw class TMOHentai : ConfigurableSource, ParsedHttpSource() { override val name = "TMOHentai" override val baseUrl = "https://tmohentai.com" override val lang = "es" override val supportsLatest = true private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override fun popularMangaRequest(page: Int) = GET("$baseUrl/section/all?view=list&page=$page&order=popularity&order-dir=desc&search[searchText]=&search[searchBy]=name&type=all", headers) override fun popularMangaSelector() = "table > tbody > tr[data-toggle=popover]" override fun popularMangaFromElement(element: Element) = SManga.create().apply { element.select("tr").let { title = it.attr("data-title") thumbnail_url = it.attr("data-content").substringAfter("src=\"").substringBeforeLast("\"") setUrlWithoutDomain(it.select("td.text-left > a").attr("href")) } } override fun popularMangaNextPageSelector() = "a[rel=next]" override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/section/all?view=list&page=$page&order=publication_date&order-dir=desc&search[searchText]=&search[searchBy]=name&type=all", headers) override fun latestUpdatesSelector() = popularMangaSelector() override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element) override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun mangaDetailsParse(document: Document) = SManga.create().apply { val parsedInformation = document.select("div.row > div.panel.panel-primary").text() val authorAndArtist = parsedInformation.substringAfter("Groups").substringBefore("Magazines").trim() title = document.select("h3.truncate").text() thumbnail_url = document.select("img.content-thumbnail-cover").attr("src") author = authorAndArtist artist = authorAndArtist description = "Sin descripción" status = SManga.UNKNOWN genre = parsedInformation.substringAfter("Genders").substringBefore("Tags").trim().split(" ").joinToString { it } } override fun chapterListSelector() = "div#app > div.container" override fun chapterFromElement(element: Element) = SChapter.create().apply { val parsedInformation = element.select("div.row > div.panel.panel-primary").text() name = element.select("h3.truncate").text() scanlator = parsedInformation.substringAfter("By").substringBefore("Language").trim() var currentUrl = element.select("a.pull-right.btn.btn-primary").attr("href") if (currentUrl.contains("/1")) { currentUrl = currentUrl.substringBeforeLast("/") } setUrlWithoutDomain(currentUrl) // date_upload = no date in the web } // "/cascade" to get all images override fun pageListRequest(chapter: SChapter): Request { val currentUrl = chapter.url val newUrl = if (getPageMethodPref() == "cascade" && currentUrl.contains("paginated")) { currentUrl.substringBefore("paginated") + "cascade" } else if (getPageMethodPref() == "paginated" && currentUrl.contains("cascade")) { currentUrl.substringBefore("cascade") + "paginated" } else currentUrl return GET("$baseUrl$newUrl", headers) } override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply { if (getPageMethodPref() == "cascade") { document.select("div#content-images img.content-image")?.forEach { add(Page(size, "", it.attr("data-original"))) } } else { val pageList = document.select("select#select-page").first().select("option").map { it.attr("value").toInt() } val url = document.baseUri() pageList.forEach { add(Page(it, "$url/$it")) } } } override fun imageUrlParse(document: Document) = document.select("div#content-images img.content-image").attr("data-original") override fun imageRequest(page: Page) = GET("$baseUrl${page.imageUrl!!}", headers) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/section/all?view=list".toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("search[searchText]", query) url.addQueryParameter("page", page.toString()) (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is Types -> { url.addQueryParameter("type", filter.toUriPart()) } is GenreList -> { filter.state .filter { genre -> genre.state } .forEach { genre -> url.addQueryParameter("genders[]", genre.id) } } is FilterBy -> { url.addQueryParameter("search[searchBy]", filter.toUriPart()) } is SortBy -> { if (filter.state != null) { url.addQueryParameter("order", SORTABLES[filter.state!!.index].second) url.addQueryParameter( "order-dir", if (filter.state!!.ascending) { "asc" } else { "desc" } ) } } } } return GET(url.build().toString(), headers) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element) override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() private fun searchMangaByIdRequest(id: String) = GET("$baseUrl/$PREFIX_CONTENTS/$id", headers) override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return if (query.startsWith(PREFIX_ID_SEARCH)) { val realQuery = query.removePrefix(PREFIX_ID_SEARCH) client.newCall(searchMangaByIdRequest(realQuery)) .asObservableSuccess() .map { response -> val details = mangaDetailsParse(response) details.url = "/$PREFIX_CONTENTS/$realQuery" MangasPage(listOf(details), false) } } else { client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response) } } } private class Genre(name: String, val id: String) : Filter.CheckBox(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Géneros", genres) override fun getFilterList() = FilterList( Types(), Filter.Separator(), FilterBy(), SortBy(), Filter.Separator(), GenreList(getGenreList()) ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } private class Types : UriPartFilter( "Filtrar por tipo", arrayOf( Pair("Ver todos", "all"), Pair("Manga", "hentai"), Pair("Light Hentai", "light-hentai"), Pair("Doujinshi", "doujinshi"), Pair("One-shot", "one-shot"), Pair("Other", "otro") ) ) private class FilterBy : UriPartFilter( "Campo de orden", arrayOf( Pair("Nombre", "name"), Pair("Artista", "artist"), Pair("Revista", "magazine"), Pair("Tag", "tag") ) ) class SortBy : Filter.Sort( "Ordenar por", SORTABLES.map { it.first }.toTypedArray(), Selection(2, false) ) /** * Last check: 17/02/2021 * https://tmohentai.com/section/hentai * * Array.from(document.querySelectorAll('#advancedSearch .list-group .list-group-item')) * .map(a => `Genre("${a.querySelector('span').innerText.replace(' ', '')}", "${a.querySelector('input').value}")`).join(',\n') */ private fun getGenreList() = listOf( Genre("Romance", "1"), Genre("Fantasy", "2"), Genre("Comedy", "3"), Genre("Parody", "4"), Genre("Student", "5"), Genre("Adventure", "6"), Genre("Milf", "7"), Genre("Orgy", "8"), Genre("Big Breasts", "9"), Genre("Bondage", "10"), Genre("Tentacles", "11"), Genre("Incest", "12"), Genre("Ahegao", "13"), Genre("Bestiality", "14"), Genre("Futanari", "15"), Genre("Rape", "16"), Genre("Monsters", "17"), Genre("Pregnant", "18"), Genre("Small Breast", "19"), Genre("Bukkake", "20"), Genre("Femdom", "21"), Genre("Fetish", "22"), Genre("Forced", "23"), Genre("3D", "24"), Genre("Furry", "25"), Genre("Adultery", "26"), Genre("Anal", "27"), Genre("FootJob", "28"), Genre("BlowJob", "29"), Genre("Toys", "30"), Genre("Vanilla", "31"), Genre("Colour", "32"), Genre("Uncensored", "33"), Genre("Netorare", "34"), Genre("Virgin", "35"), Genre("Cheating", "36"), Genre("Harem", "37"), Genre("Horror", "38"), Genre("Lolicon", "39"), Genre("Mature", "40"), Genre("Nympho", "41"), Genre("Public Sex", "42"), Genre("Sport", "43"), Genre("Domination", "44"), Genre("Tsundere", "45"), Genre("Yandere", "46") ) override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) { val pageMethodPref = androidx.preference.ListPreference(screen.context).apply { key = PAGE_METHOD_PREF title = PAGE_METHOD_PREF_TITLE entries = arrayOf("Cascada", "Páginado") entryValues = arrayOf("cascade", "paginated") summary = PAGE_METHOD_PREF_SUMMARY setDefaultValue(PAGE_METHOD_PREF_DEFAULT_VALUE) setOnPreferenceChangeListener { _, newValue -> try { val setting = preferences.edit().putString(PAGE_METHOD_PREF, newValue as String).commit() setting } catch (e: Exception) { e.printStackTrace() false } } } screen.addPreference(pageMethodPref) } private fun getPageMethodPref() = preferences.getString(PAGE_METHOD_PREF, PAGE_METHOD_PREF_DEFAULT_VALUE) companion object { private const val PAGE_METHOD_PREF = "pageMethodPref" private const val PAGE_METHOD_PREF_TITLE = "Método de descarga de imágenes" private const val PAGE_METHOD_PREF_SUMMARY = "Puede corregir errores al cargar las imágenes.\nConfiguración actual: %s" private const val PAGE_METHOD_PREF_CASCADE = "cascade" private const val PAGE_METHOD_PREF_PAGINATED = "paginated" private const val PAGE_METHOD_PREF_DEFAULT_VALUE = PAGE_METHOD_PREF_CASCADE const val PREFIX_CONTENTS = "contents" const val PREFIX_ID_SEARCH = "id:" private val SORTABLES = listOf( Pair("Alfabético", "alphabetic"), Pair("Creación", "publication_date"), Pair("Popularidad", "popularity") ) } }
src/es/tmohentai/src/eu/kanade/tachiyomi/extension/es/tmohentai/TMOHentai.kt
987302226
package org.develar.mapsforgeTileServer.pixi import org.mapsforge.core.graphics.Bitmap import org.mapsforge.map.model.DisplayModel import org.mapsforge.map.rendertheme.renderinstruction.Symbol import org.xmlpull.v1.XmlPullParser import java.io.OutputStream class PixiSymbol(displayModel:DisplayModel, elementName:String, pullParser:XmlPullParser, relativePathPrefix:String, textureAtlasInfo:TextureAtlasInfo) : Symbol(null, displayModel, elementName, pullParser), Bitmap { val index:Int init { val subPath = src!!.substring("file:".length() + 1) // relativePathPrefix = dist/renderThemes/Elevate => Elevate as renderer theme file parent directory name var slahIndex = subPath.indexOf('/') if (slahIndex == -1) { slahIndex = subPath.indexOf('\\') } index = textureAtlasInfo.getIndex(subPath.substring(slahIndex + 1, subPath.lastIndexOf('.'))) assert(index > -1) // release memory src = null if (width == 0f || height == 0f) { val region = textureAtlasInfo.getRegion(index) if (width == 0f) { width = region.width.toFloat() } if (height == 0f) { height = region.height.toFloat() } } } override fun getBitmap():Bitmap { return this } override fun compress(outputStream:OutputStream?):Unit = throw IllegalStateException() override fun incrementRefCount() { } override fun decrementRefCount() { } override fun getHeight():Int = height.toInt() override fun getWidth():Int = width.toInt() override fun scaleTo(width:Int, height:Int):Unit = throw IllegalStateException() override fun setBackgroundColor(color:Int):Unit = throw IllegalStateException() override fun hashCode():Int = index.hashCode() override fun equals(other:Any?):Boolean = other is PixiSymbol && other.index == index }
pixi/src/PixiSymbol.kt
924080770
package com.example.demo.api.tweeter.domain.auditing import com.example.demo.api.tweeter.domain.entities.Author import com.example.demo.api.tweeter.domain.entities.Tweet import com.example.demo.logging.AppLogger import javax.persistence.PrePersist import javax.persistence.PreUpdate class JpaTweetListener { @PrePersist fun beforeInsert(o: Tweet) { LOG.info("audit: preInsert $o") } @PreUpdate fun beforeUpdate(o: Tweet) { LOG.info("audit: preUpdate $o") } companion object { private val LOG = AppLogger(this::class) } }
src/main/kotlin/com/example/demo/api/tweeter/domain/auditing/JpaTweetListener.kt
1997978909
package jp.org.example.geckour.glyph.adapter import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Base64 import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import timber.log.Timber import java.io.ByteArrayOutputStream class MoshiBitmapAdapter : JsonAdapter<Bitmap>() { override fun fromJson(reader: JsonReader): Bitmap? = try { Base64.decode(reader.nextString(), Base64.DEFAULT).let { BitmapFactory.decodeByteArray(it, 0, it.size) } } catch (t: Throwable) { Timber.e(t) null } override fun toJson(writer: JsonWriter, value: Bitmap?) { if (value != null) { writer.value( Base64.encodeToString( ByteArrayOutputStream().apply { value.compress(Bitmap.CompressFormat.PNG, 100, this) }.toByteArray(), Base64.DEFAULT) ) } else { writer.nullValue() } } }
app/src/main/java/jp/org/example/geckour/glyph/adapter/MoshiBitmapAdapter.kt
2673920774
package com.habitrpg.android.habitica.utils import android.os.Build import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import java.lang.reflect.Type import java.text.DateFormat import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone class DateDeserializer : JsonDeserializer<Date>, JsonSerializer<Date> { private var dateFormats = mutableListOf<DateFormat>() init { addFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") addFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") addFormat("E MMM dd yyyy HH:mm:ss zzzz") addFormat("yyyy-MM-dd'T'HH:mm:sszzz") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { addFormat("yyyy-MM-dd'T'HH:mmX") } else { addFormat("yyyy-MM-dd'T'HH:mm") } addFormat("yyyy-MM-dd") } private fun addFormat(s: String) { val dateFormat = SimpleDateFormat(s, Locale.US) dateFormat.timeZone = TimeZone.getTimeZone("UTC") dateFormats.add(dateFormat) } @Synchronized @Suppress("ReturnCount") override fun deserialize( jsonElement: JsonElement, type: Type, jsonDeserializationContext: JsonDeserializationContext ): Date? { var element = jsonElement if (element.isJsonArray) { if (element.asJsonArray.size() == 0) { return null } element = element.asJsonArray.get(0) } if (element.asString.isEmpty()) { return null } val jsonString = element.asString var date: Date? = null var index = 0 while (index < dateFormats.size && date == null) { try { date = dateFormats[index].parse(jsonString) } catch (_: ParseException) {} index += 1 } if (date == null) { date = try { Date(element.asLong) } catch (e3: NumberFormatException) { null } } return date } override fun serialize(src: Date?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return if (src == null) { JsonPrimitive("") } else JsonPrimitive(this.dateFormats[0].format(src)) } }
Habitica/src/main/java/com/habitrpg/android/habitica/utils/DateDeserializer.kt
4291827214
package leetcode /** * https://leetcode.com/problems/find-first-palindromic-string-in-the-array/ */ class Problem2108 { fun firstPalindrome(words: Array<String>): String { for (word in words) { if (isPalindrome(word)) { return word } } return "" } private fun isPalindrome(word: String): Boolean { var i = 0 var j = word.length - 1 while (i < j) { if (word[i] != word[j]) { return false } i++ j-- } return true } }
src/main/kotlin/leetcode/Problem2108.kt
1348082265
package org.stepik.android.remote.email_address.service import io.reactivex.Completable import io.reactivex.Single import org.stepik.android.remote.email_address.model.EmailAddressRequest import org.stepik.android.remote.email_address.model.EmailAddressResponse import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Query interface EmailAddressService { @GET("api/email-addresses") fun getEmailAddresses( @Query("ids[]") ids: List<Long> ): Single<EmailAddressResponse> @POST("api/email-addresses") fun createEmailAddress( @Body request: EmailAddressRequest ): Single<EmailAddressResponse> @POST("api/email-addresses/{emailId}/set-as-primary") fun setPrimaryEmailAddress( @Path("emailId") emailId: Long ): Completable @DELETE("api/email-addresses/{emailId}") fun removeEmailAddress( @Path("emailId") emailId: Long ): Completable }
app/src/main/java/org/stepik/android/remote/email_address/service/EmailAddressService.kt
1344193442
package task_9 import kotlin.test.Test import kotlin.test.assertEquals class AppTest { @Test fun testIntcodeComputer() { val input = "3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31," + "1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104," + "999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99" assertEquals(1, IntcodeComputer("3,9,8,9,10,9,4,9,99,-1,8").addInput(8).solve(true)) assertEquals(1, IntcodeComputer("3,9,7,9,10,9,4,9,99,-1,8").addInput(7).solve(true)) assertEquals(1, IntcodeComputer("3,3,1108,-1,8,3,4,3,99").addInput(8).solve(true)) assertEquals(1, IntcodeComputer("3,3,1107,-1,8,3,4,3,99").addInput(7).solve(true)) assertEquals(999, IntcodeComputer(input).addInput(1).solve()) assertEquals(1000, IntcodeComputer(input).addInput(8).solve()) assertEquals(1001, IntcodeComputer(input).addInput(42).solve()) } @Test fun testApp() { val app = App() assertEquals(99, app.solveFirst("109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99")) assertEquals(1125899906842624L, app.solveFirst("104,1125899906842624,99")) assertEquals(1219070632396864L, app.solveFirst("1102,34915192,34915192,7,4,7,99,0")) } }
2019/task_9/src/test/kotlin/task_9/AppTest.kt
3949080972
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * * Portions, Copyright © 1991-2005 Unicode, Inc. The following applies to Unicode. * * COPYRIGHT AND PERMISSION NOTICE * * Copyright © 1991-2005 Unicode, Inc. All rights reserved. Distributed under * the Terms of Use in http://www.unicode.org/copyright.html. Permission is * hereby granted, free of charge, to any person obtaining a copy of the * Unicode data files and any associated documentation (the "Data Files") * or Unicode software and any associated documentation (the "Software") * to deal in the Data Files or Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * and/or sell copies of the Data Files or Software, and to permit persons * to whom the Data Files or Software are furnished to do so, provided that * (a) the above copyright notice(s) and this permission notice appear with * all copies of the Data Files or Software, (b) both the above copyright * notice(s) and this permission notice appear in associated documentation, * and (c) there is clear notice in each modified Data File or in the Software * as well as in the documentation associated with the Data File(s) or Software * that the data or software has been modified. * THE DATA FILES AND SOFTWARE ARE 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 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall * not be used in advertising or otherwise to promote the sale, use or other * dealings in these Data Files or Software without prior written * authorization of the copyright holder. * * 2. Additional terms from the Database: * * Copyright © 1995-1999 Unicode, Inc. All Rights reserved. * * Disclaimer * * The Unicode Character Database is provided as is by Unicode, Inc. * No claims are made as to fitness for any particular purpose. No warranties * of any kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been purchased * on magnetic or optical media from Unicode, Inc., the sole remedy for any claim * will be exchange of defective media within 90 days of receipt. This disclaimer * is applicable for all other data files accompanying the Unicode Character Database, * some of which have been compiled by the Unicode Consortium, and some of which * have been supplied by other sources. * * Limitations on Rights to Redistribute This Data * * Recipient is granted the right to make copies in any form for internal * distribution and to freely use the information supplied in the creation of * products supporting the UnicodeTM Standard. The files in * the Unicode Character Database can be redistributed to third parties or other * organizations (whether for profit or not) as long as this notice and the disclaimer * notice are retained. Information can be extracted from these files and used * in documentation or programs, as long as there is an accompanying notice * indicating the source. */ package kotlin.text.regex /** * Represents node accepting single supplementary codepoint. */ internal class SupplementaryCharSet(val codePoint: Int, ignoreCase: Boolean) : SequenceSet(fromCharArray(Char.toChars(codePoint), 0, 2), ignoreCase) { override val name: String get() = patternString override fun first(set: AbstractSet): Boolean { return when (set) { is SupplementaryCharSet -> set.codePoint == codePoint is SupplementaryRangeSet -> set.contains(codePoint) is CharSet, is RangeSet -> false else -> true } } }
runtime/src/main/kotlin/kotlin/text/regex/sets/SupplementaryCharSet.kt
2667685521
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.grammar.utils import com.cognifide.apm.core.grammar.ScriptExecutionException import com.cognifide.apm.core.grammar.argument.ArgumentResolver import com.cognifide.apm.core.grammar.argument.toPlainString import com.cognifide.apm.core.grammar.executioncontext.ExecutionContext import com.cognifide.apm.core.grammar.executioncontext.VariableHolder import com.cognifide.apm.core.grammar.parsedscript.ParsedScript class ImportScript(private val executionContext: ExecutionContext) { private val visitedScripts: MutableSet<ParsedScript> = mutableSetOf() fun import(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext): Result { val path = getPath(ctx) val importScriptVisitor = ImportScriptVisitor() importScriptVisitor.visit(ctx) return Result(path, importScriptVisitor.variableHolder) } private fun getNamespace(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext): String = if (ctx.name() != null) { ctx.name().IDENTIFIER().toPlainString() + "_" } else { "" } private fun getPath(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext) = ctx.path().STRING_LITERAL().toPlainString() private inner class ImportScriptVisitor : com.cognifide.apm.core.grammar.antlr.ApmLangBaseVisitor<Unit>() { val variableHolder = VariableHolder() val argumentResolver = ArgumentResolver(variableHolder) override fun visitDefineVariable(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.DefineVariableContext) { val variableName = ctx.IDENTIFIER().toString() val variableValue = argumentResolver.resolve(ctx.argument()) variableHolder[variableName] = variableValue } override fun visitImportScript(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext) { val path = getPath(ctx) val namespace = getNamespace(ctx) val importScriptVisitor = ImportScriptVisitor() val parsedScript = executionContext.loadScript(path) if (parsedScript !in visitedScripts) visitedScripts.add(parsedScript) else throw ScriptExecutionException("Found cyclic reference to ${parsedScript.path}") importScriptVisitor.visit(parsedScript.apm) val scriptVariableHolder = importScriptVisitor.variableHolder scriptVariableHolder.toMap().forEach { (name, value) -> variableHolder[namespace + name] = value } } } class Result(val path: String, val variableHolder: VariableHolder) { fun toMessages(): List<String> { val importedVariables = variableHolder.toMap().map { "Imported variable: ${it.key}= ${it.value}" } return listOf("Import from script $path. Notice, only DEFINE actions were processed!") + importedVariables } } }
app/aem/core/src/main/kotlin/com/cognifide/apm/core/grammar/utils/ImportScript.kt
2436648999
package com.czbix.klog.http enum class HttpContextKey(val key: String) { REQUEST("http.request"), QUERY_DATA("ctx.query.data"), POST_DATA("ctx.post.data"), COOKIES("ctx.cookies"), COOKIES_SET("ctx.cookies.set"), USER("ctx.user"), HANDLER_ARGS("handler.args"), HANDLER_MAPPER("handler.mapper"), }
src/main/kotlin/com/czbix/klog/http/HttpContextKey.kt
2743279827
package org.dictat.wikistat.utils import java.net.URLDecoder public object StringUtils { fun decodeString(encoded: String) : String { return URLDecoder.decode(URLDecoder.decode(encoded.replaceAll("\\\\x","%"), "UTF-8"), "UTF-8") .replaceAll("_", " ").trim() } fun removeSlashes(str:String) : String { if(str.startsWith('/')) { return removeSlashes(str.substring(1)) } else { return str.trim() } } }
src/main/kotlin/org/dictat/wikistat/utils/StringUtils.kt
595124870
package org.walleth.preferences import android.content.SharedPreferences import android.os.Bundle import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SeekBarPreference import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.walleth.App import org.walleth.R import org.walleth.data.config.Settings import org.walleth.data.tokens.CurrentTokenProvider import timber.log.Timber class WalletPrefsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { private val settings: Settings by inject() private val currentTokenProvider: CurrentTokenProvider by inject() override fun onResume() { super.onResume() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) findPreference<Preference>(getString(R.string.key_reference))?.summary = getString(R.string.settings_currently, settings.currentFiat) lifecycleScope.launch(Dispatchers.Main) { findPreference<Preference>(getString(R.string.key_token))?.summary = getString(R.string.settings_currently, currentTokenProvider.getCurrent().name) } } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { try { if (key == getString(R.string.key_prefs_day_night)) { App.applyNightMode(settings) activity?.recreate() } if (key == getString(R.string.key_noscreenshots)) { activity?.recreate() } if (key == getString(R.string.key_prefs_start_light)) { } } catch (ignored: IllegalStateException) { } } override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) App.extraPreferences.forEach { addPreferencesFromResource(it.first) it.second(preferenceScreen) } } }
app/src/main/java/org/walleth/preferences/WalletPrefsFragment.kt
3175195985
package com.apollographql.apollo3.graphql.ast private val typenameMetaFieldDefinition = GQLFieldDefinition( name = "__typename", type = GQLNonNullType(type = GQLNamedType(name = "String")), directives = emptyList(), arguments = emptyList(), description = "" ) private val schemaMetaFieldDefinition = GQLFieldDefinition( name = "__schema", type = GQLNonNullType(type = GQLNamedType(name = "__Schema")), directives = emptyList(), arguments = emptyList(), description = "" ) private val typeMetaFieldDefinition = GQLFieldDefinition( name = "__type", type = GQLNonNullType(type = GQLNamedType(name = "__Type")), directives = emptyList(), arguments = listOf( GQLInputValueDefinition( name = "name", type = GQLNonNullType(type = GQLNamedType(name = "String")), defaultValue = null, description = null, directives = emptyList() ) ), description = "" ) fun GQLField.definitionFromScope(schema: Schema, typeDefinitionInScope: GQLTypeDefinition): GQLFieldDefinition? { return when { name == "__typename" -> listOf(typenameMetaFieldDefinition) name == "__schema" && typeDefinitionInScope.name == schema.queryTypeDefinition.name -> listOf(schemaMetaFieldDefinition) name == "__type" && typeDefinitionInScope.name == schema.queryTypeDefinition.name -> listOf(typeMetaFieldDefinition) typeDefinitionInScope is GQLObjectTypeDefinition -> typeDefinitionInScope.fields typeDefinitionInScope is GQLInterfaceTypeDefinition -> typeDefinitionInScope.fields else -> emptyList() }.firstOrNull { it.name == name } } fun GQLField.responseName() = alias ?: name
apollo-graphql-ast/src/main/kotlin/com/apollographql/apollo3/graphql/ast/gqlfield.kt
964779995
package eu.kanade.tachiyomi.ui.browse.extension.details import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import androidx.appcompat.view.ContextThemeWrapper import androidx.core.os.bundleOf import androidx.preference.DialogPreference import androidx.preference.EditTextPreference import androidx.preference.EditTextPreferenceDialogController import androidx.preference.ListPreference import androidx.preference.ListPreferenceDialogController import androidx.preference.MultiSelectListPreference import androidx.preference.MultiSelectListPreferenceDialogController import androidx.preference.Preference import androidx.preference.PreferenceGroupAdapter import androidx.preference.PreferenceManager import androidx.preference.PreferenceScreen import androidx.preference.get import androidx.preference.getOnBindEditTextListener import androidx.preference.isNotEmpty import androidx.recyclerview.widget.LinearLayoutManager import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.SharedPreferencesDataStore import eu.kanade.tachiyomi.databinding.SourcePreferencesControllerBinding import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.getPreferenceKey import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.widget.TachiyomiTextInputEditText.Companion.setIncognito import logcat.LogPriority @SuppressLint("RestrictedApi") class SourcePreferencesController(bundle: Bundle? = null) : NucleusController<SourcePreferencesControllerBinding, SourcePreferencesPresenter>(bundle), PreferenceManager.OnDisplayPreferenceDialogListener, DialogPreference.TargetFragment { private var lastOpenPreferencePosition: Int? = null private var preferenceScreen: PreferenceScreen? = null constructor(sourceId: Long) : this( bundleOf(SOURCE_ID to sourceId), ) override fun createBinding(inflater: LayoutInflater): SourcePreferencesControllerBinding { val themedInflater = inflater.cloneInContext(getPreferenceThemeContext()) return SourcePreferencesControllerBinding.inflate(themedInflater) } override fun createPresenter(): SourcePreferencesPresenter { return SourcePreferencesPresenter(args.getLong(SOURCE_ID)) } override fun getTitle(): String? { return presenter.source?.toString() } @SuppressLint("PrivateResource") override fun onViewCreated(view: View) { super.onViewCreated(view) val source = presenter.source ?: return val context = view.context val themedContext by lazy { getPreferenceThemeContext() } val manager = PreferenceManager(themedContext) val dataStore = SharedPreferencesDataStore( context.getSharedPreferences(source.getPreferenceKey(), Context.MODE_PRIVATE), ) manager.preferenceDataStore = dataStore manager.onDisplayPreferenceDialogListener = this val screen = manager.createPreferenceScreen(themedContext) preferenceScreen = screen try { addPreferencesForSource(screen, source) } catch (e: AbstractMethodError) { logcat(LogPriority.ERROR) { "Source did not implement [addPreferencesForSource]: ${source.name}" } } manager.setPreferences(screen) binding.recycler.layoutManager = LinearLayoutManager(context) binding.recycler.adapter = PreferenceGroupAdapter(screen) } override fun onDestroyView(view: View) { preferenceScreen = null super.onDestroyView(view) } override fun onSaveInstanceState(outState: Bundle) { lastOpenPreferencePosition?.let { outState.putInt(LASTOPENPREFERENCE_KEY, it) } super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) lastOpenPreferencePosition = savedInstanceState.get(LASTOPENPREFERENCE_KEY) as? Int } private fun addPreferencesForSource(screen: PreferenceScreen, source: Source) { val context = screen.context if (source is ConfigurableSource) { val newScreen = screen.preferenceManager.createPreferenceScreen(context) source.setupPreferenceScreen(newScreen) // Reparent the preferences while (newScreen.isNotEmpty()) { val pref = newScreen[0] pref.isIconSpaceReserved = false pref.order = Int.MAX_VALUE // reset to default order // Apply incognito IME for EditTextPreference if (pref is EditTextPreference) { val setListener = pref.getOnBindEditTextListener() pref.setOnBindEditTextListener { setListener?.onBindEditText(it) it.setIncognito(viewScope) } } newScreen.removePreference(pref) screen.addPreference(pref) } } } private fun getPreferenceThemeContext(): Context { val tv = TypedValue() activity!!.theme.resolveAttribute(R.attr.preferenceTheme, tv, true) return ContextThemeWrapper(activity, tv.resourceId) } override fun onDisplayPreferenceDialog(preference: Preference) { if (!isAttached) return val screen = preference.parent!! lastOpenPreferencePosition = (0 until screen.preferenceCount).indexOfFirst { screen[it] === preference } val f = when (preference) { is EditTextPreference -> EditTextPreferenceDialogController .newInstance(preference.getKey()) is ListPreference -> ListPreferenceDialogController .newInstance(preference.getKey()) is MultiSelectListPreference -> MultiSelectListPreferenceDialogController .newInstance(preference.getKey()) else -> throw IllegalArgumentException( "Tried to display dialog for unknown " + "preference type. Did you forget to override onDisplayPreferenceDialog()?", ) } f.targetController = this f.showDialog(router) } @Suppress("UNCHECKED_CAST") override fun <T : Preference> findPreference(key: CharSequence): T? { // We track [lastOpenPreferencePosition] when displaying the dialog // [key] isn't useful since there may be duplicates return preferenceScreen!![lastOpenPreferencePosition!!] as T } } private const val SOURCE_ID = "source_id" private const val LASTOPENPREFERENCE_KEY = "last_open_preference"
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/details/SourcePreferencesController.kt
3494432696
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.actions import com.intellij.codeInsight.ExpectedTypeInfo import com.intellij.codeInsight.ExpectedTypesProvider import com.intellij.codeInsight.TailType import com.intellij.lang.java.JavaLanguage import com.intellij.lang.java.request.ExpectedJavaType import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.ExpectedType import com.intellij.lang.jvm.actions.ExpectedTypes import com.intellij.lang.jvm.types.JvmSubstitutor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.PsiModifier.ModifierConstant import com.intellij.psi.impl.compiled.ClsClassImpl @ModifierConstant internal fun JvmModifier.toPsiModifier(): String = when (this) { JvmModifier.PUBLIC -> PsiModifier.PUBLIC JvmModifier.PROTECTED -> PsiModifier.PROTECTED JvmModifier.PRIVATE -> PsiModifier.PRIVATE JvmModifier.PACKAGE_LOCAL -> PsiModifier.PACKAGE_LOCAL JvmModifier.STATIC -> PsiModifier.STATIC JvmModifier.ABSTRACT -> PsiModifier.ABSTRACT JvmModifier.FINAL -> PsiModifier.FINAL JvmModifier.NATIVE -> PsiModifier.NATIVE JvmModifier.SYNCHRONIZED -> PsiModifier.NATIVE JvmModifier.STRICTFP -> PsiModifier.STRICTFP JvmModifier.TRANSIENT -> PsiModifier.TRANSIENT JvmModifier.VOLATILE -> PsiModifier.VOLATILE JvmModifier.TRANSITIVE -> PsiModifier.TRANSITIVE } /** * Compiled classes, type parameters are not considered classes. * * @return Java PsiClass or `null` if the receiver is not a Java PsiClass */ internal fun JvmClass.toJavaClassOrNull(): PsiClass? { if (this !is PsiClass) return null if (this is PsiTypeParameter) return null if (this is ClsClassImpl) return null if (this.language != JavaLanguage.INSTANCE) return null return this } internal val visibilityModifiers = setOf( JvmModifier.PUBLIC, JvmModifier.PROTECTED, JvmModifier.PACKAGE_LOCAL, JvmModifier.PRIVATE ) internal fun extractExpectedTypes(project: Project, expectedTypes: ExpectedTypes): List<ExpectedTypeInfo> { return expectedTypes.mapNotNull { toExpectedTypeInfo(project, it) } } private fun toExpectedTypeInfo(project: Project, expectedType: ExpectedType): ExpectedTypeInfo? { if (expectedType is ExpectedJavaType) return expectedType.info val helper = JvmPsiConversionHelper.getInstance(project) val psiType = helper.convertType(expectedType.theType) ?: return null return ExpectedTypesProvider.createInfo(psiType, expectedType.theKind.infoKind(), psiType, TailType.NONE) } @ExpectedTypeInfo.Type private fun ExpectedType.Kind.infoKind(): Int { return when (this) { ExpectedType.Kind.EXACT -> ExpectedTypeInfo.TYPE_STRICTLY ExpectedType.Kind.SUPERTYPE -> ExpectedTypeInfo.TYPE_OR_SUPERTYPE ExpectedType.Kind.SUBTYPE -> ExpectedTypeInfo.TYPE_OR_SUBTYPE } } internal fun JvmSubstitutor.toPsiSubstitutor(project: Project): PsiSubstitutor { return JvmPsiConversionHelper.getInstance(project).convertSubstitutor(this) }
java/java-impl/src/com/intellij/lang/java/actions/jvmPsiUtil.kt
1021298436
package algorithms /* Goldbach's other conjecture Problem 46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? */ fun compositeOdds(): Sequence<Long> = generateSequence(3L) { it + 2 } .filter { !isPrime(it) } fun twiceSquares(): Sequence<Long> = generateSequence(1L) { it + 1 } .map { 2 * it * it } fun canBeComposedOfPrimePlusTwiceSquare(number: Long): Boolean = twiceSquares() .takeWhile { it < number } .any { isPrime(number - it) } fun firstOddCompositeBreakingGoldbachsOtherConjecture() = compositeOdds() .find { !canBeComposedOfPrimePlusTwiceSquare(it) }
src/main/kotlin/algorithms/goldbachs-other-conjecture.kt
4273912635
package abi44_0_0.expo.modules.kotlin.events class EventsDefinition(val names: Array<out String>)
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/kotlin/events/EventsDefinition.kt
250926807
package io.github.feelfreelinux.wykopmobilny.utils import android.content.Context import android.net.Uri import android.support.customtabs.CustomTabsIntent import io.github.feelfreelinux.wykopmobilny.R fun Context.openBrowser(url : String) { // Start in-app browser, handled by Chrome Customs Tabs val builder = CustomTabsIntent.Builder() val customTabsIntent = builder.build() builder.setToolbarColor(R.attr.colorPrimaryDark) customTabsIntent.launchUrl(this, Uri.parse(url)) }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/ContextExtensions.kt
3984645731
/* * 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.models import androidx.annotation.Keep import com.squareup.moshi.JsonClass @Keep @JsonClass(generateAdapter = true) data class Feature( val name: String, val title: String = "", val description: String = "", val image: String = "" )
common/models/src/main/java/app/ss/models/Feature.kt
553624213
package com.xurxodev.movieskotlinkata.domain.boundary import com.xurxodev.movieskotlinkata.domain.common.functional.Either import com.xurxodev.movieskotlinkata.domain.entity.Movie import com.xurxodev.movieskotlinkata.domain.failures.GetMovieFailure import com.xurxodev.movieskotlinkata.domain.failures.GetMoviesFailure interface MovieRepository { fun getAll (): Either<GetMoviesFailure, List<Movie>> fun getById (id: Long): Either<GetMovieFailure, Movie> }
app/src/main/kotlin/com/xurxodev/movieskotlinkata/domain/boundary/MovieRepository.kt
3302047162
package com.sjn.stamp import android.app.Service import android.content.Intent import android.os.Bundle import android.os.RemoteException import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaBrowserCompat.MediaItem import android.support.v4.media.MediaBrowserServiceCompat import android.support.v4.media.session.MediaControllerCompat import com.sjn.stamp.media.notification.NotificationManager import com.sjn.stamp.media.playback.Playback import com.sjn.stamp.media.playback.PlaybackManager import com.sjn.stamp.media.provider.MusicProvider import com.sjn.stamp.media.source.LocalMediaSource import com.sjn.stamp.ui.observer.MediaControllerObserver import com.sjn.stamp.utils.* import java.util.* class MusicService : MediaBrowserServiceCompat(), PlaybackManager.PlaybackServiceCallback { companion object { private val TAG = LogHelper.makeLogTag(MusicService::class.java) const val NOTIFICATION_CMD_PLAY = "CMD_PLAY" const val NOTIFICATION_CMD_PAUSE = "CMD_PAUSE" const val NOTIFICATION_CMD_STOP_CASTING = "CMD_STOP_CASTING" const val NOTIFICATION_CMD_KILL = "CMD_KILL" const val CUSTOM_ACTION_RELOAD_MUSIC_PROVIDER = "RELOAD_MUSIC_PROVIDER" const val CUSTOM_ACTION_SET_QUEUE = "SET_QUEUE" const val CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_TITLE = "SET_QUEUE_BUNDLE_KEY_TITLE" const val CUSTOM_ACTION_SET_QUEUE_BUNDLE_MEDIA_ID = "SET_QUEUE_BUNDLE_MEDIA_ID" const val CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_QUEUE = "SET_QUEUE_BUNDLE_KEY_QUEUE" } private var playOnPrepared = false private var playbackManager: PlaybackManager? = null private var mediaController: MediaControllerCompat? = null private val notificationManager = NotificationManager(this) private val musicProvider = MusicProvider(this, LocalMediaSource(this, object : MediaRetrieveHelper.PermissionRequiredCallback { override fun onPermissionRequired() { } })) override fun onCreate() { super.onCreate() LogHelper.d(TAG, "onCreate") musicProvider.retrieveMediaAsync(object : MusicProvider.Callback { override fun onMusicCatalogReady(success: Boolean) { LogHelper.d(TAG, "MusicProvider.callBack start") playbackManager = PlaybackManager(this@MusicService, this@MusicService, musicProvider, Playback.Type.LOCAL).apply { restorePreviousState() } sessionToken = playbackManager?.sessionToken sessionToken?.let { mediaController = MediaControllerCompat(this@MusicService, it).apply { MediaControllerObserver.register(this) } } PlayModeHelper.restore(this@MusicService) try { notificationManager.updateSessionToken() } catch (e: RemoteException) { throw IllegalStateException("Could not create a NotificationManager", e) } if (playOnPrepared) { playOnPrepared = false mediaController?.transportControls?.play() } LogHelper.d(TAG, "MusicProvider.callBack end") } }) } override fun onDestroy() { LogHelper.d(TAG, "onDestroy") mediaController?.let { it.transportControls.stop() MediaControllerObserver.unregister(it) } notificationManager.stopNotification() } override fun onStartCommand(startIntent: Intent?, flags: Int, startId: Int): Int { LogHelper.d(TAG, "onStartCommand") startIntent?.let { if (NotificationHelper.ACTION_CMD == it.action) { handleActionCommand(it.getStringExtra(NotificationHelper.CMD_NAME)) } else { playbackManager?.handleIntent(it) } } return Service.START_NOT_STICKY } /** * [MediaBrowserServiceCompat] */ override fun onCustomAction(action: String, extras: Bundle?, result: MediaBrowserServiceCompat.Result<Bundle>) { LogHelper.d(TAG, "onCustomAction $action") when (action) { CUSTOM_ACTION_RELOAD_MUSIC_PROVIDER -> { result.detach() musicProvider.cacheAndNotifyLatestMusicMap() return } CUSTOM_ACTION_SET_QUEUE -> { result.detach() extras?.let { playbackManager?.startNewQueue( extras.getString(CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_TITLE), extras.getString(CUSTOM_ACTION_SET_QUEUE_BUNDLE_MEDIA_ID), extras.getParcelableArrayList(CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_QUEUE)) } return } } result.sendError(null) } override fun onSearch(query: String, extras: Bundle?, result: MediaBrowserServiceCompat.Result<List<MediaBrowserCompat.MediaItem>>) { LogHelper.d(TAG, "onSearch $query") result.detach() if (musicProvider.isInitialized) { Thread(Runnable { result.sendResult(musicProvider.getChildren(query, resources)) }).start() } } override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): MediaBrowserServiceCompat.BrowserRoot? { LogHelper.d(TAG, "OnGetRoot: clientPackageName=$clientPackageName", "; clientUid=$clientUid ; rootHints=", rootHints) return MediaBrowserServiceCompat.BrowserRoot(MediaIDHelper.MEDIA_ID_ROOT, null) } override fun onLoadChildren(parentMediaId: String, result: MediaBrowserServiceCompat.Result<List<MediaItem>>) { LogHelper.d(TAG, "OnLoadChildren: parentMediaId=", parentMediaId) if (MediaIDHelper.MEDIA_ID_EMPTY_ROOT == parentMediaId) { result.sendResult(ArrayList()) } else { result.detach() if (musicProvider.isInitialized) { Thread(Runnable { result.sendResult(musicProvider.getChildren(parentMediaId, resources)) }).start() } } } /** * [PlaybackManager.PlaybackServiceCallback] */ override fun onPlaybackStart() { LogHelper.d(TAG, "onPlaybackStart") // The service needs to continue running even after the bound client (usually a // MediaController) disconnects, otherwise the music playback will stop. // Calling startService(Intent) will keep the service running until it is explicitly killed. startForegroundServiceCompatible(Intent(applicationContext, MusicService::class.java)) notificationManager.startForeground() } override fun onPlaybackStop() { LogHelper.d(TAG, "onPlaybackStop") notificationManager.stopForeground(false) } override fun onNotificationRequired() { LogHelper.d(TAG, "onNotificationRequired") notificationManager.startNotification() } private fun handleActionCommand(command: String) { LogHelper.d(TAG, "handleActionCommand ", command) when (command) { NOTIFICATION_CMD_PLAY -> mediaController?.transportControls?.play() ?: run { playOnPrepared = true } NOTIFICATION_CMD_PAUSE -> mediaController?.transportControls?.pause() NOTIFICATION_CMD_STOP_CASTING -> playbackManager?.stopCasting() NOTIFICATION_CMD_KILL -> playbackManager?.let { stopSelf() } } } }
app/src/main/java/com/sjn/stamp/MusicService.kt
1431825572
/* * Copyright 2002-2020 the original author or 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 * * 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 org.springframework.security.config.web.server import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.http.HttpStatus import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity import org.springframework.security.core.userdetails.MapReactiveUserDetailsService import org.springframework.security.core.userdetails.User import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.security.web.server.authentication.RedirectServerAuthenticationEntryPoint import org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.reactive.config.EnableWebFlux import java.util.* /** * Tests for [ServerExceptionHandlingDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class ServerExceptionHandlingDslTests { @JvmField val spring = SpringTestContext(this) private lateinit var client: WebTestClient @Autowired fun setup(context: ApplicationContext) { this.client = WebTestClient .bindToApplicationContext(context) .configureClient() .build() } @Test fun `unauthenticated request when custom entry point then directed to custom entry point`() { this.spring.register(EntryPointConfig::class.java).autowire() val result = this.client.get() .uri("/") .exchange() .expectStatus().is3xxRedirection .returnResult(String::class.java) result.assertWithDiagnostics { Assertions.assertThat(result.responseHeaders.location).hasPath("/auth") } } @EnableWebFluxSecurity @EnableWebFlux open class EntryPointConfig { @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { authorizeExchange { authorize(anyExchange, authenticated) } exceptionHandling { authenticationEntryPoint = RedirectServerAuthenticationEntryPoint("/auth") } } } } @Test fun `unauthorized request when custom access denied handler then directed to custom access denied handler`() { this.spring.register(AccessDeniedHandlerConfig::class.java).autowire() this.client .get() .uri("/") .header("Authorization", "Basic " + Base64.getEncoder().encodeToString("user:password".toByteArray())) .exchange() .expectStatus().isSeeOther } @EnableWebFluxSecurity @EnableWebFlux open class AccessDeniedHandlerConfig { @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { authorizeExchange { authorize(anyExchange, hasRole("ADMIN")) } httpBasic { } exceptionHandling { accessDeniedHandler = HttpStatusServerAccessDeniedHandler(HttpStatus.SEE_OTHER) } } } @Bean open fun userDetailsService(): MapReactiveUserDetailsService { val user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() return MapReactiveUserDetailsService(user) } } }
config/src/test/kotlin/org/springframework/security/config/web/server/ServerExceptionHandlingDslTests.kt
3636304862
package biz.eventually.atpl.data.network /** * Created by Thibault de Lambilly on 20/03/17. */ data class TopicNetwork( val id: Long, val name: String, val questions: Int = 0, val follow: Int?, val focus: Int?, val mean:Double? )
app/src/main/java/biz/eventually/atpl/data/network/TopicNetwork.kt
3318165381
package failchat.peka2tv import failchat.Origin import failchat.emoticon.EmoticonLoadConfiguration import failchat.emoticon.EmoticonLoadConfiguration.LoadType import failchat.emoticon.EmoticonStreamLoader class Peka2tvEmoticonLoadConfiguration(loader: Peka2tvEmoticonBulkLoader) : EmoticonLoadConfiguration<Peka2tvEmoticon> { override val origin = Origin.PEKA2TV override val loadType = LoadType.BULK override val bulkLoaders = listOf(loader) override val streamLoaders: List<EmoticonStreamLoader<Peka2tvEmoticon>> = emptyList() override val idExtractor = Peka2tvEmoticonIdExtractor }
src/main/kotlin/failchat/peka2tv/Peka2tvEmoticonLoadConfiguration.kt
3992785119
package com.fsck.k9.contacts import android.content.Context import android.util.TypedValue import android.view.ContextThemeWrapper import com.fsck.k9.K9 import com.fsck.k9.ui.R import com.fsck.k9.ui.base.Theme import com.fsck.k9.ui.base.ThemeManager class ContactLetterBitmapConfig(context: Context, themeManager: ThemeManager) { val hasDefaultBackgroundColor: Boolean = !K9.isColorizeMissingContactPictures val useDarkTheme = themeManager.appTheme == Theme.DARK val defaultBackgroundColor: Int init { defaultBackgroundColor = if (hasDefaultBackgroundColor) { val outValue = TypedValue() val themedContext = ContextThemeWrapper(context, themeManager.appThemeResourceId) themedContext.theme.resolveAttribute(R.attr.contactPictureFallbackDefaultBackgroundColor, outValue, true) outValue.data } else { 0 } } }
app/ui/legacy/src/main/java/com/fsck/k9/contacts/ContactLetterBitmapConfig.kt
3199658963
package failchat.ws.server import failchat.chat.ChatMessageSender class ClientConfigurationWsHandler( private val messageSender: ChatMessageSender ) : WsMessageHandler { override val expectedType = InboundWsMessage.Type.CLIENT_CONFIGURATION override fun handle(message: InboundWsMessage) { messageSender.sendClientConfiguration() } }
src/main/kotlin/failchat/ws/server/ClientConfigurationWsHandler.kt
2647736226
// 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.caches.project import com.intellij.openapi.module.Module import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.config.KotlinSourceRootType import org.jetbrains.kotlin.config.SourceKotlinRootType import org.jetbrains.kotlin.config.TestSourceKotlinRootType import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.base.projectStructure.productionSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.testSourceInfo import org.jetbrains.kotlin.idea.base.facet.implementingModules as implementingModulesNew import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.types.typeUtil.closure @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule' instead.", ReplaceWith("this.isNewMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.isNewMPPModule: Boolean get() = isNewMultiPlatformModule @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType' instead.", ReplaceWith("sourceType", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.sourceType: SourceType? get() = when (kotlinSourceRootType) { TestSourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.TEST SourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.PRODUCTION else -> null } @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule' instead.", ReplaceWith("isMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.isMPPModule: Boolean get() = isMultiPlatformModule @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.implementingModules' instead.", ReplaceWith("implementingModules", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.implementingModules: List<Module> get() = implementingModulesNew val ModuleDescriptor.implementingDescriptors: List<ModuleDescriptor> get() { val moduleInfo = getCapability(ModuleInfo.Capability) if (moduleInfo is PlatformModuleInfo) { return listOf(this) } val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList() val implementingModuleInfos = moduleSourceInfo.module.implementingModules .mapNotNull { module -> val sourceRootType = moduleSourceInfo.kotlinSourceRootType ?: return@mapNotNull null module.getModuleInfo(sourceRootType) } return implementingModuleInfos.mapNotNull { it.toDescriptor() } } val ModuleDescriptor.allImplementingDescriptors: Collection<ModuleDescriptor> get() = implementingDescriptors.closure(preserveOrder = true) { it.implementingDescriptors } fun Module.getModuleInfo(sourceRootType: KotlinSourceRootType): ModuleSourceInfo? { return when (sourceRootType) { SourceKotlinRootType -> productionSourceInfo TestSourceKotlinRootType -> testSourceInfo } } /** * This function returns immediate parents in dependsOn graph */ val ModuleDescriptor.implementedDescriptors: List<ModuleDescriptor> get() { val moduleInfo = getCapability(ModuleInfo.Capability) if (moduleInfo is PlatformModuleInfo) return listOf(this) val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList() return moduleSourceInfo.expectedBy.mapNotNull { it.toDescriptor() } } fun Module.toDescriptor() = (productionSourceInfo ?: testSourceInfo)?.toDescriptor() fun ModuleSourceInfo.toDescriptor() = KotlinCacheService.getInstance(module.project) .getResolutionFacadeByModuleInfo(this, platform)?.moduleDescriptor fun PsiElement.getPlatformModuleInfo(desiredPlatform: TargetPlatform): PlatformModuleInfo? { assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" } val moduleInfo = this.moduleInfoOrNull as? ModuleSourceInfo ?: return null return doGetPlatformModuleInfo(moduleInfo, desiredPlatform) } fun getPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? { assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" } return doGetPlatformModuleInfo(moduleInfo, desiredPlatform) } private fun doGetPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? { val platform = moduleInfo.platform return when { platform.isCommon() -> { val correspondingImplementingModule = moduleInfo.module.implementingModules .map { module -> val sourceRootType = moduleInfo.kotlinSourceRootType ?: return@map null module.getModuleInfo(sourceRootType) } .firstOrNull { it?.platform == desiredPlatform } ?: return null PlatformModuleInfo(correspondingImplementingModule, correspondingImplementingModule.expectedBy) } platform == desiredPlatform -> { val expectedBy = moduleInfo.expectedBy.takeIf { it.isNotEmpty() } ?: return null PlatformModuleInfo(moduleInfo, expectedBy) } else -> null } }
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt
1242210908
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.intention.impl.preview import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass 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.IntentionActionWithTextCaching import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.codeInsight.intention.impl.config.IntentionManagerSettings import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInspection.ex.QuickFixWrapper import com.intellij.diff.comparison.ComparisonManager import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.fragments.LineFragment import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import com.intellij.psi.PsiRecursiveElementWalkingVisitor import com.intellij.psi.impl.source.PostprocessReformattingAspect import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtilBase import java.io.IOException import java.util.concurrent.Callable internal class IntentionPreviewComputable(private val project: Project, private val action: IntentionAction, private val originalFile: PsiFile, private val originalEditor: Editor) : Callable<IntentionPreviewInfo> { override fun call(): IntentionPreviewInfo { val diffContent = tryCreateDiffContent() if (diffContent != null) { return diffContent } return tryCreateFallbackDescriptionContent() } private fun tryCreateFallbackDescriptionContent(): IntentionPreviewInfo { val originalAction = IntentionActionDelegate.unwrap(action) val actionMetaData = IntentionManagerSettings.getInstance().getMetaData().singleOrNull { md -> IntentionActionDelegate.unwrap(md.action) === originalAction } ?: return IntentionPreviewInfo.EMPTY return try { IntentionPreviewInfo.Html(actionMetaData.description.text.replace(HTML_COMMENT_REGEX, "")) } catch(ex: IOException) { IntentionPreviewInfo.EMPTY } } private fun tryCreateDiffContent(): IntentionPreviewInfo? { try { return generatePreview() } catch (e: IntentionPreviewUnsupportedOperationException) { return null } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { logger<IntentionPreviewComputable>().debug("There are exceptions on invocation the intention: '${action.text}' on a copy of the file.", e) return null } } fun generatePreview(): IntentionPreviewInfo? { if (project.isDisposed) return null val origPair = ShowIntentionActionsHandler.chooseFileForAction(originalFile, originalEditor, action) ?: return null val origFile: PsiFile val caretOffset: Int val fileFactory = PsiFileFactory.getInstance(project) if (origPair.first != originalFile) { val manager = InjectedLanguageManager.getInstance(project) origFile = fileFactory.createFileFromText( origPair.first.name, origPair.first.fileType, manager.getUnescapedText(origPair.first)) caretOffset = mapInjectedOffsetToUnescaped(origPair.first, origPair.second.caretModel.offset) } else { origFile = originalFile caretOffset = originalEditor.caretModel.offset } val psiFileCopy = origFile.copy() as PsiFile ProgressManager.checkCanceled() val editorCopy = IntentionPreviewEditor(psiFileCopy, caretOffset, originalEditor.settings) val writable = originalEditor.document.isWritable try { originalEditor.document.setReadOnly(true) ProgressManager.checkCanceled() var result = action.generatePreview(project, editorCopy, psiFileCopy) if (result == IntentionPreviewInfo.FALLBACK_DIFF) { if (action.getElementToMakeWritable(originalFile)?.containingFile !== originalFile) return null // Use fallback algorithm only if invokeForPreview is not explicitly overridden // in this case, the absence of diff could be intended, thus should not be logged as error val action = findCopyIntention(project, editorCopy, psiFileCopy, action) ?: return null val unwrapped = IntentionActionDelegate.unwrap(action) val cls = (if (unwrapped is QuickFixWrapper) unwrapped.fix else unwrapped)::class.java val loader = cls.classLoader val thirdParty = loader is PluginAwareClassLoader && PluginManagerCore.isDevelopedByJetBrains(loader.pluginDescriptor) if (!thirdParty) { logger<IntentionPreviewComputable>().error("Intention preview fallback is used for action ${cls.name}|${action.familyName}") } action.invoke(project, editorCopy, psiFileCopy) result = IntentionPreviewInfo.DIFF } ProgressManager.checkCanceled() return when (result) { IntentionPreviewInfo.DIFF -> { PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(psiFileCopy.viewProvider) IntentionPreviewDiffResult( psiFile = psiFileCopy, origFile = origFile, lineFragments = ComparisonManager.getInstance() .compareLines(origFile.text, editorCopy.document.text, ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE)) } IntentionPreviewInfo.EMPTY -> null is IntentionPreviewInfo.CustomDiff -> { IntentionPreviewDiffResult( fileFactory.createFileFromText("__dummy__", result.fileType(), result.modifiedText()), fileFactory.createFileFromText("__dummy__", result.fileType(), result.originalText()), ComparisonManager.getInstance() .compareLines(result.originalText(), result.modifiedText(), ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE), fakeDiff = false) } else -> result } } finally { originalEditor.document.setReadOnly(!writable) } } private fun mapInjectedOffsetToUnescaped(injectedFile: PsiFile, injectedOffset: Int): Int { var unescapedOffset = 0 var escapedOffset = 0 injectedFile.accept(object : PsiRecursiveElementWalkingVisitor() { override fun visitElement(element: PsiElement) { val leafText = InjectedLanguageUtilBase.getUnescapedLeafText(element, false) if (leafText != null) { unescapedOffset += leafText.length escapedOffset += element.textLength if (escapedOffset >= injectedOffset) { unescapedOffset -= escapedOffset - injectedOffset stopWalking() } } super.visitElement(element) } }) return unescapedOffset } } private val HTML_COMMENT_REGEX = Regex("<!--.+-->") private fun getFixes(cachedIntentions: CachedIntentions): Sequence<IntentionActionWithTextCaching> { return sequenceOf<IntentionActionWithTextCaching>() .plus(cachedIntentions.intentions) .plus(cachedIntentions.inspectionFixes) .plus(cachedIntentions.errorFixes) } private fun findCopyIntention(project: Project, editorCopy: Editor, psiFileCopy: PsiFile, originalAction: IntentionAction): IntentionAction? { val actionsToShow = ShowIntentionsPass.getActionsToShow(editorCopy, psiFileCopy, false) val cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFileCopy, editorCopy, actionsToShow) return getFixes(cachedIntentions).find { it.text == originalAction.text }?.action } internal data class IntentionPreviewDiffResult(val psiFile: PsiFile, val origFile: PsiFile, val lineFragments: List<LineFragment>, val fakeDiff: Boolean = true): IntentionPreviewInfo
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewComputable.kt
2006383841
/* * 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 org.jetbrains.plugins.ideavim.action.change.insert import com.maddyhome.idea.vim.command.VimStateMachine import org.jetbrains.plugins.ideavim.VimTestCase class InsertExitModeActionTest : VimTestCase() { fun `test exit visual mode`() { doTest("i<Esc>", "12${c}3", "1${c}23", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE) } fun `test exit visual mode on line start`() { doTest("i<Esc>", "${c}123", "${c}123", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE) } }
src/test/java/org/jetbrains/plugins/ideavim/action/change/insert/InsertExitModeActionTest.kt
2993897315
package org.katis.mymod import net.minecraft.init.Blocks import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.Mod.EventHandler as eventHandler import net.minecraftforge.fml.common.event.FMLInitializationEvent val MODID = "mymod" val VERSION = "1.0" Mod(modid = MODID, version = VERSION) class MyMod { eventHandler fun init(event: FMLInitializationEvent): Unit { print("hello") } }
src/main/kotlin/MyMod.kt
3185156132
package nl.jstege.adventofcode.aoc2015.utils.instructionset import nl.jstege.adventofcode.aoccommon.utils.machine.Instruction import nl.jstege.adventofcode.aoccommon.utils.machine.Machine /** * * @author Jelle Stege */ abstract class SimpleInstructionSet(override var operands: List<String>, override var machine: Machine) : Instruction { override fun toString() = "${this::class.java.simpleName.toLowerCase()} $operands" companion object { private const val INPUT_PATTERN_STRING = """([a-z]{3}) ([a-z+\-0-9]+)(, ([+-]\d+))?""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() fun assemble(input: List<String>, machine: Machine): List<Instruction> = input .map { INPUT_REGEX.matchEntire(it)?.groupValues ?: throw IllegalArgumentException("Invalid input") } .map { (_, instr, op1, _, op2) -> when (instr) { "hlf" -> Hlf(listOf(op1, op2), machine) "tpl" -> Tpl(listOf(op1, op2), machine) "inc" -> Inc(listOf(op1, op2), machine) "jmp" -> Jmp(listOf(op1, op2), machine) "jie" -> Jie(listOf(op1, op2), machine) "jio" -> Jio(listOf(op1, op2), machine) else -> throw IllegalArgumentException("Unparsable instruction $instr") } } } }
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/utils/instructionset/SimpleInstructionSet.kt
1986715859
/* * 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.action.motion.updown import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.normalizeLine import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.handler.toMotion import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* class MotionGotoLineFirstAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.LINE_WISE override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_JUMP) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val line = editor.normalizeLine(operatorArguments.count1 - 1) return injector.motion.moveCaretToLineWithStartOfLineOption(editor, line, caret).toMotion() } } class MotionGotoLineFirstInsertAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.EXCLUSIVE override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_CLEAR_STROKES) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val line = editor.normalizeLine(operatorArguments.count1 - 1) return injector.motion.moveCaretToLineStart(editor, line).toMotion() } }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/updown/MotionGotoLineFirstAction.kt
3806223456
package com.nagopy.android.aplin.ui.main import com.nagopy.android.aplin.domain.model.PackagesModel import com.nagopy.android.aplin.ui.prefs.SortOrder data class MainUiState( val isLoading: Boolean, val packagesModel: PackagesModel? = null, val sortOrder: SortOrder = SortOrder.DEFAULT, val searchWidgetState: SearchWidgetState = SearchWidgetState.CLOSED, val searchText: String = "", )
app/src/main/java/com/nagopy/android/aplin/ui/main/MainUiState.kt
1587857364
package org.wordpress.android.ui.posts import org.wordpress.android.ui.utils.UiString /** * This sealed class is used to hold the UI state of a Progress Dialog. * * HiddenProgressDialog: use this UI state to indicate the dialog must be dismissed * VisibleProgressDialog: use this UI state to indicate the dialog must be shown; this UI state holds * a messageString, a cancelable and indeterminate flags to personalize the dialog * IgnoreProgressDialog: use this UI state to indicate the state of the dialog should remain as it is */ sealed class ProgressDialogUiState { object HiddenProgressDialog : ProgressDialogUiState() data class VisibleProgressDialog( val messageString: UiString, val cancelable: Boolean, val indeterminate: Boolean ) : ProgressDialogUiState() object IgnoreProgressDialog : ProgressDialogUiState() }
WordPress/src/main/java/org/wordpress/android/ui/posts/ProgressDialogUiState.kt
3032298086
// 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.codeinsight.api.classic.quickfixes.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) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt
736491314
// FIR_IDENTICAL // FIR_COMPARISON fun foo(): Any? = TODO<caret> // WITH_ORDER // EXIST: { itemText: "TODO", tailText:"() (kotlin)" } // EXIST: { itemText: "TODO", tailText:" (other)" }
plugins/kotlin/completion/tests/testData/basic/multifile/ExactMatchPreferImported/ExactMatchPreferImported.kt
3410801458
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.headertoolbar import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent /** * Factory for Project-level widgets placed in main toolbar. * * Extension point: `com.intellij.projectToolbarWidget` * * @see [MainToolbarWidgetFactory] */ @ApiStatus.Experimental @ApiStatus.Internal interface MainToolbarProjectWidgetFactory : MainToolbarWidgetFactory { /** * Factory method to create widget * * @param project current project */ fun createWidget(project: Project): JComponent }
platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/MainToolbarProjectWidgetFactory.kt
2338169728
package com.pushtorefresh.storio3.common.annotations.processor fun String.startsWithIs(): Boolean = this.startsWith("is") && this.length > 2 && Character.isUpperCase(this[2]) fun String.toUpperSnakeCase(): String { val builder = StringBuilder() this.forEachIndexed { index, char -> when { char.isDigit() -> builder.append("_$char") char.isUpperCase() -> if (index == 0) builder.append(char) else builder.append("_$char") char.isLowerCase() -> builder.append(char.toUpperCase()) } } return builder.toString() }
storio-common-annotations-processor/src/main/kotlin/com/pushtorefresh/storio3/common/annotations/processor/Extensions.kt
3535070255
fun formatGreeting(name: String) : String { return "Hello $name" } fun formatGreeting(greetingProvider: SimpleGreeter, name: String) : String { return "${greetingProvider.getGreeting()} $name" }
kotlin/Mastering-Kotlin-master/Chapter09/src/main/Utilities.kt
3902945269
package org.thoughtcrime.securesms.components.settings.app.internal import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.DialogInterface import android.widget.Toast import androidx.lifecycle.ViewModelProviders import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.BuildConfig import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.database.LocalMetricsDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.RefreshAttributesJob import org.thoughtcrime.securesms.jobs.RefreshOwnProfileJob import org.thoughtcrime.securesms.jobs.RemoteConfigRefreshJob import org.thoughtcrime.securesms.jobs.RotateProfileKeyJob import org.thoughtcrime.securesms.jobs.StorageForcePushJob import org.thoughtcrime.securesms.payments.DataExportUtil import org.thoughtcrime.securesms.util.ConversationUtil import org.thoughtcrime.securesms.util.concurrent.SimpleTask class InternalSettingsFragment : DSLSettingsFragment(R.string.preferences__internal_preferences) { private lateinit var viewModel: InternalSettingsViewModel override fun bindAdapter(adapter: DSLSettingsAdapter) { val repository = InternalSettingsRepository(requireContext()) val factory = InternalSettingsViewModel.Factory(repository) viewModel = ViewModelProviders.of(this, factory)[InternalSettingsViewModel::class.java] viewModel.state.observe(viewLifecycleOwner) { adapter.submitList(getConfiguration(it).toMappingModelList()) } } private fun getConfiguration(state: InternalSettingsState): DSLConfiguration { return configure { sectionHeaderPref(R.string.preferences__internal_payments) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_payment_copy_data), summary = DSLSettingsText.from(R.string.preferences__internal_payment_copy_data_description), onClick = { copyPaymentsDataToClipboard() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_account) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_refresh_attributes), summary = DSLSettingsText.from(R.string.preferences__internal_refresh_attributes_description), onClick = { refreshAttributes() } ) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_rotate_profile_key), summary = DSLSettingsText.from(R.string.preferences__internal_rotate_profile_key_description), onClick = { rotateProfileKey() } ) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_refresh_remote_config), summary = DSLSettingsText.from(R.string.preferences__internal_refresh_remote_config_description), onClick = { refreshRemoteValues() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_misc) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_user_details), summary = DSLSettingsText.from(R.string.preferences__internal_user_details_description), isChecked = state.seeMoreUserDetails, onClick = { viewModel.setSeeMoreUserDetails(!state.seeMoreUserDetails) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_shake_to_report), summary = DSLSettingsText.from(R.string.preferences__internal_shake_to_report_description), isChecked = state.shakeToReport, onClick = { viewModel.setShakeToReport(!state.shakeToReport) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_storage_service) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_force_storage_service_sync), summary = DSLSettingsText.from(R.string.preferences__internal_force_storage_service_sync_description), onClick = { forceStorageServiceSync() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_preferences_groups_v2) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_do_not_create_gv2), summary = DSLSettingsText.from(R.string.preferences__internal_do_not_create_gv2_description), isChecked = state.gv2doNotCreateGv2Groups, onClick = { viewModel.setGv2DoNotCreateGv2Groups(!state.gv2doNotCreateGv2Groups) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_force_gv2_invites), summary = DSLSettingsText.from(R.string.preferences__internal_force_gv2_invites_description), isChecked = state.gv2forceInvites, onClick = { viewModel.setGv2ForceInvites(!state.gv2forceInvites) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_server_changes), summary = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_server_changes_description), isChecked = state.gv2ignoreServerChanges, onClick = { viewModel.setGv2IgnoreServerChanges(!state.gv2ignoreServerChanges) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_p2p_changes), summary = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_server_changes_description), isChecked = state.gv2ignoreP2PChanges, onClick = { viewModel.setGv2IgnoreP2PChanges(!state.gv2ignoreP2PChanges) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_preferences_groups_v1_migration) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_do_not_initiate_automigrate), summary = DSLSettingsText.from(R.string.preferences__internal_do_not_initiate_automigrate_description), isChecked = state.disableAutoMigrationInitiation, onClick = { viewModel.setDisableAutoMigrationInitiation(!state.disableAutoMigrationInitiation) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_do_not_notify_automigrate), summary = DSLSettingsText.from(R.string.preferences__internal_do_not_notify_automigrate_description), isChecked = state.disableAutoMigrationNotification, onClick = { viewModel.setDisableAutoMigrationNotification(!state.disableAutoMigrationNotification) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_network) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_force_censorship), summary = DSLSettingsText.from(R.string.preferences__internal_force_censorship_description), isChecked = state.forceCensorship, onClick = { viewModel.setForceCensorship(!state.forceCensorship) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_conversations_and_shortcuts) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_delete_all_dynamic_shortcuts), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_delete_all_dynamic_shortcuts), onClick = { deleteAllDynamicShortcuts() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_emoji) val emojiSummary = if (state.emojiVersion == null) { getString(R.string.preferences__internal_use_built_in_emoji_set) } else { getString( R.string.preferences__internal_current_version_d_at_density_s, state.emojiVersion.version, state.emojiVersion.density ) } switchPref( title = DSLSettingsText.from(R.string.preferences__internal_use_built_in_emoji_set), summary = DSLSettingsText.from(emojiSummary), isChecked = state.useBuiltInEmojiSet, onClick = { viewModel.setDisableAutoMigrationNotification(!state.useBuiltInEmojiSet) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_sender_key) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_clear_all_state), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_delete_all_sender_key_state), onClick = { clearAllSenderKeyState() } ) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_clear_shared_state), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_delete_all_sharing_state), onClick = { clearAllSenderKeySharedState() } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_remove_two_person_minimum), summary = DSLSettingsText.from(R.string.preferences__internal_remove_the_requirement_that_you_need), isChecked = state.removeSenderKeyMinimium, onClick = { viewModel.setRemoveSenderKeyMinimum(!state.removeSenderKeyMinimium) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_delay_resends), summary = DSLSettingsText.from(R.string.preferences__internal_delay_resending_messages_in_response_to_retry_receipts), isChecked = state.delayResends, onClick = { viewModel.setDelayResends(!state.delayResends) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_local_metrics) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_clear_local_metrics), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_clear_all_local_metrics_state), onClick = { clearAllLocalMetricsState() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_calling) radioPref( title = DSLSettingsText.from(R.string.preferences__internal_calling_default), summary = DSLSettingsText.from(BuildConfig.SIGNAL_SFU_URL), isChecked = state.callingServer == BuildConfig.SIGNAL_SFU_URL, onClick = { viewModel.setInternalGroupCallingServer(null) } ) BuildConfig.SIGNAL_SFU_INTERNAL_NAMES.zip(BuildConfig.SIGNAL_SFU_INTERNAL_URLS) .forEach { (name, server) -> radioPref( title = DSLSettingsText.from(requireContext().getString(R.string.preferences__internal_calling_s_server, name)), summary = DSLSettingsText.from(server), isChecked = state.callingServer == server, onClick = { viewModel.setInternalGroupCallingServer(server) } ) } } } private fun copyPaymentsDataToClipboard() { MaterialAlertDialogBuilder(requireContext()) .setMessage( """ Local payments history will be copied to the clipboard. It may therefore compromise privacy. However, no private keys will be copied. """.trimIndent() ) .setPositiveButton( "Copy" ) { _: DialogInterface?, _: Int -> SimpleTask.run<Any?>( SignalExecutors.UNBOUNDED, { val context: Context = ApplicationDependencies.getApplication() val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val tsv = DataExportUtil.createTsv() val clip = ClipData.newPlainText(context.getString(R.string.app_name), tsv) clipboard.setPrimaryClip(clip) null }, { Toast.makeText( context, "Payments have been copied", Toast.LENGTH_SHORT ).show() } ) } .setNegativeButton(android.R.string.cancel, null) .show() } private fun refreshAttributes() { ApplicationDependencies.getJobManager() .startChain(RefreshAttributesJob()) .then(RefreshOwnProfileJob()) .enqueue() Toast.makeText(context, "Scheduled attribute refresh", Toast.LENGTH_SHORT).show() } private fun rotateProfileKey() { ApplicationDependencies.getJobManager().add(RotateProfileKeyJob()) Toast.makeText(context, "Scheduled profile key rotation", Toast.LENGTH_SHORT).show() } private fun refreshRemoteValues() { ApplicationDependencies.getJobManager().add(RemoteConfigRefreshJob()) Toast.makeText(context, "Scheduled remote config refresh", Toast.LENGTH_SHORT).show() } private fun forceStorageServiceSync() { ApplicationDependencies.getJobManager().add(StorageForcePushJob()) Toast.makeText(context, "Scheduled storage force push", Toast.LENGTH_SHORT).show() } private fun deleteAllDynamicShortcuts() { ConversationUtil.clearAllShortcuts(requireContext()) Toast.makeText(context, "Deleted all dynamic shortcuts.", Toast.LENGTH_SHORT).show() } private fun clearAllSenderKeyState() { DatabaseFactory.getSenderKeyDatabase(requireContext()).deleteAll() DatabaseFactory.getSenderKeySharedDatabase(requireContext()).deleteAll() Toast.makeText(context, "Deleted all sender key state.", Toast.LENGTH_SHORT).show() } private fun clearAllSenderKeySharedState() { DatabaseFactory.getSenderKeySharedDatabase(requireContext()).deleteAll() Toast.makeText(context, "Deleted all sender key shared state.", Toast.LENGTH_SHORT).show() } private fun clearAllLocalMetricsState() { LocalMetricsDatabase.getInstance(ApplicationDependencies.getApplication()).clear() Toast.makeText(context, "Cleared all local metrics state.", Toast.LENGTH_SHORT).show() } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsFragment.kt
913346645
package io.ipoli.android.challenge.add import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.* import com.mikepenz.community_material_typeface_library.CommunityMaterial import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.IconicsDrawable import io.ipoli.android.Constants.Companion.DECIMAL_FORMATTER import io.ipoli.android.R import io.ipoli.android.challenge.add.EditChallengeViewState.StateType.* import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.common.redux.android.BaseViewController import io.ipoli.android.common.view.* import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import kotlinx.android.synthetic.main.controller_add_challenge_tracked_value.view.* import kotlinx.android.synthetic.main.item_challenge_summary_tracked_value.view.* class AddChallengeTrackedValueViewController(args: Bundle? = null) : BaseViewController<EditChallengeAction, EditChallengeViewState>( args ) { override val stateKey = EditChallengeReducer.stateKey private var showNext = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) applyStatusBarColors = false val view = container.inflate(R.layout.controller_add_challenge_tracked_value) view.resultCompletionIcon.setImageDrawable( IconicsDrawable(view.context) .icon(GoogleMaterial.Icon.gmd_done_all) .colorRes(R.color.md_red_500) .paddingDp(8) .sizeDp(40) ) view.resultAverageValueIcon.setImageDrawable( IconicsDrawable(view.context) .icon(CommunityMaterial.Icon.cmd_scale_balance) .colorRes(R.color.md_amber_500) .paddingDp(10) .sizeDp(40) ) view.resultCompletionBackground.dispatchOnClick { EditChallengeAction.AddCompleteAllTrackedValue } view.resultReachValueBackground.onDebounceClick { dispatch(EditChallengeAction.ShowTargetTrackedValuePicker(emptyList())) } view.resultAverageBackground.onDebounceClick { dispatch(EditChallengeAction.ShowAverageTrackedValuePicker(emptyList())) } view.expectedResultText.setTextColor(colorRes(R.color.md_dark_text_87)) view.expectedResultText.text = "Complete all Quests" view.expectedResultRemove.setImageDrawable( IconicsDrawable(view.context).normalIcon( GoogleMaterial.Icon.gmd_close, R.color.md_dark_text_87 ).respectFontBounds(true) ) view.expectedResultRemove.dispatchOnClick { EditChallengeAction.RemoveCompleteAll } view.resultCompletionDivider.gone() view.resultCompletionItem.gone() view.resultReachItems.layoutManager = LinearLayoutManager(view.context) view.resultReachItems.adapter = TrackedValueAdapter() view.resultAverageItems.layoutManager = LinearLayoutManager(view.context) view.resultAverageItems.adapter = TrackedValueAdapter() return view } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.next_wizard_menu, menu) } override fun onPrepareOptionsMenu(menu: Menu) { val nextItem = menu.findItem(R.id.actionNext) nextItem.isVisible = showNext super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.actionNext -> { dispatch(EditChallengeAction.ShowNext) true } else -> super.onOptionsItemSelected(item) } override fun render(state: EditChallengeViewState, view: View) { when (state.type) { TRACKED_VALUES_CHANGED -> { showNext = state.trackedValues.isNotEmpty() activity?.invalidateOptionsMenu() if (state.shouldTrackCompleteAll) { view.resultCompletionBackground.isEnabled = false view.resultCompletionBackground.isClickable = false view.resultCompletionBackground.isFocusable = false view.resultCompletionBackground.setOnClickListener(null) view.resultCompletionDivider.visible() view.resultCompletionItem.visible() } else { view.resultCompletionBackground.isEnabled = true view.resultCompletionBackground.isClickable = true view.resultCompletionBackground.isFocusable = true view.resultCompletionBackground.dispatchOnClick { EditChallengeAction.AddCompleteAllTrackedValue } view.resultCompletionDivider.gone() view.resultCompletionItem.gone() } (view.resultReachItems.adapter as TrackedValueAdapter).updateAll(state.trackTargetViewModels) (view.resultAverageItems.adapter as TrackedValueAdapter).updateAll(state.trackAverageViewModels) view.resultReachValueBackground.onDebounceClick { dispatch(EditChallengeAction.ShowTargetTrackedValuePicker(state.trackedValues)) } view.resultAverageBackground.onDebounceClick { dispatch(EditChallengeAction.ShowAverageTrackedValuePicker(state.trackedValues)) } } SHOW_TARGET_TRACKED_VALUE_PICKER -> navigate().toTargetValuePicker(targetValueSelectedListener = { t -> dispatch( EditChallengeAction.AddTargetTrackedValue(t) ) }) SHOW_AVERAGE_TRACKED_VALUE_PICKER -> navigate().toMaintainAverageValuePicker(trackedValueSelectedListener = { t -> dispatch( EditChallengeAction.AddAverageTrackedValue(t) ) }) else -> { } } } data class TrackedValueViewModel( override val id: String, val text: String, val trackedValue: Challenge.TrackedValue ) : RecyclerViewViewModel inner class TrackedValueAdapter : BaseRecyclerViewAdapter<TrackedValueViewModel>(R.layout.item_challenge_summary_tracked_value) { override fun onBindViewModel( vm: TrackedValueViewModel, view: View, holder: SimpleViewHolder ) { view.expectedResultRemove.setImageDrawable( IconicsDrawable(view.context).normalIcon( GoogleMaterial.Icon.gmd_close, R.color.md_dark_text_87 ).respectFontBounds(true) ) view.expectedResultRemove.dispatchOnClick { EditChallengeAction.RemoveTrackedValue(vm.id) } view.expectedResultText.setTextColor(colorRes(R.color.md_dark_text_87)) view.expectedResultText.text = vm.text when (vm.trackedValue) { is Challenge.TrackedValue.Target -> view.onDebounceClick { navigate().toTargetValuePicker( targetValueSelectedListener = { t -> dispatch(EditChallengeAction.UpdateTrackedValue(t)) }, trackedValue = vm.trackedValue ) } is Challenge.TrackedValue.Average -> view.onDebounceClick { navigate().toMaintainAverageValuePicker( trackedValueSelectedListener = { t -> dispatch(EditChallengeAction.UpdateTrackedValue(t)) }, trackedValue = vm.trackedValue ) } else -> view.setOnClickListener(null) } } } private val EditChallengeViewState.trackTargetViewModels: List<TrackedValueViewModel> get() = trackedValues .filterIsInstance(Challenge.TrackedValue.Target::class.java) .map { TrackedValueViewModel( id = it.id, text = "Reach ${DECIMAL_FORMATTER.format(it.targetValue)} ${it.units} ${it.name}", trackedValue = it ) } private val EditChallengeViewState.trackAverageViewModels: List<TrackedValueViewModel> get() = trackedValues .filterIsInstance(Challenge.TrackedValue.Average::class.java) .map { TrackedValueViewModel( id = it.id, text = "Maintain ${DECIMAL_FORMATTER.format(it.targetValue)} ${it.units} ${it.name}", trackedValue = it ) } }
app/src/main/java/io/ipoli/android/challenge/add/AddChallengeTrackedValueViewController.kt
194738583
package com.eden.orchid.languages.diagrams import com.eden.orchid.api.compilers.OrchidCompiler import com.eden.orchid.api.registration.OrchidModule import com.eden.orchid.api.theme.components.OrchidComponent import com.eden.orchid.languages.diagrams.components.MermaidJsComponent import com.eden.orchid.utilities.addToSet class DiagramsModule : OrchidModule() { override fun configure() { withResources() addToSet<OrchidCompiler, PlantUmlCompiler>() addToSet<OrchidComponent, MermaidJsComponent>() } }
languageExtensions/OrchidDiagrams/src/main/kotlin/com/eden/orchid/languages/diagrams/DiagramsModule.kt
3725607338
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spectator.api.Registry import com.netflix.spinnaker.orca.TaskImplementationResolver import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.events.StageStarted import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.ext.allUpstreamStagesComplete import com.netflix.spinnaker.orca.ext.anyUpstreamStagesFailed import com.netflix.spinnaker.orca.ext.firstAfterStages import com.netflix.spinnaker.orca.ext.firstBeforeStages import com.netflix.spinnaker.orca.ext.firstTask import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator import com.netflix.spinnaker.orca.pipeline.model.OptionalStageSupport import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CompleteExecution import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.SkipStage import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.addContextFlags import com.netflix.spinnaker.orca.q.buildBeforeStages import com.netflix.spinnaker.orca.q.buildTasks import com.netflix.spinnaker.q.AttemptsAttribute import com.netflix.spinnaker.q.MaxAttemptsAttribute import com.netflix.spinnaker.q.Queue import java.time.Clock import java.time.Duration import java.time.Instant import kotlin.collections.set import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component @Component class StartStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, override val contextParameterProcessor: ContextParameterProcessor, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val exceptionHandlers: List<ExceptionHandler>, @Qualifier("mapper") private val objectMapper: ObjectMapper, private val clock: Clock, private val registry: Registry, @Value("\${queue.retry.delay.ms:15000}") retryDelayMs: Long, private val taskImplementationResolver: TaskImplementationResolver ) : OrcaMessageHandler<StartStage>, StageBuilderAware, ExpressionAware, AuthenticationAware { private val retryDelay = Duration.ofMillis(retryDelayMs) override fun handle(message: StartStage) { message.withStage { stage -> try { stage.withAuth { if (stage.anyUpstreamStagesFailed()) { // this only happens in restart scenarios log.warn("Tried to start stage ${stage.id} but something upstream had failed (executionId: ${message.executionId})") queue.push(CompleteExecution(message)) } else if (stage.allUpstreamStagesComplete()) { if (stage.status != NOT_STARTED) { log.warn("Ignoring $message as stage is already ${stage.status}") } else if (stage.shouldSkip()) { queue.push(SkipStage(message)) } else if (stage.isAfterStartTimeExpiry()) { log.warn("Stage is being skipped because its start time is after TTL (stageId: ${stage.id}, executionId: ${message.executionId})") queue.push(SkipStage(stage)) } else { try { // Set the startTime in case we throw an exception. stage.startTime = clock.millis() repository.storeStage(stage) stage.plan() stage.status = RUNNING repository.storeStage(stage) stage.start() publisher.publishEvent(StageStarted(this, stage)) trackResult(stage) } catch (e: Exception) { val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name) if (exceptionDetails?.shouldRetry == true) { val attempts = message.getAttribute<AttemptsAttribute>()?.attempts ?: 0 log.warn("Error planning ${stage.type} stage for ${message.executionType}[${message.executionId}] (attempts: $attempts)") message.setAttribute(MaxAttemptsAttribute(40)) queue.push(message, retryDelay) } else { log.error("Error running ${stage.type}[${stage.id}] stage for ${message.executionType}[${message.executionId}]", e) stage.apply { context["exception"] = exceptionDetails context["beforeStagePlanningFailed"] = true } repository.storeStage(stage) queue.push(CompleteStage(message)) } } } } else { log.info("Re-queuing $message as upstream stages are not yet complete") queue.push(message, retryDelay) } } } catch (e: Exception) { message.withStage { stage -> log.error("Error running ${stage.type}[${stage.id}] stage for ${message.executionType}[${message.executionId}]", e) stage.apply { val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name) context["exception"] = exceptionDetails context["beforeStagePlanningFailed"] = true } repository.storeStage(stage) queue.push(CompleteStage(message)) } } } } private fun trackResult(stage: StageExecution) { // We only want to record invocations of parent-level stages; not synthetics if (stage.parentStageId != null) { return } val id = registry.createId("stage.invocations") .withTag("type", stage.type) .withTag("application", stage.execution.application) .let { id -> // TODO rz - Need to check synthetics for their cloudProvider. stage.context["cloudProvider"]?.let { id.withTag("cloudProvider", it.toString()) } ?: id }.let { id -> stage.additionalMetricTags?.let { id.withTags(stage.additionalMetricTags) } ?: id } registry.counter(id).increment() } override val messageType = StartStage::class.java private fun StageExecution.plan() { builder().let { builder -> // if we have a top level stage, ensure that context expressions are processed val mergedStage = if (this.parentStageId == null) this.withMergedContext() else this builder.addContextFlags(mergedStage) builder.buildTasks(mergedStage, taskImplementationResolver) builder.buildBeforeStages(mergedStage) { repository.addStage(it.withMergedContext()) } } } private fun StageExecution.start() { val beforeStages = firstBeforeStages() if (beforeStages.isEmpty()) { val task = firstTask() if (task == null) { // TODO: after stages are no longer planned at this point. We could skip this val afterStages = firstAfterStages() if (afterStages.isEmpty()) { queue.push(CompleteStage(this)) } else { afterStages.forEach { queue.push(StartStage(it)) } } } else { queue.push(StartTask(this, task.id)) } } else { beforeStages.forEach { queue.push(StartStage(it)) } } } private fun StageExecution.shouldSkip(): Boolean { if (this.execution.type != PIPELINE) { return false } val clonedContext: MutableMap<String, Any> = this.context.toMutableMap() val clonedStage = StageExecutionImpl(this.execution, this.type, clonedContext).also { it.refId = refId it.requisiteStageRefIds = requisiteStageRefIds it.syntheticStageOwner = syntheticStageOwner it.parentStageId = parentStageId } if (clonedStage.context.containsKey(PipelineExpressionEvaluator.SUMMARY)) { this.context.put(PipelineExpressionEvaluator.SUMMARY, clonedStage.context[PipelineExpressionEvaluator.SUMMARY]) } return OptionalStageSupport.isOptional(clonedStage.withMergedContext(), contextParameterProcessor) } private fun StageExecution.isAfterStartTimeExpiry(): Boolean = startTimeExpiry?.let { Instant.ofEpochMilli(it) }?.isBefore(clock.instant()) ?: false }
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartStageHandler.kt
2660854496
// 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.plugins.github.pullrequest import com.intellij.collaboration.async.DisposingMainScope import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.EmptyAction import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.impl.content.ToolWindowContentUi import com.intellij.ui.content.Content import com.intellij.util.cancelOnDispose import com.intellij.util.childScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager import org.jetbrains.plugins.github.pullrequest.action.GHPRSelectPullRequestForFileAction import org.jetbrains.plugins.github.pullrequest.action.GHPRSwitchRemoteAction import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabController import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabControllerImpl import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabViewModel import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHRepositoryConnectionManager import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager import javax.swing.JPanel internal class GHPRToolWindowFactory : ToolWindowFactory, DumbAware { companion object { const val ID = "Pull Requests" } override fun init(toolWindow: ToolWindow) { toolWindow.project.coroutineScope.launch { val repositoriesManager = toolWindow.project.service<GHHostedRepositoriesManager>() withContext<Unit>(Dispatchers.EDT) { repositoriesManager.knownRepositoriesState.collect { toolWindow.isAvailable = it.isNotEmpty() } } }.cancelOnDispose(toolWindow.disposable) } override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { toolWindow.component.putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true") configureToolWindow(toolWindow) val contentManager = toolWindow.contentManager val content = contentManager.factory.createContent(JPanel(null), null, false).apply { isCloseable = false setDisposer(Disposer.newDisposable("reviews tab disposable")) } configureContent(project, content) contentManager.addContent(content) } private fun configureToolWindow(toolWindow: ToolWindow) { toolWindow.setTitleActions(listOf( EmptyAction.registerWithShortcutSet("Github.Create.Pull.Request", CommonShortcuts.getNew(), toolWindow.component), GHPRSelectPullRequestForFileAction(), )) toolWindow.setAdditionalGearActions(DefaultActionGroup(GHPRSwitchRemoteAction())) } private fun configureContent(project: Project, content: Content) { val scope = DisposingMainScope(content) val repositoriesManager = project.service<GHHostedRepositoriesManager>() val accountManager = service<GHAccountManager>() val connectionManager = GHRepositoryConnectionManager(repositoriesManager, accountManager, project.service()) val vm = GHPRToolWindowTabViewModel(scope, repositoriesManager, accountManager, connectionManager, project.service()) val controller = GHPRToolWindowTabControllerImpl(scope.childScope(), project, vm, content) content.putUserData(GHPRToolWindowTabController.KEY, controller) } override fun shouldBeAvailable(project: Project): Boolean = false }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRToolWindowFactory.kt
1773301922
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ParentWithNullsImpl(val dataSource: ParentWithNullsData) : ParentWithNulls, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNulls::class.java, ChildWithNulls::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, true) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ) } override val parentData: String get() = dataSource.parentData override val child: ChildWithNulls? get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ParentWithNullsData?) : ModifiableWorkspaceEntityBase<ParentWithNulls, ParentWithNullsData>( result), ParentWithNulls.Builder { constructor() : this(ParentWithNullsData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ParentWithNulls is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isParentDataInitialized()) { error("Field ParentWithNulls#parentData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ParentWithNulls if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.parentData != dataSource.parentData) this.parentData = dataSource.parentData if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var parentData: String get() = getEntityData().parentData set(value) { checkModificationAllowed() getEntityData(true).parentData = value changedProperty.add("parentData") } override var child: ChildWithNulls? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildWithNulls } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildWithNulls } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override fun getEntityClass(): Class<ParentWithNulls> = ParentWithNulls::class.java } } class ParentWithNullsData : WorkspaceEntityData<ParentWithNulls>() { lateinit var parentData: String fun isParentDataInitialized(): Boolean = ::parentData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ParentWithNulls> { val modifiable = ParentWithNullsImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ParentWithNulls { return getCached(snapshot) { val entity = ParentWithNullsImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ParentWithNulls::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ParentWithNulls(parentData, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ParentWithNullsData if (this.entitySource != other.entitySource) return false if (this.parentData != other.parentData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ParentWithNullsData if (this.parentData != other.parentData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + parentData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentWithNullsImpl.kt
454636740
// 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.structuralsearch.search import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchTest class KotlinSSTargetedTest : KotlinStructuralSearchTest() { override fun getBasePath(): String = "targeted" fun testTargetAnyField() { doTest( """ class '_Class { val 'Field+ = '_Init? } """.trimIndent() ) } fun testTargetSpecificField() { doTest( """ class '_Class { val 'Field+ = 45 } """.trimIndent() ) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSTargetedTest.kt
3014001212
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class TypeOfAnnotationMemberFix( typeReference: KtTypeReference, private val fixedType: String ) : KotlinQuickFixAction<KtTypeReference>(typeReference), CleanupFix { override fun getText(): String = KotlinBundle.message("replace.array.of.boxed.with.array.of.primitive") override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val psiElement = element ?: return psiElement.replace(KtPsiFactory(psiElement).createType(fixedType)) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val typeReference = diagnostic.psiElement as? KtTypeReference ?: return null val type = typeReference.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return null val itemType = type.getArrayItemType() ?: return null val itemTypeName = itemType.constructor.declarationDescriptor?.name?.asString() ?: return null val fixedArrayTypeText = if (itemType.isItemTypeToFix()) { "${itemTypeName}Array" } else { return null } return TypeOfAnnotationMemberFix(typeReference, fixedArrayTypeText) } private fun KotlinType.getArrayItemType(): KotlinType? { if (!KotlinBuiltIns.isArray(this)) { return null } val boxedType = arguments.singleOrNull() ?: return null if (boxedType.isStarProjection) { return null } return boxedType.type } private fun KotlinType.isItemTypeToFix() = KotlinBuiltIns.isByte(this) || KotlinBuiltIns.isChar(this) || KotlinBuiltIns.isShort(this) || KotlinBuiltIns.isInt(this) || KotlinBuiltIns.isLong(this) || KotlinBuiltIns.isFloat(this) || KotlinBuiltIns.isDouble(this) || KotlinBuiltIns.isBoolean(this) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt
3163761789
// 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.diff.settings import com.intellij.diff.tools.external.ExternalDiffSettings import com.intellij.diff.tools.external.ExternalDiffSettings.ExternalTool import com.intellij.diff.tools.external.ExternalDiffSettings.ExternalToolGroup import com.intellij.diff.tools.external.ExternalDiffToolUtil import com.intellij.execution.impl.ConsoleViewUtil import com.intellij.ide.util.treeView.TreeState import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.* import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SmartExpander import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.* import com.intellij.ui.layout.ComponentPredicate import com.intellij.ui.treeStructure.Tree import com.intellij.util.PathUtilRt import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.ListTableModel import com.intellij.util.ui.tree.TreeUtil import java.awt.Component import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.event.TreeExpansionEvent import javax.swing.event.TreeExpansionListener import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreeCellRenderer import javax.swing.tree.TreePath internal class ExternalToolsTreePanel(private val models: ExternalToolsModels) { private var treeState: TreeState private val treeModel = models.treeModel private val root = treeModel.root as DefaultMutableTreeNode private val tree = Tree(treeModel).apply { visibleRowCount = 8 isRootVisible = false cellRenderer = ExternalToolsTreeCellRenderer() treeState = TreeState.createOn(this) addMouseListener(object : MouseAdapter() { override fun mousePressed(mouseEvent: MouseEvent) { val treePath = selectionPath ?: return if (mouseEvent.clickCount == 2 && SwingUtilities.isLeftMouseButton(mouseEvent)) { mouseEvent.consume() val node = treePath.lastPathComponent as DefaultMutableTreeNode when (node.userObject) { is ExternalTool -> editData() else -> {} } } } }) addTreeExpansionListener(object : TreeExpansionListener { override fun treeExpanded(event: TreeExpansionEvent) { treeState = TreeState.createOn(this@apply) } override fun treeCollapsed(event: TreeExpansionEvent) { treeState = TreeState.createOn(this@apply) } }) SmartExpander.installOn(this) } val component: JComponent init { val decoratedTree = ToolbarDecorator.createDecorator(tree) .setAddAction { addTool() } .setRemoveActionUpdater { isExternalToolSelected(tree.selectionPath) } .setRemoveAction { removeData() } .setEditActionUpdater { isExternalToolSelected(tree.selectionPath) } .setEditAction { editData() } .disableUpDownActions() .createPanel() component = decoratedTree } fun onModified(settings: ExternalDiffSettings): Boolean = treeModel.toMap() != settings.externalTools fun onApply(settings: ExternalDiffSettings) { settings.externalTools = treeModel.toMap() treeState = TreeState.createOn(tree) } fun onReset(settings: ExternalDiffSettings) { treeModel.update(settings.externalTools) treeState.applyTo(tree) } private fun addTool() { val dialog = AddToolDialog() if (dialog.showAndGet()) { val tool = dialog.createExternalTool() val node = DefaultMutableTreeNode(tool) val groupNode = findGroupNode(dialog.getToolGroup()) treeModel.insertNodeInto(node, groupNode, groupNode.childCount) treeModel.nodeChanged(root) tree.expandPath(TreePath(groupNode.path)) } } private fun findGroupNode(externalToolGroup: ExternalToolGroup): DefaultMutableTreeNode { for (child in root.children()) { val treeNode = child as DefaultMutableTreeNode val valueNode = treeNode.userObject as ExternalToolGroup if (valueNode == externalToolGroup) return treeNode } val groupNode = DefaultMutableTreeNode(externalToolGroup) treeModel.insertNodeInto(groupNode, root, root.childCount) return groupNode } private fun removeData() { val treePath = tree.selectionPath ?: return val node = treePath.lastPathComponent as DefaultMutableTreeNode val parentNode = treePath.parentPath.lastPathComponent as DefaultMutableTreeNode val toolGroup = parentNode.userObject as ExternalToolGroup val externalTool = node.userObject as ExternalTool if (isConfigurationRegistered(externalTool, toolGroup)) { Messages.showWarningDialog(DiffBundle.message("settings.external.tool.tree.remove.warning.message"), DiffBundle.message("settings.external.tool.tree.remove.warning.title")) return } val dialog = MessageDialogBuilder.okCancel(DiffBundle.message("settings.external.diff.table.remove.dialog.title"), DiffBundle.message("settings.external.diff.table.remove.dialog.message")) if (dialog.guessWindowAndAsk()) { treeModel.removeNodeFromParent(node) if (parentNode.childCount == 0) { treeModel.removeNodeFromParent(parentNode) } } } private fun editData() { val treePath = tree.selectionPath ?: return val node = treePath.lastPathComponent as DefaultMutableTreeNode if (node.userObject !is ExternalTool) { return } val currentTool = node.userObject as ExternalTool val dialog = AddToolDialog(currentTool) if (dialog.showAndGet()) { val editedTool = dialog.createExternalTool() val groupNode = findGroupNode(dialog.getToolGroup()) val toolGroup = groupNode.userObject as ExternalToolGroup node.userObject = editedTool treeModel.nodeChanged(node) models.tableModel.updateEntities(toolGroup, currentTool, editedTool) } } private fun isConfigurationRegistered(externalTool: ExternalTool, externalToolGroup: ExternalToolGroup): Boolean { val configurations = models.tableModel.items return when (externalToolGroup) { ExternalToolGroup.DIFF_TOOL -> configurations.any { it.diffToolName == externalTool.name } ExternalToolGroup.MERGE_TOOL -> configurations.any { it.mergeToolName == externalTool.name } } } private fun isExternalToolSelected(selectionPath: TreePath?): Boolean { if (selectionPath == null) return false val node = selectionPath.lastPathComponent as DefaultMutableTreeNode return when (node.userObject) { is ExternalTool -> true else -> false } } private class ExternalToolsTreeCellRenderer : TreeCellRenderer { private val renderer = SimpleColoredComponent() override fun getTreeCellRendererComponent(tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { return renderer.apply { val node = value as DefaultMutableTreeNode val text = when (val userObject = node.userObject) { null -> "" // Special for root (not visible in tree) is ExternalToolGroup -> userObject.groupName // NON-NLS is ExternalTool -> userObject.name // NON-NLS else -> userObject.toString() // NON-NLS } clear() append(text) } } } private inner class AddToolDialog( private val oldToolName: String? = null, private val isEditMode: Boolean = false, ) : DialogWrapper(null) { private val groupField = ComboBox( arrayOf(ExternalToolGroup.DIFF_TOOL, ExternalToolGroup.MERGE_TOOL) ).apply { renderer = object : ColoredListCellRenderer<ExternalToolGroup>() { override fun customizeCellRenderer(list: JList<out ExternalToolGroup>, value: ExternalToolGroup, index: Int, selected: Boolean, hasFocus: Boolean) { append(value.groupName) // NON-NLS } } } private var isAutocompleteToolName = true private val toolNameField = JBTextField().apply { document.addDocumentListener(object : DocumentListener { override fun insertUpdate(event: DocumentEvent) { if (isFocusOwner) isAutocompleteToolName = false } override fun removeUpdate(event: DocumentEvent) {} override fun changedUpdate(event: DocumentEvent) {} }) } private val programPathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(DiffBundle.message("select.external.program.dialog.title"), null, null, FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()) textField.document.addDocumentListener(object : DocumentListener { override fun insertUpdate(event: DocumentEvent) { if (isAutocompleteToolName) { val guessToolName = StringUtil.capitalize(PathUtilRt.getFileName(text)) toolNameField.text = guessToolName } } override fun removeUpdate(event: DocumentEvent) {} override fun changedUpdate(event: DocumentEvent) {} }) } private val argumentPatternField = JBTextField(DIFF_TOOL_DEFAULT_ARGUMENT_PATTERN) private val isMergeTrustExitCode = JBCheckBox(DiffBundle.message("settings.external.diff.trust.process.exit.code")) private val testDiffButton = JButton(DiffBundle.message("settings.external.diff.test.diff")).apply { addActionListener { showTestDiff() } } private val testThreeSideDiffButton = JButton(DiffBundle.message("settings.external.diff.test.three.side.diff")).apply { addActionListener { showTestThreeDiff() } } private val testMergeButton = JButton(DiffBundle.message("settings.external.diff.test.merge")).apply { addActionListener { showTestMerge() } } private val toolOutputEditor = ConsoleViewUtil.setupConsoleEditor(null, false, false).also { it.settings.additionalLinesCount = 3 } private var toolOutputConsole: MyTestOutputConsole? = null constructor(externalTool: ExternalTool) : this(externalTool.name, true) { isAutocompleteToolName = false toolNameField.text = externalTool.name programPathField.text = externalTool.programPath argumentPatternField.text = externalTool.argumentPattern isMergeTrustExitCode.isSelected = externalTool.isMergeTrustExitCode groupField.selectedItem = externalTool.groupName title = DiffBundle.message("settings.external.tool.tree.edit.dialog.title") } init { title = DiffBundle.message("settings.external.tool.tree.add.dialog.title") Disposer.register(disposable) { toolOutputConsole?.let { Disposer.dispose(it) } } init() } override fun createCenterPanel(): JComponent = panel { lateinit var argumentPatternDescription: JEditorPane row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.group")) { cell(groupField).align(AlignX.FILL) }.visible(!isEditMode) row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.program.path")) { cell(programPathField).align(AlignX.FILL) } row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.tool.name")) { cell(toolNameField).align(AlignX.FILL).validationOnApply { toolFieldValidation(groupField.item, it.text) } } row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.argument.pattern")) { cell(argumentPatternField).align(AlignX.FILL) } row { cell(isMergeTrustExitCode).align(AlignX.FILL) .visibleIf(object : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { groupField.addItemListener { val isMergeGroup = invoke() testDiffButton.isVisible = !isMergeGroup testThreeSideDiffButton.isVisible = !isMergeGroup testMergeButton.isVisible = isMergeGroup if (!isEditMode) { argumentPatternField.text = if (isMergeGroup) MERGE_TOOL_DEFAULT_ARGUMENT_PATTERN else DIFF_TOOL_DEFAULT_ARGUMENT_PATTERN } argumentPatternDescription.text = if (isMergeGroup) createDescription(ExternalToolGroup.MERGE_TOOL) else createDescription(ExternalToolGroup.DIFF_TOOL) listener(isMergeGroup) } } override fun invoke(): Boolean { val item = groupField.selectedItem as ExternalToolGroup return item == ExternalToolGroup.MERGE_TOOL } }) } row { argumentPatternDescription = comment(createDescription(ExternalToolGroup.DIFF_TOOL), DEFAULT_COMMENT_WIDTH).component } row { val isMergeGroup = isMergeTrustExitCode.isVisible cell(testDiffButton).visible(!isMergeGroup) cell(testThreeSideDiffButton).visible(!isMergeGroup) cell(testMergeButton).visible(isMergeGroup) }.topGap(TopGap.MEDIUM) row { cell(toolOutputEditor.component) .align(Align.FILL) .applyToComponent { preferredSize = JBUI.size(400, 150) } }.resizableRow() } fun createExternalTool(): ExternalTool = ExternalTool(toolNameField.text, programPathField.text, argumentPatternField.text, isMergeTrustExitCode.isVisible && isMergeTrustExitCode.isSelected, groupField.item) fun getToolGroup(): ExternalToolGroup = groupField.item private fun toolFieldValidation(toolGroup: ExternalToolGroup, toolName: String): ValidationInfo? { if (toolName.isEmpty()) { return ValidationInfo(DiffBundle.message("settings.external.tool.tree.validation.empty")) } if (isToolAlreadyExist(toolGroup, toolName) && toolName != oldToolName) { return ValidationInfo(DiffBundle.message("settings.external.tool.tree.validation.already.exist", toolGroup, toolName)) } return null } private fun isToolAlreadyExist(toolGroup: ExternalToolGroup, toolName: String): Boolean { val isNodeExist = TreeUtil.findNode(findGroupNode(toolGroup)) { node -> when (val externalTool = node.userObject) { is ExternalTool -> externalTool.name == toolName else -> false // skip root } } return isNodeExist != null } @NlsContexts.DetailedDescription private fun createDescription(toolGroup: ExternalToolGroup): String { val title = DiffBundle.message("settings.external.tools.parameters.description") val argumentPattern = when (toolGroup) { ExternalToolGroup.DIFF_TOOL -> DiffBundle.message("settings.external.tools.parameters.diff") ExternalToolGroup.MERGE_TOOL -> DiffBundle.message("settings.external.tools.parameters.merge") } return "$title<br>$argumentPattern" } private fun showTestDiff() { ExternalDiffToolUtil.testDiffTool2(null, createExternalTool(), resetToolOutputConsole()) } private fun showTestThreeDiff() { ExternalDiffToolUtil.testDiffTool3(null, createExternalTool(), resetToolOutputConsole()) } private fun showTestMerge() { ExternalDiffToolUtil.testMergeTool(null, createExternalTool(), resetToolOutputConsole()) } @RequiresEdt private fun resetToolOutputConsole(): ExternalDiffToolUtil.TestOutputConsole { toolOutputConsole?.let { Disposer.dispose(it) } toolOutputConsole = MyTestOutputConsole(toolOutputEditor) return toolOutputConsole!! } } private fun DefaultTreeModel.toMap(): MutableMap<ExternalToolGroup, List<ExternalTool>> { val root = this.root as DefaultMutableTreeNode val model = mutableMapOf<ExternalToolGroup, List<ExternalTool>>() for (group in root.children()) { if (group.childCount == 0) continue val groupNode = group as DefaultMutableTreeNode val tools = mutableListOf<ExternalTool>() for (child in group.children()) { val childNode = child as DefaultMutableTreeNode val tool = childNode.userObject as ExternalTool tools.add(tool) } model[groupNode.userObject as ExternalToolGroup] = tools } return model } private fun DefaultTreeModel.update(value: Map<ExternalToolGroup, List<ExternalTool>>) { val root = this.root as DefaultMutableTreeNode root.removeAllChildren() value.toSortedMap().forEach { (group, tools) -> if (tools.isEmpty()) return@forEach val groupNode = DefaultMutableTreeNode(group) tools.forEach { groupNode.add(DefaultMutableTreeNode(it)) } insertNodeInto(groupNode, root, root.childCount) } nodeStructureChanged(root) } private fun ListTableModel<ExternalDiffSettings.ExternalToolConfiguration>.updateEntities( toolGroup: ExternalToolGroup, oldTool: ExternalTool, newTool: ExternalTool ) { items.forEach { configuration -> if (toolGroup == ExternalToolGroup.DIFF_TOOL) { if (configuration.diffToolName == oldTool.name) { configuration.diffToolName = newTool.name } } else { if (configuration.mergeToolName == oldTool.name) { configuration.mergeToolName = newTool.name } } } } companion object { private const val DIFF_TOOL_DEFAULT_ARGUMENT_PATTERN = "%1 %2 %3" private const val MERGE_TOOL_DEFAULT_ARGUMENT_PATTERN = "%1 %2 %3 %4" } private class MyTestOutputConsole(private val editor: Editor) : ExternalDiffToolUtil.TestOutputConsole, Disposable { private val document = editor.document private val modalityState = ModalityState.stateForComponent(editor.component) private var isDisposed: Boolean = false private var wasTerminated: Boolean = false // better handling for out-of-order events init { document.setText("") } override fun getComponent(): JComponent = editor.component override fun appendOutput(outputType: Key<*>, line: String) { appendText("$outputType: $line", false) } override fun processTerminated(exitCode: Int) { appendText(DiffBundle.message("settings.external.tools.test.process.exit.text", exitCode), true) } private fun appendText(text: String, isTermination: Boolean) { runInEdt(modalityState) { if (isDisposed) return@runInEdt // the next test session has started if (isTermination) wasTerminated = true val offset = if (!isTermination && wasTerminated && document.lineCount > 1) { // the last line is termination line, insert output next-to-last-line document.getLineStartOffset(document.lineCount - 2) // -2, as process termination line also ends with \n } else { // insert into the end document.textLength } val line = if (text.endsWith('\n')) text else text + '\n' document.insertString(offset, line) } } override fun dispose() { isDisposed = true } } }
platform/diff-impl/src/com/intellij/diff/settings/ExternalToolsTreePanel.kt
1810345984
KtNamedFunction: B.foo
plugins/kotlin/fir/testData/search/implementations/methods/singleSuperMethod.result.kt
955449383
// 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.search.usagesSearch.operators import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceOrNull import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.uast.UMethod import org.jetbrains.uast.UastContext import org.jetbrains.uast.convertOpt class InvokeOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtCallExpression>(targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = emptyList()) { private val callArgumentsSize: Int? init { val uastContext = targetFunction.project.serviceOrNull<UastContext>() callArgumentsSize = when { uastContext != null -> { val uMethod = uastContext.convertOpt<UMethod>(targetDeclaration, null) val uastParameters = uMethod?.uastParameters if (uastParameters != null) { val isStableNumberOfArguments = uastParameters.none { uParameter -> @Suppress("UElementAsPsi") uParameter.uastInitializer != null || uParameter.isVarArgs } if (isStableNumberOfArguments) { val numberOfArguments = uastParameters.size when { targetFunction.isExtensionDeclaration() -> numberOfArguments - 1 else -> numberOfArguments } } else { null } } else { null } } else -> null } } override fun processPossibleReceiverExpression(expression: KtExpression) { val callExpression = expression.parent as? KtCallExpression ?: return processReferenceElement(callExpression) } override fun isReferenceToCheck(ref: PsiReference) = ref is KtInvokeFunctionReference override fun extractReference(element: KtElement): PsiReference? { val callExpression = element as? KtCallExpression ?: return null if (callArgumentsSize != null && callArgumentsSize != callExpression.valueArguments.size) { return null } return callExpression.references.firstIsInstance<KtInvokeFunctionReference>() } }
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/InvokeOperatorReferenceSearcher.kt
3607514580
sealed class X { internal abstract fun /*rename*/overridableMethod(x: Int): Int abstract class Y : X() { override fun overridableMethod(x: Int): Int = 1 } class Z : Y() { override fun overridableMethod(x: Int): Int = if (x > 0) x else super.overridableMethod(x) } } fun get() : X? { return X.Z() } fun test() { get()?.overridableMethod(2) }
plugins/kotlin/idea/tests/testData/refactoring/rename/internalFunWithOverrides/before/test.kt
4226363836
// 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.internal.statistic.eventLog import com.intellij.internal.statistic.utils.StatisticsUploadAssistant import com.intellij.openapi.util.registry.Registry class FeatureUsageFileEventLoggerProvider : FeatureUsageEventLoggerProvider { override fun createLogger(): FeatureUsageEventLogger { return FeatureUsageFileEventLogger() } override fun isEnabled() : Boolean { return StatisticsUploadAssistant.isSendAllowed() && Registry.`is`("feature.usage.event.log.collect.and.upload") } }
platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageFileEventLoggerProvider.kt
99703112
package org.thoughtcrime.securesms.keyvalue import androidx.annotation.WorkerThread import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.Subject import org.signal.core.util.logging.Log import org.signal.donations.StripeApi import org.thoughtcrime.securesms.badges.Badges import org.thoughtcrime.securesms.badges.models.Badge import org.thoughtcrime.securesms.database.model.databaseprotos.BadgeList import org.thoughtcrime.securesms.jobs.SubscriptionReceiptRequestResponseJob import org.thoughtcrime.securesms.payments.currency.CurrencyUtil import org.thoughtcrime.securesms.subscription.LevelUpdateOperation import org.thoughtcrime.securesms.subscription.Subscriber import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription import org.whispersystems.signalservice.api.subscriptions.IdempotencyKey import org.whispersystems.signalservice.api.subscriptions.SubscriberId import org.whispersystems.signalservice.internal.util.JsonUtil import java.util.Currency import java.util.Locale import java.util.concurrent.TimeUnit internal class DonationsValues internal constructor(store: KeyValueStore) : SignalStoreValues(store) { companion object { private val TAG = Log.tag(DonationsValues::class.java) private const val KEY_SUBSCRIPTION_CURRENCY_CODE = "donation.currency.code" private const val KEY_CURRENCY_CODE_ONE_TIME = "donation.currency.code.boost" private const val KEY_SUBSCRIBER_ID_PREFIX = "donation.subscriber.id." private const val KEY_LAST_KEEP_ALIVE_LAUNCH = "donation.last.successful.ping" private const val KEY_LAST_END_OF_PERIOD_SECONDS = "donation.last.end.of.period" private const val EXPIRED_BADGE = "donation.expired.badge" private const val EXPIRED_GIFT_BADGE = "donation.expired.gift.badge" private const val USER_MANUALLY_CANCELLED = "donation.user.manually.cancelled" private const val KEY_LEVEL_OPERATION_PREFIX = "donation.level.operation." private const val KEY_LEVEL_HISTORY = "donation.level.history" private const val DISPLAY_BADGES_ON_PROFILE = "donation.display.badges.on.profile" private const val SUBSCRIPTION_REDEMPTION_FAILED = "donation.subscription.redemption.failed" private const val SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT = "donation.should.cancel.subscription.before.next.subscribe.attempt" private const val SUBSCRIPTION_CANCELATION_CHARGE_FAILURE = "donation.subscription.cancelation.charge.failure" private const val SUBSCRIPTION_CANCELATION_REASON = "donation.subscription.cancelation.reason" private const val SUBSCRIPTION_CANCELATION_TIMESTAMP = "donation.subscription.cancelation.timestamp" private const val SUBSCRIPTION_CANCELATION_WATERMARK = "donation.subscription.cancelation.watermark" private const val SHOW_CANT_PROCESS_DIALOG = "show.cant.process.dialog" } override fun onFirstEverAppLaunch() = Unit override fun getKeysToIncludeInBackup(): MutableList<String> = mutableListOf( KEY_CURRENCY_CODE_ONE_TIME, KEY_LAST_KEEP_ALIVE_LAUNCH, KEY_LAST_END_OF_PERIOD_SECONDS, SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, SUBSCRIPTION_CANCELATION_REASON, SUBSCRIPTION_CANCELATION_TIMESTAMP, SUBSCRIPTION_CANCELATION_WATERMARK, SHOW_CANT_PROCESS_DIALOG ) private val subscriptionCurrencyPublisher: Subject<Currency> by lazy { BehaviorSubject.createDefault(getSubscriptionCurrency()) } val observableSubscriptionCurrency: Observable<Currency> by lazy { subscriptionCurrencyPublisher } private val oneTimeCurrencyPublisher: Subject<Currency> by lazy { BehaviorSubject.createDefault(getOneTimeCurrency()) } val observableOneTimeCurrency: Observable<Currency> by lazy { oneTimeCurrencyPublisher } fun getSubscriptionCurrency(): Currency { val currencyCode = getString(KEY_SUBSCRIPTION_CURRENCY_CODE, null) val currency: Currency? = if (currencyCode == null) { val localeCurrency = CurrencyUtil.getCurrencyByLocale(Locale.getDefault()) if (localeCurrency == null) { val e164: String? = SignalStore.account().e164 if (e164 == null) { null } else { CurrencyUtil.getCurrencyByE164(e164) } } else { localeCurrency } } else { CurrencyUtil.getCurrencyByCurrencyCode(currencyCode) } return if (currency != null && StripeApi.Validation.supportedCurrencyCodes.contains(currency.currencyCode.uppercase(Locale.ROOT))) { currency } else { Currency.getInstance("USD") } } fun getOneTimeCurrency(): Currency { val oneTimeCurrency = getString(KEY_CURRENCY_CODE_ONE_TIME, null) return if (oneTimeCurrency == null) { val currency = getSubscriptionCurrency() setOneTimeCurrency(currency) currency } else { Currency.getInstance(oneTimeCurrency) } } fun setOneTimeCurrency(currency: Currency) { putString(KEY_CURRENCY_CODE_ONE_TIME, currency.currencyCode) oneTimeCurrencyPublisher.onNext(currency) } fun getSubscriber(currency: Currency): Subscriber? { val currencyCode = currency.currencyCode val subscriberIdBytes = getBlob("$KEY_SUBSCRIBER_ID_PREFIX$currencyCode", null) return if (subscriberIdBytes == null) { null } else { Subscriber(SubscriberId.fromBytes(subscriberIdBytes), currencyCode) } } fun getSubscriber(): Subscriber? { return getSubscriber(getSubscriptionCurrency()) } fun requireSubscriber(): Subscriber { return getSubscriber() ?: throw Exception("Subscriber ID is not set.") } fun setSubscriber(subscriber: Subscriber) { Log.i(TAG, "Setting subscriber for currency ${subscriber.currencyCode}", Exception(), true) val currencyCode = subscriber.currencyCode store.beginWrite() .putBlob("$KEY_SUBSCRIBER_ID_PREFIX$currencyCode", subscriber.subscriberId.bytes) .putString(KEY_SUBSCRIPTION_CURRENCY_CODE, currencyCode) .apply() subscriptionCurrencyPublisher.onNext(Currency.getInstance(currencyCode)) } fun getLevelOperation(level: String): LevelUpdateOperation? { val idempotencyKey = getBlob("${KEY_LEVEL_OPERATION_PREFIX}$level", null) return if (idempotencyKey != null) { LevelUpdateOperation(IdempotencyKey.fromBytes(idempotencyKey), level) } else { null } } fun setLevelOperation(levelUpdateOperation: LevelUpdateOperation) { addLevelToHistory(levelUpdateOperation.level) putBlob("$KEY_LEVEL_OPERATION_PREFIX${levelUpdateOperation.level}", levelUpdateOperation.idempotencyKey.bytes) } private fun getLevelHistory(): Set<String> { return getString(KEY_LEVEL_HISTORY, "").split(",").toSet() } private fun addLevelToHistory(level: String) { val levels = getLevelHistory() + level putString(KEY_LEVEL_HISTORY, levels.joinToString(",")) } fun clearLevelOperations() { val levelHistory = getLevelHistory() val write = store.beginWrite() for (level in levelHistory) { write.remove("${KEY_LEVEL_OPERATION_PREFIX}$level") } write.apply() } fun setExpiredBadge(badge: Badge?) { if (badge != null) { putBlob(EXPIRED_BADGE, Badges.toDatabaseBadge(badge).toByteArray()) } else { remove(EXPIRED_BADGE) } } fun getExpiredBadge(): Badge? { val badgeBytes = getBlob(EXPIRED_BADGE, null) ?: return null return Badges.fromDatabaseBadge(BadgeList.Badge.parseFrom(badgeBytes)) } fun setExpiredGiftBadge(badge: Badge?) { if (badge != null) { putBlob(EXPIRED_GIFT_BADGE, Badges.toDatabaseBadge(badge).toByteArray()) } else { remove(EXPIRED_GIFT_BADGE) } } fun getExpiredGiftBadge(): Badge? { val badgeBytes = getBlob(EXPIRED_GIFT_BADGE, null) ?: return null return Badges.fromDatabaseBadge(BadgeList.Badge.parseFrom(badgeBytes)) } fun getLastKeepAliveLaunchTime(): Long { return getLong(KEY_LAST_KEEP_ALIVE_LAUNCH, 0L) } fun setLastKeepAliveLaunchTime(timestamp: Long) { putLong(KEY_LAST_KEEP_ALIVE_LAUNCH, timestamp) } fun getLastEndOfPeriod(): Long { return getLong(KEY_LAST_END_OF_PERIOD_SECONDS, 0L) } fun setLastEndOfPeriod(timestamp: Long) { putLong(KEY_LAST_END_OF_PERIOD_SECONDS, timestamp) } /** * True if the local user is likely a sustainer, otherwise false. Note the term 'likely', because this is based on cached data. Any serious decisions that * rely on this should make a network request to determine subscription status. */ fun isLikelyASustainer(): Boolean { return TimeUnit.SECONDS.toMillis(getLastEndOfPeriod()) > System.currentTimeMillis() } fun isUserManuallyCancelled(): Boolean { return getBoolean(USER_MANUALLY_CANCELLED, false) } fun markUserManuallyCancelled() { putBoolean(USER_MANUALLY_CANCELLED, true) } fun clearUserManuallyCancelled() { remove(USER_MANUALLY_CANCELLED) } fun setDisplayBadgesOnProfile(enabled: Boolean) { putBoolean(DISPLAY_BADGES_ON_PROFILE, enabled) } fun getDisplayBadgesOnProfile(): Boolean { return getBoolean(DISPLAY_BADGES_ON_PROFILE, false) } fun getSubscriptionRedemptionFailed(): Boolean { return getBoolean(SUBSCRIPTION_REDEMPTION_FAILED, false) } fun markSubscriptionRedemptionFailed() { Log.w(TAG, "markSubscriptionRedemptionFailed()", Throwable(), true) putBoolean(SUBSCRIPTION_REDEMPTION_FAILED, true) } fun clearSubscriptionRedemptionFailed() { putBoolean(SUBSCRIPTION_REDEMPTION_FAILED, false) } fun setUnexpectedSubscriptionCancelationChargeFailure(chargeFailure: ActiveSubscription.ChargeFailure?) { if (chargeFailure == null) { remove(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE) } else { putString(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE, JsonUtil.toJson(chargeFailure)) } } fun getUnexpectedSubscriptionCancelationChargeFailure(): ActiveSubscription.ChargeFailure? { val json = getString(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE, null) return if (json.isNullOrEmpty()) { null } else { JsonUtil.fromJson(json, ActiveSubscription.ChargeFailure::class.java) } } var unexpectedSubscriptionCancelationReason: String? by stringValue(SUBSCRIPTION_CANCELATION_REASON, null) var unexpectedSubscriptionCancelationTimestamp: Long by longValue(SUBSCRIPTION_CANCELATION_TIMESTAMP, 0L) var unexpectedSubscriptionCancelationWatermark: Long by longValue(SUBSCRIPTION_CANCELATION_WATERMARK, 0L) @get:JvmName("showCantProcessDialog") var showCantProcessDialog: Boolean by booleanValue(SHOW_CANT_PROCESS_DIALOG, true) /** * Denotes that the previous attempt to subscribe failed in some way. Either an * automatic renewal failed resulting in an unexpected expiration, or payment failed * on Stripe's end. * * Before trying to resubscribe, we should first ensure there are no subscriptions set * on the server. Otherwise, we could get into a situation where the user is unable to * resubscribe. */ var shouldCancelSubscriptionBeforeNextSubscribeAttempt: Boolean get() = getBoolean(SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, false) set(value) = putBoolean(SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, value) /** * Consolidates a bunch of data clears that should occur whenever a user manually cancels their * subscription: * * 1. Clears keep-alive flag * 1. Clears level operation * 1. Marks the user as manually cancelled * 1. Clears out unexpected cancelation state * 1. Clears expired badge if it is for a subscription */ @WorkerThread fun updateLocalStateForManualCancellation() { synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) { Log.d(TAG, "[updateLocalStateForManualCancellation] Clearing donation values.") setLastEndOfPeriod(0L) clearLevelOperations() markUserManuallyCancelled() shouldCancelSubscriptionBeforeNextSubscribeAttempt = false setUnexpectedSubscriptionCancelationChargeFailure(null) unexpectedSubscriptionCancelationReason = null unexpectedSubscriptionCancelationTimestamp = 0L val expiredBadge = getExpiredBadge() if (expiredBadge != null && expiredBadge.isSubscription()) { Log.d(TAG, "[updateLocalStateForManualCancellation] Clearing expired badge.") setExpiredBadge(null) } } } /** * Consolidates a bunch of data clears that should occur whenever a user begins a new subscription: * * 1. Manual cancellation marker * 1. Any set level operations * 1. Unexpected cancelation flags * 1. Expired badge, if it is of a subscription */ @WorkerThread fun updateLocalStateForLocalSubscribe() { synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) { Log.d(TAG, "[updateLocalStateForLocalSubscribe] Clearing donation values.") clearUserManuallyCancelled() clearLevelOperations() shouldCancelSubscriptionBeforeNextSubscribeAttempt = false setUnexpectedSubscriptionCancelationChargeFailure(null) unexpectedSubscriptionCancelationReason = null unexpectedSubscriptionCancelationTimestamp = 0L val expiredBadge = getExpiredBadge() if (expiredBadge != null && expiredBadge.isSubscription()) { Log.d(TAG, "[updateLocalStateForLocalSubscribe] Clearing expired badge.") setExpiredBadge(null) } } } }
app/src/main/java/org/thoughtcrime/securesms/keyvalue/DonationsValues.kt
3390410513
package com.strumenta.kolasu.codegen import com.strumenta.kolasu.model.ReferenceByName import org.junit.Test import kotlin.test.assertEquals class ASTCodeGeneratorTest { @Test fun printSimpleKotlinExpression() { val ex = KMethodCallExpression( KThisExpression(), ReferenceByName("myMethod"), mutableListOf(KStringLiteral("abc"), KIntLiteral(123), KStringLiteral("qer")) ) val code = KotlinPrinter().printToString(ex) assertEquals("""this.myMethod("abc", 123, "qer")""", code) } @Test fun printSimpleFile() { val cu = KCompilationUnit( KPackageDecl("my.splendid.packag"), mutableListOf(KImport("my.imported.stuff")), mutableListOf(KFunctionDeclaration("foo")), ) val code = KotlinPrinter().printToString(cu) assertEquals( """package my.splendid.packag | |import my.imported.stuff | | |fun foo() { |} | """.trimMargin(), code ) } }
core/src/test/kotlin/com/strumenta/kolasu/codegen/ASTCodeGeneratorTest.kt
1201861311
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.flexbox import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView /** * Implementation for the [FlexItemChangedListener]. * It expects RecyclerView as the underlying flex container implementation. */ internal class FlexItemChangedListenerImplRecyclerView(private val flexContainer: FlexContainer, private val adapter: RecyclerView.Adapter<*>) : FlexItemChangedListener { override fun onFlexItemChanged(flexItem: FlexItem, viewIndex: Int) { val view = flexContainer.getFlexItemAt(viewIndex) view.layoutParams = flexItem as ViewGroup.LayoutParams adapter.notifyDataSetChanged() // TODO: An Exception is thrown if notifyItemChanged(int) is used. // Investigate that, but using LinearLayoutManager also produces the same Exception // java.lang.IllegalArgumentException: Called attach on a child which is not detached: } }
demo-playground/src/main/java/com/google/android/flexbox/FlexItemChangedListenerImplRecyclerView.kt
3079413601
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* import kotlinx.coroutines.* /** * A frame received or ready to be sent. It is not reusable and not thread-safe * @property fin is it final fragment, should be always `true` for control frames and if no fragmentation is used * @property frameType enum value * @property data - a frame content or fragment content * @property disposableHandle could be invoked when the frame is processed */ public expect sealed class Frame private constructor( fin: Boolean, frameType: FrameType, data: ByteArray, disposableHandle: DisposableHandle = NonDisposableHandle, rsv1: Boolean = false, rsv2: Boolean = false, rsv3: Boolean = false ) { public val fin: Boolean /** * First extension bit. */ public val rsv1: Boolean /** * Second extension bit. */ public val rsv2: Boolean /** * Third extension bit. */ public val rsv3: Boolean public val frameType: FrameType public val data: ByteArray public val disposableHandle: DisposableHandle /** * Represents an application level binary frame. * In a RAW web socket session a big text frame could be fragmented * (separated into several text frames so they have [fin] = false except the last one). * Note that usually there is no need to handle fragments unless you have a RAW web socket session. */ public class Binary public constructor( fin: Boolean, data: ByteArray, rsv1: Boolean = false, rsv2: Boolean = false, rsv3: Boolean = false ) : Frame { public constructor(fin: Boolean, data: ByteArray) public constructor(fin: Boolean, packet: ByteReadPacket) } /** * Represents an application level text frame. * In a RAW web socket session a big text frame could be fragmented * (separated into several text frames so they have [fin] = false except the last one). * Please note that a boundary between fragments could be in the middle of multi-byte (unicode) character * so don't apply String constructor to every fragment but use decoder loop instead of concatenate fragments first. * Note that usually there is no need to handle fragments unless you have a RAW web socket session. */ public class Text public constructor( fin: Boolean, data: ByteArray, rsv1: Boolean = false, rsv2: Boolean = false, rsv3: Boolean = false, ) : Frame { public constructor(fin: Boolean, data: ByteArray) public constructor(text: String) public constructor(fin: Boolean, packet: ByteReadPacket) } /** * Represents a low-level level close frame. It could be sent to indicate web socket session end. * Usually there is no need to send/handle it unless you have a RAW web socket session. */ public class Close(data: ByteArray) : Frame { public constructor(reason: CloseReason) public constructor(packet: ByteReadPacket) public constructor() } /** * Represents a low-level ping frame. Could be sent to test connection (peer should reply with [Pong]). * Usually there is no need to send/handle it unless you have a RAW web socket session. */ public class Ping(data: ByteArray) : Frame { public constructor(packet: ByteReadPacket) } /** * Represents a low-level pong frame. Should be sent in reply to a [Ping] frame. * Usually there is no need to send/handle it unless you have a RAW web socket session. */ public class Pong( data: ByteArray, disposableHandle: DisposableHandle = NonDisposableHandle ) : Frame { public constructor(packet: ByteReadPacket) } /** * Creates a frame copy */ public fun copy(): Frame public companion object { /** * Create a particular [Frame] instance by frame type */ public fun byType( fin: Boolean, frameType: FrameType, data: ByteArray, rsv1: Boolean, rsv2: Boolean, rsv3: Boolean ): Frame } } /** * Read text content from text frame. Shouldn't be used for fragmented frames: such frames need to be reassembled first */ public fun Frame.Text.readText(): String { require(fin) { "Text could be only extracted from non-fragmented frame" } return Charsets.UTF_8.newDecoder().decode(buildPacket { writeFully(data) }) } /** * Read binary content from a frame. For fragmented frames only returns this fragment. */ public fun Frame.readBytes(): ByteArray { return data.copyOf() } /** * Read close reason from close frame or null if no close reason provided */ @Suppress("CONFLICTING_OVERLOADS") public fun Frame.Close.readReason(): CloseReason? { if (data.size < 2) { return null } val packet = buildPacket { writeFully(data) } val code = packet.readShort() val message = packet.readText() return CloseReason(code, message) } internal object NonDisposableHandle : DisposableHandle { override fun dispose() {} override fun toString(): String = "NonDisposableHandle" }
ktor-shared/ktor-websockets/common/src/io/ktor/websocket/FrameCommon.kt
1857748208