content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/** * * by Cherepanov Aleksei (PI-171) * * [email protected] * **/ package RBTree import Interfaces.Tree class RedBlackTree<K:Comparable<K>,V>:Tree<K,V>, Iterable<RBNode<K, V>>{ /*private*/var root: RBNode<K,V>? = null override fun insert(key:K,value:V){ val newNode = RBNode(key, value) var y:RBNode<K,V>?=null var x:RBNode<K,V>?=this.root while (x!=null){ y=x when { newNode.key < x.key -> x= x.left newNode.key > x.key -> x=x.right newNode.key == x.key -> { x.value = newNode.value return } } } newNode.parent=y if(y==null) { this.root=newNode } else if(newNode.key<y.key){ y.left=newNode } else{ y.right=newNode } newNode.color=true newNode.right=null newNode.left=null this.stabilization(newNode) } fun stabilization(newNode: RBNode<K, V>?){ var z = newNode var y:RBNode<K,V>? while(z!!.parent?.color==true){ if (z.parent== z.parent?.parent?.left){ y=z.parent!!.parent!!.right if(y?.color ==true){ z.parent!!.color=false y.color=false z.parent!!.parent!!.color=true z=z.parent!!.parent }else if(z== z.parent!!.right){ z=z.parent leftRotate(z!!) }else if(z==z.parent!!.left) { z.parent!!.color = false z.parent!!.parent!!.color = true rightRotate(z.parent!!.parent!!) } }else{ y= z.parent?.parent?.left if(y?.color==true){ z.parent!!.color=false y.color=false z.parent!!.parent!!.color=true z=z.parent!!.parent }else if(z== z.parent!!.left){ z=z.parent rightRotate(z!!) }else if(z== z.parent!!.right) { z.parent!!.color = false z.parent?.parent?.color = true leftRotate(z.parent!!.parent!!) } } } this.root!!.color=false } override fun delete(key: K) { val node = searchNode(key, root) ?: return val min = searchMin(node.right) when { ((node.right != null) && (node.left != null)) -> { val nextKey = min!!.key val nextValue = min.value delete(min.key) node.key = nextKey node.value = nextValue } ((node == root) && (node.right == null && node.left == null)) -> { root = null return } (node.color == true && node.right == null && node.left == null) -> { if (node.key < node.parent!!.key) { node.parent!!.left = null } else { node.parent!!.right = null } return } (node.color == false && ((node.left != null) && (node.left!!.color == true))) -> { node.key = node.left!!.key node.value = node.left!!.value node.left = null return } (node.color == false && (node.right != null) && (node.right!!.color == true)) -> { node.key = node.right!!.key node.value = node.right!!.value node.right = null return } else -> { deleteCase1(node) } } if (node.key == key) { if (node.key < node.parent!!.key) { node.parent!!.left = null } else { node.parent!!.right = null } } return } private fun deleteCase1(node: RBNode<K,V>) { if (node == root) { node.color = false return } val brother = node.brother() if (brother!!.color) { node.parent!!.recoloring() brother.recoloring() if (node == node.parent!!.left) { leftRotate(node.parent!!) } else { rightRotate(node.parent!!) } deleteCase1(node) return } deleteCase2(node) } private fun deleteCase2(node: RBNode<K,V>) { val brother = node.brother() if (((brother!!.left == null) || !brother.left!!.color) && ((brother.right == null) || !brother.right!!.color)) { node.color = false brother.recoloring() if (node.parent!!.color == true) { node.parent!!.recoloring() return } deleteCase1(node.parent!!) return } if (node == node.parent!!.left) { deleteCase3(node) } else { deleteCase4(node) } } private fun deleteCase3(node: RBNode<K,V>) { val brother = node.brother() if ((brother!!.right == null) || brother.right!!.color == false) { brother.recoloring() brother.left!!.recoloring() rightRotate(brother) deleteCase1(node) return } deleteCase3_2(node) } private fun deleteCase4(node: RBNode<K,V>) { val brother = node.brother() if ((brother!!.left == null) || brother.left!!.color == false) { brother.recoloring() brother.right!!.recoloring() leftRotate(brother) deleteCase1(node) return } deleteCase4_2(node) } private fun deleteCase3_2(node: RBNode<K,V>) { val brother = node.brother() if ((brother!!.right != null) && brother.right!!.color == true) { brother.color = node.parent!!.color node.color = false node.parent!!.color = false brother.right!!.color = false leftRotate(node.parent!!) return } } private fun deleteCase4_2(node: RBNode<K,V>) { val brother = node.brother() if ((brother!!.left != null) && brother.left!!.color == true) { brother.color = node.parent!!.color node.color = false node.parent!!.color = false brother.left!!.color = false rightRotate(node.parent!!) return } } private fun leftRotate(x: RBNode<K,V>?){ val y:RBNode<K,V>?= x?.right x?.right= y?.left y?.left?.parent=x y?.parent =x?.parent if(x?.parent==null){ this.root=y } if(x == x?.parent?.left){ x?.parent?.left=y } if(x== x?.parent?.right){ x?.parent?.right=y } y?.left =x x?.parent=y } private fun rightRotate(x: RBNode<K,V>?){ val y:RBNode<K,V>?= x!!.left x.left= y!!.right y.right?.parent=x y.parent=x.parent if(x.parent==null){ this.root=y } if(x==x.parent?.right){ x.parent?.right=y } if(x==x.parent?.left){ x.parent!!.left=y } y.right=x x.parent=y } override fun search(key: K)=searchNode(key)?.value /*private*/fun searchNode(key: K, node: RBNode<K,V>?=root): RBNode<K,V>? { if(node==null) return null if(key == node.key)return node if(key < node.key) return searchNode(key, node.left) else return searchNode(key, node.right) } private fun searchMax(node: RBNode<K, V>?=root): RBNode<K, V>? { var max = node while (max?.right != null) { max = max.right } return max } private fun searchMin(node: RBNode<K, V>?=root): RBNode<K, V>? { var min = node while (min?.left != null) { min = min.left } return min } override fun iterator(): Iterator<RBNode<K, V>> { return (object : Iterator<RBNode<K, V>> { var node = searchMax() var next = searchMax() val last = searchMin() override fun hasNext(): Boolean { return (node != null) && (node!!.key >= last!!.key) } override fun next(): RBNode<K, V> { next = node node = nextSmaller(node) return next!! } }) } private fun nextSmaller(node: RBNode<K, V>?): RBNode<K, V>?{ var smaller = node ?: return null if ((smaller.left != null)) { return searchMax(smaller.left!!) } else if ((smaller == smaller.parent?.left)) { while (smaller == smaller.parent?.left) { smaller = smaller.parent!! } } return smaller.parent } }
src/RBTree/RBTree.kt
892397425
package de.codehat.signcolors.permission enum class Permissions(private var permission: String) { ALL("signcolors.all"), CMD_INFO("signcolors.command.info"), CMD_HELP("signcolors.command.help"), CMD_RELOAD("signcolors.command.reload"), CMD_COLOR_CODES("signcolors.command.colorcodes"), CMD_GIVE_SIGN("signcolors.command.givesign"), CMD_MIGRATE_DATABASE("signcolors.command.migratedatabase"), SPECIAL_SIGN_CREATE("signcolors.specialsign.create"), SPECIAL_SIGN_USE("signcolors.specialsign.use"), USE_SPECIFIC_COLOR("signcolors.color."), USE_SPECIFIC_FORMAT("signcolors.formatting."), USE_ALL_COLORS("signcolors.color.all"), USE_ALL_FORMATS("signcolors.formatting.all"), BYPASS_SIGN_CRAFTING("signcolors.craftsigns.bypass"), BYPASS_BLOCKED_FIRST_LINES("signcolors.blockedfirstlines.bypass"), SHOW_UPDATE_MESSAGE("signcolors.updatemessage"); override fun toString() = permission }
src/main/kotlin/de/codehat/signcolors/permission/Permissions.kt
1393750321
/* * Copyright (c) 2015 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.app.util.timeago internal class HoursAgoPrinter(private val currentTimer: CurrentTimer) : TimePrettyPrinter { override fun print(referenceTime: Long): String { val currentTimeInMills = currentTimer.inMills val diff = currentTimeInMills - referenceTime return "${diff / HOUR_IN_MILLS } ชั่วโมงที่แล้ว" } }
ffc/src/main/kotlin/ffc/app/util/timeago/HoursAgoPrinter.kt
3740294378
package org.wikipedia.page import android.location.Location import android.os.Parcelable import kotlinx.parcelize.IgnoredOnParcel import kotlinx.parcelize.Parcelize import kotlinx.parcelize.TypeParceler import org.wikipedia.auth.AccountUtil import org.wikipedia.dataclient.page.PageSummary import org.wikipedia.dataclient.page.Protection import org.wikipedia.parcel.DateParceler import org.wikipedia.util.DateUtil import org.wikipedia.util.DimenUtil import org.wikipedia.util.ImageUrlUtil import org.wikipedia.util.UriUtil import java.util.* @Parcelize @TypeParceler<Date, DateParceler>() data class PageProperties constructor( val pageId: Int = 0, val namespace: Namespace, val revisionId: Long = 0, val lastModified: Date = Date(), val displayTitle: String = "", private var editProtectionStatus: String = "", val isMainPage: Boolean = false, /** Nullable URL with no scheme. For example, foo.bar.com/ instead of http://foo.bar.com/. */ val leadImageUrl: String? = null, val leadImageName: String? = null, val leadImageWidth: Int = 0, val leadImageHeight: Int = 0, val geo: Location? = null, val wikiBaseItem: String? = null, val descriptionSource: String? = null, // FIXME: This is not a true page property, since it depends on current user. var canEdit: Boolean = false ) : Parcelable { @IgnoredOnParcel var protection: Protection? = null set(value) { field = value editProtectionStatus = value?.firstAllowedEditorRole.orEmpty() canEdit = editProtectionStatus.isEmpty() || isLoggedInUserAllowedToEdit } /** * Side note: Should later be moved out of this class but I like the similarities with * PageProperties(JSONObject). */ constructor(pageSummary: PageSummary) : this( pageSummary.pageId, pageSummary.ns, pageSummary.revision, if (pageSummary.timestamp.isEmpty()) Date() else DateUtil.iso8601DateParse(pageSummary.timestamp), pageSummary.displayTitle, isMainPage = pageSummary.type == PageSummary.TYPE_MAIN_PAGE, leadImageUrl = pageSummary.thumbnailUrl?.let { ImageUrlUtil.getUrlForPreferredSize(it, DimenUtil.calculateLeadImageWidth()) }, leadImageName = UriUtil.decodeURL(pageSummary.leadImageName.orEmpty()), leadImageWidth = pageSummary.thumbnailWidth, leadImageHeight = pageSummary.thumbnailHeight, geo = pageSummary.geo, wikiBaseItem = pageSummary.wikiBaseItem, descriptionSource = pageSummary.descriptionSource ) constructor(title: PageTitle, isMainPage: Boolean) : this(namespace = title.namespace(), displayTitle = title.displayText, isMainPage = isMainPage) private val isLoggedInUserAllowedToEdit: Boolean get() = protection?.run { AccountUtil.isMemberOf(editRoles) } ?: false }
app/src/main/java/org/wikipedia/page/PageProperties.kt
3525676436
package com.sapuseven.untis.models import com.sapuseven.untis.models.untis.UntisDateTime import com.sapuseven.untis.models.untis.UntisTime import kotlinx.serialization.Serializable @Serializable data class UntisExam( val id: Int, val examType: String?, val startDateTime: UntisDateTime, val endDateTime: UntisDateTime, val departmentId: Int, val subjectId: Int, val klasseIds: List<Int>, val roomIds: List<Int>, val teacherIds: List<Int>, val invigilators: List<UntisInvigilator>, val name: String, val text: String ) @Serializable data class UntisInvigilator( val id: Int, val startTime: UntisTime, val endTime: UntisTime )
app/src/main/java/com/sapuseven/untis/models/UntisExam.kt
836415103
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.sample.embedding import android.content.ComponentName import android.content.Intent import android.os.Build import android.os.Bundle import android.view.View import android.widget.CompoundButton import android.widget.RadioGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.util.Consumer import androidx.window.embedding.ActivityFilter import androidx.window.embedding.EmbeddingRule import androidx.window.embedding.SplitController import androidx.window.embedding.SplitInfo import androidx.window.embedding.SplitPairFilter import androidx.window.embedding.SplitPairRule import androidx.window.embedding.SplitPlaceholderRule import androidx.window.embedding.SplitRule import androidx.window.sample.R import androidx.window.sample.databinding.ActivitySplitPipActivityLayoutBinding import androidx.window.sample.util.PictureInPictureUtil.setPictureInPictureParams import androidx.window.sample.util.PictureInPictureUtil.startPictureInPicture /** * Sample showcase of split activity rules with picture-in-picture. Allows the user to select some * split and PiP configuration options with checkboxes and launch activities with those options * applied. */ abstract class SplitPipActivityBase : AppCompatActivity(), CompoundButton.OnCheckedChangeListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener { lateinit var splitController: SplitController lateinit var viewBinding: ActivitySplitPipActivityLayoutBinding lateinit var componentNameA: ComponentName lateinit var componentNameB: ComponentName lateinit var componentNameNotPip: ComponentName lateinit var componentNamePlaceholder: ComponentName private val splitChangeListener = SplitStateChangeListener() private val splitRatio = 0.5f private var enterPipOnUserLeave = false private var autoEnterPip = false /** In the process of updating checkboxes based on split rule. */ private var updatingConfigs = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivitySplitPipActivityLayoutBinding.inflate(layoutInflater) setContentView(viewBinding.root) componentNameA = ComponentName(packageName, SplitPipActivityA::class.java.name) componentNameB = ComponentName(packageName, SplitPipActivityB::class.java.name) componentNameNotPip = ComponentName(packageName, SplitPipActivityNoPip::class.java.name) componentNamePlaceholder = ComponentName(packageName, SplitPipActivityPlaceholder::class.java.name) splitController = SplitController.getInstance(this) // Buttons for split rules of the main activity. viewBinding.splitMainCheckBox.setOnCheckedChangeListener(this) viewBinding.finishPrimaryWithSecondaryCheckBox.setOnCheckedChangeListener(this) viewBinding.finishSecondaryWithPrimaryCheckBox.setOnCheckedChangeListener(this) // Buttons for split rules of the secondary activity. viewBinding.launchBButton.setOnClickListener(this) viewBinding.usePlaceHolderCheckBox.setOnCheckedChangeListener(this) viewBinding.useStickyPlaceHolderCheckBox.setOnCheckedChangeListener(this) // Buttons for launching an activity that doesn't support PiP viewBinding.launchNoPipButton.setOnClickListener(this) // Buttons for PiP options. viewBinding.enterPipButton.setOnClickListener(this) viewBinding.supportPipRadioGroup.setOnCheckedChangeListener(this) } /** Called on checkbox changed. */ override fun onCheckedChanged(button: CompoundButton, isChecked: Boolean) { if (button.id == R.id.split_main_check_box) { if (isChecked) { viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = true viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = true } else { viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = false viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked = false viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = false viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked = false } } if (button.id == R.id.use_place_holder_check_box) { if (isChecked) { viewBinding.useStickyPlaceHolderCheckBox.isEnabled = true } else { viewBinding.useStickyPlaceHolderCheckBox.isEnabled = false viewBinding.useStickyPlaceHolderCheckBox.isChecked = false } } if (!updatingConfigs) { updateSplitRules() } } /** Called on button clicked. */ override fun onClick(button: View) { when (button.id) { R.id.launch_b_button -> { startActivity(Intent(this, SplitPipActivityB::class.java)) return } R.id.launch_no_pip_button -> { startActivity(Intent(this, SplitPipActivityNoPip::class.java)) return } R.id.enter_pip_button -> { startPictureInPicture(this, autoEnterPip) } } } /** Called on RatioGroup (PiP options) changed. */ override fun onCheckedChanged(group: RadioGroup, id: Int) { when (id) { R.id.support_pip_not_enter_on_exit -> { enterPipOnUserLeave = false autoEnterPip = false } R.id.support_pip_enter_on_user_leave -> { enterPipOnUserLeave = true autoEnterPip = false } R.id.support_pip_auto_enter -> { enterPipOnUserLeave = false autoEnterPip = true if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { Toast.makeText(this, "auto enter PiP not supported", Toast.LENGTH_LONG) .show() } } } setPictureInPictureParams(this, autoEnterPip) } /** Enters PiP if enterPipOnUserLeave checkbox is checked. */ override fun onUserLeaveHint() { super.onUserLeaveHint() if (enterPipOnUserLeave) { startPictureInPicture(this, autoEnterPip) } } /** Updates the checkboxes states after the split rules are changed by other activity. */ internal fun updateCheckboxes() { updatingConfigs = true val curRules = splitController.getSplitRules() val splitRule = curRules.firstOrNull { isRuleForSplit(it) } val placeholderRule = curRules.firstOrNull { isRuleForPlaceholder(it) } if (splitRule != null && splitRule is SplitPairRule) { viewBinding.splitMainCheckBox.isChecked = true viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = true viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked = splitRule.finishPrimaryWithSecondary == SplitRule.FINISH_ALWAYS viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = true viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked = splitRule.finishSecondaryWithPrimary == SplitRule.FINISH_ALWAYS } else { viewBinding.splitMainCheckBox.isChecked = false viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = false viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked = false viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = false viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked = false } if (placeholderRule != null && placeholderRule is SplitPlaceholderRule) { viewBinding.usePlaceHolderCheckBox.isChecked = true viewBinding.useStickyPlaceHolderCheckBox.isEnabled = true viewBinding.useStickyPlaceHolderCheckBox.isChecked = placeholderRule.isSticky } else { viewBinding.usePlaceHolderCheckBox.isChecked = false viewBinding.useStickyPlaceHolderCheckBox.isEnabled = false viewBinding.useStickyPlaceHolderCheckBox.isChecked = false } updatingConfigs = false } /** Whether the given rule is for splitting activity A and others. */ private fun isRuleForSplit(rule: EmbeddingRule): Boolean { if (rule !is SplitPairRule) { return false } for (filter in rule.filters) { if (filter.primaryActivityName.className == SplitPipActivityA::class.java.name) { return true } } return false } /** Whether the given rule is for launching placeholder with activity B. */ private fun isRuleForPlaceholder(rule: EmbeddingRule): Boolean { if (rule !is SplitPlaceholderRule) { return false } for (filter in rule.filters) { if (filter.componentName.className == SplitPipActivityB::class.java.name) { return true } } return false } /** Updates the split rules based on the current selection on checkboxes. */ private fun updateSplitRules() { splitController.clearRegisteredRules() if (viewBinding.splitMainCheckBox.isChecked) { val pairFilters = HashSet<SplitPairFilter>() pairFilters.add(SplitPairFilter(componentNameA, componentNameB, null)) pairFilters.add(SplitPairFilter(componentNameA, componentNameNotPip, null)) val finishAWithB = viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked val finishBWithA = viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked val rule = SplitPairRule.Builder(pairFilters) .setMinWidthDp(0) .setMinSmallestWidthDp(0) .setFinishPrimaryWithSecondary( if (finishAWithB) SplitRule.FINISH_ALWAYS else SplitRule.FINISH_NEVER) .setFinishSecondaryWithPrimary( if (finishBWithA) SplitRule.FINISH_ALWAYS else SplitRule.FINISH_NEVER) .setClearTop(true) .setSplitRatio(splitRatio) .build() splitController.registerRule(rule) } if (viewBinding.usePlaceHolderCheckBox.isChecked) { val activityFilters = HashSet<ActivityFilter>() activityFilters.add(ActivityFilter(componentNameB, null)) val intent = Intent().setComponent(componentNamePlaceholder) val isSticky = viewBinding.useStickyPlaceHolderCheckBox.isChecked val rule = SplitPlaceholderRule.Builder(activityFilters, intent) .setMinWidthDp(0) .setMinSmallestWidthDp(0) .setSticky(isSticky) .setFinishPrimaryWithPlaceholder(SplitRule.FINISH_ADJACENT) .setSplitRatio(splitRatio) .build() splitController.registerRule(rule) } } override fun onStart() { super.onStart() splitController.addSplitListener( this, ContextCompat.getMainExecutor(this), splitChangeListener ) } override fun onStop() { super.onStop() splitController.removeSplitListener(splitChangeListener) } /** Updates the embedding status when receives callback from the extension. */ inner class SplitStateChangeListener : Consumer<List<SplitInfo>> { override fun accept(newSplitInfos: List<SplitInfo>) { var isInSplit = false for (info in newSplitInfos) { if (info.contains(this@SplitPipActivityBase) && info.splitRatio > 0) { isInSplit = true break } } runOnUiThread { viewBinding.activityEmbeddedStatusTextView.visibility = if (isInSplit) View.VISIBLE else View.GONE updateCheckboxes() } } } }
window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityBase.kt
3442315519
/* package tech.salroid.filmy.ui.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.widget.RemoteViews import com.bumptech.glide.Glide import com.bumptech.glide.request.target.AppWidgetTarget import tech.salroid.filmy.R import tech.salroid.filmy.ui.activities.MovieDetailsActivity import tech.salroid.filmy.data.local.database.FilmContract class FilmyWidgetProvider : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { var movieId = " " var movieTitle = " " var moviePoster = " " for (element in appWidgetIds) { val appWidgetId = element val moviesForTheUri = FilmContract.MoviesEntry.CONTENT_URI val selection: String? = null val selectionArgs: Array<String>? = null val cursor = context.contentResolver.query( moviesForTheUri, MovieProjection.MOVIE_COLUMNS, selection, selectionArgs, null ) if (cursor != null && cursor.count > 0) { cursor.moveToFirst() val idIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_ID) val titleIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_TITLE) val posterIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_POSTER_LINK) val yearIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_YEAR) movieId = cursor.getString(idIndex) movieTitle = cursor.getString(titleIndex) moviePoster = cursor.getString(posterIndex) //String imdb_id = cursor.getString(id_index); //int movie_year = cursor.getInt(year_index); } cursor?.close() val remoteViews = RemoteViews(context.packageName, R.layout.filmy_appwidget) remoteViews.setTextViewText(R.id.widget_movie_name, movieTitle) val appWidgetTarget = AppWidgetTarget(context, R.id.widget_movie_image, remoteViews, *appWidgetIds) Glide.with(context) .asBitmap() .load(moviePoster) .into(appWidgetTarget) val intent = Intent(context, MovieDetailsActivity::class.java) intent.putExtra("title", movieTitle) intent.putExtra("activity", true) intent.putExtra("type", -1) intent.putExtra("database_applicable", false) intent.putExtra("network_applicable", true) intent.putExtra("id", movieId) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) remoteViews.setOnClickPendingIntent(R.id.activity_opener, pendingIntent) appWidgetManager.updateAppWidget(appWidgetId, remoteViews) } } }*/
app/src/main/java/tech/salroid/filmy/ui/widget/FilmyWidgetProvider.kt
659594564
package com.vimeo.networking2.functions class InternalFunctionContainer { internal fun internalFunction(): String = "Hello World" }
model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/functions/InternalFunctionContainer.kt
1233597277
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.psi.PsiElement import org.rust.FileTree import org.rust.RsTestBase import org.rust.fileTree import org.rust.launchAction class RsDowngradeModuleToFileTest : RsTestBase() { fun `test works on file`() = checkAvailable( "foo/mod.rs", fileTree { dir("foo") { rust("mod.rs", "fn hello() {}") } }, fileTree { rust("foo.rs", "fn hello() {}") } ) fun `test works on directory`() = checkAvailable( "foo", fileTree { dir("foo") { rust("mod.rs", "fn hello() {}") } }, fileTree { rust("foo.rs", "fn hello() {}") } ) fun `test not available on wrong file`() = checkNotAvailable( "foo/bar.rs", fileTree { dir("foo") { rust("mod.rs", "") rust("bar.rs", "") } } ) fun `test not available on full directory`() = checkNotAvailable( "foo/mod.rs", fileTree { dir("foo") { rust("mod.rs", "") rust("bar.rs", "") } } ) private fun checkAvailable(target: String, before: FileTree, after: FileTree) { val file = before.create().psiFile(target) testActionOnElement(file, shouldBeEnabled = true) after.assertEquals(myFixture.findFileInTempDir(".")) } private fun checkNotAvailable(target: String, before: FileTree) { val file = before.create().psiFile(target) testActionOnElement(file, shouldBeEnabled = false) } private fun testActionOnElement(element: PsiElement, shouldBeEnabled: Boolean) { myFixture.launchAction( "Rust.RsDowngradeModuleToFile", CommonDataKeys.PSI_ELEMENT to element, shouldBeEnabled = shouldBeEnabled ) } }
src/test/kotlin/org/rust/ide/refactoring/RsDowngradeModuleToFileTest.kt
3903121568
package Model import org.jetbrains.dokka.Model.CodeNode import org.junit.Test import kotlin.test.assertEquals class CodeNodeTest { @Test fun text_normalisesInitialWhitespace() { val expected = "Expected\ntext in this\ttest" val sut = CodeNode("\n \t \r $expected", "") assertEquals(expected, sut.text()) } }
core/src/test/kotlin/Model/CodeNodeTest.kt
1470921256
package de.tum.`in`.tumcampusapp.component.other.generic.activity import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient import de.tum.`in`.tumcampusapp.api.tumonline.TUMOnlineClient /** * This Activity can be extended by concrete Activities that access information from TUM Cabe. It * includes methods for fetching content (both via [TUMOnlineClient] and from the local * cache, and implements error and retry handling. * * @param T The type of object that is loaded from the TUMCabe API */ abstract class ActivityForAccessingTumCabe<T>(layoutId: Int) : ProgressActivity<T>(layoutId) { protected val apiClient: TUMCabeClient by lazy { TUMCabeClient.getInstance(this) } }
app/src/main/java/de/tum/in/tumcampusapp/component/other/generic/activity/ActivityForAccessingTumCabe.kt
2344557667
/* * 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.foundation.text import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction.Companion.Default import androidx.compose.ui.text.input.ImeAction.Companion.None import androidx.compose.ui.text.input.ImeAction.Companion.Go import androidx.compose.ui.text.input.ImeAction.Companion.Search import androidx.compose.ui.text.input.ImeAction.Companion.Send import androidx.compose.ui.text.input.ImeAction.Companion.Previous import androidx.compose.ui.text.input.ImeAction.Companion.Next import androidx.compose.ui.text.input.ImeAction.Companion.Done import androidx.compose.ui.text.input.TextInputSession /** * This class can be used to run keyboard actions when the user triggers an IME action. */ internal class KeyboardActionRunner : KeyboardActionScope { /** * The developer specified [KeyboardActions]. */ lateinit var keyboardActions: KeyboardActions /** * A reference to the [FocusManager] composition local. */ lateinit var focusManager: FocusManager /** * A reference to the current [TextInputSession]. */ // TODO(b/241399013) replace with SoftwareKeyboardController when it becomes stable. var inputSession: TextInputSession? = null /** * Run the keyboard action corresponding to the specified imeAction. If a keyboard action is * not specified, use the default implementation provided by [defaultKeyboardAction]. */ fun runAction(imeAction: ImeAction) { val keyboardAction = when (imeAction) { Done -> keyboardActions.onDone Go -> keyboardActions.onGo Next -> keyboardActions.onNext Previous -> keyboardActions.onPrevious Search -> keyboardActions.onSearch Send -> keyboardActions.onSend Default, None -> null else -> error("invalid ImeAction") } keyboardAction?.invoke(this) ?: defaultKeyboardAction(imeAction) } /** * Default implementations for [KeyboardActions]. */ override fun defaultKeyboardAction(imeAction: ImeAction) { when (imeAction) { Next -> focusManager.moveFocus(FocusDirection.Next) Previous -> focusManager.moveFocus(FocusDirection.Previous) Done -> inputSession?.hideSoftwareKeyboard() // Note: Don't replace this with an else. These are specified explicitly so that we // don't forget to update this when statement when new imeActions are added. Go, Search, Send, Default, None -> Unit // Do Nothing. } } }
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/KeyboardActionRunner.kt
1347736885
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.desktop.examples.popupexample import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import java.awt.image.BufferedImage import javax.imageio.ImageIO object AppState { private val imageRes: String = "androidx/compose/desktop/example/tray.png" private var icon: BufferedImage? = null var isMainWindowOpen by mutableStateOf(true) private set val secondaryWindowIds = mutableStateListOf<Int>() private var lastId = 0 fun openSecondaryWindow() { secondaryWindowIds.add(lastId++) } fun closeMainWindow() { isMainWindowOpen = false } fun closeSecondaryWindow(id: Int) { secondaryWindowIds.remove(id) } fun closeAll() { isMainWindowOpen = false secondaryWindowIds.clear() } fun image(): BufferedImage { if (icon != null) { return icon!! } try { val img = Thread.currentThread().contextClassLoader.getResource(imageRes) val bitmap: BufferedImage? = ImageIO.read(img) if (bitmap != null) { icon = bitmap return bitmap } } catch (e: Exception) { e.printStackTrace() } return BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB) } val wndTitle = mutableStateOf("Desktop Compose Popup") val popupState = mutableStateOf(false) val amount = mutableStateOf(0) val undecorated = mutableStateOf(false) val alertDialog = mutableStateOf(false) val notify = mutableStateOf(true) val warn = mutableStateOf(false) val error = mutableStateOf(false) fun diselectOthers(state: MutableState<Boolean>) { if (notify != state) { notify.value = false } if (warn != state) { warn.value = false } if (error != state) { error.value = false } } }
compose/desktop/desktop/samples/src/jvmMain/kotlin/androidx/compose/desktop/examples/popupexample/AppState.jvm.kt
2043036927
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.android import android.graphics.Bitmap import android.graphics.Rect import android.os.Build import android.os.Handler import android.os.Looper import android.view.PixelCopy import android.view.View import android.view.ViewTreeObserver import android.view.Window import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.test.ComposeTimeoutException import androidx.compose.ui.test.InternalTestApi import androidx.compose.ui.test.MainTestClock import androidx.compose.ui.test.TestContext import androidx.test.platform.graphics.HardwareRendererCompat import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @RequiresApi(Build.VERSION_CODES.O) internal fun Window.captureRegionToImage( testContext: TestContext, boundsInWindow: Rect, ): ImageBitmap { // Turn on hardware rendering, if necessary return withDrawingEnabled { // First force drawing to happen decorView.forceRedraw(testContext) // Then we generate the bitmap generateBitmap(boundsInWindow).asImageBitmap() } } private fun <R> withDrawingEnabled(block: () -> R): R { val wasDrawingEnabled = HardwareRendererCompat.isDrawingEnabled() try { if (!wasDrawingEnabled) { HardwareRendererCompat.setDrawingEnabled(true) } return block.invoke() } finally { if (!wasDrawingEnabled) { HardwareRendererCompat.setDrawingEnabled(false) } } } internal fun View.forceRedraw(testContext: TestContext) { var drawDone = false handler.post { if (Build.VERSION.SDK_INT >= 29 && isHardwareAccelerated) { FrameCommitCallbackHelper.registerFrameCommitCallback(viewTreeObserver) { drawDone = true } } else { viewTreeObserver.addOnDrawListener(object : ViewTreeObserver.OnDrawListener { var handled = false override fun onDraw() { if (!handled) { handled = true handler.postAtFrontOfQueue { drawDone = true viewTreeObserver.removeOnDrawListener(this) } } } }) } invalidate() } @OptIn(InternalTestApi::class) testContext.testOwner.mainClock.waitUntil(timeoutMillis = 2_000) { drawDone } } @RequiresApi(Build.VERSION_CODES.O) private fun Window.generateBitmap(boundsInWindow: Rect): Bitmap { val destBitmap = Bitmap.createBitmap( boundsInWindow.width(), boundsInWindow.height(), Bitmap.Config.ARGB_8888 ) generateBitmapFromPixelCopy(boundsInWindow, destBitmap) return destBitmap } @RequiresApi(Build.VERSION_CODES.O) private fun Window.generateBitmapFromPixelCopy(boundsInWindow: Rect, destBitmap: Bitmap) { val latch = CountDownLatch(1) var copyResult = 0 val onCopyFinished = PixelCopy.OnPixelCopyFinishedListener { result -> copyResult = result latch.countDown() } PixelCopyHelper.request( this, boundsInWindow, destBitmap, onCopyFinished, Handler(Looper.getMainLooper()) ) if (!latch.await(1, TimeUnit.SECONDS)) { throw AssertionError("Failed waiting for PixelCopy!") } if (copyResult != PixelCopy.SUCCESS) { throw AssertionError("PixelCopy failed!") } } // Unfortunately this is a copy paste from AndroidComposeTestRule. At this moment it is a bit // tricky to share this method. We can expose it on TestOwner in theory. private fun MainTestClock.waitUntil(timeoutMillis: Long, condition: () -> Boolean) { val startTime = System.nanoTime() while (!condition()) { if (autoAdvance) { advanceTimeByFrame() } // Let Android run measure, draw and in general any other async operations. Thread.sleep(10) if (System.nanoTime() - startTime > timeoutMillis * 1_000_000) { throw ComposeTimeoutException( "Condition still not satisfied after $timeoutMillis ms" ) } } } @RequiresApi(Build.VERSION_CODES.Q) private object FrameCommitCallbackHelper { @DoNotInline fun registerFrameCommitCallback(viewTreeObserver: ViewTreeObserver, runnable: Runnable) { viewTreeObserver.registerFrameCommitCallback(runnable) } } @RequiresApi(Build.VERSION_CODES.O) private object PixelCopyHelper { @DoNotInline fun request( source: Window, srcRect: Rect?, dest: Bitmap, listener: PixelCopy.OnPixelCopyFinishedListener, listenerThread: Handler ) { PixelCopy.request(source, srcRect, dest, listener, listenerThread) } }
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/android/WindowCapture.android.kt
1600762411
package com.developerphil.adbidea.preference.accessor interface PreferenceAccessor { fun saveString(key: String, value: String) fun getString(key: String, defaultValue: String): String }
src/main/kotlin/com/developerphil/adbidea/preference/accessor/PreferenceAccessor.kt
2920967519
/* * 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.node import androidx.compose.runtime.collection.mutableVectorOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.autofill.Autofill import androidx.compose.ui.autofill.AutofillTree import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.hapticfeedback.HapticFeedback import androidx.compose.ui.input.InputModeManager import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.pointer.PointerIconService import androidx.compose.ui.modifier.ModifierLocalManager import androidx.compose.ui.modifier.modifierLocalConsumer import androidx.compose.ui.modifier.modifierLocalOf import androidx.compose.ui.modifier.modifierLocalProvider import androidx.compose.ui.platform.AccessibilityManager import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.TextToolbar import androidx.compose.ui.platform.ViewConfiguration import androidx.compose.ui.platform.WindowInfo import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.TextInputService import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @OptIn(ExperimentalComposeUiApi::class) @RunWith(JUnit4::class) class ModifierLocalConsumerEntityTest { private val default = "Default" private val ModifierLocalString = modifierLocalOf { "Default" } private val owner = FakeOwner() private val layoutNode = LayoutNode() @Test fun `unattached modifier local consumer does not invoke lambda`() { // Arrange. var receivedValue = "" TestBox(Modifier.modifierLocalConsumer { receivedValue = ModifierLocalString.current }) // Assert. assertThat(receivedValue).isEmpty() } @Test fun `attached modifier local consumer with no provider reads default value`() { // Arrange. lateinit var receivedValue: String TestBox(Modifier.modifierLocalConsumer { receivedValue = ModifierLocalString.current }) // Act. attach() // Assert. assertThat(receivedValue).isEqualTo(default) } @Test fun `changing the consumer modifier with no provider reads default value`() { // Arrange. lateinit var receivedValue: String TestBox(Modifier.modifierLocalConsumer { receivedValue = ModifierLocalString.current }) attach() receivedValue = "" // Act. changeModifier(Modifier.modifierLocalConsumer { receivedValue = ModifierLocalString.current }) // Assert. assertThat(receivedValue).isEqualTo(default) } @Test fun `detached modifier local consumer with no provider invokes with default providers`() { // Arrange. lateinit var receivedValue: String TestBox(Modifier.modifierLocalConsumer { receivedValue = ModifierLocalString.current }) attach() receivedValue = "" // Act. detach() // Assert. assertThat(receivedValue).isEqualTo(default) } @Test fun `unattached modifier local consumer with provider does not invoke lambda`() { // Arrange. var receivedValue = "" TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { "Initial Value" } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) // Assert. assertThat(receivedValue).isEmpty() } @Test fun `attached modifier local consumer with provider reads provided value`() { // Arrange. val providedValue = "Provided Value" lateinit var receivedValue: String TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { providedValue } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) // Act. attach() // Assert. assertThat(receivedValue).isEqualTo(providedValue) } @Test fun `changing provided value causes consumer to receive new provided value`() { // Arrange. val initialValue = "Initial Value" val finalValue = "Final Value" var providedValue by mutableStateOf(initialValue) lateinit var receivedValue: String TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { providedValue } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) attach() // Act. Snapshot.withMutableSnapshot { providedValue = finalValue } // Assert. assertThat(receivedValue).isEqualTo(finalValue) } @Test fun `changing provided value after detaching modifier does not invoke consumer lambda`() { // Arrange. val initialValue = "Initial Value" val finalValue = "Final Value" var providedValue by mutableStateOf(initialValue) lateinit var receivedValue: String TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { providedValue } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) attach() detach() receivedValue = "" // Act. Snapshot.withMutableSnapshot { providedValue = finalValue } // Assert. assertThat(receivedValue).isEmpty() } @Test fun `changing modifiers after detaching modifier does not invoke consumer lambda`() { // Arrange. lateinit var receivedValue: String TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { "Provided Value" } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) attach() detach() receivedValue = "" // Act. changeModifier(Modifier.modifierLocalConsumer { receivedValue = ModifierLocalString.current }) // Assert. assertThat(receivedValue).isEmpty() } @Test fun `changing the consumer modifier with provider reads provided value`() { // Arrange. val providedValue = "Provided Value" lateinit var receivedValue: String TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { providedValue } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) attach() receivedValue = "" // Act. changeModifier( Modifier .modifierLocalProvider(ModifierLocalString) { providedValue } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) // Assert. assertThat(receivedValue).isEqualTo(providedValue) } @Test fun `detached modifier local consumer with provider invokes with default provider`() { // Arrange. lateinit var receivedValue: String TestBox( modifier = Modifier .modifierLocalProvider(ModifierLocalString) { "Provided Value" } .modifierLocalConsumer { receivedValue = ModifierLocalString.current } ) attach() receivedValue = "" // Act. detach() // Assert. assertThat(receivedValue).isEqualTo(default) } private fun TestBox(modifier: Modifier = Modifier) { owner.snapshotObserver.startObserving() layoutNode.modifier = modifier } private fun attach() { // Apply changes after attaching layoutNode.attach(owner) owner.onEndApplyChanges() } private fun detach() { // Apply changes after detaching layoutNode.detach() owner.onEndApplyChanges() } private fun changeModifier(modifier: Modifier) { with(layoutNode) { if (isAttached) { forEachNodeCoordinator { it.detach() } } this.modifier = modifier if (isAttached) { forEachNodeCoordinator { it.attach() } } owner?.onEndApplyChanges() } } @OptIn(ExperimentalComposeUiApi::class) private class FakeOwner : Owner { val listeners = mutableVectorOf<() -> Unit>() @OptIn(InternalCoreApi::class) override var showLayoutBounds: Boolean = false override val snapshotObserver: OwnerSnapshotObserver = OwnerSnapshotObserver { it.invoke() } override val modifierLocalManager: ModifierLocalManager = ModifierLocalManager(this) override fun registerOnEndApplyChangesListener(listener: () -> Unit) { listeners += listener } override fun onEndApplyChanges() { while (listeners.isNotEmpty()) { listeners.removeAt(0).invoke() } } override fun registerOnLayoutCompletedListener(listener: Owner.OnLayoutCompletedListener) { TODO("Not yet implemented") } override fun onRequestMeasure( layoutNode: LayoutNode, affectsLookahead: Boolean, forceRequest: Boolean ) {} override fun onAttach(node: LayoutNode) = node.forEachNodeCoordinator { it.attach() } override fun onDetach(node: LayoutNode) = node.forEachNodeCoordinator { it.detach() } override val root: LayoutNode get() = TODO("Not yet implemented") override val sharedDrawScope: LayoutNodeDrawScope get() = TODO("Not yet implemented") override val rootForTest: RootForTest get() = TODO("Not yet implemented") override val hapticFeedBack: HapticFeedback get() = TODO("Not yet implemented") override val inputModeManager: InputModeManager get() = TODO("Not yet implemented") override val clipboardManager: ClipboardManager get() = TODO("Not yet implemented") override val accessibilityManager: AccessibilityManager get() = TODO("Not yet implemented") override val textToolbar: TextToolbar get() = TODO("Not yet implemented") override val density: Density get() = TODO("Not yet implemented") override val textInputService: TextInputService get() = TODO("Not yet implemented") override val pointerIconService: PointerIconService get() = TODO("Not yet implemented") override val focusManager: FocusManager get() = TODO("Not yet implemented") override val windowInfo: WindowInfo get() = TODO("Not yet implemented") @Deprecated( "fontLoader is deprecated, use fontFamilyResolver", replaceWith = ReplaceWith("fontFamilyResolver") ) @Suppress("DEPRECATION") override val fontLoader: Font.ResourceLoader get() = TODO("Not yet implemented") override val fontFamilyResolver: FontFamily.Resolver get() = TODO("Not yet implemented") override val layoutDirection: LayoutDirection get() = TODO("Not yet implemented") override val measureIteration: Long get() = TODO("Not yet implemented") override val viewConfiguration: ViewConfiguration get() = TODO("Not yet implemented") override val autofillTree: AutofillTree get() = TODO("Not yet implemented") override val autofill: Autofill get() = TODO("Not yet implemented") override fun createLayer(drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit) = TODO("Not yet implemented") override fun onRequestRelayout( layoutNode: LayoutNode, affectsLookahead: Boolean, forceRequest: Boolean ) = TODO("Not yet implemented") override fun requestOnPositionedCallback(layoutNode: LayoutNode) { TODO("Not yet implemented") } override fun calculatePositionInWindow(localPosition: Offset) = TODO("Not yet implemented") override fun calculateLocalPosition(positionInWindow: Offset) = TODO("Not yet implemented") override fun requestFocus() = TODO("Not yet implemented") override fun measureAndLayout(sendPointerUpdate: Boolean) = TODO("Not yet implemented") override fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) { TODO("Not yet implemented") } override fun forceMeasureTheSubtree(layoutNode: LayoutNode) = TODO("Not yet implemented") override fun onSemanticsChange() = TODO("Not yet implemented") override fun onLayoutChange(layoutNode: LayoutNode) = TODO("Not yet implemented") override fun getFocusDirection(keyEvent: KeyEvent) = TODO("Not yet implemented") } } private fun LayoutNode.forEachNodeCoordinator(action: (NodeCoordinator) -> Unit) { var coordinator: NodeCoordinator? = outerCoordinator while (coordinator != null) { action.invoke(coordinator) coordinator = coordinator.wrapped } }
compose/ui/ui/src/test/kotlin/androidx/compose/ui/node/ModifierLocalConsumerEntityTest.kt
200322204
package tornadofx import javafx.beans.property.ObjectProperty import javafx.beans.property.Property import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.collections.ObservableMap import javafx.scene.Node import javafx.scene.control.ListCell import javafx.scene.control.ListView import javafx.scene.control.SelectionMode import javafx.scene.control.TableView import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.scene.input.MouseEvent import javafx.util.Callback import tornadofx.FX.IgnoreParentBuilder.No import tornadofx.FX.IgnoreParentBuilder.Once import kotlin.reflect.KClass /** * Execute action when the enter key is pressed or the mouse is clicked * @param clickCount The number of mouse clicks to trigger the action * @param action The runnable to execute on select */ fun <T> ListView<T>.onUserSelect(clickCount: Int = 2, action: (T) -> Unit) { addEventFilter(MouseEvent.MOUSE_CLICKED) { event -> val selectedItem = this.selectedItem if (event.clickCount == clickCount && selectedItem != null && event.target.isInsideRow()) action(selectedItem) } addEventFilter(KeyEvent.KEY_PRESSED) { event -> val selectedItem = this.selectedItem if (event.code == KeyCode.ENTER && !event.isMetaDown && selectedItem != null) action(selectedItem) } } val <T> ListView<T>.selectedItem: T? get() = selectionModel.selectedItem fun <T> ListView<T>.asyncItems(func: () -> Collection<T>) = task { func() } success { if (items == null) items = FXCollections.observableArrayList(it) else items.setAll(it) } fun <T> ListView<T>.onUserDelete(action: (T) -> Unit) { addEventFilter(KeyEvent.KEY_PRESSED) { event -> val selectedItem = this.selectedItem if (event.code == KeyCode.BACK_SPACE && selectedItem != null) action(selectedItem) } } class ListCellCache<T>(private val cacheProvider: (T) -> Node) { private val store = mutableMapOf<T, Node>() fun getOrCreateNode(value: T) = store.getOrPut(value, { cacheProvider(value) }) } abstract class ItemFragment<T> : Fragment() { val itemProperty: ObjectProperty<T> = SimpleObjectProperty(this, "item") val item by itemProperty } abstract class RowItemFragment<S, T> : ItemFragment<T>() { val rowItemProperty: ObjectProperty<S> = SimpleObjectProperty(this, "rowItem") val rowItem by rowItemProperty } abstract class ListCellFragment<T> : ItemFragment<T>() { val cellProperty: ObjectProperty<ListCell<T>?> = SimpleObjectProperty() var cell by cellProperty val editingProperty = SimpleBooleanProperty(false) val editing by editingProperty open fun startEdit() { cell?.startEdit() } open fun commitEdit(newValue: T) { cell?.commitEdit(newValue) } open fun cancelEdit() { cell?.cancelEdit() } open fun onEdit(op: () -> Unit) { editingProperty.onChange { if (it) op() } } } @Suppress("UNCHECKED_CAST") open class SmartListCell<T>(val scope: Scope = DefaultScope, listView: ListView<T>?, properties: Map<Any,Any>? = null) : ListCell<T>() { /** * A convenience constructor allowing to omit `listView` completely, if needed. */ constructor(scope: Scope = DefaultScope, properties : Map<Any,Any>? = null) : this(scope, null, properties) private val smartProperties: ObservableMap<Any,Any> = listView?.properties ?: HashMap(properties.orEmpty()).observable() private val editSupport: (ListCell<T>.(EditEventType, T?) -> Unit)? get() = smartProperties["tornadofx.editSupport"] as (ListCell<T>.(EditEventType, T?) -> Unit)? private val cellFormat: (ListCell<T>.(T) -> Unit)? get() = smartProperties["tornadofx.cellFormat"] as (ListCell<T>.(T) -> Unit)? private val cellCache: ListCellCache<T>? get() = smartProperties["tornadofx.cellCache"] as ListCellCache<T>? private var cellFragment: ListCellFragment<T>? = null private var fresh = true init { if (listView != null) { properties?.let { listView.properties?.putAll(it) } listView.properties["tornadofx.cellFormatCapable"] = true listView.properties["tornadofx.cellCacheCapable"] = true listView.properties["tornadofx.editCapable"] = true } indexProperty().onChange { if (it == -1) clearCellFragment() } } override fun startEdit() { super.startEdit() editSupport?.invoke(this, EditEventType.StartEdit, null) } override fun commitEdit(newValue: T) { super.commitEdit(newValue) editSupport?.invoke(this, EditEventType.CommitEdit, newValue) } override fun cancelEdit() { super.cancelEdit() editSupport?.invoke(this, EditEventType.CancelEdit, null) } override fun updateItem(item: T, empty: Boolean) { super.updateItem(item, empty) if (item == null || empty) { textProperty().unbind() graphicProperty().unbind() text = null graphic = null clearCellFragment() } else { FX.ignoreParentBuilder = Once try { cellCache?.apply { graphic = getOrCreateNode(item) } } finally { FX.ignoreParentBuilder = No } if (fresh) { val cellFragmentType = smartProperties["tornadofx.cellFragment"] as KClass<ListCellFragment<T>>? cellFragment = if (cellFragmentType != null) find(cellFragmentType, scope) else null fresh = false } cellFragment?.apply { editingProperty.cleanBind(editingProperty()) itemProperty.value = item cellProperty.value = this@SmartListCell graphic = root } cellFormat?.invoke(this, item) } } private fun clearCellFragment() { cellFragment?.apply { cellProperty.value = null itemProperty.value = null editingProperty.unbind() editingProperty.value = false } } } fun <T> ListView<T>.bindSelected(property: Property<T>) { selectionModel.selectedItemProperty().onChange { property.value = it } } fun <T> ListView<T>.bindSelected(model: ItemViewModel<T>) = this.bindSelected(model.itemProperty) fun <T, F : ListCellFragment<T>> ListView<T>.cellFragment(scope: Scope = DefaultScope, fragment: KClass<F>) { properties["tornadofx.cellFragment"] = fragment if (properties["tornadofx.cellFormatCapable"] != true) cellFactory = Callback { SmartListCell(scope, it) } } @Suppress("UNCHECKED_CAST") fun <T> ListView<T>.cellFormat(scope: Scope = DefaultScope, formatter: (ListCell<T>.(T) -> Unit)) { properties["tornadofx.cellFormat"] = formatter if (properties["tornadofx.cellFormatCapable"] != true) cellFactory = Callback { SmartListCell(scope, it) } } fun <T> ListView<T>.onEdit(scope: Scope = DefaultScope, eventListener: ListCell<T>.(EditEventType, T?) -> Unit) { isEditable = true properties["tornadofx.editSupport"] = eventListener // Install a edit capable cellFactory it none is present. The default cellFormat factory will do. if (properties["tornadofx.editCapable"] != true) cellFormat(scope) { } } /** * Calculate a unique Node per item and set this Node as the graphic of the ListCell. * * To support this feature, a custom cellFactory is automatically installed, unless an already * compatible cellFactory is found. The cellFactories installed via #cellFormat already knows * how to retrieve cached values. */ fun <T> ListView<T>.cellCache(scope: Scope = DefaultScope, cachedGraphicProvider: (T) -> Node) { properties["tornadofx.cellCache"] = ListCellCache(cachedGraphicProvider) // Install a cache capable cellFactory it none is present. The default cellFormat factory will do. if (properties["tornadofx.cellCacheCapable"] != true) { cellFormat(scope) { } } } fun <T> ListView<T>.multiSelect(enable: Boolean = true) { selectionModel.selectionMode = if (enable) SelectionMode.MULTIPLE else SelectionMode.SINGLE }
src/main/java/tornadofx/ListView.kt
3943106559
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.flv.audio /** * Created by pedro on 29/04/21. */ enum class AudioSize(val value: Int) { SND_8_BIT(0), SND_16_BIT(1) }
rtmp/src/main/java/com/pedro/rtmp/flv/audio/AudioSize.kt
3668431657
package io.mockk.impl.platform import java.lang.ref.ReferenceQueue import java.lang.ref.WeakReference import java.util.concurrent.ConcurrentHashMap class JvmWeakConcurrentMap<K, V>() : MutableMap<K, V> { private val map = ConcurrentHashMap<Any, V>() private val queue = ReferenceQueue<K>() override fun get(key: K): V? { return map[StrongKey(key)] } override fun put(key: K, value: V): V? { expunge() return map.put(WeakKey(key, queue), value) } override fun remove(key: K): V? { expunge() return map.remove(StrongKey(key)) } private fun expunge() { var ref = queue.poll() while (ref != null) { val value = map.remove(ref) if (value is Disposable) { value.dispose() } ref = queue.poll() } } private class WeakKey<K>(key: K, queue: ReferenceQueue<K>) : WeakReference<K>(key, queue) { private val hashCode: Int init { hashCode = System.identityHashCode(key) } override fun equals(other: Any?): Boolean { if (other === this) { return true } else { val key = get() if (key != null) { if (other is WeakKey<*>) { return key === other.get() } else if (other is StrongKey<*>) { return key === other.get() } } } return false } override fun hashCode(): Int { return hashCode } } private class StrongKey<K>(private val key: K) { private val hashCode: Int init { hashCode = System.identityHashCode(key) } override fun equals(other: Any?): Boolean { if (this === other) { return true } else { val key = get() if (key != null) { if (other is WeakKey<*>) { return key === other.get() } else if (other is StrongKey<*>) { return key === other.get() } } } return false } override fun hashCode(): Int { return hashCode } fun get(): K? { return key } } override val size get() = map.size override fun isEmpty(): Boolean { return map.isEmpty() } override fun containsKey(key: K): Boolean { return get(key) != null } override fun containsValue(value: V): Boolean { return map.containsValue(value) } override fun putAll(from: Map<out K, V>) { throw UnsupportedOperationException("putAll") } override fun clear() { map.clear() } override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = throw UnsupportedOperationException("entries") override val keys: MutableSet<K> get() = throw UnsupportedOperationException("entries") override val values: MutableCollection<V> get() = map.values }
mockk/jvm/src/main/kotlin/io/mockk/impl/platform/JvmWeakConcurrentMap.kt
2881739593
package net.gouline.slackuploader import com.beust.jcommander.JCommander import com.beust.jcommander.Parameter import com.beust.jcommander.ParameterException import okhttp3.* import java.io.File import java.util.* import kotlin.system.exitProcess fun main(args: Array<String>) { val cmd = Commands() val commander = JCommander(cmd) commander.setProgramName("slack-uploader") try { commander.parse(*args) } catch (e: ParameterException) { error(e.message) } if (cmd.help) { commander.usage() } else if (cmd.token == null) { error("No token provided.") } else if (cmd.title == null) { error("No title provided.") } else if (cmd.channels.isEmpty()) { error("No channels provided.") } else if (cmd.files.isEmpty()) { error("No files provided.") } else { val file = File(cmd.files.first()) if (!file.exists()) { error("File not found.") } else { SlackClient(cmd.token!!).upload(file, cmd.title!!, cmd.channels) } } } /** * Minimal Slack client. */ class SlackClient(val token: String) { companion object { private const val BASE_URL = "https://slack.com/api" private const val FILES_UPLOAD_URL = "$BASE_URL/files.upload" } private val client = OkHttpClient() /** * Uploads file to channels. */ fun upload(file: File, title: String, channels: List<String>) { val response = execute(FILES_UPLOAD_URL, { it.addFormDataPart("title", title) .addFormDataPart("channels", channels.joinToString(",")) .addFormDataPart("file", file.name, RequestBody.create(null, file)) }) if (response.isSuccessful) { success(response.body().string()) } else { error("Request failed: $response") } } private inline fun execute(url: String, f: (MultipartBody.Builder) -> Unit): Response { val body = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("token", token) .apply { f(this) } .build() val request = Request.Builder() .url(url) .post(body) .build() return client.newCall(request).execute() } } /** * CLI input commands. */ class Commands { @Parameter(names = arrayOf("--help", "-h"), description = "Displays this usage.", help = true) var help = false @field:Parameter(names = arrayOf("--token", "-a"), description = "Authentication token (requires scope 'files:write:user').", required = true) var token: String? = null @field:Parameter(names = arrayOf("--title", "-t"), description = "Title of file.", required = true) var title: String? = null @field:Parameter(names = arrayOf("--channel", "-c"), description = "Channel names or IDs where the file will be shared.", required = true) var channels: List<String> = ArrayList() @field:Parameter(description = "FILE", required = true) var files: List<String> = ArrayList() } /** * Prints success message. */ private fun success(message: String?) { println("SUCCESS: $message") exitProcess(0) } /** * Prints error message and quits. */ private fun error(message: String?) { println("ERROR: $message") exitProcess(1) }
src/main/java/net/gouline/slackuploader/app.kt
156991466
package com.castlefrog.agl.domains.connect4 import com.google.common.truth.Truth.assertThat import org.junit.Assert.assertThrows import org.junit.Test class Connect4SimulatorTest { @Test fun getInitialState() { val simulator = Connect4Simulator() val initialState = simulator.initialState assertThat(initialState.toString()).isEqualTo( """ |----------------- |: - - - - - - - : |: - - - - - - - : |: - - - - - - - : |: - - - - - - - : |: - - - - - - - : |: - - - - - - - : |----------------- """.trimMargin() ) } @Test fun calculateRewardsInitialState() { val simulator = Connect4Simulator() val state = simulator.initialState assertThat(simulator.calculateRewards(state)).isEqualTo(intArrayOf(0, 0)) } @Test fun calculateRewardsAfterSomeMovesNoWinner() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(1, 16384)) assertThat(simulator.calculateRewards(state)).isEqualTo(intArrayOf(0, 0)) } @Test fun calculateRewardsHorizontalWinnerPlayer1() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(2113665, 33026)) assertThat(simulator.calculateRewards(state)).isEqualTo(intArrayOf(1, -1)) } @Test fun calculateRewardsHorizontalWinnerPlayer2() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(57209232818176, 8865355661312)) assertThat(simulator.calculateRewards(state)).isEqualTo(intArrayOf(-1, 1)) } @Test fun calculateRewardsVerticalWinnerPlayer1() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(31457280, 268451969)) assertThat(simulator.calculateRewards(state)).isEqualTo(intArrayOf(1, -1)) } @Test fun calculateRewardsVerticalWinnerPlayer2() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(17280, 15)) assertThat(simulator.calculateRewards(state)).isEqualTo(intArrayOf(-1, 1)) } @Test fun calculateLegalActionsInitialState() { val simulator = Connect4Simulator() val state = simulator.initialState assertThat(simulator.calculateLegalActions(state)).isEqualTo( arrayListOf( setOf( Connect4Action.valueOf(0), Connect4Action.valueOf(1), Connect4Action.valueOf(2), Connect4Action.valueOf(3), Connect4Action.valueOf(4), Connect4Action.valueOf(5), Connect4Action.valueOf(6) ), setOf() ) ) } @Test fun calculateLegalActionsOneMove() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(1, 0)) assertThat(simulator.calculateLegalActions(state)).isEqualTo( arrayListOf( setOf(), setOf( Connect4Action.valueOf(0), Connect4Action.valueOf(1), Connect4Action.valueOf(2), Connect4Action.valueOf(3), Connect4Action.valueOf(4), Connect4Action.valueOf(5), Connect4Action.valueOf(6) ) ) ) } @Test fun calculateLegalActionsFullColumn() { val simulator = Connect4Simulator() val state = Connect4State(longArrayOf(2688, 5376)) assertThat(simulator.calculateLegalActions(state)).isEqualTo( arrayListOf( setOf( Connect4Action.valueOf(0), Connect4Action.valueOf(2), Connect4Action.valueOf(3), Connect4Action.valueOf(4), Connect4Action.valueOf(5), Connect4Action.valueOf(6) ), setOf() ) ) } @Test fun stateTransitionInvalidNumberOfActions() { val simulator = Connect4Simulator() assertThrows( IllegalArgumentException::class.java ) { simulator.stateTransition(simulator.initialState, emptyMap()) } } @Test fun stateTransitionMove1() { val simulator = Connect4Simulator() val state = simulator.stateTransition(simulator.initialState, mapOf(Pair(0, Connect4Action.valueOf(3)))) val expectedState = Connect4State(longArrayOf(2097152, 0)) assertThat(state).isEqualTo(expectedState) } @Test fun stateTransitionNullAction() { val simulator = Connect4Simulator() val state = simulator.stateTransition(simulator.initialState, mapOf(Pair(0, Connect4Action.valueOf(2)))) assertThrows( IllegalArgumentException::class.java ) { simulator.stateTransition(state, mapOf(Pair(0, Connect4Action.valueOf(2)))) } } @Test fun stateTransitionMove2() { val simulator = Connect4Simulator() val state2 = simulator.stateTransition(simulator.initialState, mapOf(Pair(0, Connect4Action.valueOf(2)))) val state3 = simulator.stateTransition(state2, mapOf(Pair(1, Connect4Action.valueOf(2)))) val expectedState = Connect4State(longArrayOf(16384, 32768)) assertThat(state3).isEqualTo(expectedState) } }
src/test/kotlin/com/castlefrog/agl/domains/connect4/Connect4SimulatorTest.kt
1045506956
/* * Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg) * * 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.jrgonzalezg.openlibrary.app import javax.inject.Scope import kotlin.annotation.AnnotationRetention.RUNTIME @Scope @Retention(RUNTIME) annotation class ActivityScope
app/src/main/kotlin/com/github/jrgonzalezg/openlibrary/app/ActivityScope.kt
250583417
package info.macias.kaconf import info.macias.kaconf.sources.AbstractPropertySource import junit.framework.TestCase import org.junit.Test class PropertySourceTest : TestCase("Test Property Sources") { val b: Byte = -123 val c: Char = '!' val s: Short = 30000 val i: Int = -2000000000 val l: Long = 30000000000 val str = "ola ke ase" val properties = object : AbstractPropertySource() { val keyVals = mapOf( "b" to b.toString(), "c" to c.toString(), "s" to s.toString(), "i" to i.toString(), "l" to l.toString(), "str" to str ) override fun get(key: String?): String? = keyVals.get(key) override fun isAvailable() = true } @Test fun testPropertyConversion() { assertEquals(properties.get("b", java.lang.Byte::class.java), b) assertEquals(properties.get("c", java.lang.Character::class.java), c) assertEquals(properties.get("s", java.lang.Short::class.java), s) assertEquals(properties.get("i", java.lang.Integer::class.java), i) assertEquals(properties.get("l", java.lang.Long::class.java), l) assertEquals(properties.get("str", java.lang.String::class.java), str) } @Test fun testNullResults() { assertNull(properties.get("abc", java.lang.Byte::class.java)) assertNull(properties.get("def", java.lang.Character::class.java)) assertNull(properties.get("ghi", java.lang.Short::class.java)) assertNull(properties.get("jkl", java.lang.Integer::class.java)) assertNull(properties.get("mno", java.lang.Long::class.java)) assertNull(properties.get("pqr", java.lang.String::class.java)) } @Test(expected = IllegalArgumentException::class) fun testUnexistingConverters() { var illegalArgumentExceptionThrown = false; try { properties.get("b", Object::class.java) } catch (e:ConfiguratorException) { illegalArgumentExceptionThrown = true; } assert(illegalArgumentExceptionThrown) } }
src/test/kotlin/info/macias/kaconf/PropertySourceTest.kt
4070710965
package com.blok.post.Infrastructure import com.blok.common.DatabaseSetup import com.blok.model.* import com.github.andrewoma.kwery.core.DefaultSession import com.github.andrewoma.kwery.core.Row import com.github.andrewoma.kwery.core.dialect.PostgresDialect import java.sql.Connection import java.sql.DriverManager import java.sql.Timestamp fun Post.toMap(): Map<String, Any?> = mapOf( "id" to this.id(), "title" to this.title, "content" to this.content, "publishing_date" to Timestamp.valueOf(this.publishingDate) ) fun Comment.toMap(): Map<String, Any?> = mapOf( "id" to this.id(), "content" to this.content, "author" to this.author, "post_id" to this.post_id(), "approved" to this.approved, "submission_date" to Timestamp.valueOf(this.submissionDate) ) open class PostgresPostRepository(dbSetup: DatabaseSetup) : PostRepository { val postMapper: (Row) -> Post = { row -> Post(PostId(row.string("id")), row.string("title"), row.string("content"), row.timestamp("publishing_date").toLocalDateTime(), row.stringOrNull("categories")?.split(',')?:listOf() ) } val commentMapper: (Row) -> Comment = {row -> Comment(CommentId(row.string("id")), PostId(row.string("post_id")), row.string("author"), row.string("content"), row.timestamp("submission_date").toLocalDateTime(), row.boolean("approved") ) } protected val session: DefaultSession init { Class.forName( "org.postgresql.Driver" ) val connection: Connection = DriverManager.getConnection( "jdbc:postgresql://${dbSetup.host}:${dbSetup.port}/${dbSetup.name}?", dbSetup.username, dbSetup.password) session = DefaultSession(connection, PostgresDialect()) } override fun save(post: Post): PostId { session.transaction { val sql = "INSERT INTO " + "posts (id, title, content, publishing_date) " + "VALUES (:id, :title, :content, :publishing_date) ON CONFLICT (id) " + "DO UPDATE SET (title, content, publishing_date) = (:title, :content, :publishing_date) " + "WHERE posts.id = :id" session.update(sql, post.toMap()) session.update("DELETE FROM posts_categories WHERE id = :id", mapOf("id" to post.id())) val sqlCategories = "INSERT INTO " + "posts_categories(id, category) " + "VALUES (:id, :category)" post.categories.forEach { category -> session.update(sqlCategories, mapOf("id" to post.id(), "category" to category)) } } return post.id } override fun save(comment: Comment): CommentId { val sql = "INSERT INTO " + "comments " + "(id, post_id, author, content, approved, submission_date) " + "VALUES " + "(:id, :post_id, :author, :content, :approved, :submission_date)" session.update(sql, comment.toMap()) return comment.id } override fun update(post: Post) { save(post) } override fun listAllPosts(): List<Post> { return session.select( "SELECT p.id, p.title, p.content, p.publishing_date,string_agg(pc.category,',') AS categories " + "FROM posts AS p LEFT JOIN posts_categories AS pc ON p.id = pc.id " + "GROUP BY p.id", mapper = postMapper) } override fun getAllCommentsOn(id: PostId): List<Comment> { if (!existPost(id)) throw PostRepository.PostNotFound(id) return session.select( "SELECT * " + "FROM comments " + "WHERE post_id=:post_id", hashMapOf("post_id" to id()), mapper = commentMapper ) } override fun existPost(id: PostId): Boolean { return session.select("SELECT " + "FROM posts " + "WHERE id=:post_id", hashMapOf("post_id" to id()), mapper = {} ).count() == 1 } override fun getPost(id: PostId): Post { return session.select( "SELECT p.id, p.title, p.content, p.publishing_date,string_agg(pc.category,',') AS categories " + "FROM posts AS p LEFT JOIN posts_categories AS pc ON p.id = pc.id " + "WHERE p.id=:post_id " + "GROUP BY p.id", hashMapOf("post_id" to id()), mapper = postMapper ).firstOrNull()?: throw PostRepository.PostNotFound(id) } override fun deletePost(id: PostId) { if (!existPost(id)) throw PostRepository.PostNotFound(id) session.update("DELETE FROM posts WHERE id=:post_id", hashMapOf("post_id" to id())) } override fun deleteComment(id: CommentId) { session.update("DELETE FROM comments WHERE id=:comment_id", hashMapOf("comment_id" to id())) } } class PostgresPostRepositoryForTesting(dbSetup: DatabaseSetup) : PostgresPostRepository(dbSetup), PostRepositoryForTesting, PostRepository { override fun cleanDatabase() { session.update("TRUNCATE posts CASCADE") } }
lib/Domain/src/main/kotlin/com/blok/post/Infrastructure/PostgresPostRepository.kt
3148694780
package org.jmailen.gradle.kotlinter.support import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.core.Reporter import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap import java.util.concurrent.ConcurrentSkipListSet /** * A wrapper for a Reporter that guarantees thread safety and consistent ordering of all the calls to the reporter. * As a downside, the calls to the wrapped reporter are delayed until the end of the execution. */ class SortedThreadSafeReporterWrapper( private val wrapped: Reporter, ) : Reporter { private val callsToBefore: ConcurrentMap<String, Unit> = ConcurrentHashMap() private val lintErrorReports: ConcurrentMap<String, ConcurrentSkipListSet<LintErrorReport>> = ConcurrentHashMap() private val callsToAfter: ConcurrentMap<String, Unit> = ConcurrentHashMap() override fun beforeAll() { wrapped.beforeAll() } override fun before(file: String) { callsToBefore[file] = Unit } override fun onLintError(file: String, err: LintError, corrected: Boolean) { lintErrorReports.putIfAbsent(file, ConcurrentSkipListSet()) lintErrorReports[file]!!.add(LintErrorReport(err, corrected)) } override fun after(file: String) { callsToAfter[file] = Unit } override fun afterAll() { (callsToBefore.keys + lintErrorReports.keys + callsToAfter.keys) .sorted() .forEach { fileName -> if (callsToBefore.contains(fileName)) { wrapped.before(fileName) } lintErrorReports[fileName]?.let { lintErrorReports -> lintErrorReports.forEach { wrapped.onLintError(fileName, it.lintError, it.corrected) } } if (callsToAfter.contains(fileName)) { wrapped.after(fileName) } } wrapped.afterAll() } fun unwrap() = wrapped private data class LintErrorReport( val lintError: LintError, val corrected: Boolean, ) : Comparable<LintErrorReport> { override fun compareTo(other: LintErrorReport) = when (lintError.line == other.lintError.line) { true -> lintError.col.compareTo(other.lintError.col) false -> lintError.line.compareTo(other.lintError.line) } } }
src/main/kotlin/org/jmailen/gradle/kotlinter/support/SortedThreadSafeReporterWrapper.kt
369946199
package com.commonsense.android.kotlin.system.permissions import android.content.* import android.support.annotation.* import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.extensions.collections.* import com.commonsense.android.kotlin.system.base.* //region Permission enum extensions @UiThread fun PermissionEnum.useIfPermitted(context: Context, usePermission: EmptyFunction, useError: EmptyFunction) { havePermission(context) .ifTrue(usePermission) .ifFalse(useError) } @UiThread inline fun PermissionEnum.usePermission(context: Context, usePermission: EmptyFunction) { havePermission(context).ifTrue(usePermission) } @UiThread fun PermissionEnum.havePermission(context: Context): Boolean = context.havePermission(permissionValue) //endregion //region activity / fragment permissions extensions //region Base activity permission enum /** * Asks iff necessary, for the use of the given permission * if allowed, the usePermission callback will be called * if not allowed the onFailed callback will be called */ @UiThread fun BaseActivity.usePermissionEnum(permission: PermissionEnum, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissionsEnum( listOf(permission), this, usePermission, onFailed) } @UiThread fun BaseActivity.usePermissionEnumFull(permission: PermissionEnum, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissionsEnumFull( listOf(permission), this, usePermission, onFailed) } @UiThread fun BaseActivity.usePermissionEnums(permissions: List<PermissionEnum>, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissionsEnum( permissions, this, usePermission, onFailed) } @UiThread fun BaseActivity.usePermissionEnumsFull(permissions: List<PermissionEnum>, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissionsEnumFull( permissions, this, usePermission, onFailed) } //endregion //region Base activity permission string @UiThread fun BaseActivity.usePermission(permission: @DangerousPermissionString String, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissions( listOf(permission), this, usePermission, onFailed) } @UiThread fun BaseActivity.usePermissionFull(permission: @DangerousPermissionString String, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissionsFull( listOf(permission), this, usePermission, onFailed) } @UiThread fun BaseActivity.usePermissions(permissions: List<@DangerousPermissionString String>, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissions( permissions.toList(), this, usePermission, onFailed) } @UiThread fun BaseActivity.usePermissionsFull(permissions: List<@DangerousPermissionString String>, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback? = null) { permissionHandler.performActionForPermissionsFull( permissions.toList(), this, usePermission, onFailed) } //endregion //region Base fragment use permission enum /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permission PermissionEnum * @param usePermission EmptyFunction * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissionEnum(permission: PermissionEnum, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissionEnum( permission, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), listOf(permission.permissionValue)) } } /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permission PermissionEnum * @param usePermission PermissionsSuccessCallback * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissionEnumFull(permission: PermissionEnum, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissionEnumFull( permission, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), listOf(permission.permissionValue)) } } /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permissions List<PermissionEnum> * @param usePermission EmptyFunction * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissionEnums(permissions: List<PermissionEnum>, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissionEnums( permissions, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), permissions.map { it.permissionValue }) } } /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permissions List<PermissionEnum> * @param usePermission PermissionsSuccessCallback * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissionEnumsFull(permissions: List<PermissionEnum>, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissionEnumsFull( permissions, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), permissions.map { it.permissionValue }) } } //endregion //region base fragment use permission string /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permission @DangerousPermissionString String * @param usePermission EmptyFunction * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermission(permission: @DangerousPermissionString String, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermission( permission, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), listOf(permission)) } } /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permission @DangerousPermissionString String * @param usePermission PermissionsSuccessCallback * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissionFull(permission: @DangerousPermissionString String, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissionFull( permission, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), listOf(permission)) } } /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permission List<@DangerousPermissionString String> * @param usePermission EmptyFunction * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissions(permission: List<@DangerousPermissionString String>, usePermission: EmptyFunction, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissions( permission, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), permission) } } /** * * NB if the activity IS NOT A BASEACTIVITY then onfailed will be called * @receiver BaseFragment * @param permission List<@DangerousPermissionString String> * @param usePermission PermissionsSuccessCallback * @param onFailed PermissionsFailedCallback? */ @UiThread fun BaseFragment.usePermissionsFull(permission: List<@DangerousPermissionString String>, usePermission: PermissionsSuccessCallback, onFailed: PermissionsFailedCallback?) { val baseAct = baseActivity if (baseAct != null) { baseAct.usePermissionsFull( permission, usePermission, onFailed) } else { onFailed?.invoke(emptyList(), permission) } } //endregion //endregion
system/src/main/kotlin/com/commonsense/android/kotlin/system/permissions/PermissionsExtensions.kt
2377070812
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.base.dto import com.google.gson.annotations.SerializedName import kotlin.Int enum class BaseSex( val value: Int ) { @SerializedName("0") UNKNOWN(0), @SerializedName("1") FEMALE(1), @SerializedName("2") MALE(2); }
api/src/main/java/com/vk/sdk/api/base/dto/BaseSex.kt
2222757666
package ca.fuwafuwa.kaku.Windows import android.content.Context import ca.fuwafuwa.kaku.* /** * It seems like opening and closing a bunch of windows causes Android to start to lag pretty hard. * Therefore, we should keep only one instance of each type of window in memory, and show()ing and * hide()ing the window when necessary. This class is to help facilitate this communication. * * Edit: The lag actually might have been caused by a memory leak. But this is here now, so might * as well keep it. */ class WindowCoordinator(private val context: Context) { val windows: MutableMap<String, Window> = mutableMapOf() private val windowInitMap: Map<String, () -> Window> = mutableMapOf( WINDOW_INFO to fun(): Window { return InformationWindow(context, this) }, WINDOW_EDIT to fun(): Window { return EditWindow(context, this) }, WINDOW_CAPTURE to fun(): Window { return CaptureWindow(context, this) }, WINDOW_INSTANT_KANJI to fun(): Window { return InstantKanjiWindow(context, this) }, //WINDOW_HISTORY to fun(): Window { return HistoryWindow(context, this) }, WINDOW_KANJI_CHOICE to fun(): Window { return KanjiChoiceWindow(context, this) } ) fun getWindow(key: String) : Window { if (!windows.containsKey(key)) { windows[key] = windowInitMap.getValue(key).invoke() } return windows[key]!! } fun <WindowType> getWindowOfType(key: String) : WindowType { return getWindow(key) as WindowType } /** * Should only be called by {@link Window#stop()} - calling this outside that method may result in a memory leak */ fun removeWindow(window: Window) { var key : String? = null windows.forEach { if (it.value === window) { key = it.key } } if (key != null) windows.remove(key!!) } fun hasWindow(key: String) : Boolean { return windows.containsKey(key) } fun reinitAllWindows() { windows.forEach { it.value.reInit(Window.ReinitOptions()) } } fun stopAllWindows() { val windows = windows.toList() windows.forEach { it.second.stop() } } }
app/src/main/java/ca/fuwafuwa/kaku/Windows/WindowCoordinator.kt
3172813304
package y2k.joyreactor.viewmodel import y2k.joyreactor.common.platform.NavigationService import y2k.joyreactor.common.platform.open import y2k.joyreactor.common.ui import y2k.joyreactor.model.Post import y2k.joyreactor.services.PostService /** * Created by y2k on 10/07/16. */ class PostItemViewModel( private val navigation: NavigationService, private val postService: PostService, val post: Post) { fun postClicked() { navigation.open<PostViewModel>(post.id) } fun playClicked() { if (post.image?.isAnimated ?: false) navigation.open<VideoViewModel>(post.id) else navigation.open<ImageViewModel>(post.image!!.fullUrl()) } fun changeLike() { navigation.open<PostLikeViewModel>("" + post.id) } fun toggleFavorite() { postService.toggleFavorite(post.id).ui() } }
core/src/main/kotlin/y2k/joyreactor/viewmodel/PostItemViewModel.kt
3819545769
package com.github.sybila.ode.generator import com.github.sybila.ode.model.Evaluable /** * Utility class that allows us to define any arbitrary equation by simply listing values */ class ExplicitEvaluable( override val varIndex: Int, private val values: Map<Double, Double> = mapOf() ) : Evaluable { override fun eval(value: Double) = values[value] ?: throw IllegalArgumentException("Function not defined for $value") }
src/test/kotlin/com/github/sybila/ode/generator/ExplicitEvaluable.kt
1445999403
package de.westnordost.streetcomplete.data.elementfilter import de.westnordost.osmapi.map.data.Element import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.NODES import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.WAYS import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.RELATIONS import de.westnordost.streetcomplete.data.elementfilter.filters.ElementFilter import java.util.* /** Represents a parse result of a string in filter syntax, i.e. * "ways with (highway = residential or highway = tertiary) and !name" */ class ElementFilterExpression( private val elementsTypes: EnumSet<ElementsTypeFilter>, private val elementExprRoot: BooleanExpression<ElementFilter, Element>? ) { /** returns whether the given element is found through (=matches) this expression */ fun matches(element: Element): Boolean = includesElementType(element.type) && (elementExprRoot?.matches(element) ?: true) fun includesElementType(elementType: Element.Type): Boolean = when (elementType) { Element.Type.NODE -> elementsTypes.contains(NODES) Element.Type.WAY -> elementsTypes.contains(WAYS) Element.Type.RELATION -> elementsTypes.contains(RELATIONS) else -> false } /** returns this expression as a Overpass query string */ fun toOverpassQLString(): String = OverpassQueryCreator(elementsTypes, elementExprRoot).create() } /** Enum that specifies which type(s) of elements to retrieve */ enum class ElementsTypeFilter { NODES, WAYS, RELATIONS }
app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/ElementFilterExpression.kt
527702334
package de.westnordost.streetcomplete.quests import dagger.Module import dagger.Provides import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.data.meta.CountryInfos import de.westnordost.streetcomplete.data.osmnotes.notequests.OsmNoteQuestType import de.westnordost.streetcomplete.data.quest.QuestTypeRegistry import de.westnordost.streetcomplete.quests.accepts_cash.AddAcceptsCash import de.westnordost.streetcomplete.quests.address.AddAddressStreet import de.westnordost.streetcomplete.quests.housenumber.AddHousenumber import de.westnordost.streetcomplete.quests.baby_changing_table.AddBabyChangingTable import de.westnordost.streetcomplete.quests.bench_backrest.AddBenchBackrest import de.westnordost.streetcomplete.quests.bike_parking_capacity.AddBikeParkingCapacity import de.westnordost.streetcomplete.quests.bike_parking_cover.AddBikeParkingCover import de.westnordost.streetcomplete.quests.bike_parking_type.AddBikeParkingType import de.westnordost.streetcomplete.quests.bikeway.AddCycleway import de.westnordost.streetcomplete.quests.board_type.AddBoardType import de.westnordost.streetcomplete.quests.bridge_structure.AddBridgeStructure import de.westnordost.streetcomplete.quests.building_levels.AddBuildingLevels import de.westnordost.streetcomplete.quests.building_type.AddBuildingType import de.westnordost.streetcomplete.quests.building_underground.AddIsBuildingUnderground import de.westnordost.streetcomplete.quests.bus_stop_bench.AddBenchStatusOnBusStop import de.westnordost.streetcomplete.quests.bus_stop_shelter.AddBusStopShelter import de.westnordost.streetcomplete.quests.car_wash_type.AddCarWashType import de.westnordost.streetcomplete.quests.construction.MarkCompletedBuildingConstruction import de.westnordost.streetcomplete.quests.construction.MarkCompletedHighwayConstruction import de.westnordost.streetcomplete.quests.crossing_type.AddCrossingType import de.westnordost.streetcomplete.quests.crossing_island.AddCrossingIsland import de.westnordost.streetcomplete.quests.defibrillator.AddIsDefibrillatorIndoor import de.westnordost.streetcomplete.quests.diet_type.AddVegan import de.westnordost.streetcomplete.quests.diet_type.AddVegetarian import de.westnordost.streetcomplete.quests.ferry.AddFerryAccessMotorVehicle import de.westnordost.streetcomplete.quests.ferry.AddFerryAccessPedestrian import de.westnordost.streetcomplete.quests.fire_hydrant.AddFireHydrantType import de.westnordost.streetcomplete.quests.foot.AddProhibitedForPedestrians import de.westnordost.streetcomplete.quests.general_fee.AddGeneralFee import de.westnordost.streetcomplete.quests.handrail.AddHandrail import de.westnordost.streetcomplete.quests.step_count.AddStepCount import de.westnordost.streetcomplete.quests.internet_access.AddInternetAccess import de.westnordost.streetcomplete.quests.leaf_detail.AddForestLeafType import de.westnordost.streetcomplete.quests.bus_stop_name.AddBusStopName import de.westnordost.streetcomplete.quests.bus_stop_ref.AddBusStopRef import de.westnordost.streetcomplete.quests.road_name.AddRoadName import de.westnordost.streetcomplete.quests.road_name.data.RoadNameSuggestionsDao import de.westnordost.streetcomplete.quests.max_height.AddMaxHeight import de.westnordost.streetcomplete.quests.max_speed.AddMaxSpeed import de.westnordost.streetcomplete.quests.max_weight.AddMaxWeight import de.westnordost.streetcomplete.quests.motorcycle_parking_capacity.AddMotorcycleParkingCapacity import de.westnordost.streetcomplete.quests.motorcycle_parking_cover.AddMotorcycleParkingCover import de.westnordost.streetcomplete.quests.oneway.AddOneway import de.westnordost.streetcomplete.quests.oneway_suspects.AddSuspectedOneway import de.westnordost.streetcomplete.quests.oneway_suspects.data.TrafficFlowSegmentsApi import de.westnordost.streetcomplete.quests.oneway_suspects.data.WayTrafficFlowDao import de.westnordost.streetcomplete.quests.opening_hours.AddOpeningHours import de.westnordost.streetcomplete.quests.atm_operator.AddAtmOperator import de.westnordost.streetcomplete.quests.charging_station_capacity.AddChargingStationCapacity import de.westnordost.streetcomplete.quests.charging_station_operator.AddChargingStationOperator import de.westnordost.streetcomplete.quests.clothing_bin_operator.AddClothingBinOperator import de.westnordost.streetcomplete.quests.diet_type.AddKosher import de.westnordost.streetcomplete.quests.drinking_water.AddDrinkingWater import de.westnordost.streetcomplete.quests.existence.CheckExistence import de.westnordost.streetcomplete.quests.lanes.AddLanes import de.westnordost.streetcomplete.quests.kerb_height.AddKerbHeight import de.westnordost.streetcomplete.quests.orchard_produce.AddOrchardProduce import de.westnordost.streetcomplete.quests.parking_access.AddBikeParkingAccess import de.westnordost.streetcomplete.quests.parking_access.AddParkingAccess import de.westnordost.streetcomplete.quests.parking_fee.AddBikeParkingFee import de.westnordost.streetcomplete.quests.parking_fee.AddParkingFee import de.westnordost.streetcomplete.quests.parking_type.AddParkingType import de.westnordost.streetcomplete.quests.place_name.AddPlaceName import de.westnordost.streetcomplete.quests.playground_access.AddPlaygroundAccess import de.westnordost.streetcomplete.quests.postbox_collection_times.AddPostboxCollectionTimes import de.westnordost.streetcomplete.quests.postbox_ref.AddPostboxRef import de.westnordost.streetcomplete.quests.postbox_royal_cypher.AddPostboxRoyalCypher import de.westnordost.streetcomplete.quests.powerpoles_material.AddPowerPolesMaterial import de.westnordost.streetcomplete.quests.railway_crossing.AddRailwayCrossingBarrier import de.westnordost.streetcomplete.quests.summit_register.AddSummitRegister import de.westnordost.streetcomplete.quests.recycling.AddRecyclingType import de.westnordost.streetcomplete.quests.recycling_glass.DetermineRecyclingGlass import de.westnordost.streetcomplete.quests.recycling_material.AddRecyclingContainerMaterials import de.westnordost.streetcomplete.quests.religion.AddReligionToPlaceOfWorship import de.westnordost.streetcomplete.quests.religion.AddReligionToWaysideShrine import de.westnordost.streetcomplete.quests.roof_shape.AddRoofShape import de.westnordost.streetcomplete.quests.segregated.AddCyclewaySegregation import de.westnordost.streetcomplete.quests.self_service.AddSelfServiceLaundry import de.westnordost.streetcomplete.quests.shop_type.CheckShopType import de.westnordost.streetcomplete.quests.sidewalk.AddSidewalk import de.westnordost.streetcomplete.quests.sport.AddSport import de.westnordost.streetcomplete.quests.steps_incline.AddStepsIncline import de.westnordost.streetcomplete.quests.steps_ramp.AddStepsRamp import de.westnordost.streetcomplete.quests.surface.* import de.westnordost.streetcomplete.quests.tactile_paving.AddTactilePavingBusStop import de.westnordost.streetcomplete.quests.tactile_paving.AddTactilePavingCrosswalk import de.westnordost.streetcomplete.quests.tactile_paving.AddTactilePavingKerb import de.westnordost.streetcomplete.quests.toilet_availability.AddToiletAvailability import de.westnordost.streetcomplete.quests.toilets_fee.AddToiletsFee import de.westnordost.streetcomplete.quests.tourism_information.AddInformationToTourism import de.westnordost.streetcomplete.quests.tracktype.AddTracktype import de.westnordost.streetcomplete.quests.traffic_signals_button.AddTrafficSignalsButton import de.westnordost.streetcomplete.quests.traffic_signals_vibrate.AddTrafficSignalsVibration import de.westnordost.streetcomplete.quests.traffic_signals_sound.AddTrafficSignalsSound import de.westnordost.streetcomplete.quests.way_lit.AddWayLit import de.westnordost.streetcomplete.quests.wheelchair_access.* import java.util.concurrent.FutureTask import javax.inject.Singleton @Module object QuestModule { @Provides @Singleton fun questTypeRegistry( osmNoteQuestType: OsmNoteQuestType, roadNameSuggestionsDao: RoadNameSuggestionsDao, trafficFlowSegmentsApi: TrafficFlowSegmentsApi, trafficFlowDao: WayTrafficFlowDao, featureDictionaryFuture: FutureTask<FeatureDictionary>, countryInfos: CountryInfos ): QuestTypeRegistry = QuestTypeRegistry(listOf( // ↓ 1. notes osmNoteQuestType, // ↓ 2. important data that is used by many data consumers AddRoadName(roadNameSuggestionsDao), AddPlaceName(featureDictionaryFuture), AddOneway(), // not that useful as such, but should be shown before CheckExistence because this is // basically the check whether the postbox is still there in countries in which it is enabled AddPostboxCollectionTimes(), CheckExistence(featureDictionaryFuture), AddSuspectedOneway(trafficFlowSegmentsApi, trafficFlowDao), AddCycleway(), // for any cyclist routers (and cyclist maps) AddSidewalk(), // for any pedestrian routers AddBusStopName(), AddBusStopRef(), AddIsBuildingUnderground(), //to avoid asking AddHousenumber and other for underground buildings AddHousenumber(), AddAddressStreet(roadNameSuggestionsDao), CheckShopType(), MarkCompletedHighwayConstruction(), AddReligionToPlaceOfWorship(), // icons on maps are different - OSM Carto, mapy.cz, OsmAnd, Sputnik etc AddParkingAccess(), //OSM Carto, mapy.cz, OSMand, Sputnik etc // ↓ 3. useful data that is used by some data consumers AddRecyclingType(), AddRecyclingContainerMaterials(), AddSport(), AddRoadSurface(), // used by BRouter, OsmAnd, OSRM, graphhopper, HOT map style... AddMaxSpeed(), // should best be after road surface because it excludes unpaved roads AddMaxHeight(), // OSRM and other routing engines AddLanes(), // abstreet, certainly most routing engines AddRailwayCrossingBarrier(), // useful for routing AddOpeningHours(featureDictionaryFuture), AddBikeParkingCapacity(), // used by cycle map layer on osm.org, OsmAnd AddOrchardProduce(), AddBuildingType(), // because housenumber, building levels etc. depend on it AddProhibitedForPedestrians(), // uses info from AddSidewalk quest, should be after it AddCrossingType(), AddCrossingIsland(), AddBuildingLevels(), AddBusStopShelter(), // at least OsmAnd AddVegetarian(), AddVegan(), AddInternetAccess(), // used by OsmAnd AddParkingFee(), // used by OsmAnd AddMotorcycleParkingCapacity(), AddPathSurface(), // used by OSM Carto, BRouter, OsmAnd, OSRM, graphhopper... AddTracktype(), // widely used in map rendering - OSM Carto, OsmAnd... AddMaxWeight(), // used by OSRM and other routing engines AddForestLeafType(), // used by OSM Carto AddBikeParkingType(), // used by OsmAnd AddBikeParkingAccess(), AddBikeParkingFee(), AddStepsRamp(), AddWheelchairAccessToilets(), // used by wheelmap, OsmAnd, MAPS.ME AddPlaygroundAccess(), //late as in many areas all needed access=private is already mapped AddWheelchairAccessBusiness(featureDictionaryFuture), // used by wheelmap, OsmAnd, MAPS.ME AddToiletAvailability(), //OSM Carto, shown in OsmAnd descriptions AddFerryAccessPedestrian(), AddFerryAccessMotorVehicle(), AddAcceptsCash(featureDictionaryFuture), // ↓ 4. definitely shown as errors in QA tools // ↓ 5. may be shown as missing in QA tools DetermineRecyclingGlass(), // because most recycling:glass=yes is a tagging mistake // ↓ 6. may be shown as possibly missing in QA tools // ↓ 7. data useful for only a specific use case AddWayLit(), // used by OsmAnd if "Street lighting" is enabled. (Configure map, Map rendering, Details) AddToiletsFee(), // used by OsmAnd in the object description AddBabyChangingTable(), // used by OsmAnd in the object description AddBikeParkingCover(), // used by OsmAnd in the object description AddDrinkingWater(), // used by AnyFinder AddTactilePavingCrosswalk(), // Paving can be completed while waiting to cross AddTactilePavingKerb(), // Paving can be completed while waiting to cross AddKerbHeight(), // Should be visible while waiting to cross AddTrafficSignalsSound(), // Sound needs to be done as or after you're crossing AddTrafficSignalsVibration(), AddRoofShape(countryInfos), AddWheelchairAccessPublicTransport(), AddWheelchairAccessOutside(), AddTactilePavingBusStop(), AddBridgeStructure(), AddReligionToWaysideShrine(), AddCyclewaySegregation(), MarkCompletedBuildingConstruction(), AddGeneralFee(), AddSelfServiceLaundry(), AddStepsIncline(), // can be gathered while walking perpendicular to the way e.g. the other side of the road or when running/cycling past AddHandrail(), // for accessibility of pedestrian routing, can be gathered when walking past AddStepCount(), // can only be gathered when walking along this way, also needs the most effort and least useful AddInformationToTourism(), AddAtmOperator(), AddChargingStationCapacity(), AddChargingStationOperator(), AddClothingBinOperator(), AddKosher(), // ↓ 8. defined in the wiki, but not really used by anyone yet. Just collected for // the sake of mapping it in case it makes sense later AddPitchSurface(), AddIsDefibrillatorIndoor(), AddSummitRegister(), AddCyclewayPartSurface(), AddFootwayPartSurface(), AddMotorcycleParkingCover(), AddFireHydrantType(), AddParkingType(), AddPostboxRef(), AddWheelchairAccessToiletsPart(), AddBoardType(), AddPowerPolesMaterial(), AddCarWashType(), AddBenchStatusOnBusStop(), AddBenchBackrest(), AddTrafficSignalsButton(), AddPostboxRoyalCypher() )) @Provides @Singleton fun osmNoteQuestType(): OsmNoteQuestType = OsmNoteQuestType() }
app/src/main/java/de/westnordost/streetcomplete/quests/QuestModule.kt
720553515
package com.habitrpg.android.habitica.modules import android.content.Context import android.content.SharedPreferences import com.habitrpg.android.habitica.BuildConfig import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.TaskRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.helpers.TaskAlarmManager import com.habitrpg.android.habitica.helpers.UserScope import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel import dagger.Module import dagger.Provides import javax.inject.Named @Module class UserModule { @Provides @UserScope fun providesTaskAlarmManager( context: Context, taskRepository: TaskRepository, @Named(NAMED_USER_ID) userId: String ): TaskAlarmManager { return TaskAlarmManager(context, taskRepository, userId) } @Provides @Named(NAMED_USER_ID) @UserScope fun providesUserID(sharedPreferences: SharedPreferences): String { return if (BuildConfig.DEBUG && BuildConfig.TEST_USER_ID.isNotEmpty()) { BuildConfig.TEST_USER_ID } else { sharedPreferences.getString("UserID", "") ?: "" } } @Provides @UserScope fun providesUserViewModel( @Named(NAMED_USER_ID) userID: String, userRepository: UserRepository, socialRepository: SocialRepository ) = MainUserViewModel(userID, userRepository, socialRepository) companion object { const val NAMED_USER_ID = "userId" } }
Habitica/src/main/java/com/habitrpg/android/habitica/modules/UserModule.kt
3370301666
package com.habitrpg.android.habitica.models.social import com.habitrpg.android.habitica.models.user.Authentication import com.habitrpg.android.habitica.models.user.Flags import com.habitrpg.android.habitica.models.user.Items import com.habitrpg.android.habitica.models.user.Outfit import com.habitrpg.android.habitica.models.user.Preferences import com.habitrpg.android.habitica.models.user.Stats import com.habitrpg.shared.habitica.models.Avatar import io.realm.RealmObject import io.realm.annotations.RealmClass @RealmClass(embedded = true) open class UserStyles : RealmObject(), Avatar { override val currentMount: String? get() = items?.currentMount override val currentPet: String? get() = items?.currentPet override val sleep: Boolean get() = false override val gemCount: Int get() = 0 override val hourglassCount: Int get() = 0 override val costume: Outfit? get() = items?.gear?.costume override val equipped: Outfit? get() = items?.gear?.equipped override val hasClass: Boolean get() { return false } override var balance: Double = 0.0 override var authentication: Authentication? = null override var stats: Stats? = null override var preferences: Preferences? = null override var flags: Flags? = null override var items: Items? = null }
Habitica/src/main/java/com/habitrpg/android/habitica/models/social/UserStyles.kt
2334110974
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.qos.bufferstate import com.netflix.spinnaker.orca.qos.BufferState.INACTIVE import com.netflix.spinnaker.orca.qos.BufferStateSupplier class DefaultBufferStateSupplier : BufferStateSupplier { override fun enabled() = true override fun get() = INACTIVE }
orca-qos/src/main/kotlin/com/netflix/spinnaker/orca/qos/bufferstate/DefaultBufferStateSupplier.kt
148139758
package me.liuqingwen.android.projectrefreshrecyclerview import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("me.liuqingwen.android.projectrefreshrecyclerview", appContext.packageName) } }
ProjectRefreshRecyclerView/app/src/androidTest/java/me/liuqingwen/android/projectrefreshrecyclerview/ExampleInstrumentedTest.kt
1773160906
/* Copyright 2022 Braden Farmer * * 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.farmerbb.notepad.model import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import de.schnettler.datastore.manager.PreferenceRequest object PrefKeys { val Theme = stringPreferencesKey("theme") val FontSize = stringPreferencesKey("font_size") val SortBy = stringPreferencesKey("sort_by") val ExportFilename = stringPreferencesKey("export_filename") val ShowDialogs = booleanPreferencesKey("show_dialogs") val ShowDate = booleanPreferencesKey("show_date") val DirectEdit = booleanPreferencesKey("direct_edit") val Markdown = booleanPreferencesKey("markdown") val RtlSupport = booleanPreferencesKey("rtl_layout") val ShowDoubleTapMessage = booleanPreferencesKey("show_double_tap_message") val FirstRun = intPreferencesKey("first-run") val FirstLoad = intPreferencesKey("first-load") } object Prefs { object Theme: PreferenceRequest<String>( key = PrefKeys.Theme, defaultValue = "light-sans" ) object FontSize: PreferenceRequest<String>( key = PrefKeys.FontSize, defaultValue = "normal" ) object SortBy: PreferenceRequest<String>( key = PrefKeys.SortBy, defaultValue = "date" ) object ExportFilename: PreferenceRequest<String>( key = PrefKeys.ExportFilename, defaultValue = "text-only" ) object ShowDialogs: PreferenceRequest<Boolean>( key = PrefKeys.ShowDialogs, defaultValue = false ) object ShowDate: PreferenceRequest<Boolean>( key = PrefKeys.ShowDate, defaultValue = false ) object DirectEdit: PreferenceRequest<Boolean>( key = PrefKeys.DirectEdit, defaultValue = false ) object Markdown: PreferenceRequest<Boolean>( key = PrefKeys.Markdown, defaultValue = false ) object RtlSupport: PreferenceRequest<Boolean>( key = PrefKeys.RtlSupport, defaultValue = false ) object ShowDoubleTapMessage: PreferenceRequest<Boolean>( key = PrefKeys.ShowDoubleTapMessage, defaultValue = true ) object FirstRun: PreferenceRequest<Int>( key = PrefKeys.FirstRun, defaultValue = 0 ) object FirstLoad: PreferenceRequest<Int>( key = PrefKeys.FirstLoad, defaultValue = 0 ) } enum class SortOrder(val stringValue: String) { DateDescending("date"), DateAscending("date-reversed"), TitleDescending("name-reversed"), TitleAscending("name"), } enum class FilenameFormat(val stringValue: String) { TitleOnly("text-only"), TitleAndTimestamp("text-timestamp"), TimestampAndTitle("timestamp-text"), }
app/src/main/java/com/farmerbb/notepad/model/Prefs.kt
2968165036
package com.commit451.gitlab.extension import com.commit451.gitlab.util.FileUtil import io.reactivex.rxjava3.core.Single import okhttp3.MultipartBody import java.io.File fun File.toPart(): Single<MultipartBody.Part> { return Single.fromCallable { FileUtil.toPart(this) } }
app/src/main/java/com/commit451/gitlab/extension/File.kt
2276163136
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase import org.junit.Assert import org.junit.Test class DanaRsPacketReviewGetPumpDecRatioTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRSPacketReviewGetPumpDecRatio) { it.aapsLogger = aapsLogger it.danaPump = danaPump } } } @Test fun runTest() { val packet = DanaRSPacketReviewGetPumpDecRatio(packetInjector) val array = ByteArray(100) putByteToArray(array, 0, 4.toByte()) packet.handleMessage(array) Assert.assertEquals(20, danaPump.decRatio) Assert.assertEquals("REVIEW__GET_PUMP_DEC_RATIO", packet.friendlyName) } }
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewGetPumpDecRatioTest.kt
1290072685
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.kernel.services import android.content.Context import de.greenrobot.event.EventBus import host.exp.exponent.experience.BaseExperienceActivity.ExperienceBackgroundedEvent import host.exp.exponent.experience.BaseExperienceActivity.ExperienceForegroundedEvent import host.exp.exponent.kernel.ExperienceKey abstract class BaseKernelService(protected val context: Context) { protected var currentExperienceKey: ExperienceKey? = null private set abstract fun onExperienceForegrounded(experienceKey: ExperienceKey) abstract fun onExperienceBackgrounded(experienceKey: ExperienceKey) fun onEvent(event: ExperienceBackgroundedEvent) { currentExperienceKey = null onExperienceBackgrounded(event.experienceKey) } fun onEvent(event: ExperienceForegroundedEvent) { currentExperienceKey = event.experienceKey onExperienceForegrounded(event.experienceKey) } init { EventBus.getDefault().register(this) } }
android/expoview/src/main/java/host/exp/exponent/kernel/services/BaseKernelService.kt
1696883966
package com.android import com.android.todolist.R import com.redux.AppAction import com.redux.AppState import com.redux.DevToolPresenter import javax.inject.Inject class MainPresenter @Inject constructor(private val devToolPresenter: DevToolPresenter<AppAction, AppState>) { fun bind(activity: BaseActivity) = devToolPresenter.bind(activity.findViewById(R.id.dev_tools_drawer)) }
examples/app-redux-android-todolist-kotlin/src/debug/kotlin/com/android/MainPresenter.kt
3761538288
package io.chesslave.eyes import io.chesslave.eyes.sikuli.SikuliScreen import io.chesslave.model.Color import io.chesslave.visual.Images import org.junit.Assume.assumeTrue import org.junit.Ignore import org.junit.Test import java.awt.Desktop import java.net.URI @Ignore class BoardObserverTestRunner { @Test fun example() { assumeTrue(Desktop.isDesktopSupported()) Desktop.getDesktop().browse(URI("https://www.chess.com/analysis-board-editor")) // 5 seconds to open the browser Thread.sleep(5000) val config = analyzeBoardImage(Images.read("/images/set1/initial-board.png")) val moves = BoardObserver(config, SikuliScreen()).start(Color.WHITE) moves.blockingLast() // waiting forever } }
backend/src/test/java/io/chesslave/eyes/BoardObserverTestRunner.kt
686255088
package com.mariokartleaderboard import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumentation test, which will execute on an Android device. * * @see [Testing documentation](http://d.android.com/tools/testing) */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test @Throws(Exception::class) fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.mariokartleaderboard", appContext.packageName) } }
app/src/androidTest/java/com/mariokartleaderboard/ExampleInstrumentedTest.kt
3762512935
package net.cyclestreets.views.overlay import android.content.Context import android.content.SharedPreferences import android.graphics.Canvas import android.graphics.drawable.Drawable import android.hardware.GeomagneticField import android.location.Location import android.location.LocationManager import android.util.Log import android.view.LayoutInflater import android.view.Surface import android.view.WindowManager import androidx.core.content.res.ResourcesCompat import com.google.android.material.floatingactionbutton.FloatingActionButton import net.cyclestreets.util.Logging import net.cyclestreets.view.R import net.cyclestreets.views.CycleMapView import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Overlay import org.osmdroid.views.overlay.compass.IOrientationConsumer import org.osmdroid.views.overlay.compass.IOrientationProvider import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider import org.osmdroid.views.overlay.mylocation.IMyLocationConsumer import org.osmdroid.views.overlay.mylocation.IMyLocationProvider class RotateMapOverlay(private val mapView: CycleMapView) : Overlay(), PauseResumeListener, IMyLocationConsumer, IOrientationConsumer { private val rotateButton: FloatingActionButton private val onIcon: Drawable private val offIcon: Drawable private val locationProvider: IMyLocationProvider private val compassProvider: IOrientationProvider private var rotate = false private var gpsspeed = 0f private var lat = 0f private var lon = 0f private var alt = 0f private var timeOfFix: Long = 0 private var deviceOrientation = 0 init { val context = mapView.context onIcon = ResourcesCompat.getDrawable(context.resources, R.drawable.compass, null)!! offIcon = ResourcesCompat.getDrawable(context.resources, R.drawable.compass_off, null)!! val rotateButtonView = LayoutInflater.from(context).inflate(R.layout.compassbutton, null) rotateButton = rotateButtonView.findViewById(R.id.compass_button) rotateButton.setOnClickListener { setRotation(!rotate) } mapView.addView(rotateButtonView) locationProvider = UseEverythingLocationProvider(context) compassProvider = InternalCompassOrientationProvider(context) } private fun setRotation(state: Boolean) { Log.d(TAG, "Setting map rotation to $state") rotateButton.setImageDrawable(if (state) onIcon else offIcon) if (state) startRotate() else endRotate() rotate = state } private fun startRotate() { locationProvider.startLocationProvider(this) compassProvider.startOrientationProvider(this) } private fun endRotate() { locationProvider.stopLocationProvider() compassProvider.stopOrientationProvider() resetMapOrientation() rotateButton.rotation = 0f } override fun onLocationChanged(location: Location?, source: IMyLocationProvider?) { if (location == null) return gpsspeed = location.speed lat = location.latitude.toFloat() lon = location.longitude.toFloat() alt = location.altitude.toFloat() timeOfFix = location.time if (gpsspeed > onTheMoveThreshold) setMapOrientation(location.bearing) } override fun onOrientationChanged(orientationToMagneticNorth: Float, source: IOrientationProvider?) { if (gpsspeed > onTheMoveThreshold) return val gf = GeomagneticField(lat, lon, alt, timeOfFix) var trueNorth = orientationToMagneticNorth + gf.declination synchronized(trueNorth) { if (trueNorth > 360) trueNorth -= 360 setMapOrientation(trueNorth) } } private fun setMapOrientation(orientation: Float) { var mapOrientation = 360 - orientation - deviceOrientation if (mapOrientation < 0) mapOrientation += 360 if (mapOrientation > 360) mapOrientation -= 360 //help smooth everything out mapOrientation = ((mapOrientation / 5).toInt()) * 5f mapView.mapView().apply { setMapCenterOffset(0, height / 4) setMapOrientation(mapOrientation) } rotateButton.rotation = mapOrientation } private fun resetMapOrientation() { mapView.mapView().apply { setMapCenterOffset(0, 0) setMapOrientation(0f) } } private fun captureDeviceOrientation() { val rotation = (mapView.context.getSystemService( Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation deviceOrientation = when (rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 else -> 270 } } override fun draw(c: Canvas, osmv: MapView, shadow: Boolean) {} ///////////////////////////////////////// override fun onResume(prefs: SharedPreferences) { setRotation(prefs.getBoolean(ROTATE_PREF, false)) captureDeviceOrientation() } override fun onPause(prefs: SharedPreferences.Editor) { endRotate() prefs.putBoolean(ROTATE_PREF, rotate) } companion object { private val TAG = Logging.getTag(RotateMapOverlay::class.java) private const val ROTATE_PREF = "rotateMap" private const val onTheMoveThreshold = 1 // if speed is below this, prefer the compass for orientation // once we're move, prefer gps } private class UseEverythingLocationProvider(context: Context) : GpsMyLocationProvider(context) { init { val locMan = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager for (source in locMan.getProviders(true)) addLocationSource(source) } } }
libraries/cyclestreets-view/src/main/java/net/cyclestreets/views/overlay/RotateMapOverlay.kt
893172996
package com.jtmcn.archwiki.viewer.tasks import android.os.AsyncTask import com.jtmcn.archwiki.viewer.data.SearchResult import com.jtmcn.archwiki.viewer.data.WikiPage import com.jtmcn.archwiki.viewer.data.buildPage import com.jtmcn.archwiki.viewer.data.parseSearchResults /** * Wrapper for [FetchUrl] which gives an easy to use interface * for fetching [SearchResult] and [WikiPage]. */ object Fetch { private val SEARCH_RESULTS_MAPPER = { _: String, html: StringBuilder -> parseSearchResults(html.toString()) } private val WIKI_PAGE_MAPPER = { url: String, html: StringBuilder -> buildPage(url, html) } /** * Fetches a List<SearchResults> from the url. * * @param onFinish The listener called when search results are ready. * @param url The url to fetch the search results from. * @return the async task fetching the data. */ fun search(onFinish: (List<SearchResult>) -> Unit, url: String): AsyncTask<String, Void, List<SearchResult>> { return FetchUrl(onFinish, SEARCH_RESULTS_MAPPER).execute(url) } /** * Fetches a [WikiPage] from the url. * * @param onFinish The listener called when the page is ready. * @param url The url to fetch the page from. * @return the async task fetching the data. */ fun page(onFinish: (WikiPage) -> Unit, url: String): AsyncTask<String, Void, WikiPage> { return FetchUrl(onFinish, WIKI_PAGE_MAPPER).execute(url) } }
app/src/main/java/com/jtmcn/archwiki/viewer/tasks/Fetch.kt
3657666600
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.host import arcs.core.host.api.HandleHolder import arcs.sdk.Particle import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ParticleIdentifierTest { @Test fun from_emptyString_throws() { val e = assertFailsWith<IllegalArgumentException> { ParticleIdentifier.from("") } assertThat(e).hasMessageThat().contains("Canonical variant of \"\" is blank") } @Test fun from_blankString_throws() { val e = assertFailsWith<IllegalArgumentException> { ParticleIdentifier.from(" \t") } assertThat(e).hasMessageThat().contains("Canonical variant of \" \t\" is blank") } @Test fun from_allSlashes_throws() { val e = assertFailsWith<IllegalArgumentException> { ParticleIdentifier.from("////////") } assertThat(e).hasMessageThat().contains("Canonical variant of \"////////\" is blank") } @Test fun from_almostAllSlashes() { val pid = ParticleIdentifier.from("///a/////") assertThat(pid.id).isEqualTo("a") } @Test fun from_simple() { val pid = ParticleIdentifier.from("ThisIsMe") assertThat(pid.id).isEqualTo("ThisIsMe") } @Test fun from_bazelPath() { val pid = ParticleIdentifier.from("//java/arcs/core/host/ParticleIdentifier") assertThat(pid.id).isEqualTo("java.arcs.core.host.ParticleIdentifier") } @Test fun kclassToParticleIdentifier() { val pid = MyParticleImplementation::class.toParticleIdentifier() assertThat(pid.id) .isEqualTo("arcs.core.host.ParticleIdentifierTest.MyParticleImplementation") } @Test fun anonymousKClassToParticleIdentifier() { val pid = ( object : Particle { override val handles: HandleHolder get() = throw UnsupportedOperationException() } )::class.toParticleIdentifier() assertThat(pid.id) .isEqualTo("arcs.core.host.ParticleIdentifierTest.anonymousKClassToParticleIdentifier.pid.1") } private class MyParticleImplementation : Particle { override val handles: HandleHolder get() = throw UnsupportedOperationException() } }
javatests/arcs/core/host/ParticleIdentifierTest.kt
2002316974
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.utils.DayTester /** * Test for Day04 * @author Jelle Stege */ class Day04Test : DayTester(Day04())
aoc-2015/src/test/kotlin/nl/jstege/adventofcode/aoc2015/days/Day04Test.kt
636769216
package com.timepath.hl2.io.image import com.timepath.EnumFlags import com.timepath.Logger import com.timepath.StringUtils import com.timepath.io.utils.ViewableData import java.awt.Graphics2D import java.awt.Image import java.awt.image.BufferedImage import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.nio.BufferUnderflowException import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.logging.Level import javax.swing.ImageIcon /** * TODO: .360.vtf files seem to be a slightly different format... and LZMA compressed. */ public class VTF : ViewableData { private var buf: ByteBuffer? = null public var bumpScale: Float = 0f private set public var depth: Int = 0 private set public var flags: Int = 0 private set public var format: ImageFormat? = null private set public var frameCount: Int = 0 private set /** * Zero indexed */ public var frameFirst: Int = 0 private set public var headerSize: Int = 0 private set public var height: Int = 0 private set public var mipCount: Int = 0 private set public var reflectivity: FloatArray? = null private set public var thumbFormat: ImageFormat? = null private set public var thumbHeight: Int = 0 private set private var thumbImage: Image? = null public var thumbWidth: Int = 0 private set public var version: IntArray? = null private set public var width: Int = 0 private set throws(IOException::class) fun loadFromStream(`is`: InputStream): Boolean { val magic = `is`.read() or (`is`.read() shl 8) or (`is`.read() shl 16) val type = `is`.read() if (magic != HEADER) { LOG.log(Level.FINE, { "Invalid VTF file: ${magic}" }) return false } val array = ByteArray(4 + `is`.available()) `is`.read(array, 4, array.size() - 4) buf = ByteBuffer.wrap(array) buf!!.order(ByteOrder.LITTLE_ENDIAN) buf!!.position(4) version = intArrayOf(buf!!.getInt(), buf!!.getInt()) headerSize = buf!!.getInt() if (type == 'X'.toInt()) { flags = buf!!.getInt() } width = buf!!.getShort().toInt() height = buf!!.getShort().toInt() if (type == 'X'.toInt()) { depth = buf!!.getShort().toInt() } if (type == 0) { flags = buf!!.getInt() } val enumSet = EnumFlags.decode(flags, javaClass<VTFFlags>()) frameCount = buf!!.getShort().toInt() if (type == 0) { frameFirst = buf!!.getShort().toInt() buf!!.get(ByteArray(4)) } else if (type == 'X'.toInt()) { val preloadDataSize = buf!!.getShort() val mipSkipCount = buf!!.get() val numResources = buf!!.get() } reflectivity = floatArrayOf(buf!!.getFloat().toFloat(), buf!!.getFloat().toFloat(), buf!!.getFloat().toFloat()) if (type == 0) { buf!!.get(ByteArray(4)) } bumpScale = buf!!.getFloat() format = ImageFormat.getEnumForIndex(buf!!.getInt()) if (type == 0) { mipCount = buf!!.get().toInt() thumbFormat = ImageFormat.getEnumForIndex(buf!!.getInt()) thumbWidth = buf!!.get().toInt() thumbHeight = buf!!.get().toInt() depth = buf!!.getShort().toInt() } else if (type == 'X'.toInt()) { val lowResImageSample = ByteArray(4) buf!!.get(lowResImageSample) val compressedSize = buf!!.getInt() } val debug = arrayOf(arrayOf("Width = ", width), arrayOf("Height = ", height), arrayOf("Frames = ", frameCount), arrayOf<Any?>("Flags = ", enumSet), arrayOf("Format = ", format), arrayOf("MipCount = ", mipCount)) LOG.fine({ StringUtils.fromDoubleArray(debug, "VTF:") }) return true } public fun getControls() { buf!!.position(headerSize - 8) // 8 bytes for CRC or other things. I have no idea what the data after the first 64 bytes up // until here are for val crcHead = buf!!.getInt() val crc = buf!!.getInt() if (crcHead == VTF_RSRC_TEXTURE_CRC) { LOG.info({ "CRC=0x${Integer.toHexString(crc).toUpperCase()}" }) } else { LOG.log(Level.WARNING, { "CRC header ${crcHead} is invalid" }) } } override fun getIcon() = ImageIcon(getThumbImage()) public fun getThumbImage(): Image { if (thumbImage == null) { buf!!.position(headerSize) val thumbData = ByteArray((Math.max(thumbWidth, 4) * Math.max(thumbHeight, 4)) / 2) // DXT1. Each 'block' is 4*4 pixels. 16 pixels become 8 // bytes buf!!.get(thumbData) thumbImage = DXTLoader.loadDXT1(thumbData, thumbWidth, thumbHeight) } return thumbImage!! } /** * Return the image for the given level of detail * * @param level From 0 to {@link #mipCount}-1 * @return * * @throws IOException */ throws(IOException::class) public fun getImage(level: Int): Image? = getImage(level, frameFirst) /** * Return the image for the given level of detail and frame * * @param level From 0 to {@link #mipCount}-1 * @param frame From 0 to {@link #frameCount}-1 */ public fun getImage(level: Int, frame: Int): Image? { if ((level < 0) || (level >= mipCount)) { return null } if ((frame < 0) || (frame >= frameCount)) { return null } var thumbLen = (Math.max(thumbWidth, 4) * Math.max(thumbHeight, 4)) / 2 // Thumbnail is a minimum of 4*4 if ((thumbWidth == 0) || (thumbHeight == 0)) { thumbLen = 0 } buf!!.position(headerSize + thumbLen) val sizesX = IntArray(mipCount) // smallest -> largest {1, 2, 4, 8, 16, 32, 64, 128} val sizesY = IntArray(mipCount) for (n in 0..mipCount - 1) { sizesX[mipCount - 1 - n] = Math.max(width.ushr(n), 1) sizesY[mipCount - 1 - n] = Math.max(height.ushr(n), 1) } var image: BufferedImage? = null for (i in 0..mipCount - 1) { val w = sizesX[i] val h = sizesY[i] LOG.log(Level.FINE, { "${w}, ${h}" }) val nBytes = format!!.getBytes(w, h) if (i == (mipCount - level - 1)) { val imageData = ByteArray(nBytes * frameCount) try { buf!![imageData] } catch (ignored: BufferUnderflowException) { LOG.log(Level.SEVERE, { "Underflow; ${nBytes}" }) } System.arraycopy(imageData, frame * nBytes, imageData, 0, nBytes) LOG.info({ "VTF format ${format}" }) image = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g = image.getGraphics() as Graphics2D g.drawImage(format!!.load(imageData, w, h), 0, 0, w, h, null) } else { buf!![ByteArray(nBytes * frameCount)] } } return image } companion object { /** * 'VTF\0' as little endian */ private val HEADER = 4609110 private val LOG = Logger() /** * 'CRC\2' as little endian */ private val VTF_RSRC_TEXTURE_CRC = 37966403 throws(IOException::class) public fun load(s: String): VTF? { return load(FileInputStream(s)) } throws(IOException::class) public fun load(`is`: InputStream): VTF? { val vtf = VTF() if (vtf.loadFromStream(`is`)) { return vtf } return null } } }
src/main/kotlin/com/timepath/hl2/io/image/VTF.kt
1484350064
/* * Copyright 2019 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 * * 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 promotion import common.gradleWrapper import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay import jetbrains.buildServer.configs.kotlin.v2019_2.RelativeId import vcsroots.gradlePromotionMaster object StartReleaseCycle : BasePromotionBuildType(vcsRootId = gradlePromotionMaster) { init { id("Promotion_StartReleaseCycle") name = "Start Release Cycle" description = "Promotes a successful build on master as the start of a new release cycle on the release branch" params { text("gitUserEmail", "", label = "Git user.email Configuration", description = "Enter the git 'user.email' configuration to commit change under", display = ParameterDisplay.PROMPT, allowEmpty = true) text("confirmationCode", "", label = "Confirmation Code", description = "Enter the value 'startCycle' (no quotes) to confirm the promotion", display = ParameterDisplay.PROMPT, allowEmpty = false) text("gitUserName", "", label = "Git user.name Configuration", description = "Enter the git 'user.name' configuration to commit change under", display = ParameterDisplay.PROMPT, allowEmpty = true) } steps { gradleWrapper { name = "Promote" tasks = "clean promoteStartReleaseCycle" useGradleWrapper = true gradleParams = """-PcommitId=%dep.${RelativeId("Check_Stage_ReadyforNightly_Trigger")}.build.vcs.number% -PconfirmationCode=%confirmationCode% "-PgitUserName=%gitUserName%" "-PgitUserEmail=%gitUserEmail%" """ param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL") } } dependencies { snapshot(RelativeId("Check_Stage_ReadyforNightly_Trigger")) { } } } }
.teamcity/src/main/kotlin/promotion/StartReleaseCycle.kt
3395075015
/* * Copyright 2018 Duncan Casteleyn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package be.duncanc.discordmodbot.data.services import be.duncanc.discordmodbot.data.entities.IAmRolesCategory import be.duncanc.discordmodbot.data.repositories.jpa.IAmRolesRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* @Transactional(readOnly = true) @Service class IAmRolesService @Autowired constructor( private val iAmRolesRepository: IAmRolesRepository ) { companion object { private val illegalArgumentException = IllegalArgumentException("The entity does not exist within the database.") } fun getAllCategoriesForGuild(guildId: Long): List<IAmRolesCategory> { return iAmRolesRepository.findByGuildId(guildId).toList() } fun getExistingCategoryNames(guildId: Long): Set<String> { val list: MutableSet<String> = HashSet() iAmRolesRepository.findByGuildId(guildId) .forEach { it.categoryName.let { categoryName -> list.add(categoryName) } } return list } @Transactional fun removeRole(guildId: Long, roleId: Long) { val byGuildId = iAmRolesRepository.findByGuildId(guildId) val effectedCategories = byGuildId.filter { it.roles.contains(roleId) }.toList() effectedCategories.forEach { it.roles.remove(roleId) } iAmRolesRepository.saveAll(effectedCategories) } @Transactional fun addNewCategory(guildId: Long, categoryName: String, allowedRoles: Int) { iAmRolesRepository.save(IAmRolesCategory(guildId, null, categoryName, allowedRoles)) } @Transactional fun removeCategory(guildId: Long, categoryId: Long) { iAmRolesRepository.deleteById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) } @Transactional fun changeCategoryName(guildId: Long, categoryId: Long, newName: String) { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } iAmRolesCategory.categoryName = newName iAmRolesRepository.save(iAmRolesCategory) } /** * @return returns true when added and false when the role was removed */ @Transactional fun addOrRemoveRole(guildId: Long, categoryId: Long, roleId: Long): Boolean { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } return if (iAmRolesCategory.roles.contains(roleId)) { iAmRolesCategory.roles.remove(roleId) false } else { iAmRolesCategory.roles.add(roleId) true } } @Transactional fun changeAllowedRoles(guildId: Long, categoryId: Long, newAmount: Int) { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } iAmRolesCategory.allowedRoles = newAmount iAmRolesRepository.save(iAmRolesCategory) } fun getRoleIds(guildId: Long, categoryId: Long): Set<Long> { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } return HashSet(iAmRolesCategory.roles) } }
src/main/kotlin/be/duncanc/discordmodbot/data/services/IAmRolesService.kt
1309250401
package org.wordpress.android.models.usecases import dagger.Reusable import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.fluxc.store.CommentsStore import org.wordpress.android.modules.BG_THREAD import javax.inject.Inject import javax.inject.Named @Reusable class ModerateCommentsResourceProvider @Inject constructor( val commentsStore: CommentsStore, val localCommentCacheUpdateHandler: LocalCommentCacheUpdateHandler, @Named(BG_THREAD) val bgDispatcher: CoroutineDispatcher )
WordPress/src/main/java/org/wordpress/android/models/usecases/ModerateCommentsResourceProvider.kt
1313257460
package com.subakstudio.wifi /** * Created by yeoupooh on 4/11/16. */ class WiFiAccessPoint(val ssid: String, val bssid: String, val rssi: Int, val channel: String, val ht: String, val cc: String, val securities: String) { override fun toString(): String { return String.format("${this.javaClass.simpleName}{ssid=[${ssid}] bssid=[${bssid}] rssi=[${rssi}] channel=[${channel}] ht=[${ht}] cc=[${cc}] securities=[${securities}]}") } }
src/main/kotlin/com/subakstudio/wifi/WiFiAccessPoint.kt
745372481
package org.wordpress.android.ui.bloggingprompts.onboarding interface BloggingPromptsReminderSchedulerListener { fun onSetPromptReminderClick(siteId: Int) }
WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/onboarding/BloggingPromptsReminderSchedulerListener.kt
1229249455
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.util.caching import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleByEntity import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity abstract class WorkspaceEntityChangeListener<Entity : WorkspaceEntity, Value : Any>( protected val project: Project, private val afterChangeApplied: Boolean = true ) : WorkspaceModelChangeListener { protected abstract val entityClass: Class<Entity> protected abstract fun map(storage: EntityStorage, entity: Entity): Value? protected abstract fun entitiesChanged(outdated: List<Value>) final override fun beforeChanged(event: VersionedStorageChange) { if (!afterChangeApplied) { handleEvent(event) } } final override fun changed(event: VersionedStorageChange) { if (afterChangeApplied) { handleEvent(event) } } private fun handleEvent(event: VersionedStorageChange) { val storageBefore = event.storageBefore val changes = event.getChanges(entityClass).ifEmpty { return } val outdatedEntities: List<Value> = changes.asSequence() .mapNotNull(EntityChange<Entity>::oldEntity) .mapNotNull { map(storageBefore, it) } .toList() if (outdatedEntities.isNotEmpty()) { entitiesChanged(outdatedEntities) } } } abstract class ModuleEntityChangeListener(project: Project) : WorkspaceEntityChangeListener<ModuleEntity, Module>(project) { override val entityClass: Class<ModuleEntity> get() = ModuleEntity::class.java override fun map(storage: EntityStorage, entity: ModuleEntity): Module? = storage.findModuleByEntity(entity) ?: // TODO: workaround to bypass bug with new modules not present in storageAfter WorkspaceModel.getInstance(project).entityStorage.current.findModuleByEntity(entity) }
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/caching/WorkspaceEntityChangeListener.kt
1065555463
package com.intellij.settingsSync import com.intellij.settingsSync.CloudConfigServerCommunicator.Companion.createCloudConfigClient import com.intellij.util.io.inputStream import org.junit.Assert import java.util.concurrent.CountDownLatch internal class TestCloudConfigRemoteCommunicator : TestRemoteCommunicator() { private val cloudConfigServerCommunicator = CloudConfigServerCommunicator() private val versionContext = CloudConfigVersionContext() private val client = createCloudConfigClient(versionContext) private lateinit var pushedLatch: CountDownLatch override fun prepareFileOnServer(snapshot: SettingsSnapshot) { val zip = SettingsSnapshotZipSerializer.serializeToZip(snapshot) versionContext.doWithVersion(null) { client.write(SETTINGS_SYNC_SNAPSHOT_ZIP, zip.inputStream()) } } override fun checkServerState(): ServerState = cloudConfigServerCommunicator.checkServerState() override fun receiveUpdates(): UpdateResult = cloudConfigServerCommunicator.receiveUpdates() override fun awaitForPush(): SettingsSnapshot? { pushedLatch = CountDownLatch(1) Assert.assertTrue("Didn't await until changes are pushed", pushedLatch.await(30, TIMEOUT_UNIT)) return latestPushedSnapshot } override fun push(snapshot: SettingsSnapshot, force: Boolean): SettingsSyncPushResult { val result = cloudConfigServerCommunicator.push(snapshot, force) latestPushedSnapshot = snapshot if (::pushedLatch.isInitialized) pushedLatch.countDown() return result } override fun delete() = cloudConfigServerCommunicator.delete() }
plugins/settings-sync/tests/com/intellij/settingsSync/TestCloudConfigRemoteCommunicator.kt
3608423217
// WITH_STDLIB // INTENTION_TEXT: "Add '@JvmOverloads' annotation to secondary constructor" // AFTER-WARNING: Parameter 'a' is never used // AFTER-WARNING: Parameter 'b' is never used class A { constructor(a: String = ""<caret>, b: Int) }
plugins/kotlin/idea/tests/testData/intentions/addJvmOverloads/secondaryConstructor.kt
1677815397
// "Make 'foo' not open" "true" class A() { <caret>open fun foo() {} }
plugins/kotlin/idea/tests/testData/quickfix/modifiers/openMemberInFinalClass2.kt
938313314
/* * 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.jetbrains.python.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.* import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import com.jetbrains.python.psi.types.* import one.util.streamex.StreamEx class PyDataclassTypeProvider : PyTypeProviderBase() { override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { return getDataclassesReplaceType(referenceExpression, context) } override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? { val result = when { referenceTarget is PyClass && anchor is PyCallExpression -> getDataclassTypeForClass(referenceTarget, context) referenceTarget is PyParameter && referenceTarget.isSelf && anchor is PyCallExpression -> { PsiTreeUtil.getParentOfType(referenceTarget, PyFunction::class.java) ?.takeIf { it.modifier == PyFunction.Modifier.CLASSMETHOD } ?.let { it.containingClass?.let { getDataclassTypeForClass(it, context) } } } else -> null } return PyTypeUtil.notNullToRef(result) } override fun getParameterType(param: PyNamedParameter, func: PyFunction, context: TypeEvalContext): Ref<PyType>? { if (!param.isPositionalContainer && !param.isKeywordContainer && param.annotationValue == null && func.name == DUNDER_POST_INIT) { val cls = func.containingClass val name = param.name if (cls != null && name != null && parseStdDataclassParameters(cls, context)?.init == true) { cls .findClassAttribute(name, false, context) // `true` is not used here because ancestor should be a dataclass ?.let { return Ref.create(getTypeForParameter(cls, it, PyDataclassParameters.PredefinedType.STD, context)) } for (ancestor in cls.getAncestorClasses(context)) { if (parseStdDataclassParameters(ancestor, context) != null) { ancestor .findClassAttribute(name, false, context) ?.let { return Ref.create(getTypeForParameter(ancestor, it, PyDataclassParameters.PredefinedType.STD, context)) } } } } } return null } companion object { private fun getDataclassesReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null val callee = call.callee as? PyReferenceExpression ?: return null val resolveContext = PyResolveContext.defaultContext(context) val resolvedCallee = PyUtil.multiResolveTopPriority(callee.getReference(resolveContext)).singleOrNull() return if (resolvedCallee is PyCallable) getDataclassesReplaceType(resolvedCallee, call, context) else null } private fun getDataclassesReplaceType(resolvedCallee: PyCallable, call: PyCallExpression, context: TypeEvalContext): PyCallableType? { val instanceName = when (resolvedCallee.qualifiedName) { "dataclasses.replace" -> "obj" "attr.assoc", "attr.evolve" -> "inst" else -> return null } val obj = call.getArgument(0, instanceName, PyTypedElement::class.java) ?: return null val objType = context.getType(obj) as? PyClassType ?: return null if (objType.isDefinition) return null val dataclassType = getDataclassTypeForClass(objType.pyClass, context) ?: return null val dataclassParameters = dataclassType.getParameters(context) ?: return null val parameters = mutableListOf<PyCallableParameter>() val elementGenerator = PyElementGenerator.getInstance(resolvedCallee.project) parameters.add(PyCallableParameterImpl.nonPsi(instanceName, objType)) parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() dataclassParameters.mapTo(parameters) { PyCallableParameterImpl.nonPsi(it.name, it.getType(context), ellipsis) } return PyCallableTypeImpl(parameters, dataclassType.getReturnType(context)) } private fun getDataclassTypeForClass(cls: PyClass, context: TypeEvalContext): PyCallableType? { val clsType = (context.getType(cls) as? PyClassLikeType) ?: return null val resolveContext = PyResolveContext.defaultContext(context) val elementGenerator = PyElementGenerator.getInstance(cls.project) val ellipsis = elementGenerator.createEllipsis() val collected = linkedMapOf<String, PyCallableParameter>() var seenInit = false val keywordOnly = linkedSetOf<String>() var seenKeywordOnlyClass = false val seenNames = mutableSetOf<String>() for (currentType in StreamEx.of(clsType).append(cls.getAncestorTypes(context))) { if (currentType == null || !currentType.resolveMember(PyNames.INIT, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty() || !currentType.resolveMember(PyNames.NEW, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty() || currentType !is PyClassType) { if (seenInit) continue else break } val current = currentType.pyClass val parameters = parseDataclassParameters(current, context) if (parameters == null) { if (PyKnownDecoratorUtil.hasUnknownDecorator(current, context)) break else continue } else if (parameters.type.asPredefinedType == null) { break } seenInit = seenInit || parameters.init seenKeywordOnlyClass = seenKeywordOnlyClass || parameters.kwOnly if (seenInit) { current .classAttributes .asReversed() .asSequence() .filterNot { PyTypingTypeProvider.isClassVar(it, context) } .mapNotNull { fieldToParameter(current, it, parameters.type, ellipsis, context) } .filterNot { it.first in seenNames } .forEach { (name, kwOnly, parameter) -> // note: attributes are visited from inheritors to ancestors, in reversed order for every of them if ((seenKeywordOnlyClass || kwOnly) && name !in collected) { keywordOnly += name } if (parameter == null) { seenNames.add(name) } else if (parameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) { // std: attribute that overrides ancestor's attribute does not change the order but updates type collected[name] = collected.remove(name) ?: parameter } else if (!collected.containsKey(name)) { // attrs: attribute that overrides ancestor's attribute changes the order collected[name] = parameter } } } } return if (seenInit) PyCallableTypeImpl(buildParameters(elementGenerator, collected, keywordOnly), clsType.toInstance()) else null } private fun buildParameters(elementGenerator: PyElementGenerator, fields: Map<String, PyCallableParameter>, keywordOnly: Set<String>): List<PyCallableParameter> { if (keywordOnly.isEmpty()) return fields.values.reversed() val positionalOrKeyword = mutableListOf<PyCallableParameter>() val keyword = mutableListOf<PyCallableParameter>() for ((name, value) in fields.entries.reversed()) { if (name !in keywordOnly) { positionalOrKeyword += value } else { keyword += value } } val singleStarParameter = elementGenerator.createSingleStarParameter() return positionalOrKeyword + listOf(PyCallableParameterImpl.psi(singleStarParameter)) + keyword } private fun fieldToParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): Triple<String, Boolean, PyCallableParameter?>? { val fieldName = field.name ?: return null val stub = field.stub val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(field) else stub.getCustomStub(PyDataclassFieldStub::class.java) if (fieldStub != null && !fieldStub.initValue()) return Triple(fieldName, false, null) if (fieldStub == null && field.annotationValue == null) return null // skip fields that are not annotated val parameterName = fieldName.let { if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && PyUtil.getInitialUnderscores(it) == 1) { it.substring(1) } else it } val parameter = PyCallableParameterImpl.nonPsi( parameterName, getTypeForParameter(cls, field, dataclassType, context), getDefaultValueForParameter(cls, field, fieldStub, dataclassType, ellipsis, context) ) return Triple(parameterName, fieldStub?.kwOnly() == true, parameter) } private fun getTypeForParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, context: TypeEvalContext): PyType? { if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && context.maySwitchToAST(field)) { (field.findAssignedValue() as? PyCallExpression) ?.getKeywordArgument("type") ?.let { PyTypingTypeProvider.getType(it, context) } ?.apply { return get() } } val type = context.getType(field) if (type is PyCollectionType && type.classQName == DATACLASSES_INITVAR_TYPE) { return type.elementTypes.firstOrNull() } if (type == null && dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) { methodDecoratedAsAttributeDefault(cls, field.name) ?.let { context.getReturnType(it) } ?.let { return PyUnionType.createWeakType(it) } } return type } private fun getDefaultValueForParameter(cls: PyClass, field: PyTargetExpression, fieldStub: PyDataclassFieldStub?, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): PyExpression? { return if (fieldStub == null) { when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } } else if (fieldStub.hasDefault() || fieldStub.hasDefaultFactory() || dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && methodDecoratedAsAttributeDefault(cls, field.name) != null) { ellipsis } else null } private fun methodDecoratedAsAttributeDefault(cls: PyClass, attributeName: String?): PyFunction? { if (attributeName == null) return null return cls.methods.firstOrNull { it.decoratorList?.findDecorator("$attributeName.default") != null } } } }
python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyDataclassTypeProvider.kt
610304613
package com.devbrackets.android.androidmarkup.parser.markdown import com.devbrackets.android.androidmarkup.parser.core.MarkupElement import com.devbrackets.android.androidmarkup.parser.core.SpanType import org.commonmark.node.* /** * A Converter that will take the commonmark-java * node structure and convert it to a * [com.devbrackets.android.androidMarkup.parser.core.MarkupDocument] */ open class MarkdownDocumentConverter { open fun convert(node: Node) : MarkupElement { val converterVisitor = ConverterVisitor() node.accept(converterVisitor) return converterVisitor.rootElement } open class Builder { open fun build() : MarkdownDocumentConverter { return MarkdownDocumentConverter() } } open class ConverterVisitor : AbstractVisitor() { val rootElement = MarkupElement(null) var currentElement = rootElement override fun visit(thematicBreak: ThematicBreak) { super.visit(thematicBreak) } override fun visit(blockQuote: BlockQuote) { super.visit(blockQuote) } override fun visit(code: Code) { super.visit(code) } override fun visit(fencedCodeBlock: FencedCodeBlock) { super.visit(fencedCodeBlock) } override fun visit(indentedCodeBlock: IndentedCodeBlock) { super.visit(indentedCodeBlock) } override fun visit(heading: Heading) { super.visit(heading) } override fun visit(htmlInline: HtmlInline) { super.visit(htmlInline) } override fun visit(htmlBlock: HtmlBlock) { super.visit(htmlBlock) } override fun visit(image: Image) { super.visit(image) } override fun visit(paragraph: Paragraph) { super.visit(paragraph) val element = MarkupElement(currentElement) element.spanType = SpanType.TEXT currentElement.addChild(element) element.text = "\n" } override fun visit(orderedList: OrderedList) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.ORDERED_LIST currentElement.parent?.addChild(currentElement) visitChildren(orderedList) currentElement = parent } override fun visit(bulletList: BulletList) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.UNORDERED_LIST currentElement.parent?.addChild(currentElement) visitChildren(bulletList) currentElement = parent } override fun visit(listItem: ListItem) { super.visit(listItem) } override fun visit(emphasis: Emphasis) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.ITALIC currentElement.parent?.addChild(currentElement) visitChildren(emphasis) currentElement = parent } override fun visit(strongEmphasis: StrongEmphasis) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.BOLD currentElement.parent?.addChild(currentElement) visitChildren(strongEmphasis) currentElement = parent } override fun visit(text: Text) { val element = MarkupElement(currentElement) element.spanType = SpanType.TEXT currentElement.addChild(element) element.text = text.literal.orEmpty() } override fun visit(hardLineBreak: HardLineBreak) { val element = MarkupElement(currentElement) element.spanType = SpanType.TEXT currentElement.addChild(element) element.text = "\n" } } }
library/src/main/kotlin/com/devbrackets/android/androidmarkup/parser/markdown/MarkdownDocumentConverter.kt
3648237259
/* * OysterPurse.kt * * Copyright 2019 Michael Farrell <[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 au.id.micolous.metrodroid.transit.oyster import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.transit.TransitBalance import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.util.ImmutableByteArray @Parcelize class OysterPurse( val value: Int, private val sequence: Int, private val subsequence: Int ) : Comparable<OysterPurse>, TransitBalance { override val balance: TransitCurrency get() = TransitCurrency.GBP(value) internal constructor(record: ImmutableByteArray) : this( subsequence = record.getBitsFromBuffer(4, 4), sequence = record.byteArrayToInt(1, 1), value = record.getBitsFromBufferSignedLeBits(25, 15) ) override fun compareTo(other: OysterPurse): Int { val c = sequence.compareTo(other.sequence) return when { c != 0 -> c else -> subsequence.compareTo(other.subsequence) } } companion object { internal fun parse(a: ImmutableByteArray?, b: ImmutableByteArray?) : OysterPurse? { val purseA = a?.let { OysterPurse(it) } val purseB = b?.let { OysterPurse(it) } return when { purseA == null -> purseB purseB == null -> purseA else -> maxOf(purseA, purseB) } } internal fun parse(card: ClassicCard) : OysterPurse? { return parse(card[1, 1].data, card[1, 2].data) } } }
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/oyster/OysterPurse.kt
4162210475
package csumissu.weatherforecast.util import android.app.Activity import android.app.Application import android.os.Bundle /** * @author yxsun * @since 06/08/2017 */ abstract class SimpleActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, bundle: Bundle?) { } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle?) { } override fun onActivityDestroyed(activity: Activity) { } }
app/src/main/java/csumissu/weatherforecast/util/SimpleActivityLifecycleCallbacks.kt
414272974
package com.janyo.janyoshare.util.bitmap import android.graphics.* /** * Created by mystery0. */ class RectangleBitmapCrop : BitmapCrop() { override fun crop(bitmap: Bitmap): Bitmap { val width = bitmap.width val height = bitmap.height val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) val paint = Paint() val rectF = RectF(width * 20 / 192f, height * 20 / 192f, width * 172 / 192f, height * 172 / 192f) paint.isAntiAlias = true canvas.drawARGB(0, 0, 0, 0) canvas.drawRect(rectF, paint) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)//设置图像重叠时的处理方式 canvas.drawBitmap(bitmap, 0f, 0f, paint) return output } }
app/src/main/java/com/janyo/janyoshare/util/bitmap/RectangleBitmapCrop.kt
1593173545
package com.mobilesolutionworks.android.controller.test.basic import android.support.test.espresso.Espresso.onView import android.support.test.espresso.UiController import android.support.test.espresso.matcher.ViewMatchers.isRoot import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry import android.support.test.runner.lifecycle.Stage import android.view.Surface import android.view.View import com.linkedin.android.testbutler.TestButler import com.mobilesolutionworks.android.controller.test.R import com.mobilesolutionworks.android.controller.test.base.RotationTest import com.mobilesolutionworks.android.controller.test.util.ConfigurationChangeLatch import com.mobilesolutionworks.android.controller.test.util.HostAndController import com.mobilesolutionworks.android.controller.test.util.PerformRootAction import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.* /** * Created by yunarta on 12/3/17. */ @RunWith(AndroidJUnit4::class) class ConfigurationChangesTest : RotationTest() { @Rule @JvmField var mActivityTestRule = ActivityTestRule(ConfigurationChangesTestWorksActivity::class.java) @Test public fun testConfigurationChanges() { val activityCheck = HostAndController<TestWorksController>(false) val fragmentCheck = HostAndController<TestWorksController>(false) val dialogCheck = HostAndController<TestWorksController>(false) val latch = ConfigurationChangeLatch() mActivityTestRule.activity.registerComponentCallbacks(latch) onView(isRoot()).perform(object : PerformRootAction() { override fun perform(uiController: UiController, view: View) { val resumedActivities = ArrayList(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) val activity = resumedActivities[0] as TestWorksActivity activityCheck.set(activity) val manager = activity.supportFragmentManager val fragment = manager.findFragmentById(R.id.fragment_container) as TestWorksFragment fragmentCheck.set(fragment) val dialogFragment = TestWorksDialogFragment() dialogFragment.show(manager, "dialog") manager.executePendingTransactions() dialogCheck.set(dialogFragment) } }) TestButler.setRotation(Surface.ROTATION_90) latch.await() TestButler.setRotation(Surface.ROTATION_0) latch.await() onView(isRoot()).perform(object : PerformRootAction() { override fun perform(uiController: UiController, view: View) { val resumedActivities = ArrayList(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) val activity = resumedActivities[0] as TestWorksActivity activityCheck.validate(activity) assertEquals(2, activity.controller!!.configChangesCount.toLong()) val fragment = activity.supportFragmentManager.findFragmentById(R.id.fragment_container) as TestWorksFragment fragmentCheck.validate(fragment) assertEquals(2, fragment.controller!!.configChangesCount.toLong()) val dialog = activity.supportFragmentManager.findFragmentByTag("dialog") as TestWorksDialogFragment dialogCheck.validate(dialog) assertEquals(2, dialog.controller!!.configChangesCount.toLong()) } }) } }
test-app/src/androidTest/kotlin/com/mobilesolutionworks/android/controller/test/basic/ConfigurationChangesTest.kt
3205460521
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ThreadContext") @file:Experimental package com.intellij.concurrency import com.intellij.openapi.application.AccessToken import org.jetbrains.annotations.ApiStatus.Experimental import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.VisibleForTesting import java.util.concurrent.Callable import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext private val tlCoroutineContext: ThreadLocal<CoroutineContext?> = ThreadLocal() @Internal @VisibleForTesting fun checkUninitializedThreadContext() { check(tlCoroutineContext.get() == null) { "Thread context was already set" } } /** * @return current thread context */ fun currentThreadContext(): CoroutineContext { return tlCoroutineContext.get() ?: EmptyCoroutineContext } /** * Resets the current thread context to initial value. * * @return handle to restore the previous thread context */ fun resetThreadContext(): AccessToken { return updateThreadContext { null } } /** * Replaces the current thread context with [coroutineContext]. * * @return handle to restore the previous thread context */ fun replaceThreadContext(coroutineContext: CoroutineContext): AccessToken { return updateThreadContext { coroutineContext } } /** * Updates the current thread context with [coroutineContext] as per [CoroutineContext.plus], * and runs the [action]. * * @return result of [action] invocation */ fun <X> withThreadContext(coroutineContext: CoroutineContext, action: () -> X): X { return withThreadContext(coroutineContext).use { action() } } /** * Updates the current thread context with [coroutineContext] as per [CoroutineContext.plus]. * * @return handle to restore the previous thread context */ fun withThreadContext(coroutineContext: CoroutineContext): AccessToken { return updateThreadContext { current -> if (current == null) { coroutineContext } else { current + coroutineContext } } } private fun updateThreadContext( update: (CoroutineContext?) -> CoroutineContext? ): AccessToken { val previousContext = tlCoroutineContext.get() val newContext = update(previousContext) tlCoroutineContext.set(newContext) return object : AccessToken() { override fun finish() { val currentContext = tlCoroutineContext.get() tlCoroutineContext.set(previousContext) check(currentContext === newContext) { "Context was not reset correctly" } } } } /** * Returns a `Runnable` instance, which saves [currentThreadContext] and, * when run, installs the saved context and runs original [runnable] within the installed context. * ``` * val executor = Executors.newSingleThreadExecutor() * val context = currentThreadContext() * executor.submit { * replaceThreadContext(context).use { * runnable.run() * } * } * // is roughly equivalent to * executor.submit(captureThreadContext(runnable)) * ``` * * Before installing the saved context, the returned `Runnable` asserts that there is no context already installed in the thread. * This check effectively forbids double capturing, e.g. `captureThreadContext(captureThreadContext(runnable))` will fail. * This method should be used with executors from [java.util.concurrent.Executors] or with [java.util.concurrent.CompletionStage] methods. * Do not use this method with executors returned from [com.intellij.util.concurrency.AppExecutorUtil], they already capture the context. */ fun captureThreadContext(runnable: Runnable): Runnable { return ContextRunnable(true, runnable) } /** * Same as [captureThreadContext] but for [Callable]. */ fun <V> captureThreadContext(callable: Callable<V>): Callable<V> { return ContextCallable(true, callable) }
platform/util/src/com/intellij/concurrency/threadContext.kt
1308217289
// "Convert expression to 'Char'" "true" fun char(x: Char) {} fun test(l: Long) { char(<caret>l) }
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/numberConversion/toChar/long.kt
1453155721
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade class KotlinClearPackageCachesListener(private val project: Project) : DynamicPluginListener, ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent): Unit = clearPackageCaches() override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean): Unit = clearPackageCaches() override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean): Unit = clearPackageCaches() override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor): Unit = clearPackageCaches() private fun clearPackageCaches(): Unit = KotlinJavaPsiFacade.getInstance(project).clearPackageCaches() }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinClearPackageCachesListener.kt
608176843
// "class org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix" "false" @Deprecated("", ReplaceWith("order.safeAddItem(...)")) fun oldFun() { } fun foo() { <caret>oldFun() }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/mailformedExpression.kt
260911158
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.test.java import org.junit.Test class SimpleJavaRenderLogTest : AbstractJavaRenderLogTest() { @Test fun testDataClass() = doTest("DataClass/DataClass.java") @Test fun testEnumSwitch() = doTest("Simple/EnumSwitch.java") @Test fun testLocalClass() = doTest("Simple/LocalClass.java") @Test fun testReturnX() = doTest("Simple/ReturnX.java") @Test fun testJava() = doTest("Simple/Simple.java") @Test fun testClass() = doTest("Simple/SuperTypes.java") @Test fun testTryWithResources() = doTest("Simple/TryWithResources.java") @Test fun testEnumValueMembers() = doTest("Simple/EnumValueMembers.java") @Test fun testQualifiedConstructorCall() = doTest("Simple/QualifiedConstructorCall.java") @Test fun testAnonymousClassWithParameters() = doTest("Simple/AnonymousClassWithParameters.java") @Test fun testVariableAnnotation() = doTest("Simple/VariableAnnotation.java") @Test fun testPackageInfo() = doTest("Simple/package-info.java") @Test fun testStrings() = doTest("Simple/Strings.java") @Test fun testAnnotation() = doTest("Simple/Annotation.java") @Test fun testComplexCalls() = doTest("Simple/ComplexCalls.java") @Test fun testImports() = doTest("Simple/External.java") }
uast/uast-tests/test/org/jetbrains/uast/test/java/SimpleJavaRenderLogTest.kt
3132819352
package org.kethereum.encodings import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.walleth.khex.hexToByteArray class Base58Test { // Tests from https://github.com/bitcoin/bitcoin/blob/master/src/test/data/base58_encode_decode.json val TEST_VECTORS = mapOf( "" to "", "61" to "2g", "626262" to "a3gV", "636363" to "aPEr", "73696d706c792061206c6f6e6720737472696e67" to "2cFupjhnEsSn59qHXstmK2ffpLv2", "00eb15231dfceb60925886b67d065299925915aeb172c06647" to "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L", "516b6fcd0f" to "ABnLTmg", "bf4f89001e670274dd" to "3SEo3LWLoPntC", "572e4794" to "3EFU7m", "ecac89cad93923c02321" to "EJDM8drfXA6uyA", "10c8511e" to "Rt5zm", "00000000000000000000" to "1111111111" ) @Test fun encodingToBase58Works() { TEST_VECTORS.forEach { assertThat(it.key.hexToByteArray().encodeToBase58String()).isEqualTo(it.value) } } @Test fun decodingFromBase58Works() { TEST_VECTORS.forEach { assertThat(it.value.decodeBase58()).isEqualTo(it.key.hexToByteArray()) } } }
base58/src/test/kotlin/org/kethereum/encodings/Base58Test.kt
996897166
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.frame import com.intellij.icons.AllIcons import com.intellij.ui.ColoredTextContainer import com.intellij.ui.SimpleTextAttributes import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XStackFrame import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.* // isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint) class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame, override val viewSupport: DebuggerViewSupport, val script: Script? = null, sourceInfo: SourceInfo? = null, isInLibraryContent: Boolean? = null, override val vm: Vm? = null) : XStackFrame(), VariableContext { private val sourceInfo = sourceInfo ?: viewSupport.getSourceInfo(script, callFrame) private val isInLibraryContent: Boolean = isInLibraryContent ?: (this.sourceInfo != null && viewSupport.isInLibraryContent(this.sourceInfo, script)) private var evaluator: XDebuggerEvaluator? = null override fun getEqualityObject(): Any = callFrame.equalityObject override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) createAndAddScopeList(node, callFrame.variableScopes, this, callFrame) } override val evaluateContext: EvaluateContext get() = callFrame.evaluateContext override fun watchableAsEvaluationExpression(): Boolean = true override val memberFilter: Promise<MemberFilter> get() = viewSupport.getMemberFilter(this) fun getMemberFilter(scope: Scope): Promise<MemberFilter> = createVariableContext(scope, this, callFrame).memberFilter override fun getEvaluator(): XDebuggerEvaluator? { if (evaluator == null) { evaluator = viewSupport.createFrameEvaluator(this) } return evaluator } override fun getSourcePosition(): SourceInfo? = sourceInfo override fun customizePresentation(component: ColoredTextContainer) { if (sourceInfo == null) { val scriptName = if (script == null) "unknown" else script.url.trimParameters().toDecodedForm() val line = callFrame.line component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES) return } val fileName = sourceInfo.file.name val line = sourceInfo.line + 1 val textAttributes = if (isInLibraryContent || callFrame.isFromAsyncStack) SimpleTextAttributes.GRAYED_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES val functionName = sourceInfo.functionName if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope)) { if (fileName.startsWith("index.")) { sourceInfo.file.parent?.let { component.append("${it.name}/", textAttributes) } } component.append("$fileName:$line", textAttributes) } else { if (functionName.isEmpty()) { component.append("anonymous", if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES) } else { component.append(functionName, textAttributes) } component.append("(), $fileName:$line", textAttributes) } component.setIcon(AllIcons.Debugger.StackFrame) } }
platform/script-debugger/debugger-ui/src/CallFrameView.kt
3839000052
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.sample.navigation.material import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi import com.google.accompanist.navigation.material.ModalBottomSheetLayout import com.google.accompanist.navigation.material.bottomSheet import com.google.accompanist.navigation.material.rememberBottomSheetNavigator import com.google.accompanist.sample.AccompanistSampleTheme import java.util.UUID class BottomSheetNavSample : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AccompanistSampleTheme { BottomSheetNavDemo() } } } } private object Destinations { const val Home = "HOME" const val Feed = "FEED" const val Sheet = "SHEET" } @OptIn(ExperimentalMaterialNavigationApi::class) @Composable fun BottomSheetNavDemo() { val bottomSheetNavigator = rememberBottomSheetNavigator() val navController = rememberNavController(bottomSheetNavigator) ModalBottomSheetLayout(bottomSheetNavigator) { NavHost(navController, Destinations.Home) { composable(Destinations.Home) { HomeScreen( showSheet = { navController.navigate(Destinations.Sheet + "?arg=From Home Screen") }, showFeed = { navController.navigate(Destinations.Feed) } ) } composable(Destinations.Feed) { Text("Feed!") } bottomSheet(Destinations.Sheet + "?arg={arg}") { backstackEntry -> val arg = backstackEntry.arguments?.getString("arg") ?: "Missing argument :(" BottomSheet( showFeed = { navController.navigate(Destinations.Feed) }, showAnotherSheet = { navController.navigate(Destinations.Sheet + "?arg=${UUID.randomUUID()}") }, arg = arg ) } } } } @Composable private fun HomeScreen(showSheet: () -> Unit, showFeed: () -> Unit) { Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) { Text("Body") Button(onClick = showSheet) { Text("Show sheet!") } Button(onClick = showFeed) { Text("Navigate to Feed") } } } @Composable private fun BottomSheet(showFeed: () -> Unit, showAnotherSheet: () -> Unit, arg: String) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Text("Sheet with arg: $arg") Button(onClick = showFeed) { Text("Click me to navigate!") } Button(onClick = showAnotherSheet) { Text("Click me to show another sheet!") } } }
sample/src/main/java/com/google/accompanist/sample/navigation/material/BottomSheetNavSample.kt
2752946466
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package com.google.accompanist.swiperefresh import androidx.compose.animation.core.Animatable import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlin.math.absoluteValue import kotlin.math.roundToInt private const val DragMultiplier = 0.5f /** * Creates a [SwipeRefreshState] that is remembered across compositions. * * Changes to [isRefreshing] will result in the [SwipeRefreshState] being updated. * * @param isRefreshing the value for [SwipeRefreshState.isRefreshing] */ @Deprecated( """ accompanist/swiperefresh is deprecated. The androidx.compose equivalent of rememberSwipeRefreshState() is rememberPullRefreshState(). For more migration information, please visit https://google.github.io/accompanist/swiperefresh/#migration """, replaceWith = ReplaceWith( "rememberPullRefreshState(isRefreshing, onRefresh = )", "androidx.compose.material.pullrefresh.rememberPullRefreshState" ) ) @Composable fun rememberSwipeRefreshState( isRefreshing: Boolean ): SwipeRefreshState { return remember { SwipeRefreshState( isRefreshing = isRefreshing ) }.apply { this.isRefreshing = isRefreshing } } /** * A state object that can be hoisted to control and observe changes for [SwipeRefresh]. * * In most cases, this will be created via [rememberSwipeRefreshState]. * * @param isRefreshing the initial value for [SwipeRefreshState.isRefreshing] */ @Deprecated( """ accompanist/swiperefresh is deprecated. The androidx.compose equivalent of SwipeRefreshState is PullRefreshState. For more migration information, please visit https://google.github.io/accompanist/swiperefresh/#migration """ ) @Stable class SwipeRefreshState( isRefreshing: Boolean, ) { private val _indicatorOffset = Animatable(0f) private val mutatorMutex = MutatorMutex() /** * Whether this [SwipeRefreshState] is currently refreshing or not. */ var isRefreshing: Boolean by mutableStateOf(isRefreshing) /** * Whether a swipe/drag is currently in progress. */ var isSwipeInProgress: Boolean by mutableStateOf(false) internal set /** * The current offset for the indicator, in pixels. */ val indicatorOffset: Float get() = _indicatorOffset.value internal suspend fun animateOffsetTo(offset: Float) { mutatorMutex.mutate { _indicatorOffset.animateTo(offset) } } /** * Dispatch scroll delta in pixels from touch events. */ internal suspend fun dispatchScrollDelta(delta: Float) { mutatorMutex.mutate(MutatePriority.UserInput) { _indicatorOffset.snapTo(_indicatorOffset.value + delta) } } } private class SwipeRefreshNestedScrollConnection( private val state: SwipeRefreshState, private val coroutineScope: CoroutineScope, private val onRefresh: () -> Unit, ) : NestedScrollConnection { var enabled: Boolean = false var refreshTrigger: Float = 0f override fun onPreScroll( available: Offset, source: NestedScrollSource ): Offset = when { // If swiping isn't enabled, return zero !enabled -> Offset.Zero // If we're refreshing, return zero state.isRefreshing -> Offset.Zero // If the user is swiping up, handle it source == NestedScrollSource.Drag && available.y < 0 -> onScroll(available) else -> Offset.Zero } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset = when { // If swiping isn't enabled, return zero !enabled -> Offset.Zero // If we're refreshing, return zero state.isRefreshing -> Offset.Zero // If the user is swiping down and there's y remaining, handle it source == NestedScrollSource.Drag && available.y > 0 -> onScroll(available) else -> Offset.Zero } private fun onScroll(available: Offset): Offset { if (available.y > 0) { state.isSwipeInProgress = true } else if (state.indicatorOffset.roundToInt() == 0) { state.isSwipeInProgress = false } val newOffset = (available.y * DragMultiplier + state.indicatorOffset).coerceAtLeast(0f) val dragConsumed = newOffset - state.indicatorOffset return if (dragConsumed.absoluteValue >= 0.5f) { coroutineScope.launch { state.dispatchScrollDelta(dragConsumed) } // Return the consumed Y Offset(x = 0f, y = dragConsumed / DragMultiplier) } else { Offset.Zero } } override suspend fun onPreFling(available: Velocity): Velocity { // If we're dragging, not currently refreshing and scrolled // past the trigger point, refresh! if (!state.isRefreshing && state.indicatorOffset >= refreshTrigger) { onRefresh() } // Reset the drag in progress state state.isSwipeInProgress = false // Don't consume any velocity, to allow the scrolling layout to fling return Velocity.Zero } } /** * A layout which implements the swipe-to-refresh pattern, allowing the user to refresh content via * a vertical swipe gesture. * * This layout requires its content to be scrollable so that it receives vertical swipe events. * The scrollable content does not need to be a direct descendant though. Layouts such as * [androidx.compose.foundation.lazy.LazyColumn] are automatically scrollable, but others such as * [androidx.compose.foundation.layout.Column] require you to provide the * [androidx.compose.foundation.verticalScroll] modifier to that content. * * Apps should provide a [onRefresh] block to be notified each time a swipe to refresh gesture * is completed. That block is responsible for updating the [state] as appropriately, * typically by setting [SwipeRefreshState.isRefreshing] to `true` once a 'refresh' has been * started. Once a refresh has completed, the app should then set * [SwipeRefreshState.isRefreshing] to `false`. * * If an app wishes to show the progress animation outside of a swipe gesture, it can * set [SwipeRefreshState.isRefreshing] as required. * * This layout does not clip any of it's contents, including the indicator. If clipping * is required, apps can provide the [androidx.compose.ui.draw.clipToBounds] modifier. * * @sample com.google.accompanist.sample.swiperefresh.SwipeRefreshSample * * @param state the state object to be used to control or observe the [SwipeRefresh] state. * @param onRefresh Lambda which is invoked when a swipe to refresh gesture is completed. * @param modifier the modifier to apply to this layout. * @param swipeEnabled Whether the the layout should react to swipe gestures or not. * @param refreshTriggerDistance The minimum swipe distance which would trigger a refresh. * @param indicatorAlignment The alignment of the indicator. Defaults to [Alignment.TopCenter]. * @param indicatorPadding Content padding for the indicator, to inset the indicator in if required. * @param indicator the indicator that represents the current state. By default this * will use a [SwipeRefreshIndicator]. * @param clipIndicatorToPadding Whether to clip the indicator to [indicatorPadding]. If false is * provided the indicator will be clipped to the [content] bounds. Defaults to true. * @param content The content containing a scroll composable. */ @Deprecated( """ accompanist/swiperefresh is deprecated. The androidx.compose equivalent of SwipeRefresh is Modifier.pullRefresh(). This is often migrated as: Box(modifier = Modifier.pullRefresh(refreshState)) { ... PullRefreshIndicator(...) } For more migration information, please visit https://google.github.io/accompanist/swiperefresh/#migration """ ) @Composable fun SwipeRefresh( state: SwipeRefreshState, onRefresh: () -> Unit, modifier: Modifier = Modifier, swipeEnabled: Boolean = true, refreshTriggerDistance: Dp = 80.dp, indicatorAlignment: Alignment = Alignment.TopCenter, indicatorPadding: PaddingValues = PaddingValues(0.dp), indicator: @Composable (state: SwipeRefreshState, refreshTrigger: Dp) -> Unit = { s, trigger -> SwipeRefreshIndicator(s, trigger) }, clipIndicatorToPadding: Boolean = true, content: @Composable () -> Unit, ) { val coroutineScope = rememberCoroutineScope() val updatedOnRefresh = rememberUpdatedState(onRefresh) // Our LaunchedEffect, which animates the indicator to its resting position LaunchedEffect(state.isSwipeInProgress) { if (!state.isSwipeInProgress) { // If there's not a swipe in progress, rest the indicator at 0f state.animateOffsetTo(0f) } } val refreshTriggerPx = with(LocalDensity.current) { refreshTriggerDistance.toPx() } // Our nested scroll connection, which updates our state. val nestedScrollConnection = remember(state, coroutineScope) { SwipeRefreshNestedScrollConnection(state, coroutineScope) { // On refresh, re-dispatch to the update onRefresh block updatedOnRefresh.value.invoke() } }.apply { this.enabled = swipeEnabled this.refreshTrigger = refreshTriggerPx } Box(modifier.nestedScroll(connection = nestedScrollConnection)) { content() Box( Modifier // If we're not clipping to the padding, we use clipToBounds() before the padding() // modifier. .let { if (!clipIndicatorToPadding) it.clipToBounds() else it } .padding(indicatorPadding) .matchParentSize() // Else, if we're are clipping to the padding, we use clipToBounds() after // the padding() modifier. .let { if (clipIndicatorToPadding) it.clipToBounds() else it } ) { Box(Modifier.align(indicatorAlignment)) { indicator(state, refreshTriggerDistance) } } } }
swiperefresh/src/main/java/com/google/accompanist/swiperefresh/SwipeRefresh.kt
2895839061
/* * 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.server.servlet import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.util.* import io.ktor.util.* import kotlin.random.* /** * Web resources serve configuration */ public class WebResourcesConfig @Deprecated( "Direct instantiation will be impossible in 2.0.0. " + "Use Route.webResources {} function instead " + "or file an issue describing why do you need it.", level = DeprecationLevel.ERROR ) constructor() { /** * Path predicates to be included. All files will be served if no include rules specified. * A path provided to a predicate is always slash-separated (`/`). */ public val includes: MutableList<(String) -> Boolean> = mutableListOf() /** * Path predicates to be excluded. By default WEB-INF directory is excluded. * A path provided to a predicate is always slash-separated (`/`). */ public val excludes: MutableList<(String) -> Boolean> = mutableListOf() /** * Content-type resolution, uses [defaultForFileExtension] by default */ public var mimeResolve: (String) -> ContentType = { ContentType.defaultForFileExtension(it) } /** * Add [predicate] to [includes] * @see includes */ public fun include(predicate: (path: String) -> Boolean) { includes.add(predicate) } /** * Add [predicate] exclusion rule to [excludes] * @see excludes */ public fun exclude(predicate: (path: String) -> Boolean) { excludes.add(predicate) } init { excludes.add { path -> path == "WEB-INF" || path.startsWith("WEB-INF/") } } } /** * Serve web resources (usually a directory named webapp containing WEB-INF/web.xml). Note that WEB-INF directory * itself is not served by default. * @param subPath slash-delimited web resources root path (relative to webapp directory) */ @OptIn(InternalAPI::class) public fun Route.webResources(subPath: String = "/", configure: WebResourcesConfig.() -> Unit = {}) { @Suppress("DEPRECATION_ERROR") val config = WebResourcesConfig().apply(configure) val pathParameterName = pathParameterName + "_" + Random.nextInt(0, Int.MAX_VALUE) val prefix = subPath.split('/', '\\').filter { it.isNotEmpty() } get("{$pathParameterName...}") { val filteredPath = call.parameters.getAll(pathParameterName)?.normalizePathComponents() ?: return@get val path = (prefix + filteredPath).joinToString("/", prefix = "/") if (config.excludes.any { it(path) }) { return@get } if (config.includes.isNotEmpty() && config.includes.none { it(path) }) { return@get } val url = application.attributes.getOrNull(ServletContextAttribute)?.getResource(path) ?: return@get val content = resourceClasspathResource(url, path, config.mimeResolve) ?: return@get call.respond(content) } } private const val pathParameterName = "web_resources_path_parameter"
ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/WebResources.kt
4055808428
package com.beust.kobalt import com.beust.jcommander.Parameter class Args { @Parameter var targets: List<String> = arrayListOf() @Parameter(names = arrayOf("-bf", "--buildFile"), description = "The build file") var buildFile: String? = null @Parameter(names = arrayOf("--checkVersions"), description = "Check if there are any newer versions of the " + "dependencies") var checkVersions = false @Parameter(names = arrayOf("--client")) var client: Boolean = false @Parameter(names = arrayOf("--dev"), description = "Turn on dev mode, resulting in a more verbose log output") var dev: Boolean = false @Parameter(names = arrayOf("--download"), description = "Force a download from the downloadUrl in the wrapper") var download: Boolean = false @Parameter(names = arrayOf("--dryRun"), description = "Display all the tasks that will get run without " + "actually running them") var dryRun: Boolean = false @Parameter(names = arrayOf("--force"), description = "Force a new server to be launched even if another one" + " is already running") var force: Boolean = false @Parameter(names = arrayOf("--gc"), description = "Delete old files") var gc: Boolean = false @Parameter(names = arrayOf("--help", "--usage"), description = "Display the help") var usage: Boolean = false @Parameter(names = arrayOf("-i", "--init"), description = "Invoke the templates named, separated by a comma") var templates: String? = null @Parameter(names = arrayOf("--listTemplates"), description = "List the available templates") var listTemplates: Boolean = false @Parameter(names = arrayOf("--log"), description = "Define the log level (1-3)") var log: Int = 1 @Parameter(names = arrayOf("--forceIncremental"), description = "Force the build to be incremental even if the build file was modified") var forceIncremental: Boolean = false @Parameter(names = arrayOf("--noIncremental"), description = "Turn off incremental builds") var noIncremental: Boolean = false @Parameter(names = arrayOf("--plugins"), description = "Comma-separated list of plug-in Maven id's") var pluginIds: String? = null @Parameter(names = arrayOf("--pluginJarFiles"), description = "Comma-separated list of plug-in jar files") var pluginJarFiles: String? = null @Parameter(names = arrayOf("--port"), description = "Port, if --server was specified") var port: Int? = null @Parameter(names = arrayOf("--profiles"), description = "Comma-separated list of profiles to run") var profiles: String? = null @Parameter(names = arrayOf("--resolve"), description = "Resolve the given comma-separated dependencies and display their dependency tree") var dependencies: String? = null @Parameter(names = arrayOf("--projectInfo"), description = "Display information about the current projects") var projectInfo: Boolean = false @Parameter(names = arrayOf("--server"), description = "Run in server mode") var serverMode: Boolean = false @Parameter(names = arrayOf("--tasks"), description = "Display the tasks available for this build") var tasks: Boolean = false @Parameter(names = arrayOf("--update"), description = "Update to the latest version of Kobalt") var update: Boolean = false }
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/Args.kt
2046501976
package sds.classfile.attribute import sds.classfile.ClassfileStream import sds.classfile.constant_pool.Constant class EnclosingMethod(data: ClassfileStream, pool: Array<Constant>): Attribute() { val _class: String = extract(data.short(), pool) val method: String = { x: Int -> if(x - 1 > 0) extract(x, pool) else "" }(data.short()) override fun toString(): String = "[EnclosingMethod]: ${_class}.$method" }
src/main/kotlin/sds/classfile/attribute/EnclosingMethod.kt
4288859434
package blue.aodev.animeultimetv.data.converters import blue.aodev.animeultimetv.data.model.EpisodeReleaseId import okhttp3.ResponseBody import org.jsoup.Jsoup import org.jsoup.nodes.Element import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type internal class EpisodeReleaseHistoryAdapter : Converter<ResponseBody, List<EpisodeReleaseId>> { companion object { val FACTORY: Converter.Factory = object : Converter.Factory() { override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? { if (type is ParameterizedType && getRawType(type) === List::class.java && getParameterUpperBound(0, type) === EpisodeReleaseId::class.java) { return EpisodeReleaseHistoryAdapter() } return null } } } override fun convert(responseBody: ResponseBody): List<EpisodeReleaseId> { return Jsoup.parse(responseBody.string()) .select(".history tr") .map { convertEpisodeElement(it) } .filterNotNull() } private fun convertEpisodeElement(episodeElement: Element): EpisodeReleaseId? { val tds = episodeElement.select("td") if (tds.size < 2) return null val id = tds[0].child(0).attr("href").split("/")[1].toInt() val numbers = tds[1].text() return EpisodeReleaseId(id, numbers) } }
app/src/main/java/blue/aodev/animeultimetv/data/converters/EpisodeReleaseHistoryAdapter.kt
1272413074
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.colors import com.demonwav.mcdev.nbt.lang.NbttLexerAdapter import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType class NbttSyntaxHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer() = NbttLexerAdapter() override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { return when (tokenType) { NbttTypes.BYTES, NbttTypes.INTS, NbttTypes.LONGS -> KEYWORD_KEYS NbttTypes.STRING_LITERAL -> STRING_KEYS NbttTypes.UNQUOTED_STRING_LITERAL -> UNQUOTED_STRING_KEYS NbttTypes.BYTE_LITERAL -> BYTE_KEYS NbttTypes.SHORT_LITERAL -> SHORT_KEYS NbttTypes.INT_LITERAL -> INT_KEYS NbttTypes.LONG_LITERAL -> LONG_KEYS NbttTypes.FLOAT_LITERAL -> FLOAT_KEYS NbttTypes.DOUBLE_LITERAL -> DOUBLE_KEYS else -> EMPTY_KEYS } } companion object { val KEYWORD = TextAttributesKey.createTextAttributesKey("NBTT_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD) val STRING = TextAttributesKey.createTextAttributesKey("NBTT_STRING", DefaultLanguageHighlighterColors.STRING) val UNQUOTED_STRING = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING", STRING) val STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_STRING_NAME", STRING) val UNQUOTED_STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING_NAME", STRING_NAME) val BYTE = TextAttributesKey.createTextAttributesKey("NBTT_BYTE", DefaultLanguageHighlighterColors.NUMBER) val SHORT = TextAttributesKey.createTextAttributesKey("NBTT_SHORT", DefaultLanguageHighlighterColors.NUMBER) val INT = TextAttributesKey.createTextAttributesKey("NBTT_INT", DefaultLanguageHighlighterColors.NUMBER) val LONG = TextAttributesKey.createTextAttributesKey("NBTT_LONG", DefaultLanguageHighlighterColors.NUMBER) val FLOAT = TextAttributesKey.createTextAttributesKey("NBTT_FLOAT", DefaultLanguageHighlighterColors.NUMBER) val DOUBLE = TextAttributesKey.createTextAttributesKey("NBTT_DOUBLE", DefaultLanguageHighlighterColors.NUMBER) val MATERIAL = TextAttributesKey.createTextAttributesKey("NBTT_MATERIAL", STRING) val KEYWORD_KEYS = arrayOf(KEYWORD) val STRING_KEYS = arrayOf(STRING) val UNQUOTED_STRING_KEYS = arrayOf(UNQUOTED_STRING) val BYTE_KEYS = arrayOf(BYTE) val SHORT_KEYS = arrayOf(SHORT) val INT_KEYS = arrayOf(INT) val LONG_KEYS = arrayOf(LONG) val FLOAT_KEYS = arrayOf(FLOAT) val DOUBLE_KEYS = arrayOf(DOUBLE) val EMPTY_KEYS = emptyArray<TextAttributesKey>() } }
src/main/kotlin/com/demonwav/mcdev/nbt/lang/colors/NbttSyntaxHighlighter.kt
2938555030
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.debug import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder val MIXIN_DEBUG_KEY = Key.create<Boolean>("mixin.debug") fun UserDataHolder.hasMixinDebugKey(): Boolean = getUserData(MIXIN_DEBUG_KEY) == true
src/main/kotlin/com/demonwav/mcdev/platform/mixin/debug/MixinDebug.kt
1677390309
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * 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 fredboat.audio.queue /** * Created by napster on 16.03.17. * * Helps us transfer some information about playlists. */ class PlaylistInfo(var totalTracks: Int, var name: String, var source: Source) { enum class Source { PASTESERVICE, SPOTIFY } }
FredBoat/src/main/java/fredboat/audio/queue/PlaylistInfo.kt
4142032274
package org.spekframework.spek2 import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.runBlockingTest import org.spekframework.spek2.style.specification.describe @OptIn(ExperimentalStdlibApi::class) object TimeoutTest : AbstractSpekTest({ helper -> describe("test timeouts") { it("specification style timeouts") { val recorder = GlobalScope.async { helper.executeTest(testData.timeoutTest.SpecificationStyleTimeoutTests) } helper.assertExecutionEquals( recorder.await().events() ) { group("SpecificationStyleTimeoutTests") { group("timeouts") { test("tests running pass 300ms should fail", false) test("tests running less than 500ms should succeed") } } } } it("gherkin style timeouts") { val recorder = GlobalScope.async { helper.executeTest(testData.timeoutTest.GherkinStyleTimeoutTests) } helper.assertExecutionEquals( recorder.await().events() ) { group("GherkinStyleTimeoutTests") { group("Feature: Timeouts") { group("Scenario: Running more than 600ms") { test("Then: It should fail", false) } group("Scenario: Running less than 1200ms") { test("Then: It should succeed") } } } } } describe("global timeouts") { it("should use specified global timeout") { System.setProperty("spek2.execution.test.timeout", 100L.toString()) val recorder = GlobalScope.async { helper.executeTest(testData.timeoutTest.GlobalTimeoutTest) } helper.assertExecutionEquals( recorder.await().events() ) { group("GlobalTimeoutTest") { test("this should run for 300ms and fail since global timeout is 100ms", false) } } System.clearProperty("spek2.execution.test.timeout") } } } })
integration-test/src/jvmTest/kotlin/org/spekframework/spek2/TimeoutTest.kt
3267100077
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.organisationunit.internal import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.* import io.reactivex.Completable import io.reactivex.Single import java.io.IOException import java.util.* import org.hisp.dhis.android.core.arch.api.fields.internal.Fields import org.hisp.dhis.android.core.arch.api.filters.internal.Filter import org.hisp.dhis.android.core.arch.api.payload.internal.Payload import org.hisp.dhis.android.core.arch.cleaners.internal.CollectionCleaner import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.organisationunit.OrganisationUnit import org.hisp.dhis.android.core.user.User import org.hisp.dhis.android.core.user.UserInternalAccessor import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class OrganisationUnitCallUnitShould { private val organisationUnitPayload: Payload<OrganisationUnit> = mock() private val organisationUnitService: OrganisationUnitService = mock() // Captors for the organisationUnitService arguments: private val fieldsCaptor = argumentCaptor<Fields<OrganisationUnit>>() private val filtersCaptor = argumentCaptor<Filter<OrganisationUnit, String>>() private val pagingCaptor = argumentCaptor<Boolean>() private val pageCaptor = argumentCaptor<Int>() private val pageSizeCaptor = argumentCaptor<Int>() private val orderCaptor = argumentCaptor<String>() private val organisationUnit: OrganisationUnit = mock() private val user: User = mock() private val created: Date = mock() private val collectionCleaner: CollectionCleaner<OrganisationUnit> = mock() private val organisationUnitHandler: OrganisationUnitHandler = mock() private val userOrganisationUnitLinkStore: UserOrganisationUnitLinkStore = mock() private val organisationUnitIdentifiableObjectStore: IdentifiableObjectStore<OrganisationUnit> = mock() private val organisationUnitDisplayPathTransformer: OrganisationUnitDisplayPathTransformer = mock() // the call we are testing: private lateinit var lastUpdated: Date private lateinit var organisationUnitCall: Completable @Before @Throws(IOException::class) fun setUp() { lastUpdated = Date() val orgUnitUid = "orgUnitUid1" whenever(organisationUnit.uid()).doReturn(orgUnitUid) whenever(organisationUnit.code()).doReturn("organisation_unit_code") whenever(organisationUnit.name()).doReturn("organisation_unit_name") whenever(organisationUnit.displayName()).doReturn("organisation_unit_display_name") whenever(organisationUnit.deleted()).doReturn(false) whenever(organisationUnit.created()).doReturn(created) whenever(organisationUnit.lastUpdated()).doReturn(lastUpdated) whenever(organisationUnit.shortName()).doReturn("organisation_unit_short_name") whenever(organisationUnit.displayShortName()).doReturn("organisation_unit_display_short_name") whenever(organisationUnit.description()).doReturn("organisation_unit_description") whenever(organisationUnit.displayDescription()).doReturn("organisation_unit_display_description") whenever(organisationUnit.path()).doReturn("/root/orgUnitUid1") whenever(organisationUnit.openingDate()).doReturn(created) whenever(organisationUnit.closedDate()).doReturn(lastUpdated) whenever(organisationUnit.level()).doReturn(4) whenever(organisationUnit.parent()).doReturn(null) whenever(user.uid()).doReturn("user_uid") whenever(user.code()).doReturn("user_code") whenever(user.name()).doReturn("user_name") whenever(user.displayName()).doReturn("user_display_name") whenever(user.created()).doReturn(created) whenever(user.lastUpdated()).doReturn(lastUpdated) whenever(user.birthday()).doReturn("user_birthday") whenever(user.education()).doReturn("user_education") whenever(user.gender()).doReturn("user_gender") whenever(user.jobTitle()).doReturn("user_job_title") whenever(user.surname()).doReturn("user_surname") whenever(user.firstName()).doReturn("user_first_name") whenever(user.introduction()).doReturn("user_introduction") whenever(user.employer()).doReturn("user_employer") whenever(user.interests()).doReturn("user_interests") whenever(user.languages()).doReturn("user_languages") whenever(user.email()).doReturn("user_email") whenever(user.phoneNumber()).doReturn("user_phone_number") whenever(user.nationality()).doReturn("user_nationality") organisationUnitCall = OrganisationUnitCall( organisationUnitService, organisationUnitHandler, organisationUnitDisplayPathTransformer, userOrganisationUnitLinkStore, organisationUnitIdentifiableObjectStore, collectionCleaner ) .download(user) // Return only one organisationUnit. val organisationUnits = listOf(organisationUnit) whenever(UserInternalAccessor.accessOrganisationUnits(user)).doReturn(organisationUnits) whenever( organisationUnitService.getOrganisationUnits( fieldsCaptor.capture(), filtersCaptor.capture(), orderCaptor.capture(), pagingCaptor.capture(), pageSizeCaptor.capture(), pageCaptor.capture() ) ).doReturn(Single.just(organisationUnitPayload)) whenever(organisationUnitPayload.items()).doReturn(organisationUnits) } @Test fun invoke_server_with_correct_parameters() { organisationUnitCall.blockingGet() assertThat(fieldsCaptor.firstValue).isEqualTo(OrganisationUnitFields.allFields) assertThat(filtersCaptor.firstValue.operator()).isEqualTo("like") assertThat(filtersCaptor.firstValue.field()).isEqualTo(OrganisationUnitFields.path) assertThat(orderCaptor.firstValue).isEqualTo(OrganisationUnitFields.ASC_ORDER) assertThat(pagingCaptor.firstValue).isTrue() assertThat(pageCaptor.firstValue).isEqualTo(1) } @Test fun invoke_handler_if_request_succeeds() { organisationUnitCall.blockingGet() verify(organisationUnitHandler, times(1)).handleMany(any(), any()) } @Test fun perform_call_twice_on_consecutive_calls() { organisationUnitCall.blockingGet() organisationUnitCall.blockingGet() verify(organisationUnitHandler, times(2)).handleMany(any(), any()) } }
core/src/test/java/org/hisp/dhis/android/core/organisationunit/internal/OrganisationUnitCallUnitShould.kt
333478264
// 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 git4idea.update import com.intellij.dvcs.DvcsUtil.getPushSupport import com.intellij.dvcs.repo.Repository import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.Executor.cd import com.intellij.openapi.vcs.Executor.echo import com.intellij.openapi.vcs.update.UpdatedFiles import com.intellij.openapi.vfs.VfsUtil import git4idea.config.UpdateMethod.MERGE import git4idea.config.UpdateMethod.REBASE import git4idea.push.GitPushOperation import git4idea.push.GitPushRepoResult import git4idea.push.GitPushSupport import git4idea.push.GitRejectedPushUpdateDialog import git4idea.push.GitRejectedPushUpdateDialog.REBASE_EXIT_CODE import git4idea.repo.GitRepository import git4idea.test.* import java.io.File class GitSubmoduleTest : GitSubmoduleTestBase() { private lateinit var main: GitRepository private lateinit var sub: GitRepository private lateinit var main2: RepositoryAndParent private lateinit var sub2: File override fun setUp() { super.setUp() // prepare second clone & parent.git main2 = createPlainRepo("main") val sub3 = createPlainRepo("sub") sub2 = addSubmodule(main2.local, sub3.remote, "sub") // clone into the project cd(testRoot) git("clone --recurse-submodules ${main2.remote} maintmp") FileUtil.moveDirWithContent(File(testRoot, "maintmp"), VfsUtil.virtualToIoFile(projectRoot)) cd(projectRoot) setupDefaultUsername() val subFile = File(projectPath, "sub") cd(subFile) setupDefaultUsername() refresh() main = registerRepo(project, projectPath) sub = registerRepo(project, subFile.path) } fun `test submodule in detached HEAD state is updated via 'git submodule update'`() { // push from second clone cd(sub2) echo("a", "content\n") val submoduleHash = addCommit("in submodule") git("push") cd(main2.local) val mainHash = addCommit("Advance the submodule") git("push") insertLogMarker("update process") val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), false, true).update(MERGE) assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result) assertEquals("Last commit in submodule is incorrect", submoduleHash, sub.last()) assertEquals("Last commit in main repository is incorrect", mainHash, main.last()) assertEquals("Submodule should be in detached HEAD", Repository.State.DETACHED, sub.state) } fun `test submodule on branch is updated as a normal repository`() { // push from second clone cd(sub2) echo("a", "content\n") val submoduleHash = addCommit("in submodule") git("push") // prepare commit in first sub clone cd(sub) git("checkout master") echo("b", "content\n") addCommit("msg") insertLogMarker("update process") val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), false, true).update(REBASE) assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result) assertEquals("Submodule should be on branch", "master", sub.currentBranchName) assertEquals("Commit from 2nd clone not found in submodule", submoduleHash, sub.git("rev-parse HEAD^")) } fun `test push rejected in submodule updates it and pushes again`() { // push from second clone cd(sub2) echo("a", "content\n") val submoduleHash = addCommit("in submodule") git("push") // prepare commit in first sub clone cd(sub) git("checkout master") echo("b", "content\n") addCommit("msg") val updateAllRootsIfPushRejected = settings.shouldUpdateAllRootsIfPushRejected() try { settings.setUpdateAllRootsIfPushRejected(false) dialogManager.registerDialogHandler(GitRejectedPushUpdateDialog::class.java, TestDialogHandler { REBASE_EXIT_CODE }) val pushSpecs = listOf(main, sub).associate { it to makePushSpec(it, "master", "origin/master") } insertLogMarker("push process") val result = GitPushOperation(project, getPushSupport(vcs) as GitPushSupport, pushSpecs, null, false, false).execute() val mainResult = result.results[main]!! val subResult = result.results[sub]!! assertEquals("Submodule push result is incorrect", GitPushRepoResult.Type.SUCCESS, subResult.type) assertEquals("Main push result is incorrect", GitPushRepoResult.Type.UP_TO_DATE, mainResult.type) assertEquals("Submodule should be on branch", "master", sub.currentBranchName) assertEquals("Commit from 2nd clone not found in submodule", submoduleHash, sub.git("rev-parse HEAD^")) } finally { settings.setUpdateAllRootsIfPushRejected(updateAllRootsIfPushRejected) } } private fun insertLogMarker(title: String) { LOG.info(""); LOG.info("--------- STARTING ${title.toUpperCase()} -----------") LOG.info(""); } }
plugins/git4idea/tests/git4idea/update/GitSubmoduleTest.kt
2169078054
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.domain.aggregated.data.internal import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.dataset.DataSet @Reusable internal class AggregatedDataSyncHashHelper @Inject constructor() { fun getDataSetDataElementsHash(dataSet: DataSet): Int { return dataSet.dataSetElements()!! .map { it.dataElement().uid() } .toSet() .hashCode() } }
core/src/main/java/org/hisp/dhis/android/core/domain/aggregated/data/internal/AggregatedDataSyncHashHelper.kt
1340327581
fun f(fooBar: String){} fun g(b: Boolean, a: String, foo: String, bar: String) { f(if (b) { <caret> }) } // ORDER: bar, foo, a
plugins/kotlin/completion/tests/testData/weighers/smart/NameSimilarityForBlock.kt
252047894
package training.featuresSuggester import org.jetbrains.annotations.Nls sealed class Suggestion object NoSuggestion : Suggestion() abstract class PopupSuggestion( @Nls val message: String, val suggesterId: String ) : Suggestion() class TipSuggestion( @Nls message: String, suggesterId: String, val suggestingTipFilename: String ) : PopupSuggestion(message, suggesterId) class DocumentationSuggestion( @Nls message: String, suggesterId: String, val documentURL: String ) : PopupSuggestion(message, suggesterId)
plugins/ide-features-trainer/src/training/featuresSuggester/Suggestion.kt
430485797
package katas.kotlin.coroutines import kotlin.coroutines.* import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn object Hello { fun launchCoroutine(context: CoroutineContext, coroutineScope: suspend () -> Unit) { coroutineScope.startCoroutine(MyContinuation(context)) } fun main() { var savedContinuation: Continuation<Unit>? = null val coroutineScope: suspend () -> Unit = { println("Start of scope") suspendCoroutineUninterceptedOrReturn { continuation: Continuation<Unit> -> savedContinuation = continuation println("Suspended") COROUTINE_SUSPENDED } println("End of scope") } println("Start") // coroutineScope.startCoroutineUninterceptedOrReturn(MyContinuation(EmptyCoroutineContext)) coroutineScope.startCoroutine(MyContinuation(MyEmptyCoroutineContext)) println("About to resume") savedContinuation!!.resume(Unit) // savedContinuation!!.context.printed() println("About to resume again") savedContinuation!!.resume(Unit) println("About to resume again 2") savedContinuation!!.resume(Unit) println("End") } } class MyContinuation<Unit>(override val context: CoroutineContext): Continuation<Unit> { override fun resumeWith(result: Result<Unit>) {} } object MyEmptyCoroutineContext : CoroutineContext { @Suppress("UNCHECKED_CAST") override fun <E : CoroutineContext.Element> get(key: CoroutineContext.Key<E>): E? = if (key === ContinuationInterceptor.Key) (MyInterceptor as E?) else null override fun <R> fold(initial: R, operation: (R, CoroutineContext.Element) -> R): R = initial override fun plus(context: CoroutineContext): CoroutineContext = context override fun minusKey(key: CoroutineContext.Key<*>): CoroutineContext = this override fun hashCode(): Int = 0 override fun toString(): String = "EmptyCoroutineContext" } object MyInterceptor : ContinuationInterceptor, AbstractCoroutineContextElement(Key) { object Key : CoroutineContext.Key<MyInterceptor> override fun <T> interceptContinuation(continuation: Continuation<T>) = continuation } fun main() { Hello.main() }
kotlin/src/katas/kotlin/coroutines/hello.kt
3230786398
// EXTRACTION_TARGET: property with getter val n: Int = 1 fun foo(): Int { val m = 1 return <selection>n + m + 1</selection> }
plugins/kotlin/idea/tests/testData/refactoring/introduceProperty/extractWithParams.kt
1060077051
package bar import baz.* fun B.booExtension() {} fun A.booExtensionToA() {}
plugins/kotlin/completion/tests/testData/weighers/basic/UnavailableDslReceiver.Data1.kt
1062062536
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.imports.impl import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import org.jetbrains.annotations.NonNls import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement import org.jetbrains.plugins.groovy.lang.resolve.imports.* import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint import org.jetbrains.plugins.groovy.util.flatten internal class GroovyFileImportsImpl( override val file: GroovyFileBase, private val imports: Map<ImportKind<*>, Collection<GroovyImport>>, private val statementToImport: Map<GrImportStatement, GroovyImport>, private val importToStatement: Map<GroovyImport, GrImportStatement> ) : GroovyFileImports { @Suppress("UNCHECKED_CAST") private fun <T : GroovyImport> getImports(kind: ImportKind<T>): Collection<T> { val collection = imports[kind] ?: return emptyList() return collection as Collection<T> } private val regularImports get() = getImports(ImportKind.Regular) private val staticImports get() = getImports(ImportKind.Static) override val starImports: Collection<StarImport> get() = getImports(ImportKind.Star) override val staticStarImports: Collection<StaticStarImport> get() = getImports(ImportKind.StaticStar) override val allNamedImports: Collection<GroovyNamedImport> = flatten(regularImports, staticImports) private val allStarImports = flatten(starImports, staticStarImports) private val allNamedImportsMap by lazy { allNamedImports.groupBy { it.name } } override fun getImportsByName(name: String): Collection<GroovyNamedImport> = allNamedImportsMap[name] ?: emptyList() private fun ResolveState.putImport(import: GroovyImport): ResolveState { val state = put(importKey, import) val statement = importToStatement[import] ?: return state return state.put(ClassHint.RESOLVE_CONTEXT, statement) } @Suppress("LoopToCallChain") private fun Collection<GroovyImport>.doProcess(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { for (import in this) { if (!import.processDeclarations(processor, state.putImport(import), place, file)) return false } return true } override fun processStaticImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return staticImports.doProcess(processor, state, place) } override fun processAllNamedImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return allNamedImports.doProcess(processor, state, place) } override fun processStaticStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return staticStarImports.doProcess(processor, state, place) } override fun processAllStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return allStarImports.doProcess(processor, state, place) } override fun processDefaultImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return defaultImports.doProcess(processor, state, place) } override fun isImplicit(import: GroovyImport): Boolean = !importToStatement.containsKey(import) override fun findUnnecessaryStatements(): Collection<GrImportStatement> { return statementToImport.filterValues { it.isUnnecessary(this) }.keys } override fun findUnresolvedStatements(names: Collection<String>): Collection<GrImportStatement> { if (names.isEmpty()) return emptyList() val result = HashSet<GrImportStatement>() for (import in starImports) { val statement = importToStatement[import] ?: continue if (import.resolveImport(file) == null) { result += statement } } for (import in allNamedImports) { if (import.name !in names) continue val statement = importToStatement[import] ?: continue if (import.resolveImport(file) == null) { result += statement } } return result } @NonNls override fun toString(): String = "Regular: ${regularImports.size}; " + "static: ${staticImports.size}; " + "*: ${starImports.size}; " + "static *: ${staticStarImports.size}" }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/impl/GroovyFileImportsImpl.kt
2150307083
package io.github.tobyhs.weatherweight.data import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class LocationNotFoundErrorTest { @Test fun constructorSetsMessage() { val error = LocationNotFoundError("Nowhere") assertThat(error.message, equalTo("Location Nowhere not found")) } }
app/src/test/java/io/github/tobyhs/weatherweight/data/LocationNotFoundErrorTest.kt
24680364
package watch.gnag.website.handlers import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse import watch.gnag.website.utils.SessionUtil import java.net.URI @Component class SiteHandler { fun index(request: ServerRequest) = SessionUtil.clearSession(request.session()) .then( ServerResponse.ok() .contentType(MediaType.TEXT_HTML) .render("index") ) fun configHelper(request: ServerRequest) = SessionUtil.getTokenFromSession(request.session()) .flatMap { ServerResponse.ok() .contentType(MediaType.TEXT_HTML) .render("confighelper") } .switchIfEmpty(ServerResponse.temporaryRedirect(URI("/startAuth")).build()) }
src/main/kotlin/watch/gnag/website/handlers/SiteHandler.kt
2158887872
fun hello(): String = "hello world" fun hello(name: String): String = "hello to you $name" fun invocation() { val string = "hello" val length = string.take(5) } object Square { fun printArea(width: Int, height: Int): Unit { val area = calculateArea(width, height) println("The area is $area") } fun calculateArea(width: Int, height: Int): Int { return width * height } }
Chapter07/src/main/kotlin/com/packt/chapter4/4.3.kt
2753711245
package com.mgaetan89.showsrage.fragment import android.content.SharedPreferences import com.mgaetan89.showsrage.network.SickRageApi import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.`when` import org.mockito.Mockito.mock @RunWith(Parameterized::class) class AddShowFragment_OnQueryTextSubmitTest(val query: String?, val valid: Boolean) { private lateinit var fragment: AddShowFragment @Before fun before() { val preferences = mock(SharedPreferences::class.java) `when`(preferences.getString(anyString(), anyString())).thenReturn("") SickRageApi.instance.init(preferences) this.fragment = AddShowFragment() } @Test fun onQueryTextSubmit() { assertThat(this.fragment.onQueryTextSubmit(this.query)).isEqualTo(this.valid) } companion object { @JvmStatic @Parameterized.Parameters fun data() = AddShowFragment_IsQueryValidTest.data() } }
app/src/test/kotlin/com/mgaetan89/showsrage/fragment/AddShowFragment_OnQueryTextSubmitTest.kt
3930067520
package com.slack.api.model.kotlin_extension.block.dsl import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.composition.dsl.TextObjectDsl @BlockLayoutBuilder interface ContextBlockElementDsl : TextObjectDsl { /** * An element to insert an image as part of a larger block of content. If you want a block with only an image in * it, you're looking for the image block. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#image">Image element documentation</a> */ fun image( imageUrl: String? = null, altText: String? = null, fallback: String? = null, imageWidth: Int? = null, imageHeight: Int? = null, imageBytes: Int? = null ) }
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/dsl/ContextBlockElementDsl.kt
2515887909
package xyz.sachil.essence.repository.wrap import androidx.lifecycle.LiveData import androidx.paging.PagedList import xyz.sachil.essence.model.net.bean.TypeData import xyz.sachil.essence.model.net.bean.WeeklyPopularData import xyz.sachil.essence.util.LoadState data class DataResponse( val data: LiveData<PagedList<TypeData>>, val loadState: LiveData<LoadState>, val refresh: () -> Unit )
app/src/main/java/xyz/sachil/essence/repository/wrap/DataResponse.kt
205258666
package co.smartreceipts.android.distance.editor import android.app.AlertDialog import android.content.Context import android.os.Bundle import android.view.* import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import co.smartreceipts.analytics.Analytics import co.smartreceipts.analytics.events.Events import co.smartreceipts.android.R import co.smartreceipts.android.activities.NavigationHandler import co.smartreceipts.android.activities.SmartReceiptsActivity import co.smartreceipts.android.adapters.FooterButtonArrayAdapter import co.smartreceipts.android.autocomplete.AutoCompleteArrayAdapter import co.smartreceipts.android.autocomplete.AutoCompleteField import co.smartreceipts.android.autocomplete.AutoCompleteResult import co.smartreceipts.android.autocomplete.distance.DistanceAutoCompleteField import co.smartreceipts.android.currency.widget.CurrencyListEditorPresenter import co.smartreceipts.android.currency.widget.DefaultCurrencyListEditorView import co.smartreceipts.android.databinding.UpdateDistanceBinding import co.smartreceipts.android.date.DateFormatter import co.smartreceipts.android.distance.editor.currency.DistanceCurrencyCodeSupplier import co.smartreceipts.android.fragments.WBFragment import co.smartreceipts.android.model.AutoCompleteUpdateEvent import co.smartreceipts.android.model.Distance import co.smartreceipts.android.model.PaymentMethod import co.smartreceipts.android.model.Trip import co.smartreceipts.android.model.factory.DistanceBuilderFactory import co.smartreceipts.android.model.utils.ModelUtils import co.smartreceipts.android.persistence.DatabaseHelper import co.smartreceipts.android.receipts.editor.paymentmethods.PaymentMethodsPresenter import co.smartreceipts.android.receipts.editor.paymentmethods.PaymentMethodsView import co.smartreceipts.android.utils.SoftKeyboardManager import co.smartreceipts.android.widget.model.UiIndicator import co.smartreceipts.android.widget.ui.PriceInputEditText import com.google.android.material.snackbar.Snackbar import com.jakewharton.rxbinding3.widget.textChanges import dagger.android.support.AndroidSupportInjection import io.reactivex.Observable import io.reactivex.functions.Consumer import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import kotlinx.android.synthetic.main.update_distance.* import java.sql.Date import java.util.* import javax.inject.Inject class DistanceCreateEditFragment : WBFragment(), DistanceCreateEditView, View.OnFocusChangeListener, PaymentMethodsView { @Inject lateinit var presenter: DistanceCreateEditPresenter @Inject lateinit var analytics: Analytics @Inject lateinit var database: DatabaseHelper @Inject lateinit var dateFormatter: DateFormatter @Inject lateinit var navigationHandler: NavigationHandler<SmartReceiptsActivity> @Inject lateinit var paymentMethodsPresenter: PaymentMethodsPresenter private lateinit var paymentMethodsViewsList: List<@JvmSuppressWildcards View> override val editableItem: Distance? get() = arguments?.getParcelable(Distance.PARCEL_KEY) private val parentTrip: Trip get() = arguments?.getParcelable(Trip.PARCEL_KEY) ?: throw IllegalStateException("Distance can't exist without parent trip") private var suggestedDate: Date = Date(Calendar.getInstance().timeInMillis) private lateinit var currencyListEditorPresenter: CurrencyListEditorPresenter private lateinit var resultsAdapter: AutoCompleteArrayAdapter<Distance> private var shouldHideResults: Boolean = false private var focusedView: View? = null private lateinit var snackbar: Snackbar private lateinit var paymentMethodsAdapter: FooterButtonArrayAdapter<PaymentMethod> private var itemToRemoveOrReAdd: AutoCompleteResult<Distance>? = null private var _binding: UpdateDistanceBinding? = null private val binding get() = _binding!! override val createDistanceClicks: Observable<Distance> get() = _createDistanceClicks override val updateDistanceClicks: Observable<Distance> get() = _updateDistanceClicks override val deleteDistanceClicks: Observable<Distance> get() = _deleteDistanceClicks override val hideAutoCompleteVisibilityClick: Observable<AutoCompleteUpdateEvent<Distance>> get() =_hideAutoCompleteVisibilityClicks override val unHideAutoCompleteVisibilityClick: Observable<AutoCompleteUpdateEvent<Distance>> get() =_unHideAutoCompleteVisibilityClicks private val _createDistanceClicks: Subject<Distance> = PublishSubject.create<Distance>().toSerialized() private val _updateDistanceClicks: Subject<Distance> = PublishSubject.create<Distance>().toSerialized() private val _deleteDistanceClicks: Subject<Distance> = PublishSubject.create<Distance>().toSerialized() private val _hideAutoCompleteVisibilityClicks: Subject<AutoCompleteUpdateEvent<Distance>> = PublishSubject.create<AutoCompleteUpdateEvent<Distance>>().toSerialized() private val _unHideAutoCompleteVisibilityClicks: Subject<AutoCompleteUpdateEvent<Distance>> = PublishSubject.create<AutoCompleteUpdateEvent<Distance>>().toSerialized() override fun onAttach(context: Context) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onFocusChange(view: View, hasFocus: Boolean) { if (focusedView is PriceInputEditText && !hasFocus) { // format rate on focus lose (focusedView as PriceInputEditText).formatPriceText() } focusedView = if (hasFocus) view else null if (editableItem == null && hasFocus) { // Only launch if we have focus and it's a new distance SoftKeyboardManager.showKeyboard(view) } } override fun onResume() { super.onResume() focusedView?.requestFocus() // Make sure we're focused on the right view } override fun onPause() { SoftKeyboardManager.hideKeyboard(focusedView) super.onPause() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) if (savedInstanceState != null) { suggestedDate = Date(arguments?.getLong(ARG_SUGGESTED_DATE, suggestedDate.time) ?: suggestedDate.time) } paymentMethodsAdapter = FooterButtonArrayAdapter(requireActivity(), ArrayList(), R.string.manage_payment_methods) { analytics.record(Events.Informational.ClickedManagePaymentMethods) navigationHandler.navigateToPaymentMethodsEditor() } currencyListEditorPresenter = CurrencyListEditorPresenter( DefaultCurrencyListEditorView(requireContext()) { spinner_currency }, database, DistanceCurrencyCodeSupplier(parentTrip, editableItem), savedInstanceState ) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = UpdateDistanceBinding.inflate(inflater, container, false) paymentMethodsViewsList = listOf(binding.distanceInputGuideImagePaymentMethod, binding.distanceInputPaymentMethod) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpFocusBehavior() // Toolbar stuff when { navigationHandler.isDualPane -> toolbar.visibility = View.GONE else -> setSupportActionBar(toolbar as Toolbar) } supportActionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) setHomeAsUpIndicator(R.drawable.ic_clear_24dp) setTitle(if (editableItem == null) R.string.dialog_mileage_title_create else R.string.dialog_mileage_title_update) subtitle = "" } text_distance_rate.setDecimalPlaces(Distance.RATE_PRECISION) if (editableItem == null) { // New Distance text_distance_date.date = suggestedDate text_distance_rate.setText(presenter.getDefaultDistanceRate()) } else { // Update distance text_distance_value.setText(editableItem!!.decimalFormattedDistance) text_distance_rate.setText(editableItem!!.decimalFormattedRate) text_distance_location.setText(editableItem!!.location) text_distance_comment.setText(editableItem!!.comment) text_distance_date.date = editableItem!!.date text_distance_date.timeZone = editableItem!!.timeZone } } override fun onStart() { super.onStart() presenter.subscribe() currencyListEditorPresenter.subscribe() paymentMethodsPresenter.subscribe() } override fun onStop() { presenter.unsubscribe() currencyListEditorPresenter.unsubscribe() paymentMethodsPresenter.unsubscribe() if (::snackbar.isInitialized && snackbar.isShown) { snackbar.dismiss() } super.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) currencyListEditorPresenter.onSaveInstanceState(outState) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(if (editableItem == null) R.menu.menu_save else R.menu.menu_save_delete, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { navigationHandler.navigateBack() return true } R.id.action_save -> { when { editableItem != null -> _updateDistanceClicks.onNext(constructDistance()) else -> _createDistanceClicks.onNext(constructDistance()) } return true } R.id.action_delete -> { showDeleteDialog() return true } else -> return super.onOptionsItemSelected(item) } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun present(uiIndicator: UiIndicator<Int>) { when (uiIndicator.state) { UiIndicator.State.Success -> navigationHandler.navigateBack() else -> if (uiIndicator.state == UiIndicator.State.Error && uiIndicator.data.isPresent) { Toast.makeText(requireContext(), uiIndicator.data.get(), Toast.LENGTH_LONG).show() } } } private fun setUpFocusBehavior() { text_distance_value.onFocusChangeListener = this text_distance_rate.onFocusChangeListener = this text_distance_location.onFocusChangeListener = this text_distance_date.onFocusChangeListener = this spinner_currency.onFocusChangeListener = this text_distance_comment.onFocusChangeListener = this distance_input_payment_method.onFocusChangeListener = this // And ensure that we do not show the keyboard when clicking these views val hideSoftKeyboardOnTouchListener = SoftKeyboardManager.HideSoftKeyboardOnTouchListener() spinner_currency.setOnTouchListener(hideSoftKeyboardOnTouchListener) distance_input_payment_method.setOnTouchListener(hideSoftKeyboardOnTouchListener) text_distance_date.apply { isFocusable = false isFocusableInTouchMode = false setDateFormatter(dateFormatter) setOnTouchListener(hideSoftKeyboardOnTouchListener) } // Focused View if (focusedView == null) { focusedView = text_distance_value } } private fun constructDistance(): Distance { val distanceBuilder: DistanceBuilderFactory = when (editableItem) { null -> DistanceBuilderFactory() .setDistance(ModelUtils.tryParse(text_distance_value.text.toString())) .setRate(ModelUtils.tryParse(text_distance_rate.text.toString())) else -> DistanceBuilderFactory(editableItem!!) .setDistance(ModelUtils.tryParse(text_distance_value.text.toString(), editableItem!!.distance)) .setRate(ModelUtils.tryParse(text_distance_rate.text.toString(), editableItem!!.rate)) } val paymentMethod: PaymentMethod? = if (presenter.isUsePaymentMethods()) { distance_input_payment_method.selectedItem as PaymentMethod } else { null } return distanceBuilder .setTrip(parentTrip) .setLocation(text_distance_location.text.toString()) .setDate(text_distance_date.date) .setTimezone(text_distance_date.timeZone) .setCurrency(spinner_currency.selectedItem.toString()) .setComment(text_distance_comment.text.toString()) .setPaymentMethod(paymentMethod) .build() } private fun showDeleteDialog() { AlertDialog.Builder(activity) .setTitle(getString(R.string.delete_item, editableItem!!.location)) .setMessage(R.string.delete_sync_information) .setCancelable(true) .setPositiveButton(R.string.delete) { _, _ -> _deleteDistanceClicks.onNext(editableItem!!) } .setNegativeButton(android.R.string.cancel) { _, _ -> } .show() } override fun togglePaymentMethodFieldVisibility(): Consumer<in Boolean> { return Consumer { isVisible -> run { for (v in paymentMethodsViewsList) { v.visibility = if (isVisible) View.VISIBLE else View.GONE } } } } override fun displayPaymentMethods(list: List<PaymentMethod>) { if (isAdded) { paymentMethodsAdapter.update(list) distance_input_payment_method.adapter = paymentMethodsAdapter if (editableItem != null) { // Here we manually loop through all payment methods and check for id == id in case the user changed this via "Manage" val distancePaymentMethod = editableItem!!.paymentMethod for (i in 0 until paymentMethodsAdapter.count) { val paymentMethod = paymentMethodsAdapter.getItem(i) if (paymentMethod != null && paymentMethod.id == distancePaymentMethod.id) { distance_input_payment_method.setSelection(i) break } } } } } override fun getTextChangeStream(field: AutoCompleteField): Observable<CharSequence> { return when (field) { DistanceAutoCompleteField.Location -> text_distance_location.textChanges() DistanceAutoCompleteField.Comment -> text_distance_comment.textChanges() else -> throw IllegalArgumentException("Unsupported field type: $field") } } override fun displayAutoCompleteResults(field: AutoCompleteField, results: MutableList<AutoCompleteResult<Distance>>) { if (isAdded) { if (!shouldHideResults) { if (::snackbar.isInitialized && snackbar.isShown) { snackbar.dismiss() } resultsAdapter = AutoCompleteArrayAdapter(requireContext(), results, this) when (field) { DistanceAutoCompleteField.Location -> { text_distance_location.setAdapter(resultsAdapter) if (text_distance_location.hasFocus()) { text_distance_location.showDropDown() } } DistanceAutoCompleteField.Comment -> { text_distance_comment.setAdapter(resultsAdapter) if (text_distance_comment.hasFocus()) { text_distance_comment.showDropDown() } } else -> throw IllegalArgumentException("Unsupported field type: $field") } } else { shouldHideResults = false } } } override fun fillValueField(autoCompleteResult: AutoCompleteResult<Distance>) { shouldHideResults = true if (text_distance_location.isPopupShowing) { text_distance_location.setText(autoCompleteResult.displayName) text_distance_location.setSelection(text_distance_location.text.length) text_distance_location.dismissDropDown() } else { text_distance_comment.setText(autoCompleteResult.displayName) text_distance_comment.setSelection(text_distance_comment.text.length) text_distance_comment.dismissDropDown() } SoftKeyboardManager.hideKeyboard(focusedView) } override fun sendAutoCompleteHideEvent(autoCompleteResult: AutoCompleteResult<Distance>) { SoftKeyboardManager.hideKeyboard(focusedView) itemToRemoveOrReAdd = autoCompleteResult when(text_distance_location.isPopupShowing) { true -> _hideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(autoCompleteResult, DistanceAutoCompleteField.Location, resultsAdapter.getPosition(autoCompleteResult))) false -> _hideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(autoCompleteResult, DistanceAutoCompleteField.Comment, resultsAdapter.getPosition(autoCompleteResult))) } } override fun removeValueFromAutoComplete(position: Int) { activity!!.runOnUiThread { itemToRemoveOrReAdd = resultsAdapter.getItem(position) resultsAdapter.remove(itemToRemoveOrReAdd) resultsAdapter.notifyDataSetChanged() val view = activity!!.findViewById<ConstraintLayout>(R.id.update_distance_layout) snackbar = Snackbar.make(view, getString( R.string.item_removed_from_auto_complete, itemToRemoveOrReAdd!!.displayName), Snackbar.LENGTH_LONG) snackbar.setAction(R.string.undo) { if (text_distance_location.hasFocus()) { _unHideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(itemToRemoveOrReAdd, DistanceAutoCompleteField.Location, position)) } else { _unHideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(itemToRemoveOrReAdd, DistanceAutoCompleteField.Comment, position)) } } snackbar.show() } } override fun sendAutoCompleteUnHideEvent(position: Int) { activity!!.runOnUiThread { resultsAdapter.insert(itemToRemoveOrReAdd, position) resultsAdapter.notifyDataSetChanged() Toast.makeText(context, R.string.result_restored, Toast.LENGTH_LONG).show() } } override fun displayAutoCompleteError() { activity!!.runOnUiThread { Toast.makeText(activity, R.string.result_restore_failed, Toast.LENGTH_LONG).show() } } companion object { @JvmStatic fun newInstance() = DistanceCreateEditFragment() const val ARG_SUGGESTED_DATE = "arg_suggested_date" } }
app/src/main/java/co/smartreceipts/android/distance/editor/DistanceCreateEditFragment.kt
3355360116
package co.smartreceipts.oss_licenses import android.content.Context import android.content.Intent import co.smartreceipts.core.di.scopes.ApplicationScope import javax.inject.Inject @ApplicationScope class LicensesNavigator @Inject constructor(): LicensesNavigatorInterface { override fun getLicensesActivityIntent(context: Context, ossActivityTitleId: Int): Intent? = null }
oss_licenses/src/floss/java/co/smartreceipts/oss_licenses/LicensesNavigator.kt
2764135231
package com.mgaetan89.showsrage.fragment import android.app.SearchManager import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.SearchView import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.View import android.view.ViewGroup import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.activity.MainActivity import com.mgaetan89.showsrage.adapter.SearchResultsAdapter import com.mgaetan89.showsrage.model.SearchResultItem import com.mgaetan89.showsrage.model.SearchResults import com.mgaetan89.showsrage.network.SickRageApi import kotlinx.android.synthetic.main.fragment_add_show.empty import kotlinx.android.synthetic.main.fragment_add_show.list import retrofit.Callback import retrofit.RetrofitError import retrofit.client.Response class AddShowFragment : Fragment(), Callback<SearchResults>, SearchView.OnQueryTextListener { private val searchResults = mutableListOf<SearchResultItem>() init { this.setHasOptionsMenu(true) } override fun failure(error: RetrofitError?) { error?.printStackTrace() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val activity = this.activity if (activity is MainActivity) { activity.displayHomeAsUp(true) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.add_show, menu) val activity = this.activity ?: return val searchManager = activity.getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchMenu = menu.findItem(R.id.menu_search) (searchMenu.actionView as SearchView).also { it.setIconifiedByDefault(false) it.setOnQueryTextListener(this) it.setSearchableInfo(searchManager.getSearchableInfo(activity.componentName)) it.setQuery(getQueryFromIntent(activity.intent), true) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_add_show, container, false) override fun onDestroy() { this.searchResults.clear() super.onDestroy() } override fun onQueryTextChange(newText: String?) = false override fun onQueryTextSubmit(query: String?): Boolean { if (isQueryValid(query)) { if (this.list?.adapter?.itemCount == 0) { this.empty?.let { it.setText(R.string.loading) it.visibility = View.VISIBLE } } SickRageApi.instance.services?.search(query!!, this) return true } return false } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val columnCount = this.resources.getInteger(R.integer.shows_column_count) this.list?.adapter = SearchResultsAdapter(this.searchResults) this.list?.layoutManager = GridLayoutManager(this.activity, columnCount) } override fun success(searchResults: SearchResults?, response: Response?) { this.searchResults.clear() this.searchResults.addAll(getSearchResults(searchResults)) if (this.searchResults.isEmpty()) { this.empty?.let { it.setText(R.string.no_results) it.visibility = View.VISIBLE } this.list?.visibility = View.GONE } else { this.empty?.visibility = View.GONE this.list?.visibility = View.VISIBLE } this.list?.adapter?.notifyDataSetChanged() } companion object { fun getQueryFromIntent(intent: Intent?): String? = if (Intent.ACTION_SEARCH != intent?.action) "" else intent.getStringExtra(SearchManager.QUERY) fun getSearchResults(searchResults: SearchResults?) = searchResults?.data?.results ?: emptyList() fun isQueryValid(query: String?) = !query.isNullOrBlank() fun newInstance() = AddShowFragment() } }
app/src/main/kotlin/com/mgaetan89/showsrage/fragment/AddShowFragment.kt
1698949437
package kotlin.b /** * Not sure */ object BObjectOne { @Suppress("unused") fun sure(): String = "${BClassOne().doSomething()}${BClassTwo.NOT_USEFUL}" }
src/test/resources/kotlin/b/BObjectOne.kt
2273824412
package zlc.season.rxdownload4.manager import io.reactivex.android.schedulers.AndroidSchedulers.mainThread import io.reactivex.disposables.Disposable import io.reactivex.flowables.ConnectableFlowable import io.reactivex.rxkotlin.subscribeBy import zlc.season.rxdownload4.Progress import zlc.season.rxdownload4.delete import zlc.season.rxdownload4.file import zlc.season.rxdownload4.storage.Storage import zlc.season.rxdownload4.task.Task import zlc.season.rxdownload4.utils.safeDispose import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.TimeUnit.SECONDS class TaskManager( private val task: Task, private val storage: Storage, private val connectFlowable: ConnectableFlowable<Progress>, private val notificationCreator: NotificationCreator, taskRecorder: TaskRecorder, val taskLimitation: TaskLimitation ) { init { notificationCreator.init(task) } //For download use private val downloadHandler by lazy { StatusHandler(task) } //For record use private val recordHandler by lazy { StatusHandler(task, taskRecorder) } //For notification use private val notificationHandler by lazy { StatusHandler(task, logTag = "Notification") { val notification = notificationCreator.create(task, it) showNotification(task, notification) } } //Download disposable private var disposable: Disposable? = null private var downloadDisposable: Disposable? = null private var recordDisposable: Disposable? = null private var notificationDisposable: Disposable? = null /** * @param tag As the unique identifier for this subscription * @param receiveLastStatus If true, the last status will be received after subscribing */ internal fun addCallback(tag: Any, receiveLastStatus: Boolean, callback: (Status) -> Unit) { downloadHandler.addCallback(tag, receiveLastStatus, callback) } internal fun removeCallback(tag: Any) { downloadHandler.removeCallback(tag) } internal fun currentStatus() = downloadHandler.currentStatus internal fun getFile() = task.file(storage) internal fun innerStart() { if (isStarted()) { return } subscribeNotification() subscribeRecord() subscribeDownload() disposable = connectFlowable.connect() } private fun subscribeDownload() { downloadDisposable = connectFlowable .doOnSubscribe { downloadHandler.onStarted() } .subscribeOn(mainThread()) .observeOn(mainThread()) .doOnNext { downloadHandler.onDownloading(it) } .doOnComplete { downloadHandler.onCompleted() } .doOnError { downloadHandler.onFailed(it) } .doOnCancel { downloadHandler.onPaused() } .subscribeBy() } private fun subscribeRecord() { recordDisposable = connectFlowable.sample(10, SECONDS) .doOnSubscribe { recordHandler.onStarted() } .doOnNext { recordHandler.onDownloading(it) } .doOnComplete { recordHandler.onCompleted() } .doOnError { recordHandler.onFailed(it) } .doOnCancel { recordHandler.onPaused() } .subscribeBy() } private fun subscribeNotification() { notificationDisposable = connectFlowable.sample(500, MILLISECONDS) .doOnSubscribe { notificationHandler.onStarted() } .doOnNext { notificationHandler.onDownloading(it) } .doOnComplete { notificationHandler.onCompleted() } .doOnError { notificationHandler.onFailed(it) } .doOnCancel { notificationHandler.onPaused() } .subscribeBy() } internal fun innerStop() { //send pause status notificationHandler.onPaused() downloadHandler.onPaused() recordHandler.onPaused() notificationDisposable.safeDispose() recordDisposable.safeDispose() downloadDisposable.safeDispose() disposable.safeDispose() } internal fun innerDelete() { innerStop() task.delete(storage) //send delete status downloadHandler.onDeleted() notificationHandler.onDeleted() recordHandler.onDeleted() cancelNotification(task) } /** * Send Pending status */ internal fun innerPending() { downloadHandler.onPending() recordHandler.onPending() notificationHandler.onPending() } private fun isStarted(): Boolean { return disposable != null && !disposable!!.isDisposed } }
rxdownload4-manager/src/main/java/zlc/season/rxdownload4/manager/TaskManager.kt
1742253953