content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.brianegan.bansa.listOfCountersVariant import android.os.Bundle import android.support.v7.app.AppCompatActivity open class RootActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(RootView(this, store)) // Set the root view } }
examples/listOfCountersVariant/src/main/kotlin/com/brianegan/bansa/listOfCountersVariant/RootActivity.kt
2964565104
package org.schabi.newpipe.database.feed.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.ForeignKey.CASCADE import androidx.room.Index import org.schabi.newpipe.database.feed.model.FeedGroupSubscriptionEntity.Companion.FEED_GROUP_SUBSCRIPTION_TABLE import org.schabi.newpipe.database.feed.model.FeedGroupSubscriptionEntity.Companion.GROUP_ID import org.schabi.newpipe.database.feed.model.FeedGroupSubscriptionEntity.Companion.SUBSCRIPTION_ID import org.schabi.newpipe.database.subscription.SubscriptionEntity @Entity( tableName = FEED_GROUP_SUBSCRIPTION_TABLE, primaryKeys = [GROUP_ID, SUBSCRIPTION_ID], indices = [Index(SUBSCRIPTION_ID)], foreignKeys = [ ForeignKey( entity = FeedGroupEntity::class, parentColumns = [FeedGroupEntity.ID], childColumns = [GROUP_ID], onDelete = CASCADE, onUpdate = CASCADE, deferred = true ), ForeignKey( entity = SubscriptionEntity::class, parentColumns = [SubscriptionEntity.SUBSCRIPTION_UID], childColumns = [SUBSCRIPTION_ID], onDelete = CASCADE, onUpdate = CASCADE, deferred = true ) ] ) data class FeedGroupSubscriptionEntity( @ColumnInfo(name = GROUP_ID) var feedGroupId: Long, @ColumnInfo(name = SUBSCRIPTION_ID) var subscriptionId: Long ) { companion object { const val FEED_GROUP_SUBSCRIPTION_TABLE = "feed_group_subscription_join" const val GROUP_ID = "group_id" const val SUBSCRIPTION_ID = "subscription_id" } }
app/src/main/java/org/schabi/newpipe/database/feed/model/FeedGroupSubscriptionEntity.kt
3833873844
package org.wordpress.android.ui.stats.refresh.lists.widget.views import android.os.Bundle import android.view.MenuItem import org.wordpress.android.databinding.StatsViewsWidgetConfigureActivityBinding import org.wordpress.android.ui.LocaleAwareActivity class StatsViewsWidgetConfigureActivity : LocaleAwareActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) with(StatsViewsWidgetConfigureActivityBinding.inflate(layoutInflater)) { setContentView(root) setSupportActionBar(toolbar.toolbarMain) } supportActionBar?.let { it.setHomeButtonEnabled(true) it.setDisplayHomeAsUpEnabled(true) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } }
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/widget/views/StatsViewsWidgetConfigureActivity.kt
2200963558
package org.wordpress.android.ui.comments.unified import android.os.Bundle import androidx.viewpager2.widget.ViewPager2 import org.wordpress.android.WordPress import org.wordpress.android.databinding.UnifiedCommentsDetailsActivityBinding import org.wordpress.android.ui.LocaleAwareActivity class UnifiedCommentsDetailsActivity : LocaleAwareActivity() { private var binding: UnifiedCommentsDetailsActivityBinding? = null private lateinit var pagerAdapter: UnifiedCommentsDetailPagerAdapter public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (application as WordPress).component().inject(this) binding = UnifiedCommentsDetailsActivityBinding.inflate(layoutInflater).apply { setContentView(root) setupActionBar() setupContent() } } private fun UnifiedCommentsDetailsActivityBinding.setupContent() { pagerAdapter = UnifiedCommentsDetailPagerAdapter(this@UnifiedCommentsDetailsActivity) viewPager.adapter = pagerAdapter viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { // TODO track subsequent comment views }) } private fun UnifiedCommentsDetailsActivityBinding.setupActionBar() { setSupportActionBar(toolbarMain) supportActionBar?.let { it.setHomeButtonEnabled(true) it.setDisplayHomeAsUpEnabled(true) } } }
WordPress/src/main/java/org/wordpress/android/ui/comments/unified/UnifiedCommentsDetailsActivity.kt
2364567383
package com.rohitsuratekar.NCBSinfo.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.rohitsuratekar.NCBSinfo.R import com.rohitsuratekar.NCBSinfo.adapters.EditTransportAdjustAdapter import com.rohitsuratekar.NCBSinfo.common.Constants import com.rohitsuratekar.NCBSinfo.common.hideMe import com.rohitsuratekar.NCBSinfo.common.showMe import com.rohitsuratekar.NCBSinfo.models.EditFragment import kotlinx.android.synthetic.main.fragment_adjust_trip.* class AdjustTripFragment : EditFragment(), EditTransportAdjustAdapter.OnTripAdjust { private var tripList = mutableListOf<String>() private lateinit var adapter: EditTransportAdjustAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_adjust_trip, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) adapter = EditTransportAdjustAdapter(tripList, this) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) callback?.hideProgress() sharedModel.updateReadState(Constants.EDIT_START_TRIP) callback?.setFragmentTitle(R.string.et_adjust_trips) et_adjust_next.setOnClickListener { callback?.navigate(Constants.EDIT_CONFIRM) } et_adjust_previous.setOnClickListener { callback?.navigateWithPopback() } checkOldData() setupRecycler() } private fun setupRecycler() { adjust_recycler.adapter = adapter adjust_recycler.layoutManager = LinearLayoutManager(context) checkEmptyList() } private fun checkEmptyList() { if (tripList.isEmpty()) { adjust_holder.hideMe() adjust_note.text = getString(R.string.et_adjust_warning) } else { adjust_holder.showMe() adjust_note.text = getString(R.string.et_adjust_note) } } private fun checkOldData() { sharedModel.tripList.value?.let { tripList.clear() tripList.addAll(it) adapter.notifyDataSetChanged() checkEmptyList() } sharedModel.tripSelected.value?.let { adapter.tripSelected(it) } } override fun firstTripSelected(position: Int) { val tempList = mutableListOf<String>() val newList = mutableListOf<String>() for (i in 0 until tripList.size) { if (i < position) { tempList.add(tripList[i]) } else { newList.add(tripList[i]) } } for (i in tempList) { newList.add(i) } tripList.clear() tripList.addAll(newList) sharedModel.updateTrips(newList) adapter.tripSelected(true) adapter.notifyDataSetChanged() sharedModel.updateTripSelection(true) } }
app/src/main/java/com/rohitsuratekar/NCBSinfo/fragments/AdjustTripFragment.kt
4124152138
package org.wordpress.android.ui.notifications.utils import androidx.fragment.app.FragmentActivity import org.wordpress.android.R import org.wordpress.android.datasets.ReaderPostTable import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.SiteStore import org.wordpress.android.fluxc.tools.FormattableRange import org.wordpress.android.fluxc.tools.FormattableRangeType import org.wordpress.android.models.ReaderPost import org.wordpress.android.ui.ActivityLauncher import org.wordpress.android.ui.WPWebViewActivity import org.wordpress.android.ui.reader.ReaderActivityLauncher import org.wordpress.android.ui.reader.comments.ThreadedCommentsActionSource import org.wordpress.android.ui.reader.comments.ThreadedCommentsActionSource.ACTIVITY_LOG_DETAIL import org.wordpress.android.ui.reader.tracker.ReaderTracker import org.wordpress.android.ui.reader.utils.ReaderUtils import org.wordpress.android.ui.stats.StatsViewType.FOLLOWERS import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T.API import org.wordpress.android.util.ToastUtils import javax.inject.Inject private const val DOMAIN_WP_COM = "wordpress.com" class FormattableContentClickHandler @Inject constructor( val siteStore: SiteStore, val readerTracker: ReaderTracker ) { fun onClick( activity: FragmentActivity, clickedSpan: FormattableRange, source: String ) { if (activity.isFinishing) { return } val id = clickedSpan.id ?: 0 val siteId = clickedSpan.siteId ?: 0 val postId = clickedSpan.postId ?: 0 when (val rangeType = clickedSpan.rangeType()) { FormattableRangeType.SITE -> // Show blog preview showBlogPreviewActivity(activity, id, postId, source) FormattableRangeType.USER -> // Show blog preview showBlogPreviewActivity(activity, siteId, postId, source) FormattableRangeType.PAGE, FormattableRangeType.POST -> // Show post detail showPostActivity(activity, siteId, id) FormattableRangeType.COMMENT -> { // Load the comment in the reader list if it exists, otherwise show a webview val rootId = clickedSpan.postId ?: clickedSpan.rootId ?: 0 if (ReaderUtils.postAndCommentExists(siteId, rootId, id)) { showReaderCommentsList(activity, siteId, rootId, id, ACTIVITY_LOG_DETAIL) } else { showWebViewActivityForUrl(activity, clickedSpan.url, rangeType) } } FormattableRangeType.STAT, FormattableRangeType.FOLLOW -> // We can open native stats if the site is a wpcom or Jetpack sites showStatsActivityForSite(activity, siteId, rangeType) FormattableRangeType.LIKE -> if (ReaderPostTable.postExists(siteId, id)) { showReaderPostLikeUsers(activity, siteId, id) } else { showPostActivity(activity, siteId, id) } FormattableRangeType.REWIND_DOWNLOAD_READY -> showBackup(activity, siteId) FormattableRangeType.BLOCKQUOTE, FormattableRangeType.NOTICON, FormattableRangeType.MATCH, FormattableRangeType.MEDIA, FormattableRangeType.UNKNOWN -> { showWebViewActivityForUrl(activity, clickedSpan.url, rangeType) } FormattableRangeType.SCAN -> Unit // Do nothing FormattableRangeType.B -> Unit // Do nothing } } private fun showBlogPreviewActivity( activity: FragmentActivity, siteId: Long, postId: Long, source: String ) { val post: ReaderPost? = ReaderPostTable.getBlogPost(siteId, postId, true) ReaderActivityLauncher.showReaderBlogPreview( activity, siteId, post?.isFollowedByCurrentUser, source, readerTracker ) } private fun showPostActivity(activity: FragmentActivity, siteId: Long, postId: Long) { ReaderActivityLauncher.showReaderPostDetail(activity, siteId, postId) } private fun showStatsActivityForSite(activity: FragmentActivity, siteId: Long, rangeType: FormattableRangeType) { val site = siteStore.getSiteBySiteId(siteId) if (site == null) { // One way the site can be null: new site created, receive a notification from this site, // but the site list is not yet updated in the app. ToastUtils.showToast(activity, R.string.blog_not_found) return } showStatsActivityForSite(activity, site, rangeType) } private fun showStatsActivityForSite( activity: FragmentActivity, site: SiteModel, rangeType: FormattableRangeType ) { if (rangeType == FormattableRangeType.FOLLOW) { ActivityLauncher.viewAllTabbedInsightsStats(activity, FOLLOWERS, 0, site.id) } else { ActivityLauncher.viewBlogStats(activity, site) } } private fun showWebViewActivityForUrl(activity: FragmentActivity, url: String?, rangeType: FormattableRangeType) { if (url == null || url.isEmpty()) { AppLog.e(API, "Trying to open web view activity but the URL is missing for range type $rangeType") return } if (url.contains(DOMAIN_WP_COM)) { WPWebViewActivity.openUrlByUsingGlobalWPCOMCredentials(activity, url) } else { WPWebViewActivity.openURL(activity, url) } } private fun showReaderPostLikeUsers(activity: FragmentActivity, blogId: Long, postId: Long) { ReaderActivityLauncher.showReaderLikingUsers(activity, blogId, postId) } private fun showReaderCommentsList( activity: FragmentActivity, siteId: Long, postId: Long, commentId: Long, source: ThreadedCommentsActionSource ) { ReaderActivityLauncher.showReaderComments( activity, siteId, postId, commentId, source.sourceDescription ) } private fun showBackup(activity: FragmentActivity, siteId: Long) { val site = siteStore.getSiteBySiteId(siteId) ActivityLauncher.viewBackupList(activity, site) } }
WordPress/src/main/java/org/wordpress/android/ui/notifications/utils/FormattableContentClickHandler.kt
1108237805
// FIR_IDENTICAL // FIR_COMPARISON package a.b.c.d class B { public val mark: M<caret> = run { } interface Mark { } } // EXIST: { itemText: "Mark", tailText: " (a.b.c.d.B)" }
plugins/kotlin/completion/tests/testData/basic/common/InterfaceNameBeforeRunBug.kt
3028540255
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling.builders import org.jetbrains.kotlin.idea.gradleTooling.KotlinDependency import org.jetbrains.kotlin.idea.gradleTooling.MultiplatformModelImportingContext import org.jetbrains.plugins.gradle.model.ExternalProjectDependency interface KotlinModelComponentBuilder<TOrigin, TCtx, TRet> { fun buildComponent(origin: TOrigin, importingContext: TCtx): TRet? } interface KotlinModelComponentBuilderBase<TOrigin, TRet> : KotlinModelComponentBuilder<TOrigin, Unit, TRet> { override fun buildComponent(origin: TOrigin, importingContext: Unit): TRet? = buildComponent(origin) fun buildComponent(origin: TOrigin): TRet? } interface KotlinMultiplatformComponentBuilder<TOrigin, TRet> : KotlinModelComponentBuilder<TOrigin, MultiplatformModelImportingContext, TRet> interface KotlinMultiplatformComponentBuilderBase<TRet> : KotlinModelComponentBuilder<Any, MultiplatformModelImportingContext, TRet> /** * Returns only those dependencies with RUNTIME scope which are not present with compile scope */ fun Collection<KotlinDependency>.onlyNewDependencies(compileDependencies: Collection<KotlinDependency>): List<KotlinDependency> { val compileDependencyArtefacts = compileDependencies.flatMap { (it as? ExternalProjectDependency)?.projectDependencyArtifacts ?: emptyList() } return this.filter { if (it is ExternalProjectDependency) !(compileDependencyArtefacts.containsAll(it.projectDependencyArtifacts)) else true } }
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/builders/KotlinModelComponentBuilder.kt
2447019372
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pullUp import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.impl.light.LightField import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.classMembers.MemberInfoBase import com.intellij.refactoring.memberPullUp.PullUpData import com.intellij.refactoring.memberPullUp.PullUpHelper import com.intellij.refactoring.util.RefactoringUtil import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.dropDefaultValue import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.inspections.CONSTRUCTOR_VAL_VAR_MODIFIERS import org.jetbrains.kotlin.idea.refactoring.createJavaField import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull import org.jetbrains.kotlin.idea.util.hasComments import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.Variance class KotlinPullUpHelper( private val javaData: PullUpData, private val data: KotlinPullUpData ) : PullUpHelper<MemberInfoBase<PsiMember>> { companion object { private val MODIFIERS_TO_LIFT_IN_SUPERCLASS = listOf(KtTokens.PRIVATE_KEYWORD) private val MODIFIERS_TO_LIFT_IN_INTERFACE = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.INTERNAL_KEYWORD) } private fun KtExpression.isMovable(): Boolean { return accept( object : KtVisitor<Boolean, Nothing?>() { override fun visitKtElement(element: KtElement, arg: Nothing?): Boolean { return element.allChildren.all { (it as? KtElement)?.accept(this, arg) ?: true } } override fun visitKtFile(file: KtFile, data: Nothing?) = false override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, arg: Nothing?): Boolean { val resolvedCall = expression.getResolvedCall(data.resolutionFacade.analyze(expression)) ?: return true val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression && receiver !is KtSuperExpression) return true var descriptor: DeclarationDescriptor = resolvedCall.resultingDescriptor if (descriptor is ConstructorDescriptor) { descriptor = descriptor.containingDeclaration } // todo: local functions if (descriptor is ValueParameterDescriptor) return true if (descriptor is ClassDescriptor && !descriptor.isInner) return true if (descriptor is MemberDescriptor) { if (descriptor.source.getPsi() in propertiesToMoveInitializers) return true descriptor = descriptor.containingDeclaration } return descriptor is PackageFragmentDescriptor || (descriptor is ClassDescriptor && DescriptorUtils.isSubclass(data.targetClassDescriptor, descriptor)) } }, null ) } private fun getCommonInitializer( currentInitializer: KtExpression?, scope: KtBlockExpression?, propertyDescriptor: PropertyDescriptor, elementsToRemove: MutableSet<KtElement> ): KtExpression? { if (scope == null) return currentInitializer var initializerCandidate: KtExpression? = null for (statement in scope.statements) { statement.asAssignment()?.let body@{ val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body) val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression if (receiver != null && receiver !is KtThisExpression) return@body val resolvedCall = lhs.getResolvedCall(data.resolutionFacade.analyze(it)) ?: return@body if (resolvedCall.resultingDescriptor != propertyDescriptor) return@body if (initializerCandidate == null) { if (currentInitializer == null) { if (!statement.isMovable()) return null initializerCandidate = statement elementsToRemove.add(statement) } else { if (!KotlinPsiUnifier.DEFAULT.unify(statement, currentInitializer).isMatched) return null initializerCandidate = currentInitializer elementsToRemove.add(statement) } } else if (!KotlinPsiUnifier.DEFAULT.unify(statement, initializerCandidate).isMatched) return null } } return initializerCandidate } private data class InitializerInfo( val initializer: KtExpression?, val usedProperties: Set<KtProperty>, val usedParameters: Set<KtParameter>, val elementsToRemove: Set<KtElement> ) private fun getInitializerInfo( property: KtProperty, propertyDescriptor: PropertyDescriptor, targetConstructor: KtElement ): InitializerInfo? { val sourceConstructors = targetToSourceConstructors[targetConstructor] ?: return null val elementsToRemove = LinkedHashSet<KtElement>() val commonInitializer = sourceConstructors.fold(null as KtExpression?) { commonInitializer, constructor -> val body = (constructor as? KtSecondaryConstructor)?.bodyExpression getCommonInitializer(commonInitializer, body, propertyDescriptor, elementsToRemove) } if (commonInitializer == null) { elementsToRemove.clear() } val usedProperties = LinkedHashSet<KtProperty>() val usedParameters = LinkedHashSet<KtParameter>() val visitor = object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val context = data.resolutionFacade.analyze(expression) val resolvedCall = expression.getResolvedCall(context) ?: return val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression) return when (val target = (resolvedCall.resultingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()) { is KtParameter -> usedParameters.add(target) is KtProperty -> usedProperties.add(target) } } } commonInitializer?.accept(visitor) if (targetConstructor == ((data.targetClass as? KtClass)?.primaryConstructor ?: data.targetClass)) { property.initializer?.accept(visitor) } return InitializerInfo(commonInitializer, usedProperties, usedParameters, elementsToRemove) } private val propertiesToMoveInitializers = with(data) { membersToMove .filterIsInstance<KtProperty>() .filter { val descriptor = memberDescriptors[it] as? PropertyDescriptor descriptor != null && data.sourceClassContext[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false } } private val targetToSourceConstructors = LinkedHashMap<KtElement, MutableList<KtElement>>().let { result -> if (!data.isInterfaceTarget && data.targetClass is KtClass) { result[data.targetClass.primaryConstructor ?: data.targetClass] = ArrayList() data.sourceClass.accept( object : KtTreeVisitorVoid() { private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) { val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression] val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) { result.getOrPut(constructorElement as KtElement) { ArrayList() }.add(callingConstructorElement) } } override fun visitSuperTypeCallEntry(specifier: KtSuperTypeCallEntry) { val constructorRef = specifier.calleeExpression.constructorReferenceExpression ?: return val containingClass = specifier.getStrictParentOfType<KtClassOrObject>() ?: return val callingConstructorElement = containingClass.primaryConstructor ?: containingClass processConstructorReference(constructorRef, callingConstructorElement) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { val constructorRef = constructor.getDelegationCall().calleeExpression ?: return processConstructorReference(constructorRef, constructor) } } ) } result } private val targetConstructorToPropertyInitializerInfoMap = LinkedHashMap<KtElement, Map<KtProperty, InitializerInfo>>().let { result -> for (targetConstructor in targetToSourceConstructors.keys) { val propertyToInitializerInfo = LinkedHashMap<KtProperty, InitializerInfo>() for (property in propertiesToMoveInitializers) { val propertyDescriptor = data.memberDescriptors[property] as? PropertyDescriptor ?: continue propertyToInitializerInfo[property] = getInitializerInfo(property, propertyDescriptor, targetConstructor) ?: continue } val unmovableProperties = RefactoringUtil.transitiveClosure( object : RefactoringUtil.Graph<KtProperty> { override fun getVertices() = propertyToInitializerInfo.keys override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties } ) { !propertyToInitializerInfo.containsKey(it) } propertyToInitializerInfo.keys.removeAll(unmovableProperties) result[targetConstructor] = propertyToInitializerInfo } result } private var dummyField: PsiField? = null private fun addMovedMember(newMember: KtNamedDeclaration) { if (newMember is KtProperty) { // Add dummy light field since PullUpProcessor won't invoke moveFieldInitializations() if no PsiFields are present if (dummyField == null) { val factory = JavaPsiFacade.getElementFactory(newMember.project) val dummyField = object : LightField( newMember.manager, factory.createField("dummy", PsiType.BOOLEAN), factory.createClass("Dummy") ) { // Prevent processing by JavaPullUpHelper override fun getLanguage() = KotlinLanguage.INSTANCE } javaData.movedMembers.add(dummyField) } } when (newMember) { is KtProperty, is KtNamedFunction -> { newMember.getRepresentativeLightMethod()?.let { javaData.movedMembers.add(it) } } is KtClassOrObject -> { newMember.toLightClass()?.let { javaData.movedMembers.add(it) } } } } private fun liftVisibility(declaration: KtNamedDeclaration, ignoreUsages: Boolean = false) { val newModifier = if (data.isInterfaceTarget) KtTokens.PUBLIC_KEYWORD else KtTokens.PROTECTED_KEYWORD val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS val currentModifier = declaration.visibilityModifierTypeOrDefault() if (currentModifier !in modifiersToLift) return if (ignoreUsages || willBeUsedInSourceClass(declaration, data.sourceClass, data.membersToMove)) { if (newModifier != KtTokens.DEFAULT_VISIBILITY_KEYWORD) { declaration.addModifier(newModifier) } else { declaration.removeModifier(currentModifier) } } } override fun setCorrectVisibility(info: MemberInfoBase<PsiMember>) { val member = info.member.namedUnwrappedElement as? KtNamedDeclaration ?: return if (data.isInterfaceTarget) { member.removeModifier(KtTokens.PUBLIC_KEYWORD) } val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS if (member.visibilityModifierTypeOrDefault() in modifiersToLift) { member.accept( object : KtVisitorVoid() { override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { when (declaration) { is KtClass -> { liftVisibility(declaration) declaration.declarations.forEach { it.accept(this) } } is KtNamedFunction, is KtProperty -> { liftVisibility(declaration, declaration == member && info.isToAbstract) } } } } ) } } override fun encodeContextInfo(info: MemberInfoBase<PsiMember>) { } private fun fixOverrideAndGetClashingSuper( sourceMember: KtCallableDeclaration, targetMember: KtCallableDeclaration ): KtCallableDeclaration? { val memberDescriptor = data.memberDescriptors[sourceMember] as CallableMemberDescriptor if (memberDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() return null } val clashingSuperDescriptor = data.getClashingMemberInTargetClass(memberDescriptor) ?: return null if (clashingSuperDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() } return clashingSuperDescriptor.source.getPsi() as? KtCallableDeclaration } private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) { val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return when (data.targetClass) { is KtClass -> { data.sourceClass.removeSuperTypeListEntry(currentSpecifier) addSuperTypeEntry( currentSpecifier, data.targetClass, data.targetClassDescriptor, data.sourceClassContext, data.sourceToTargetClassSubstitutor ) } is PsiClass -> { val elementFactory = JavaPsiFacade.getElementFactory(member.project) val sourcePsiClass = data.sourceClass.toLightClass() ?: return val superRef = sourcePsiClass.implementsList ?.referenceElements ?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi } ?: return val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef)) data.sourceClass.removeSuperTypeListEntry(currentSpecifier) if (DescriptorUtils.isSubclass(data.targetClassDescriptor, classDescriptor)) return val refList = if (data.isInterfaceTarget) data.targetClass.extendsList else data.targetClass.implementsList refList?.add(elementFactory.createReferenceFromText(superTypeForTarget.canonicalText, null)) } } return } private fun removeOriginalMemberOrAddOverride(member: KtCallableDeclaration) { if (member.isAbstract()) { member.deleteWithCompanion() } else { member.addModifier(KtTokens.OVERRIDE_KEYWORD) KtTokens.VISIBILITY_MODIFIERS.types.forEach { member.removeModifier(it as KtModifierKeywordToken) } (member as? KtNamedFunction)?.valueParameters?.forEach { it.dropDefaultValue() } } } private fun moveToJavaClass(member: KtNamedDeclaration, substitutor: PsiSubstitutor) { if (!(data.targetClass is PsiClass && member.canMoveMemberToJavaClass(data.targetClass))) return // TODO: Drop after PsiTypes in light elements are properly generated if (member is KtCallableDeclaration && member.typeReference == null) { val returnType = (data.memberDescriptors[member] as CallableDescriptor).returnType returnType?.anonymousObjectSuperTypeOrNull()?.let { member.setType(it, false) } } val project = member.project val elementFactory = JavaPsiFacade.getElementFactory(project) val lightMethod = member.getRepresentativeLightMethod()!! val movedMember: PsiMember = when (member) { is KtProperty, is KtParameter -> { val newType = substitutor.substitute(lightMethod.returnType) val newField = createJavaField(member, data.targetClass) newField.typeElement?.replace(elementFactory.createTypeElement(newType)) if (member.isCompanionMemberOf(data.sourceClass)) { newField.modifierList?.setModifierProperty(PsiModifier.STATIC, true) } if (member is KtParameter) { (member.parent as? KtParameterList)?.removeParameter(member) } else { member.deleteWithCompanion() } newField } is KtNamedFunction -> { val newReturnType = substitutor.substitute(lightMethod.returnType) val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) } val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project)) val newTypeParameterBounds = lightMethod.typeParameters.map { it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType } } val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass) RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod) newMethod.returnTypeElement?.replace(elementFactory.createTypeElement(newReturnType)) newMethod.parameterList.parameters.forEachIndexed { i, parameter -> parameter.typeElement?.replace(elementFactory.createTypeElement(newParameterTypes[i])) } newMethod.typeParameters.forEachIndexed { i, typeParameter -> typeParameter.extendsList.referenceElements.forEachIndexed { j, referenceElement -> referenceElement.replace(elementFactory.createReferenceElementByType(newTypeParameterBounds[i][j])) } } removeOriginalMemberOrAddOverride(member) if (!data.isInterfaceTarget && !data.targetClass.hasModifierProperty(PsiModifier.ABSTRACT)) { data.targetClass.modifierList?.setModifierProperty(PsiModifier.ABSTRACT, true) } newMethod } else -> return } JavaCodeStyleManager.getInstance(project).shortenClassReferences(movedMember) } override fun move(info: MemberInfoBase<PsiMember>, substitutor: PsiSubstitutor) { val member = info.member.toKtDeclarationWrapperAware() ?: return if ((member is KtClass || member is KtPsiClassWrapper) && info.overrides != null) { moveSuperInterface(member, substitutor) return } if (data.targetClass is PsiClass) { moveToJavaClass(member, substitutor) return } val markedElements = markElements(member, data.sourceClassContext, data.sourceClassDescriptor, data.targetClassDescriptor) val memberCopy = member.copy() as KtNamedDeclaration fun moveClassOrObject(member: KtClassOrObject, memberCopy: KtClassOrObject): KtClassOrObject { if (data.isInterfaceTarget) { memberCopy.removeModifier(KtTokens.INNER_KEYWORD) } val movedMember = addMemberToTarget(memberCopy, data.targetClass as KtClass) as KtClassOrObject member.deleteWithCompanion() return movedMember } fun moveCallableMember(member: KtCallableDeclaration, memberCopy: KtCallableDeclaration): KtCallableDeclaration { data.targetClass as KtClass val movedMember: KtCallableDeclaration val clashingSuper = fixOverrideAndGetClashingSuper(member, memberCopy) val psiFactory = KtPsiFactory(member) val originalIsAbstract = member.hasModifier(KtTokens.ABSTRACT_KEYWORD) val toAbstract = when { info.isToAbstract -> true !data.isInterfaceTarget -> false member is KtProperty -> member.mustBeAbstractInInterface() else -> false } val classToAddTo = if (member.isCompanionMemberOf(data.sourceClass)) data.targetClass.getOrCreateCompanionObject() else data.targetClass if (toAbstract) { if (!originalIsAbstract) { makeAbstract( memberCopy, data.memberDescriptors[member] as CallableMemberDescriptor, data.sourceToTargetClassSubstitutor, data.targetClass ) } movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member.typeReference == null) { movedMember.typeReference?.addToShorteningWaitSet() } if (movedMember.nextSibling.hasComments()) { movedMember.parent.addAfter(psiFactory.createNewLine(), movedMember) } removeOriginalMemberOrAddOverride(member) } else { movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member is KtParameter && movedMember is KtParameter) { member.valOrVarKeyword?.delete() CONSTRUCTOR_VAL_VAR_MODIFIERS.forEach { member.removeModifier(it) } val superEntry = data.superEntryForTargetClass val superResolvedCall = data.targetClassSuperResolvedCall if (superResolvedCall != null) { val superCall = if (superEntry !is KtSuperTypeCallEntry || superEntry.valueArgumentList == null) { superEntry!!.replaced(psiFactory.createSuperTypeCallEntry("${superEntry.text}()")) } else superEntry val argumentList = superCall.valueArgumentList!! val parameterIndex = movedMember.parameterIndex() val prevParameterDescriptor = superResolvedCall.resultingDescriptor.valueParameters.getOrNull(parameterIndex - 1) val prevArgument = superResolvedCall.valueArguments[prevParameterDescriptor]?.arguments?.singleOrNull() as? KtValueArgument val newArgumentName = if (prevArgument != null && prevArgument.isNamed()) Name.identifier(member.name!!) else null val newArgument = psiFactory.createArgument(psiFactory.createExpression(member.name!!), newArgumentName) if (prevArgument == null) { argumentList.addArgument(newArgument) } else { argumentList.addArgumentAfter(newArgument, prevArgument) } } } else { member.deleteWithCompanion() } } if (originalIsAbstract && data.isInterfaceTarget) { movedMember.removeModifier(KtTokens.ABSTRACT_KEYWORD) } if (movedMember.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { data.targetClass.makeAbstract() } return movedMember } try { val movedMember = when (member) { is KtCallableDeclaration -> moveCallableMember(member, memberCopy as KtCallableDeclaration) is KtClassOrObject -> moveClassOrObject(member, memberCopy as KtClassOrObject) else -> return } movedMember.modifierList?.reformatted() applyMarking(movedMember, data.sourceToTargetClassSubstitutor, data.targetClassDescriptor) addMovedMember(movedMember) } finally { clearMarking(markedElements) } } override fun postProcessMember(member: PsiMember) { val declaration = member.unwrapped as? KtNamedDeclaration ?: return dropOverrideKeywordIfNecessary(declaration) } override fun moveFieldInitializations(movedFields: LinkedHashSet<PsiField>) { val psiFactory = KtPsiFactory(data.sourceClass) fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer { getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer } return addDeclaration(psiFactory.createAnonymousInitializer()) } fun KtElement.getConstructorBodyBlock(): KtBlockExpression? { return when (this) { is KtClassOrObject -> { getOrCreateClassInitializer().body } is KtPrimaryConstructor -> { getContainingClassOrObject().getOrCreateClassInitializer().body } is KtSecondaryConstructor -> { bodyExpression ?: add(psiFactory.createEmptyBody()) } else -> null } as? KtBlockExpression } fun KtClassOrObject.getDelegatorToSuperCall(): KtSuperTypeCallEntry? { return superTypeListEntries.singleOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry } fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) { if (info.usedParameters.isEmpty()) return val constructor: KtConstructor<*> = when (constructorElement) { is KtConstructor<*> -> constructorElement is KtClass -> constructorElement.createPrimaryConstructorIfAbsent() else -> return } with(constructor.getValueParameterList()!!) { info.usedParameters.forEach { val newParameter = addParameter(it) val originalType = data.sourceClassContext[BindingContext.VALUE_PARAMETER, it]!!.type newParameter.setType( data.sourceToTargetClassSubstitutor.substitute(originalType, Variance.INVARIANT) ?: originalType, false ) newParameter.typeReference!!.addToShorteningWaitSet() } } targetToSourceConstructors[constructorElement]!!.forEach { val superCall: KtCallElement? = when (it) { is KtClassOrObject -> it.getDelegatorToSuperCall() is KtPrimaryConstructor -> it.getContainingClassOrObject().getDelegatorToSuperCall() is KtSecondaryConstructor -> { if (it.hasImplicitDelegationCall()) { it.replaceImplicitDelegationCallWithExplicit(false) } else { it.getDelegationCall() } } else -> null } superCall?.valueArgumentList?.let { args -> info.usedParameters.forEach { parameter -> args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_"))) } } } } for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entries) { val properties = propertyToInitializerInfo.keys.sortedWith( Comparator { property1, property2 -> val info1 = propertyToInitializerInfo[property1]!! val info2 = propertyToInitializerInfo[property2]!! when { property2 in info1.usedProperties -> -1 property1 in info2.usedProperties -> 1 else -> 0 } } ) for (oldProperty in properties) { val info = propertyToInitializerInfo.getValue(oldProperty) addUsedParameters(constructorElement, info) info.initializer?.let { val body = constructorElement.getConstructorBodyBlock() body?.addAfter(it, body.statements.lastOrNull() ?: body.lBrace!!) } info.elementsToRemove.forEach { it.delete() } } } } override fun updateUsage(element: PsiElement) { } } internal fun KtNamedDeclaration.deleteWithCompanion() { val containingClass = this.containingClassOrObject if (containingClass is KtObjectDeclaration && containingClass.isCompanion() && containingClass.declarations.size == 1 && containingClass.getSuperTypeList() == null ) { containingClass.delete() } else { this.delete() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt
634559474
/* * VoIP.ms SMS * Copyright (C) 2015-2021 Michael Kourlas * * 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 net.kourlas.voipms_sms.utils import android.content.Context import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import net.kourlas.voipms_sms.preferences.getConnectTimeout import net.kourlas.voipms_sms.preferences.getReadTimeout import okhttp3.MultipartBody import okhttp3.Request import java.io.IOException import java.util.concurrent.TimeUnit /** * Sends a POST request with a multipart/form-data encoded request body to the * specified URL, and retrieves a JSON response body. */ @Suppress("BlockingMethodInNonBlockingContext") suspend inline fun <reified T> httpPostWithMultipartFormData( context: Context, url: String, formData: Map<String, String> = emptyMap() ): T? { val requestBodyBuilder = MultipartBody.Builder() requestBodyBuilder.setType(MultipartBody.FORM) for ((key, value) in formData) { requestBodyBuilder.addFormDataPart(key, value) } val requestBody = requestBodyBuilder.build() val request = Request.Builder() .url(url) .post(requestBody) .build() val requestClient = HttpClientManager.getInstance().client.newBuilder() .readTimeout(getReadTimeout(context) * 1000L, TimeUnit.MILLISECONDS) .connectTimeout( getConnectTimeout(context) * 1000L, TimeUnit.MILLISECONDS ) .build() val adapter = JsonParserManager.getInstance().parser.adapter(T::class.java) return withContext(Dispatchers.IO) { requestClient.newCall(request).execute().use { response -> if (!response.isSuccessful) { throw IOException("Unexpected code $response") } return@use adapter.fromJson(response.body!!.source()) } } }
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/utils/network.kt
943151884
package <%= appPackage %>.data.model import com.squareup.moshi.Json class Sprites { @Json(name="front_default") var frontDefault: String? = null }
templates/androidstarters-kotlin/app/src/main/java/io/mvpstarter/sample/data/model/Sprites.kt
2125022804
package net.squanchy.imageloader import android.graphics.drawable.Drawable import android.widget.ImageView import androidx.annotation.DrawableRes import com.bumptech.glide.RequestBuilder import com.bumptech.glide.RequestManager import com.bumptech.glide.request.RequestOptions import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference class GlideImageLoader(private val requestManager: RequestManager, private val firebaseStorage: FirebaseStorage) : ImageLoader { companion object { const val FIREBASE_URL_SCHEMA = "gs://" } override fun load(url: String): ImageRequest { return if (url.startsWith(FIREBASE_URL_SCHEMA)) { load(firebaseStorage.getReferenceFromUrl(url)) } else { GlideImageRequest(requestManager.load(url)) } } override fun load(storageReference: StorageReference): ImageRequest = GlideImageRequest(requestManager.load(storageReference)) } private class GlideImageRequest(private val request: RequestBuilder<Drawable>) : ImageRequest { private val options = RequestOptions() override fun error(@DrawableRes errorImageResId: Int) = apply { request.apply(RequestOptions.errorOf(errorImageResId)) } override fun placeholder(@DrawableRes placeholderImageResId: Int) = apply { request.apply(RequestOptions.placeholderOf(placeholderImageResId)) } override fun circleCrop() = apply { options.circleCrop() } override fun into(target: ImageView) { request.apply(options).into(target) } }
app/src/main/java/net/squanchy/imageloader/GlideImageLoader.kt
1330452819
package instep.reflection import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty import kotlin.reflect.KProperty import kotlin.reflect.full.memberProperties import kotlin.reflect.full.superclasses @Suppress("unused", "MemberVisibilityCanBePrivate") class Mirror<T : Any>(val type: KClass<T>) { constructor(instance: T) : this(instance.javaClass.kotlin) val annotations: Set<Annotation> by lazy { type.annotations.toSet() } val parents: Set<KClass<*>> by lazy { type.superclasses.toSet() } val getters: Set<KProperty.Getter<*>> by lazy { type.memberProperties.map { it.getter }.toSet() } val setters: Set<KMutableProperty.Setter<*>> by lazy { mutableProperties.map { it.setter }.toSet() } val properties = type.memberProperties.toSet() val readableProperties = type.memberProperties.filterNot { it is KMutableProperty<*> }.toSet() val mutableProperties = type.memberProperties.mapNotNull { it as? KMutableProperty<*> }.toSet() }
core/src/main/kotlin/instep/reflection/Mirror.kt
3318081465
package com.eden.orchid.changelog.adapter import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.resources.resourcesource.LocalResourceSource import com.eden.orchid.changelog.ChangelogGenerator import com.eden.orchid.changelog.model.ChangelogVersion import com.eden.orchid.utilities.OrchidUtils @Archetype(value = ConfigArchetype::class, key = ChangelogGenerator.GENERATOR_KEY) class ChangelogDirAdapter : ChangelogAdapter { @Option @StringDefault("changelog") @Description("The base directory in local resources to look for changelog entries in.") lateinit var baseDir: String @Option @StringDefault("{major}.{minor}.{patch}") @Description("The format your changelog version follow.") lateinit var format: String override fun getType() = "directory" override fun loadChangelogEntries(context: OrchidContext): List<ChangelogVersion> { return context.getDefaultResourceSource(LocalResourceSource, null).getResourceEntries( context, OrchidUtils.normalizePath(baseDir), context.compilerExtensions.toTypedArray(), true ).map { ChangelogVersion(context, format, it.reference.originalFileName, null, it) } } }
plugins/OrchidChangelog/src/main/kotlin/com/eden/orchid/changelog/adapter/ChangelogDirAdapter.kt
3792499174
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.service.slashdot import com.tickaroo.tikxml.TikXml import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory import dagger.Binds import dagger.Lazy import dagger.Module import dagger.Provides import dagger.Reusable import dagger.multibindings.IntoMap import dev.zacsweers.catchup.appconfig.AppConfig import io.reactivex.rxjava3.core.Single import io.sweers.catchup.libraries.retrofitconverters.delegatingCallFactory import io.sweers.catchup.service.api.CatchUpItem import io.sweers.catchup.service.api.DataRequest import io.sweers.catchup.service.api.DataResult import io.sweers.catchup.service.api.Mark.Companion.createCommentMark import io.sweers.catchup.service.api.Service import io.sweers.catchup.service.api.ServiceKey import io.sweers.catchup.service.api.ServiceMeta import io.sweers.catchup.service.api.ServiceMetaKey import io.sweers.catchup.service.api.SummarizationInfo import io.sweers.catchup.service.api.SummarizationType.NONE import io.sweers.catchup.service.api.TextService import io.sweers.catchup.serviceregistry.annotations.Meta import io.sweers.catchup.serviceregistry.annotations.ServiceModule import kotlinx.datetime.Instant import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import javax.inject.Inject import javax.inject.Qualifier @Qualifier private annotation class InternalApi private const val SERVICE_KEY = "sd" class SlashdotService @Inject constructor( @InternalApi private val serviceMeta: ServiceMeta, private val service: SlashdotApi ) : TextService { override fun meta() = serviceMeta override fun fetchPage(request: DataRequest): Single<DataResult> { return service.main() .map(Feed::itemList) .flattenAsObservable { it } .map { (title, id, _, summary, updated, section, comments, author, department) -> CatchUpItem( id = id.hashCode().toLong(), title = title, score = null, timestamp = updated, author = author.name, source = department, tag = section, itemClickUrl = id, summarizationInfo = SummarizationInfo(summary.substringBefore("<p>"), NONE), mark = createCommentMark( count = comments, clickUrl = "$id#comments" ) ) } .toList() .map { DataResult(it, null) } } } @Meta @ServiceModule @Module abstract class SlashdotMetaModule { @IntoMap @ServiceMetaKey(SERVICE_KEY) @Binds internal abstract fun slashdotServiceMeta(@InternalApi meta: ServiceMeta): ServiceMeta companion object { @Provides @Reusable @InternalApi internal fun provideSlashdotServiceMeta(): ServiceMeta = ServiceMeta( SERVICE_KEY, R.string.slashdot, R.color.slashdotAccent, R.drawable.logo_sd, firstPageKey = "main" ) } } @ServiceModule @Module(includes = [SlashdotMetaModule::class]) abstract class SlashdotModule { @IntoMap @ServiceKey(SERVICE_KEY) @Binds internal abstract fun slashdotService(slashdotService: SlashdotService): Service companion object { @Provides internal fun provideTikXml(): TikXml = TikXml.Builder() .exceptionOnUnreadXml(false) .addTypeConverter(Instant::class.java, InstantTypeConverter()) .build() @Provides @InternalApi internal fun provideSlashdotOkHttpClient(okHttpClient: OkHttpClient): OkHttpClient { return okHttpClient.newBuilder() .addNetworkInterceptor { chain -> val originalResponse = chain.proceed(chain.request()) // read from cache for 30 minutes, per slashdot's preferred limit val maxAge = 60 * 30 originalResponse.newBuilder() .header("Cache-Control", "public, max-age=$maxAge") .build() } .build() } @Provides internal fun provideSlashdotApi( @InternalApi client: Lazy<OkHttpClient>, rxJavaCallAdapterFactory: RxJava3CallAdapterFactory, tikXml: TikXml, appConfig: AppConfig ): SlashdotApi { val retrofit = Retrofit.Builder().baseUrl(SlashdotApi.ENDPOINT) .delegatingCallFactory(client) .addCallAdapterFactory(rxJavaCallAdapterFactory) .addConverterFactory(TikXmlConverterFactory.create(tikXml)) .validateEagerly(appConfig.isDebug) .build() return retrofit.create(SlashdotApi::class.java) } } }
services/slashdot/src/main/kotlin/io/sweers/catchup/service/slashdot/SlashdotService.kt
458104645
package com.ianhanniballake.contractiontimer.extensions import android.content.BroadcastReceiver import android.os.Build import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch /** * Run work asynchronously from a [BroadcastReceiver]. */ fun BroadcastReceiver.goAsync(block: suspend () -> Unit) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { val pendingResult = goAsync() GlobalScope.launch { block() pendingResult.finish() } } else { GlobalScope.launch { block() } } }
mobile/src/main/java/com/ianhanniballake/contractiontimer/extensions/BroadcastReceiver.kt
2519986695
val Foo: String = "" var FOO_BAR: Int = 0 var _FOO: Int = 0 const val THREE = 3 val xyzzy = 1 fun foo() { val XYZZY = 1 val BAR_BAZ = 2 } object Foo { val Foo: String = "" var FOO_BAR: Int = 0 } class D { private val _foo: String private val FOO_BAR: String val _Foo: String companion object { val Foo: String = "" var FOO_BAR: Int = 0 } } interface I { val Foo: Int } class C : I { override override val Foo = 1 } interface Parameter { val interface_p1: String val interface_p2: String } class ParameterImpl( override val interface_p1: String, private val ctor_private: String, val ctor_val: String, var ctor_var: String, ctor_param: String, ): Parameter { override val interface_p2: String = "" fun foo(fun_param: String) { val local_val = 1 } }
plugins/kotlin/idea/tests/testData/inspections/naming/property/test.kt
1916744362
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.references.KtForLoopInReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class IteratorOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtForExpression>(targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = listOf("in")) { override fun processPossibleReceiverExpression(expression: KtExpression) { val parent = expression.parent if (parent.node.elementType == KtNodeTypes.LOOP_RANGE) { processReferenceElement(parent.parent as KtForExpression) } } override fun isReferenceToCheck(ref: PsiReference): Boolean { return ref is KtForLoopInReference } override fun extractReference(element: KtElement): PsiReference? { return (element as? KtForExpression)?.references?.firstIsInstance<KtForLoopInReference>() } }
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/IteratorOperatorReferenceSearcher.kt
2721709309
fun test() { assert(2 > 3) }
plugins/kotlin/code-insight/postfix-templates/testData/expansion/assert/binary.after.kt
2900144330
// 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.github.api.data /** * States of GitHubActions * https://docs.github.com/en/graphql/reference/enums#checkstatusstate */ enum class GHCommitCheckSuiteStatusState { //The check suite or run has been completed. COMPLETED, //The check suite or run is in progress. IN_PROGRESS, //The check suite or run is in pending state. PENDING, //The check suite or run has been queued. QUEUED, //The check suite or run has been requested. REQUESTED, //The check suite or run is in waiting state. WAITING }
plugins/github/src/org/jetbrains/plugins/github/api/data/GHCommitCheckSuiteStatusState.kt
1047064743
// 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.github.ui.cloneDialog import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.UIUtil.ComponentStyle import com.intellij.util.ui.UIUtil.getRegularPanelInsets import com.intellij.util.ui.cloneDialog.AccountMenuItem import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.plugins.github.authentication.GHAccountsUtil import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.isGHAccount import org.jetbrains.plugins.github.i18n.GithubBundle.message import org.jetbrains.plugins.github.util.GithubUtil import javax.swing.JComponent private val GithubAccount.isGHEAccount: Boolean get() = !isGHAccount class GHECloneDialogExtension : BaseCloneDialogExtension() { override fun getName(): String = GithubUtil.ENTERPRISE_SERVICE_DISPLAY_NAME override fun getAccounts(): Collection<GithubAccount> = GHAccountsUtil.accounts.filter { it.isGHEAccount } override fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent = GHECloneDialogExtensionComponent(project, modalityState) } private class GHECloneDialogExtensionComponent(project: Project, modalityState: ModalityState) : GHCloneDialogExtensionComponentBase( project, modalityState, accountManager = service() ) { override fun isAccountHandled(account: GithubAccount): Boolean = account.isGHEAccount override fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent = GHECloneDialogLoginPanel(account).apply { Disposer.register(this@GHECloneDialogExtensionComponent, this) loginPanel.isCancelVisible = getAccounts().isNotEmpty() loginPanel.setCancelHandler(cancelHandler) } override fun createAccountMenuLoginActions(account: GithubAccount?): Collection<AccountMenuItem.Action> = listOf(createLoginAction(account)) private fun createLoginAction(account: GithubAccount?): AccountMenuItem.Action { val isExistingAccount = account != null return AccountMenuItem.Action( message("login.to.github.enterprise.action"), { switchToLogin(account) }, showSeparatorAbove = !isExistingAccount ) } } private class GHECloneDialogLoginPanel(account: GithubAccount?) : BorderLayoutPanel(), Disposable { private val titlePanel = simplePanel().apply { val title = JBLabel(message("login.to.github.enterprise"), ComponentStyle.LARGE).apply { font = JBFont.label().biggerOn(5.0f) } addToLeft(title) } val loginPanel = CloneDialogLoginPanel(account).apply { Disposer.register(this@GHECloneDialogLoginPanel, this) if (account == null) setServer("", true) setTokenUi() } init { addToTop(titlePanel.apply { border = JBEmptyBorder(getRegularPanelInsets().apply { bottom = 0 }) }) addToCenter(loginPanel) } override fun dispose() = loginPanel.cancelLogin() }
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHECloneDialogExtension.kt
4066932755
package org.thoughtcrime.securesms.components.settings.app.wrapped import androidx.fragment.app.Fragment import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.preferences.AdvancedPinPreferenceFragment class WrappedAdvancedPinPreferenceFragment : SettingsWrapperFragment() { override fun getFragment(): Fragment { toolbar.setTitle(R.string.preferences__advanced_pin_settings) return AdvancedPinPreferenceFragment() } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/wrapped/WrappedAdvancedPinPreferenceFragment.kt
3551401121
package org.kethereum.crypto.impl.hashing sealed class DigestParams(val keySize: Int) { object Sha256 : DigestParams(256) object Sha512 : DigestParams(512) }
crypto_api/src/main/kotlin/org/kethereum/crypto/impl/hashing/DigestParams.kt
1165040451
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testing import com.intellij.execution.Executor import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.jetbrains.python.PyNames import com.jetbrains.python.PythonHelper import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant /** * Py.test runner */ class PyTestSettingsEditor(configuration: PyAbstractTestConfiguration) : PyAbstractTestSettingsEditor( PyTestSharedForm.create(configuration, PyTestSharedForm.CustomOption( PyTestConfiguration::keywords.name, PyRunTargetVariant.PATH, PyRunTargetVariant.PYTHON))) class PyPyTestExecutionEnvironment(configuration: PyTestConfiguration, environment: ExecutionEnvironment) : PyTestExecutionEnvironment<PyTestConfiguration>(configuration, environment) { override fun getRunner(): PythonHelper = PythonHelper.PYTEST } class PyTestConfiguration(project: Project, factory: PyTestFactory) : PyAbstractTestConfiguration(project, factory, PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.PY_TEST)) { @ConfigField var keywords: String = "" override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? = PyPyTestExecutionEnvironment(this, environment) override fun createConfigurationEditor(): SettingsEditor<PyAbstractTestConfiguration> = PyTestSettingsEditor(this) override fun getCustomRawArgumentsString(forRerun: Boolean): String = when { keywords.isEmpty() -> "" else -> "-k $keywords" } + if (forRerun) " --last-failed" else "" override fun isFrameworkInstalled(): Boolean = VFSTestFrameworkListener.getInstance().isTestFrameworkInstalled(sdk, PyNames.PY_TEST) override fun setMetaInfo(metaInfo: String) { keywords = metaInfo } override fun isSameAsLocation(target: ConfigurationTarget, metainfo: String?): Boolean { return super.isSameAsLocation(target, metainfo) && metainfo == keywords } } object PyTestFactory : PyAbstractTestFactory<PyTestConfiguration>() { override fun createTemplateConfiguration(project: Project): PyTestConfiguration = PyTestConfiguration(project, this) override fun getName(): String = PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.PY_TEST) }
python/src/com/jetbrains/python/testing/PyTest.kt
2150015171
package info.deskchan.core import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.util.* class PluginProperties(private val proxyInterface: PluginProxyInterface) : MessageDataMap() { /** Loads properties from default location and overwrites current properties map. **/ fun load(){ load_impl(true) } /** Loads properties from default location and merges current properties map. **/ fun merge(){ load_impl(false) } private fun load_impl(clear: Boolean){ val configPath = proxyInterface.dataDirPath.resolve("config.properties") val properties = Properties() try { val ip = FileInputStream(configPath) properties.load(ip) ip.close() } catch (e: Exception) { return } if (clear){ for (key in keys) if (key !in properties.keys) remove(key) } for ((key, value) in properties){ val obj:Any? = get(key) try { if (obj is Number) put(key.toString(), value.toString().toDouble()) else if (obj is Boolean) put(key.toString(), value.toString().toLowerCase().equals("true")) else put(key.toString(), value.toString()) } catch (e: Exception){ put(key.toString(), value.toString()) } } proxyInterface.log("Properties loaded") } /** Saves properties to default location. **/ fun save(){ if (size == 0) return val configPath = proxyInterface.dataDirPath.resolve("config.properties") try { val properties = Properties() for ((key, value) in this) properties.put(key, value.toString()) val ip = FileOutputStream(configPath) properties.store(ip, proxyInterface.getId() + " config") ip.close() } catch (e: Exception) { proxyInterface.log(IOException("Cannot save file: " + configPath, e)) } } }
src/main/kotlin/info/deskchan/core/PluginProperties.kt
1278701739
/* * Copyright (C) 2019 Contentful GmbH * * 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.contentful.java.cma import com.contentful.java.cma.lib.ModuleTestUtils import com.contentful.java.cma.lib.TestCallback import com.contentful.java.cma.lib.TestUtils import com.contentful.java.cma.model.CMAAsset import com.contentful.java.cma.model.CMAAssetFile import com.contentful.java.cma.model.CMALink import com.contentful.java.cma.model.CMAType import com.google.gson.Gson import okhttp3.HttpUrl import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Before import java.io.IOException import java.util.logging.LogManager import kotlin.test.* import org.junit.Test as test import org.skyscreamer.jsonassert.JSONAssert.assertEquals as assertEqualJsons class AssetTests { var server: MockWebServer? = null var client: CMAClient? = null var gson: Gson? = null @Before fun setUp() { LogManager.getLogManager().reset() // MockWebServer server = MockWebServer() server!!.start() // Client client = CMAClient.Builder() .setAccessToken("token") .setCoreEndpoint(server!!.url("/").toString()) .setUploadEndpoint(server!!.url("/").toString()) .setSpaceId("configuredSpaceId") .setEnvironmentId("configuredEnvironmentId") .build() gson = CMAClient.createGson() } @After fun tearDown() { server!!.shutdown() } @test fun testArchive() { val cli = CMAClient.Builder() .setAccessToken("token") .setCoreEndpoint(server!!.url("/").toString()) .setCallbackExecutor { it.run() } .build() val responseBody = TestUtils.fileToString("asset_archive_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() .setSpaceId("spaceid") .setId("assetid") assertFalse(asset.isArchived) val result = assertTestCallback(cli.assets().async().archive( asset, TestCallback()) as TestCallback)!! // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid/archived", recordedRequest.path) assertTrue(result.isArchived) } @test fun testCreate() { val requestBody = TestUtils.fileToString("asset_create_request.json") val responseBody = TestUtils.fileToString("asset_create_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() asset.fields.localize("en-US") .setTitle("title") .setDescription("description") assertTestCallback(client!!.assets().async().create( "spaceid", "master", asset, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets", recordedRequest.path) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test fun testCreateWithConfiguredSpaceAndEnvironment() { val requestBody = TestUtils.fileToString("asset_create_request.json") val responseBody = TestUtils.fileToString("asset_create_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() asset.fields.localize("en-US").apply { title = "title" description = "description" } assertTestCallback(client!!.assets().async().create( asset, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.method) assertEquals("/spaces/configuredSpaceId/environments/configuredEnvironmentId/assets", recordedRequest.path) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test fun testCreateWithId() { val requestBody = TestUtils.fileToString("asset_create_request.json") val responseBody = TestUtils.fileToString("asset_create_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() .setId("assetid") asset.fields.localize("en-US") .setTitle("title") .setDescription("description") assertTestCallback(client!!.assets().async().create( "spaceid", "master", asset, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid", recordedRequest.path) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test fun testDeleteWithObject() { val responseBody = "" server!!.enqueue(MockResponse().setResponseCode(204).setBody(responseBody)) assertTestCallback(client!!.assets().async().delete( CMAAsset().setSpaceId("spaceid").setId("assetid"), TestCallback() ) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid", recordedRequest.path) } @test fun testFetchAll() { val responseBody = TestUtils.fileToString("asset_fetch_all_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.assets().async().fetchAll( "spaceid", "master", TestCallback()) as TestCallback)!! assertEquals(CMAType.Array, result.system.type) assertEquals(1, result.total) val items = result.items assertEquals(1, items.size) val fields = items[0].fields.localize("en-US") assertNull(fields.description) assertEquals("Bonanza Coffee Heroes", fields.title) assertNotNull(fields.file) assertEquals("hash.jpg", fields.file.fileName) assertEquals("image/jpeg", fields.file.contentType) assertEquals("//images.contentful.com/spaceid/a/b/c.jpg", fields.file.url) assertNull(fields.file.uploadFrom) assertNull(fields.file.uploadUrl) assertNotNull(fields.file.details) assertEquals(101905, fields.file.details.size) assertEquals(960, fields.file.details.imageMeta.width) assertEquals(720, fields.file.details.imageMeta.height) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/environments/master/assets?limit=100", request.path) } @test fun testFetchAllWithConfiguredSpaceAndEnvironment() { val responseBody = TestUtils.fileToString("asset_fetch_all_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.assets().async().fetchAll(TestCallback()) as TestCallback)!! // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals( "/spaces/configuredSpaceId/environments/configuredEnvironmentId/assets?limit=100", request.path) } @test fun testFetchAllWithQuery() { server!!.enqueue(MockResponse().setResponseCode(200).setBody( TestUtils.fileToString("asset_fetch_all_response.json"))) val query = hashMapOf(Pair("skip", "1"), Pair("limit", "2"), Pair("content_type", "foo")) assertTestCallback(client!!.assets().async().fetchAll( "spaceid", "environmentId", query, TestCallback()) as TestCallback) // Request val request = server!!.takeRequest() val url = HttpUrl.parse(server!!.url(request.path).toString())!! assertEquals("1", url.queryParameter("skip")) assertEquals("2", url.queryParameter("limit")) assertEquals("foo", url.queryParameter("content_type")) } @test fun testFetchAllWithQueryWithConfiguredSpaceAndEnvironment() { server!!.enqueue(MockResponse().setResponseCode(200).setBody( TestUtils.fileToString("asset_fetch_all_response.json"))) val query = hashMapOf("skip" to "1", "limit" to "2", "content_type" to "foo") assertTestCallback(client!!.assets().async().fetchAll(query, TestCallback()) as TestCallback) // Request val request = server!!.takeRequest() val url = HttpUrl.parse(server!!.url(request.path).toString())!! assertEquals("1", url.queryParameter("skip")) assertEquals("2", url.queryParameter("limit")) assertEquals("foo", url.queryParameter("content_type")) assertEquals( "/spaces/configuredSpaceId/environments/configuredEnvironmentId/" + "assets?limit=2&content_type=foo&skip=1", request.path) } @test fun testFetchWithId() { val responseBody = TestUtils.fileToString("asset_publish_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.assets().async().fetchOne( "spaceid", "master", "assetid", TestCallback(true)) as TestCallback) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid", request.path) } @test fun testFetchWithIdWithConfiguredSpaceAndEnvironment() { val responseBody = TestUtils.fileToString("asset_publish_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.assets().async().fetchOne("assetid", TestCallback(true)) as TestCallback) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/configuredSpaceId/environments/configuredEnvironmentId" + "/assets/assetid", request.path) } @test fun testProcess() { val responseBody = "" server!!.enqueue(MockResponse().setResponseCode(204).setBody(responseBody)) val asset = CMAAsset() .setId("assetid") .setSpaceId("spaceid") assertTestCallback(client!!.assets().async().process(asset, "locale", TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals( "/spaces/spaceid/environments/master/assets/assetid/files/locale/process", recordedRequest.path) } @test fun testPublish() { val responseBody = TestUtils.fileToString("asset_publish_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() .setId("assetid") .setSpaceId("spaceid") .setVersion(1) assertFalse(asset.isPublished) val result = assertTestCallback(client!!.assets().async().publish( asset, TestCallback()) as TestCallback)!! // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid/published", recordedRequest.path) assertNotNull(recordedRequest.getHeader("X-Contentful-Version")) assertTrue(result.isPublished) } @test fun testUnArchive() { val responseBody = TestUtils.fileToString("asset_publish_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() .setId("assetid") .setSpaceId("spaceid") assertTestCallback(client!!.assets().async().unArchive( asset, TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid/archived", recordedRequest.path) } @test fun testUnPublish() { val responseBody = TestUtils.fileToString("asset_publish_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.assets().async().unPublish( CMAAsset().setId("assetid").setSpaceId("spaceid"), TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid/published", recordedRequest.path) } @test fun testUpdate() { val requestBody = TestUtils.fileToString("asset_update_request.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(requestBody)) val asset = CMAAsset() asset.setId("assetid") .setSpaceId("spaceid") .setVersion(1) asset.fields.localize("en-US") .file = CMAAssetFile() .setContentType("image/jpeg") .setUploadUrl("https://www.nowhere.com/image.jpg") .setFileName("example.jpg") assertTestCallback(client!!.assets().async().update(asset, TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid", recordedRequest.path) assertNotNull(recordedRequest.getHeader("X-Contentful-Version")) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test fun testUpdateWithFluidInterface() { val requestBody = TestUtils.fileToString("asset_update_request.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(requestBody)) val asset = CMAAsset() .setId("assetid") .setSpaceId("spaceid") .setVersion(1) asset.fields.localize("en-US") .file = CMAAssetFile() .setContentType("image/jpeg") .setUploadUrl("https://www.nowhere.com/image.jpg") .setFileName("example.jpg") assertTestCallback( client!! .assets() .async() .update(asset, TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets/assetid", recordedRequest.path) assertNotNull(recordedRequest.getHeader("X-Contentful-Version")) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test(expected = RuntimeException::class) fun testRetainsSysOnNetworkError() { val badClient = CMAClient.Builder() .setAccessToken("accesstoken") .setCoreCallFactory { throw IOException(it.url().toString(), IOException()) } .build() val asset = CMAAsset().setVersion(31337) try { badClient.assets().create("spaceid", "environmentId", asset) } catch (e: RuntimeException) { assertEquals(31337, asset.version) throw e } } @test fun testNullVersionDoesNotThrow() { assertNull(CMAAsset().version) } @test(expected = Exception::class) fun testUpdateFailsWithoutVersion() { ModuleTestUtils.assertUpdateWithoutVersion { client!!.assets().update(CMAAsset().setId("aid").setSpaceId("spaceid")) } } @test fun testDoNotChangeSysOnException() { val asset = CMAAsset().setId("aid").setSpaceId("spaceid") val system = asset.system try { ModuleTestUtils.assertUpdateWithoutVersion { client!!.assets().update(asset) } } catch (e: Exception) { assertEquals(system, asset.system) } } @test fun testCreateAssetWithUploadId() { val client = CMAClient.Builder() .setAccessToken("token") .setCoreEndpoint(server!!.url("/").toString()) .setCallbackExecutor { it.run() } .build() val responseBody = TestUtils.fileToString("asset_create_with_upload_id_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() .setSpaceId("spaceid") .setVersion(1) asset.fields.localize("en-US").file = CMAAssetFile() .setContentType("image/jpeg") .setUploadFrom(CMALink().setId("some_secret_keys")) .setFileName("example.jpg") assertTestCallback(client.assets().async() .create("spaceid", "master", asset, TestCallback()) as TestCallback)!! // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.method) assertEquals("/spaces/spaceid/environments/master/assets", recordedRequest.path) } @test fun testFetchOneFromEnvironment() { val responseBody = TestUtils.fileToString("asset_fetch_one_from_environment.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback( client!! .assets() .async() .fetchOne( "spaceid", "staging", "2ReMHJhXoAcy4AyamgsgwQ", TestCallback() ) as TestCallback)!! assertEquals(CMAType.Asset, result.system.type) assertEquals("staging", result.environmentId) assertEquals("Lewis Carroll", result.fields.getTitle("en-US")) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/environments/staging/assets/2ReMHJhXoAcy4AyamgsgwQ", request.path) } @test fun testFetchAllFromEnvironment() { val responseBody = TestUtils.fileToString("asset_fetch_all_from_environment.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback( client!! .assets() .async() .fetchAll( "spaceid", "staging", TestCallback() ) as TestCallback)!! assertEquals(CMAType.Array, result.system.type) assertEquals(47, result.total) val items = result.items assertEquals(47, items.size) val fields = items[0].fields.localize("en-US") assertEquals("Lewis Carroll", fields.title) assertEquals("staging", items[0].environmentId) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/environments/staging/assets?limit=100", request.path) } @test fun testFetchAllFromEnvironmentWithQuery() { val responseBody = TestUtils.fileToString( "asset_fetch_all_from_environment_with_query.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback( client!! .assets() .async() .fetchAll( "spaceid", "staging", hashMapOf(Pair("limit", "1")), TestCallback() ) as TestCallback)!! assertEquals(CMAType.Array, result.system.type) assertEquals(47, result.total) val items = result.items assertEquals(1, items.size) val fields = items[0].fields.localize("en-US") assertEquals("budah-small", fields.title) assertEquals("staging", items[0].environmentId) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/environments/staging/assets?limit=1", request.path) } @test fun testCreateInEnvironment() { val responseBody = TestUtils.fileToString("asset_create_in_environment.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val asset = CMAAsset() asset.fields.localize("en-US").apply { title = "title" description = "description" } val result = assertTestCallback( client!! .assets() .async() .create( "spaceid", "staging", asset, TestCallback() ) as TestCallback)!! assertEquals(CMAType.Asset, result.system.type) assertEquals("staging", result.environmentId) assertEquals("title", result.fields.getTitle("en-US")) assertEquals("description", result.fields.getDescription("en-US")) // Request val request = server!!.takeRequest() assertEquals("POST", request.method) assertEquals("/spaces/spaceid/environments/staging/assets", request.path) } @test fun testDeleteFromEnvironment() { server!!.enqueue(MockResponse().setResponseCode(204).setBody("")) val result = assertTestCallback( client!! .assets() .async() .delete(CMAAsset().apply { spaceId = "spaceid" environmentId = "staging" id = "1fgii3GZo4euykA6u6mKmi" }, TestCallback() ) as TestCallback)!! assertEquals(204, result) // Request val request = server!!.takeRequest() assertEquals("DELETE", request.method) assertEquals("/spaces/spaceid/environments/staging/assets/1fgii3GZo4euykA6u6mKmi", request.path) } @test(expected = IllegalArgumentException::class) fun testThrowIfNotConfigured() { val client = CMAClient.Builder() .setAccessToken("token") .setCoreEndpoint(server!!.url("/").toString()) .setUploadEndpoint(server!!.url("/").toString()) .build() try { client.assets().fetchAll() } catch (e: IllegalArgumentException) { assertTrue(e.message!!.contains("spaceId may not be null")) throw e } } }
src/test/kotlin/com/contentful/java/cma/AssetTests.kt
2822500040
/* * 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.network.util import io.ktor.network.sockets.* import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* import io.ktor.utils.io.pool.* /** * ChunkBuffer pool for UDP datagrams */ public val DefaultDatagramChunkBufferPool: ObjectPool<ChunkBuffer> = DefaultBufferPool(MAX_DATAGRAM_SIZE, 2048)
ktor-network/nix/src/io/ktor/network/util/Pools.kt
1645283544
package com.androidarchitecture.data.auth import android.text.TextUtils import com.androidarchitecture.BuildConfig import com.androidarchitecture.entity.auth.GrantType import com.androidarchitecture.entity.auth.Token import com.androidarchitecture.utility.L import retrofit2.Retrofit import java.io.IOException class AuthorizationService constructor(internal val mTokenStore: TokenStore, retrofit: Retrofit) { private val mService: AuthorizationServiceContract = retrofit.create(AuthorizationServiceContract::class.java) internal val refreshToken: Token? @Synchronized get() { var newToken: Token? = null val token = mTokenStore.userToken try { if (TextUtils.isEmpty(token!!.refreshToken)) { return null } val call = mService.getRefreshToken(GrantType.GR_REFRESH_TOKEN, token.refreshToken, BuildConfig.API_CONSUMER_KEY) val response = call.execute() newToken = response.body() mTokenStore.saveUserToken(newToken) } catch (e: IOException) { L.e(e.message, e) } return newToken } @Synchronized fun getPasswordAccessToken(username: String, password: String): Token? { val call = mService.getPasswordToken(GrantType.GR_PASSWORD, username, password, BuildConfig.API_CONSUMER_KEY) val response = call.execute() val token = response.body() mTokenStore.saveUserToken(token) return token } }
app/src/main/java/com/androidarchitecture/data/auth/AuthorizationService.kt
1337681348
package lt.markmerkk.utils interface HashSettings { fun save() fun load() fun set(key: String, value: String) fun get(key: String, defaultValue: String): String fun getLong(key: String, defaultValue: Long): Long fun getInt(key: String, defaultValue: Int): Int fun getBoolean(key: String, defaultValue: Boolean): Boolean }
components/src/main/java/lt/markmerkk/utils/HashSettings.kt
401197568
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.userprefs.data import android.content.res.Resources import android.graphics.Color import android.util.TypedValue import com.doctoror.particleswallpaper.R import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class DefaultSceneSettingsTest { private val res: Resources = mock() private val theme: Resources.Theme = mock() private val typedValue: TypedValue = mock() private val typedValueFactory: DefaultSceneSettings.TypedValueFactory = mock { on { it.newTypedValue() }.thenReturn(typedValue) } @Test fun obtainsBackgroundColorFromResources() { // Given val value = Color.DKGRAY @Suppress("DEPRECATION") whenever(res.getColor(R.color.defaultBackground)).thenReturn(value) whenever(res.getColor(R.color.defaultBackground, theme)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.backgroundColor) } @Test fun backgroundUriIsNoUri() { val underTest = DefaultSceneSettings(res, theme, typedValueFactory) assertEquals(NO_URI, underTest.backgroundUri) } @Test fun obtainsParticleScaleFromResources() { // Given val value = 0.6f whenever(res.getDimension(R.dimen.defaultParticleScale)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.particleScale) } @Test fun doesNotReturnParticleScaleLessThanHalf() { // Given val value = 0.49f whenever(res.getDimension(R.dimen.defaultParticleScale)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(0.5f, underTest.particleScale) } @Test fun obtainsFrameDelayFromResources() { // Given val value = 10 whenever(res.getInteger(R.integer.defaultFrameDelay)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.frameDelay) } @Test fun obtainsLineLengthFromResources() { // Given val value = 1.1f whenever(res.getDimension(R.dimen.defaultLineLength)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.lineLength) } @Test fun obtainsLineScaleFromResources() { // Given val value = 1.1f whenever(res.getDimension(R.dimen.defaultLineScale)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.lineScale) } @Test fun doesNotReturnLineScaleLessThan1() { // Given val value = 0.99f whenever(res.getDimension(R.dimen.defaultLineScale)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(1f, underTest.lineScale) } @Test fun obtainsDensityFromResources() { // Given val value = 2 whenever(res.getInteger(R.integer.defaultDensity)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.density) } @Test fun obtainsParticleColorFromResources() { // Given val value = Color.CYAN @Suppress("DEPRECATION") whenever(res.getColor(R.color.defaultParticleColor)).thenReturn(value) whenever(res.getColor(R.color.defaultParticleColor, theme)).thenReturn(value) // When val underTest = newUnderTestInstance() // Then assertEquals(value, underTest.particleColor) } @Test fun obtainsSpeedFactorFromResources() { // Given val value = 1.1f val typedValue: TypedValue = mock { on(it.float).doReturn(value) } whenever(typedValueFactory.newTypedValue()).thenReturn(typedValue) // When val underTest = newUnderTestInstance() // Then verify(res).getValue(R.dimen.defaultSpeedFactor, typedValue, true) assertEquals(value, underTest.speedFactor) } private fun newUnderTestInstance() = DefaultSceneSettings(res, theme, typedValueFactory) }
app/src/test/java/com/doctoror/particleswallpaper/userprefs/data/DefaultSceneSettingsTest.kt
4048619605
package eu.kanade.tachiyomi.data.track import android.content.Context import eu.kanade.tachiyomi.data.track.anilist.Anilist import eu.kanade.tachiyomi.data.track.bangumi.Bangumi import eu.kanade.tachiyomi.data.track.kitsu.Kitsu import eu.kanade.tachiyomi.data.track.komga.Komga import eu.kanade.tachiyomi.data.track.myanimelist.MyAnimeList import eu.kanade.tachiyomi.data.track.shikimori.Shikimori class TrackManager(context: Context) { companion object { const val MYANIMELIST = 1 const val ANILIST = 2 const val KITSU = 3 const val SHIKIMORI = 4 const val BANGUMI = 5 const val KOMGA = 6 } val myAnimeList = MyAnimeList(context, MYANIMELIST) val aniList = Anilist(context, ANILIST) val kitsu = Kitsu(context, KITSU) val shikimori = Shikimori(context, SHIKIMORI) val bangumi = Bangumi(context, BANGUMI) val komga = Komga(context, KOMGA) val services = listOf(myAnimeList, aniList, kitsu, shikimori, bangumi, komga) fun getService(id: Int) = services.find { it.id == id } fun hasLoggedServices() = services.any { it.isLogged } }
app/src/main/java/eu/kanade/tachiyomi/data/track/TrackManager.kt
229433687
import javax.swing.table.AbstractTableModel import github.jk1.smtpidea.store.Clearable /** * */ public abstract class MessageFolder<T> : AbstractTableModel(), Clearable { /** * @return collection of all messages in this folder */ public abstract fun getMessages(): List<T> /** * @return number of messages in this folder */ public abstract fun messageCount(): Int /** * @return a particular message by it's number */ public abstract fun get(i: Int): T public abstract fun add(message: T) }
src/main/kotlin/github/jk1/smtpidea/store/MessageFolder.kt
1139944715
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.userprefs.preview import android.app.Activity import com.doctoror.particleswallpaper.app.REQUEST_CODE_CHANGE_WALLPAPER import com.doctoror.particleswallpaper.framework.lifecycle.OnActivityResultCallback import com.doctoror.particleswallpaper.userprefs.ConfigFragment import io.reactivex.Completable import org.junit.Test import org.mockito.kotlin.* class PreviewPreferencePresenterTest { private val activity: Activity = mock() private val useCase: OpenChangeWallpaperIntentUseCase = mock() private val underTest = PreviewPreferencePresenter(activity) private fun setHostAndExtractOnActivityResultCallback( host: ConfigFragment = mock() ): OnActivityResultCallback { underTest.host = host val callbackCapturer = argumentCaptor<OnActivityResultCallback>() verify(host).registerCallback(callbackCapturer.capture()) return callbackCapturer.firstValue } @Test fun registersOnActivityResultCallback() { // Given val host: ConfigFragment = mock() // When underTest.host = host // Then verify(host).registerCallback(any()) } @Test fun unregistersOnActivityResultCallbackOnHostChange() { // Given val host: ConfigFragment = mock() val callback = setHostAndExtractOnActivityResultCallback(host) // When underTest.host = null // Then verify(host).unregsiterCallback(callback) } @Test fun finishesOnWallpaperChange() { // Given val callback = setHostAndExtractOnActivityResultCallback() // When callback.onActivityResult(REQUEST_CODE_CHANGE_WALLPAPER, Activity.RESULT_OK, null) // Then verify(activity).finish() } @Test fun doesNotFinishWhenWallpaperNotChanged() { // Given val callback = setHostAndExtractOnActivityResultCallback() // When callback.onActivityResult(REQUEST_CODE_CHANGE_WALLPAPER, Activity.RESULT_CANCELED, null) // Then verify(activity, never()).finish() } @Test fun opensChangeWallpaper() { // Given val useCaseSource = spy(Completable.complete()) whenever(useCase.action()).thenReturn(useCaseSource) underTest.useCase = useCase // When underTest.onClick() // Then verify(useCaseSource).subscribe() } }
app/src/test/java/com/doctoror/particleswallpaper/userprefs/preview/PreviewPreferencePresenterTest.kt
1184786044
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.texter.movement import android.location.Location object DistanceCalculator { fun distanceKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val distance = FloatArray(2) Location.distanceBetween(lat1, lon1, lat2, lon2, distance) return distance[0] / 1000.0 } fun speedKph(loc1: Location, loc2: Location, time: Long): Double { val seconds = time / 1000.0 val hours = seconds / 3600.0 val distance = distanceKm(loc1.latitude, loc1.longitude, loc2.latitude, loc2.longitude) return distance / hours } }
texter/src/main/kotlin/pl/org/seva/texter/movement/DistanceCalculator.kt
3794644325
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package llvm import org.lwjgl.generator.* val LLVMOrcCLookupSet = "LLVMOrcCLookupSet".handle val LLVMOrcDefinitionGeneratorRef = "LLVMOrcDefinitionGeneratorRef".handle val LLVMOrcDumpObjectsRef = "LLVMOrcDumpObjectsRef".handle val LLVMOrcExecutionSessionRef = "LLVMOrcExecutionSessionRef".handle val LLVMOrcIRTransformLayerRef = "LLVMOrcIRTransformLayerRef".handle val LLVMOrcIndirectStubsManagerRef = "LLVMOrcIndirectStubsManagerRef".handle val LLVMOrcJITDylibRef = "LLVMOrcJITDylibRef".handle val LLVMOrcJITTargetMachineBuilderRef = "LLVMOrcJITTargetMachineBuilderRef".handle val LLVMOrcLazyCallThroughManagerRef = "LLVMOrcLazyCallThroughManagerRef".handle val LLVMOrcLLJITBuilderRef = "LLVMOrcLLJITBuilderRef".handle val LLVMOrcLLJITRef = "LLVMOrcLLJITRef".handle val LLVMOrcLookupStateRef = "LLVMOrcLookupStateRef".handle val LLVMOrcMaterializationResponsibilityRef = "LLVMOrcMaterializationResponsibilityRef".handle val LLVMOrcMaterializationUnitRef = "LLVMOrcMaterializationUnitRef".handle val LLVMOrcObjectLayerRef = "LLVMOrcObjectLayerRef".handle val LLVMOrcObjectLinkingLayerRef = "LLVMOrcObjectLinkingLayerRef".handle val LLVMOrcObjectTransformLayerRef = "LLVMOrcObjectTransformLayerRef".handle val LLVMOrcResourceTrackerRef = "LLVMOrcResourceTrackerRef".handle val LLVMOrcSymbolStringPoolEntryRef = "LLVMOrcSymbolStringPoolEntryRef".handle val LLVMOrcSymbolStringPoolRef = "LLVMOrcSymbolStringPoolRef".handle val LLVMOrcThreadSafeContextRef = "LLVMOrcThreadSafeContextRef".handle val LLVMOrcThreadSafeModuleRef = "LLVMOrcThreadSafeModuleRef".handle val LLVMJITSymbolTargetFlags = typedef(uint8_t, "LLVMJITSymbolTargetFlags") val LLVMOrcExecutorAddress = typedef(uint64_t, "LLVMOrcExecutorAddress") val LLVMOrcJITTargetAddress = typedef(uint64_t, "LLVMOrcJITTargetAddress") val LLVMJITSymbolGenericFlags = "LLVMJITSymbolGenericFlags".enumType val LLVMOrcJITDylibLookupFlags = "LLVMOrcJITDylibLookupFlags".enumType val LLVMOrcLookupKind = "LLVMOrcLookupKind".enumType val LLVMOrcSymbolLookupFlags = "LLVMOrcSymbolLookupFlags".enumType val LLVMJITSymbolFlags = struct(Module.LLVM, "LLVMJITSymbolFlags") { documentation = "Represents the linkage flags for a symbol definition." uint8_t("GenericFlags", "") uint8_t("TargetFlags", "") } val LLVMJITEvaluatedSymbol = struct(Module.LLVM, "LLVMJITEvaluatedSymbol") { documentation = "Represents an evaluated symbol address and flags." LLVMOrcExecutorAddress("Address", "") LLVMJITSymbolFlags("Flags", "") } val LLVMOrcErrorReporterFunction = Module.LLVM.callback { void( "LLVMOrcErrorReporterFunction", "Error reporter function.", opaque_p("Ctx", ""), LLVMErrorRef("Err", ""), nativeType = "LLVMOrcErrorReporterFunction" ) { documentation = "Instances of this interface may be passed to the #OrcExecutionSessionSetErrorReporter() method." } } val LLVMOrcCSymbolFlagsMapPair = struct(Module.LLVM, "LLVMOrcCSymbolFlagsMapPair") { documentation = "Represents a pair of a symbol name and {@code LLVMJITSymbolFlags}." LLVMOrcSymbolStringPoolEntryRef("Name", "") LLVMJITSymbolFlags("Flags", "") } val LLVMOrcCSymbolFlagsMapPairs = typedef(LLVMOrcCSymbolFlagsMapPair.p, "LLVMOrcCSymbolFlagsMapPairs") val LLVMJITCSymbolMapPair = struct(Module.LLVM, "LLVMJITCSymbolMapPair") { documentation = "Represents a pair of a symbol name and an evaluated symbol." LLVMOrcSymbolStringPoolEntryRef("Name", "") LLVMJITEvaluatedSymbol("Sym", "") } val LLVMOrcCSymbolMapPairs = typedef(LLVMJITCSymbolMapPair.p, "LLVMOrcCSymbolMapPairs") val LLVMOrcCSymbolAliasMapEntry = struct(Module.LLVM, "LLVMOrcCSymbolAliasMapEntry") { documentation = "Represents a {@code SymbolAliasMapEntry}" LLVMOrcSymbolStringPoolEntryRef("Name", "") LLVMJITSymbolFlags("Flags", "") } val LLVMOrcCSymbolAliasMapPair = struct(Module.LLVM, "LLVMOrcCSymbolAliasMapPair") { documentation = "Represents a pair of a symbol name and {@code SymbolAliasMapEntry}." LLVMOrcSymbolStringPoolEntryRef("Name", "") LLVMOrcCSymbolAliasMapEntry("Entry", "") } val LLVMOrcCSymbolAliasMapPairs = typedef(LLVMOrcCSymbolAliasMapPair.p, "LLVMOrcCSymbolAliasMapPairs") val LLVMOrcCSymbolsList = struct(Module.LLVM, "LLVMOrcCSymbolsList") { documentation = "Represents a list of {@code LLVMOrcSymbolStringPoolEntryRef} and the associated length." LLVMOrcSymbolStringPoolEntryRef.p("Symbols", "") AutoSize("Symbols")..size_t("Length", "") } val LLVMOrcCDependenceMapPair = struct(Module.LLVM, "LLVMOrcCDependenceMapPair") { documentation = "Represents a pair of a {@code JITDylib} and {@code LLVMOrcCSymbolsList}." LLVMOrcJITDylibRef("JD", "") LLVMOrcCSymbolsList("Names", "") } val LLVMOrcCDependenceMapPairs = typedef(LLVMOrcCDependenceMapPair.p, "LLVMOrcCDependenceMapPairs") val LLVMOrcCLookupSetElement = struct(Module.LLVM, "LLVMOrcCLookupSetElement") { documentation = "An element type for a symbol lookup set." LLVMOrcSymbolStringPoolEntryRef("Name", "") LLVMOrcSymbolLookupFlags("LookupFlags", "") } val LLVMOrcMaterializationUnitMaterializeFunction = Module.LLVM.callback { void( "LLVMOrcMaterializationUnitMaterializeFunction", """ A {@code MaterializationUnit} materialize callback. Ownership of the {@code Ctx} and {@code MR} arguments passes to the callback which must adhere to the {@code LLVMOrcMaterializationResponsibilityRef} contract (see comment for that type). If this callback is called then the ##LLVMOrcMaterializationUnitDestroyFunction callback will NOT be called. """, opaque_p("Ctx", ""), LLVMOrcMaterializationResponsibilityRef("MR", ""), nativeType = "LLVMOrcMaterializationUnitMaterializeFunction" ) { documentation = "Instances of this interface may be passed to the #OrcCreateCustomMaterializationUnit() method." } } val LLVMOrcMaterializationUnitDiscardFunction = Module.LLVM.callback { void( "LLVMOrcMaterializationUnitDiscardFunction", """ A {@code MaterializationUnit} discard callback. Ownership of {@code JD} and {@code Symbol} remain with the caller: These arguments should not be disposed of or released. """, opaque_p("Ctx", ""), LLVMOrcJITDylibRef("JD", ""), LLVMOrcSymbolStringPoolEntryRef("Symbol", ""), nativeType = "LLVMOrcMaterializationUnitDiscardFunction" ) { documentation = "Instances of this interface may be passed to the #OrcCreateCustomMaterializationUnit() method." } } val LLVMOrcMaterializationUnitDestroyFunction = Module.LLVM.callback { void( "LLVMOrcMaterializationUnitDestroyFunction", """ A {@code MaterializationUnit} destruction callback. If a custom {@code MaterializationUnit} is destroyed before its {@code Materialize} function is called then this function will be called to provide an opportunity for the underlying program representation to be destroyed. """, opaque_p("Ctx", ""), nativeType = "LLVMOrcMaterializationUnitDestroyFunction" ) { documentation = "Instances of this interface may be passed to the #OrcCreateCustomMaterializationUnit() method." } } val LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction = Module.LLVM.callback { LLVMErrorRef( "LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction", """ A custom generator function. This can be used to create a custom generator object using #OrcCreateCustomCAPIDefinitionGenerator(). The resulting object can be attached to a {@code JITDylib}, via #OrcJITDylibAddGenerator(), to receive callbacks when lookups fail to match existing definitions. """, LLVMOrcDefinitionGeneratorRef("GeneratorObj", "will contain the address of the custom generator object"), opaque_p("Ctx", "will contain the context object passed to {@code LLVMOrcCreateCustomCAPIDefinitionGenerator}."), LLVMOrcLookupStateRef.p( "LookupState", """ will contain a pointer to an {@code LLVMOrcLookupStateRef} object. This can optionally be modified to make the definition generation process asynchronous: If the {@code LookupStateRef} value is copied, and the original {@code LLVMOrcLookupStateRef} set to null, the lookup will be suspended. Once the asynchronous definition process has been completed clients must call {@code LLVMOrcLookupStateContinueLookup} to continue the lookup (this should be done unconditionally, even if errors have occurred in the mean time, to free the lookup state memory and notify the query object of the failures). If {@code LookupState} is captured this function must return #ErrorSuccess. """ ), LLVMOrcLookupKind("Kind", "can be inspected to determine the lookup kind (e.g. as-if-during-static-link, or as-if-during-dlsym)"), LLVMOrcJITDylibRef("JD", "specifies which {@code JITDylib} the definitions should be generated into"), LLVMOrcJITDylibLookupFlags("JDLookupFlags", "can be inspected to determine whether the original lookup included non-exported symbols"), LLVMOrcCLookupSet("LookupSet", "contains the set of symbols that could not be found in {@code JD} already (the set of generation candidates)"), AutoSize("LookupSet")..size_t("LookupSetSize", ""), nativeType = "LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction" ) { documentation = "Instances of this interface may be passed to the #OrcCreateCustomCAPIDefinitionGenerator() method." } } val LLVMOrcSymbolPredicate = Module.LLVM.callback { int( "LLVMOrcSymbolPredicate", "Predicate function for {@code SymbolStringPoolEntries}.", opaque_p("Ctx", ""), LLVMOrcSymbolStringPoolEntryRef("Sym", ""), nativeType = "LLVMOrcSymbolPredicate" ) { documentation = "Instances of this interface may be passed to the #OrcCreateDynamicLibrarySearchGeneratorForProcess() method." } } val LLVMOrcGenericIRModuleOperationFunction = Module.LLVM.callback { LLVMErrorRef( "LLVMOrcGenericIRModuleOperationFunction", "A function for inspecting/mutating IR modules, suitable for use with #OrcThreadSafeModuleWithModuleDo().", opaque_p("Ctx", ""), LLVMModuleRef("M", ""), nativeType = "LLVMOrcGenericIRModuleOperationFunction" ) { documentation = "Instances of this interface may be passed to the #OrcThreadSafeModuleWithModuleDo() method." } } val LLVMOrcIRTransformLayerTransformFunction = Module.LLVM.callback { LLVMErrorRef( "LLVMOrcIRTransformLayerTransformFunction", """ A function for applying transformations as part of an transform layer. Implementations of this type are responsible for managing the lifetime of the {@code Module} pointed to by {@code ModInOut}: If the {@code LLVMModuleRef} value is overwritten then the function is responsible for disposing of the incoming module. If the module is simply accessed/mutated in-place then ownership returns to the caller and the function does not need to do any lifetime management. Clients can call #OrcLLJITGetIRTransformLayer() to obtain the transform layer of a {@code LLJIT} instance, and use #OrcIRTransformLayerSetTransform() to set the function. This can be used to override the default transform layer. """, opaque_p("Ctx", ""), Check(1)..LLVMOrcThreadSafeModuleRef.p("ModInOut", ""), LLVMOrcMaterializationResponsibilityRef("MR", ""), nativeType = "LLVMOrcIRTransformLayerTransformFunction" ) { documentation = "Instances of this interface may be passed to the #OrcIRTransformLayerSetTransform() method." } } val LLVMOrcObjectTransformLayerTransformFunction = Module.LLVM.callback { LLVMErrorRef( "LLVMOrcObjectTransformLayerTransformFunction", """ A function for applying transformations to an object file buffer. Implementations of this type are responsible for managing the lifetime of the memory buffer pointed to by {@code ObjInOut}: If the {@code LLVMMemoryBufferRef} value is overwritten then the function is responsible for disposing of the incoming buffer. If the buffer is simply accessed/mutated in-place then ownership returns to the caller and the function does not need to do any lifetime management. The transform is allowed to return an error, in which case the {@code ObjInOut} buffer should be disposed of and set to null. """, opaque_p("Ctx", ""), Check(1)..LLVMMemoryBufferRef.p("ObjInOut", ""), nativeType = "LLVMOrcObjectTransformLayerTransformFunction" ) { documentation = "Instances of this interface may be passed to the #OrcObjectTransformLayerSetTransform() method." } }
modules/lwjgl/llvm/src/templates/kotlin/llvm/OrcTypes.kt
1770444604
package de.flocksserver.domain.exceptions /** * Created by marcel on 03.08.17. */ class MyException(override val message: String?) : Exception(message)
domain/src/main/java/de/flocksserver/domain/exceptions/MyException.kt
1503949581
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val KHR_surface_protected_capabilities = "KHRSurfaceProtectedCapabilities".nativeClassVK("KHR_surface_protected_capabilities", type = "instance", postfix = "KHR") { documentation = """ This extension extends ##VkSurfaceCapabilities2KHR, providing applications a way to query whether swapchains <b>can</b> be created with the #SWAPCHAIN_CREATE_PROTECTED_BIT_KHR flag set. Vulkan 1.1 added (optional) support for protect memory and protected resources including buffers (#BUFFER_CREATE_PROTECTED_BIT), images (#IMAGE_CREATE_PROTECTED_BIT), and swapchains (#SWAPCHAIN_CREATE_PROTECTED_BIT_KHR). However, on implementations which support multiple windowing systems, not all window systems <b>may</b> be able to provide a protected display path. This extension provides a way to query if a protected swapchain created for a surface (and thus a specific windowing system) <b>can</b> be displayed on screen. It extends the existing ##VkSurfaceCapabilities2KHR structure with a new ##VkSurfaceProtectedCapabilitiesKHR structure from which the application <b>can</b> obtain information about support for protected swapchain creation through #GetPhysicalDeviceSurfaceCapabilities2KHR(). <h5>VK_KHR_surface_protected_capabilities</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_KHR_surface_protected_capabilities}</dd> <dt><b>Extension Type</b></dt> <dd>Instance extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>240</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.1</li> <li>Requires {@link KHRGetSurfaceCapabilities2 VK_KHR_get_surface_capabilities2} to be enabled</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Sandeep Shinde <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_surface_protected_capabilities]%20@sashinde%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_surface_protected_capabilities%20extension*">sashinde</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2018-12-18</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Sandeep Shinde, NVIDIA</li> <li>James Jones, NVIDIA</li> <li>Daniel Koch, NVIDIA</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "KHR_SURFACE_PROTECTED_CAPABILITIES_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "KHR_SURFACE_PROTECTED_CAPABILITIES_EXTENSION_NAME".."VK_KHR_surface_protected_capabilities" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR".."1000239000" ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_surface_protected_capabilities.kt
1369052044
package org.wikipedia.page class Page(var title: PageTitle, var sections: List<Section>, var pageProperties: PageProperties) { constructor(title: PageTitle, pageProperties: PageProperties) : this(title, emptyList(), pageProperties) val displayTitle = pageProperties.displayTitle.orEmpty() val isMainPage = pageProperties.isMainPage val isArticle = !isMainPage && title.namespace() === Namespace.MAIN val isProtected = !pageProperties.canEdit() }
app/src/main/java/org/wikipedia/page/Page.kt
3574818878
package src import api.Fibonacci import java.awt.Color /** * Created by vicboma on 31/10/15. */ class Functional : Fibonacci { init { println("Initialize Fibonacci Functional") } override fun method(n : Long) : Long { fun _method(index: Long, ant: Long = 0, act: Long = 1): Long = when (index) { 0L -> ant else -> _method(index - 1, act, ant + act) } return _method(n, 0, 1) } }
src/main/java/src/Functional.kt
1211855914
/* * 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.program.internal import dagger.Reusable import io.reactivex.Single import javax.inject.Inject import org.hisp.dhis.android.core.arch.api.executors.internal.APIDownloader import org.hisp.dhis.android.core.arch.call.factories.internal.UidsCall import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.common.ObjectWithUid import org.hisp.dhis.android.core.program.ProgramIndicator @Reusable internal class ProgramIndicatorCall @Inject constructor( private val service: ProgramIndicatorService, private val handler: Handler<ProgramIndicator>, private val apiDownloader: APIDownloader, private val programStore: ProgramStoreInterface ) : UidsCall<ProgramIndicator> { companion object { const val MAX_UID_LIST_SIZE = 50 } override fun download(uids: Set<String>): Single<List<ProgramIndicator>> { val programUids = programStore.selectUids() val firstPayload = apiDownloader.downloadPartitioned( uids = programUids.toSet(), pageSize = MAX_UID_LIST_SIZE, pageDownloader = { partitionUids -> val displayInFormFilter = ProgramIndicatorFields.displayInForm.eq(true) val programUidsFilter = "program.${ObjectWithUid.uid.`in`(partitionUids).generateString()}" service.getProgramIndicator( fields = ProgramIndicatorFields.allFields, displayInForm = displayInFormFilter, program = programUidsFilter, uids = null, false ) } ) val secondPayload = apiDownloader.downloadPartitioned( uids = uids, pageSize = MAX_UID_LIST_SIZE, pageDownloader = { partitionUids -> service.getProgramIndicator( fields = ProgramIndicatorFields.allFields, displayInForm = null, program = null, uids = ProgramIndicatorFields.uid.`in`(partitionUids), false ) } ) return Single.merge(firstPayload, secondPayload).reduce { t1, t2 -> val data = t1 + t2 data.distinctBy { it.uid() } }.doOnSuccess { handler.handleMany(it) }.toSingle() } }
core/src/main/java/org/hisp/dhis/android/core/program/internal/ProgramIndicatorCall.kt
3898992160
/* * Copyright (C) 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 com.android.gradle.replicator.model.internal import com.android.gradle.replicator.model.DependencyType import com.android.gradle.replicator.model.PluginType import com.android.gradle.replicator.model.internal.fixtures.project import com.google.common.truth.Truth import org.junit.Test class ProjectAdapterTest { @Test fun `test write empty project`() { Truth.assertThat(emptyProjectObject().toJson()).isEqualTo(EMPTY_PROJECT) } @Test fun `test load empty project`() { val project = emptyProjectObject() val loadedProject = EMPTY_PROJECT.fromJson(ProjectAdapter()) Truth.assertThat(loadedProject).isEqualTo(project) } @Test fun `test load + write empty project`() { val loadedProject = EMPTY_PROJECT.fromJson(ProjectAdapter()) Truth.assertThat(loadedProject.toJson()).isEqualTo(EMPTY_PROJECT) } @Test fun `test write full module`() { Truth.assertThat(fullProjectObject().toJson()).isEqualTo(FULL_PROJECT) } @Test fun `test load full module`() { val project = fullProjectObject() val loadedProject = FULL_PROJECT.fromJson(ProjectAdapter()) Truth.assertThat(loadedProject).isEqualTo(project) } @Test fun `test load + write full module`() { val loadedProject = FULL_PROJECT.fromJson(ProjectAdapter()) Truth.assertThat(loadedProject.toJson()).isEqualTo(FULL_PROJECT) } // -------------------------- /** * this should match [EMPTY_MODULE] */ private fun emptyProjectObject() = project { gradleVersion = "6.5" agpVersion = "4.2" kotlinVersion = "1.3.72" } /** * this should match [FULL_MODULE] */ private fun fullProjectObject()= project { gradleVersion = "6.5" agpVersion = "4.2" kotlinVersion = "1.3.72" rootModule { path = ":foo" plugins = listOf(PluginType.ANDROID_APP, PluginType.KOTLIN_ANDROID) javaSources { fileCount = 1 } kotlinSources { fileCount = 2 } dependencies = listOf( DefaultDependenciesInfo(DependencyType.MODULE, "module1", "api"), DefaultDependenciesInfo(DependencyType.MODULE, "module2", "implementation"), DefaultDependenciesInfo(DependencyType.EXTERNAL_LIBRARY, "lib:foo:1.0", "api") ) android { compileSdkVersion = "android-30" minSdkVersion = 24 targetSdkVersion = 30 buildFeatures { androidResources = true compose = true } } } } } private val EMPTY_PROJECT = """ { "gradle": "6.5", "agp": "4.2", "kotlin": "1.3.72", "properties": [], "rootModule": { "path": ":", "plugins": [], "dependencies": [] }, "modules": [] } """.trimIndent() private val FULL_PROJECT = """ { "gradle": "6.5", "agp": "4.2", "kotlin": "1.3.72", "properties": [], "rootModule": { "path": ":foo", "plugins": [ "com.android.application", "org.jetbrains.kotlin.android" ], "javaSources": { "fileCount": 1 }, "kotlinSources": { "fileCount": 2 }, "dependencies": [ { "moduleName": "module1", "method": "api" }, { "moduleName": "module2", "method": "implementation" }, { "library": "lib:foo:1.0", "method": "api" } ], "android": { "compileSdkVersion": "android-30", "minSdkVersion": 24, "targetSdkVersion": 30, "buildFeatures": { "androidResources": true, "compose": true } } }, "modules": [] }""".trimIndent()
model/src/test/kotlin/com/android/gradle/replicator/model/internal/ProjectAdapterTest.kt
1020429386
// WITH_STDLIB // IS_APPLICABLE: false fun foo(list: List<String>): Int? { var index = 0 <caret>for ((i, s) in list.withIndex()) { val x = s.length * index * i index++ if (x > 0) return x } return null }
plugins/kotlin/idea/tests/testData/intentions/useWithIndex/alreadyWithIndex.kt
3218643075
fun println(s: String) {} fun test(x: Double, i: Int) { if (x > 0.0) { <caret>if (i == 1) { println("a") } else if (i == 2) { println("b") } else { println("none") } } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/cascadeIf/insideOtherIf.kt
2949780698
package katas.kotlin.diamond import nonstdlib.tail import datsok.shouldEqual import nonstdlib.times import org.junit.Test class Diamond4 { @Test fun `diamonds of various sizes`() { diamond(from = 'A', to = 'A') shouldEqual "A" diamond(from = 'A', to = 'B') shouldEqual """ |-A- |B-B |-A- """.trimMargin() diamond(from = 'A', to = 'C') shouldEqual """ |--A-- |-B-B- |C---C |-B-B- |--A-- """.trimMargin() } private fun diamond(from: Char, to: Char): String { val size = to - from + 1 return 0.until(size) .map { i -> val leftPad = size - (i + 1) val rightPad = i ("-" * leftPad) + (from + i) + ("-" * rightPad) } .map { it.mirrored() } .mirrored() .joinToString("\n") } private fun String.mirrored() = this + this.reversed().tail() private fun <E> List<E>.mirrored() = this + this.reversed().tail() }
kotlin/src/katas/kotlin/diamond/Diamond4.kt
2315464676
fun kotlinUsageSynthetic() { Kotlin().smth }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/javaMethodSyntheticGet/KotlinUsageSynthetic.kt
1742657797
// INTENTION_TEXT: "Import members from 'java.util.regex.Pattern'" // WITH_STDLIB fun foo() { java.util.regex.Pattern<caret>.CASE_INSENSITIVE }
plugins/kotlin/idea/tests/testData/intentions/importAllMembers/QualifiedName.kt
4087860571
package i_introduction._1_Java_To_Kotlin_Converter import util.TODO fun todoTask1(collection: Collection<Int>): Nothing = TODO( """ Task 1. Convert the Java method 'task1' of the class 'JavaCode1' into Kotlin. In IntelliJ IDEA or Android Studio, you can copy the Java code, paste it into the Kotlin file and let IDE convert it. Please use automatic conversion for this task only. """, references = { JavaCode1().task1(collection) }) fun task1(collection: Collection<Int>): String { todoTask1(collection) }
src/i_introduction/_1_Java_To_Kotlin_Converter/n01JavaToKotlinConverter.kt
223045517
package com.github.kurtyan.fanfou4j.request.status import com.github.kurtyan.fanfou4j.core.AbstractRequest import com.github.kurtyan.fanfou4j.core.HttpMethod import com.github.kurtyan.fanfou4j.entity.Status /** * List homepage timeline of specified user. * * Created by yanke on 2016/12/6. */ class ListHomepageTimelineRequest : AbstractRequest<Array<Status>>("/statuses/home_timeline.json", HttpMethod.GET){ var id: String by stringDelegate // userId var sinceId: String by stringDelegate var maxId: String by stringDelegate var count: Int by intDelegate var page: Int by intDelegate }
src/main/java/com/github/kurtyan/fanfou4j/request/status/ListHomepageTimelineRequest.kt
1208393166
package com.xmartlabs.bigbang.test.helpers import android.view.View import android.widget.ImageButton import androidx.annotation.IdRes import androidx.annotation.StringRes import androidx.appcompat.widget.Toolbar import androidx.test.espresso.Espresso.onView import androidx.test.espresso.ViewInteraction import androidx.test.espresso.matcher.ViewMatchers.* import org.hamcrest.Matchers.allOf /** * Utility class for managing Espresso views */ class EspressoUtils { companion object { /** * Retrieves the [ViewInteraction] of the up button * * @return the [ViewInteraction] instance */ @JvmStatic fun onUpButtonView() = onView( allOf<View>(isAssignableFrom(ImageButton::class.java), withParent(isAssignableFrom(Toolbar::class.java)), isClickable())) /** * Creates a [ViewInteraction] for the view with the given resource id, if found * * @param id the views' resource id * * @return the [ViewInteraction] instance */ @JvmStatic fun onViewWithId(@IdRes id: Int) = onView(withId(id)) /** * Creates a [ViewInteraction] for the view that is displaying the text with the resource `id` * * @param textResId the id of the text resource to find * * @return the [ViewInteraction] instance */ @JvmStatic fun onViewWithText(@StringRes textResId: Int) = onView(withText(textResId)) /** * Creates a [ViewInteraction] for the TextView whose text property value matches `text` * * @return the [ViewInteraction] instance */ @JvmStatic fun onViewWithText(text: String) = onView(withText(text)) } }
instrumental-test/src/main/java/com/xmartlabs/bigbang/test/helpers/EspressoUtils.kt
2413770664
class LazyProperty(val initializer: () -> Int) { val lazyValue: Int by lazy { initializer() } }
lesson4/task3/src/Task.kt
1838844289
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.ex import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase import com.intellij.openapi.options.SchemeState import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.testFramework.runInInitMode import com.intellij.util.io.readText import com.intellij.util.io.write import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule import org.junit.Rule import org.junit.Test class InspectionSchemeTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @JvmField @Rule val fsRule = InMemoryFsRule() @Test fun loadSchemes() { val schemeFile = fsRule.fs.getPath("inspection/Bar.xml") val schemeData = """ <inspections version="1.0"> <option name="myName" value="Bar" /> <inspection_tool class="Since15" enabled="true" level="ERROR" enabled_by_default="true" /> "</inspections>""".trimIndent() schemeFile.write(schemeData) val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath("")) val profileManager = ApplicationInspectionProfileManager(schemeManagerFactory) profileManager.forceInitProfiles(true) profileManager.initProfiles() assertThat(profileManager.profiles).hasSize(1) val scheme = profileManager.profiles.first() assertThat(scheme.schemeState).isEqualTo(SchemeState.UNCHANGED) assertThat(scheme.name).isEqualTo("Bar") runInInitMode { scheme.initInspectionTools(null) } schemeManagerFactory.save() assertThat(scheme.schemeState).isEqualTo(SchemeState.UNCHANGED) assertThat(schemeFile.readText()).isEqualTo(schemeData) profileManager.profiles // test reload schemeManagerFactory.process { it.reload() } assertThat(profileManager.profiles).hasSize(1) } }
java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionSchemeTest.kt
1928766942
package de.ph1b.audiobook.persistence.pref import io.reactivex.Observable import kotlin.properties.ReadWriteProperty abstract class Pref<T : Any> : ReadWriteProperty<Any, T> { @Suppress("LeakingThis") var value: T by this abstract val stream: Observable<T> }
app/src/main/java/de/ph1b/audiobook/persistence/pref/Pref.kt
3298057873
package backend.model.sponsoring import backend.model.event.Team import backend.model.event.TeamService import backend.model.misc.Email import backend.model.misc.EmailAddress import backend.model.user.Sponsor import backend.model.user.UserService import backend.services.mail.MailService import org.javamoney.moneta.Money import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.math.BigDecimal import javax.transaction.Transactional @Service class SponsoringServiceImpl(private val sponsoringRepository: SponsoringRepository, private val mailService: MailService, private val teamService: TeamService, private val userService: UserService) : SponsoringService { override fun findAllRegisteredSponsorsWithSponsoringAtEvent(eventId: Long): Iterable<Sponsor> { return sponsoringRepository.findAllRegisteredSponsorsWithSponsoringsAtEvent(eventId) } override fun findAllUnregisteredSponsorsWithSponsoringAtEvent(eventId: Long): Iterable<UnregisteredSponsor> { return sponsoringRepository.findAllUnregisteredSponsorsWithSponsoringsAtEvent(eventId) } private val logger: Logger = LoggerFactory.getLogger(SponsoringServiceImpl::class.java) @Transactional override fun createSponsoring(sponsor: Sponsor, team: Team, amountPerKm: Money, limit: Money): Sponsoring { val sponsoring = Sponsoring(sponsor, team, amountPerKm, limit) mailService.sendSponsoringWasAddedEmail(sponsoring) return sponsoringRepository.save(sponsoring) } override fun sendEmailsToSponsorsWhenEventHasStarted() { userService.findAllSponsors() .filter { it.challenges.count() + it.sponsorings.count() > 0 } .apply { logger.info("Sending emails that event has started to ${this.count()} sponsors") } .forEach { val mail = Email( to = listOf(EmailAddress(it.email)), subject = "BreakOut 2016 - Jetzt geht's los", body = getEmailBodyWhenEventHasStarted(it), buttonText = "ZUM LIVEBLOG", buttonUrl = "https://event.break-out.org/?utm_source=backend&utm_medium=email&utm_content=intial&utm_campaign=event_started_sponsor") mailService.sendAsync(mail) } } private fun getEmailBodyWhenEventHasStarted(sponsor: Sponsor): String { val title = when (sponsor.gender) { "male" -> "Sehr geehrter Herr" "female" -> "Sehr geehrte Frau" else -> "Sehr geehrte*r" } return "$title ${sponsor.firstname} ${sponsor.lastname},<br><br>" + "BreakOut 2016 hat begonnen! Wir freuen uns sehr, Sie als Sponsor dabei zu haben!<br>" + "Sie können unter <a href=\"https://event.break-out.org/?utm_source=backend&utm_medium=email&u" + "tm_content=intial&utm_campaign=event_started_sponsor\">https://event.break-out.org/</a> die nächsten 36 Stunden live mitverfolgen, " + "wohin die Reise geht und welche Abenteuer Ihr Team dabei erlebt. Natürlich können Sie " + "während der 36h Ihr Team noch mit spontanen Challenges herausfordern. " + "Wir wünschen Ihnen viel Spaß dabei!!<br><br>" + "Herzliche Grüße<br>" + "Ihr BreakOut-Team" } override fun sendEmailsToSponsorsWhenEventHasEnded() { userService.findAllSponsors() .filter { it.challenges.count() + it.sponsorings.count() > 0 } .apply { logger.info("Sending emails that event has ended to ${this.count()} sponsors") } .forEach { val mail = Email( to = listOf(EmailAddress(it.email)), subject = "BreakOut 2016 - War ein voller Erfolg!", body = getEmailBodyWhenEventHasEnded(it), buttonText = "ZUM LIVEBLOG", buttonUrl = "https://event.break-out.org/?utm_source=backend&utm_medium=email&utm_content=intial&utm_campaign=event_ended_sponsor") mailService.sendAsync(mail) } } private fun getEmailBodyWhenEventHasEnded(sponsor: Sponsor): String { val title = when (sponsor.gender) { "male" -> "Sehr geehrter Herr" "female" -> "Sehr geehrte Frau" else -> "Sehr geehrte Frau / Herr" } return "$title ${sponsor.firstname} ${sponsor.lastname},<br><br>" + "BreakOut 2016 ist vollendet. Vielen herzlichen Dank, dass Sie als Sponsor die Reise Ihres Teams unterstützt und damit den Erfolg unseres Projektes erst ermöglicht haben." + "Ein riesiges Dankeschön von uns!<br><br>" + "Ihr Team erholt sich gerade von den kräftezehrenden 36 Stunden während wir Ihr genaues Spendenversprechen ermitteln." + "Dazu werden Sie morgen Abend eine E-Mail mit dem genauen Spendenbetrag von uns erhalten.<br><br>" + "Herzliche Grüße<br>" + "Ihr BreakOut-Team" } @Transactional override fun createSponsoringWithOfflineSponsor(team: Team, amountPerKm: Money, limit: Money, unregisteredSponsor: UnregisteredSponsor): Sponsoring { val sponsoring = Sponsoring(unregisteredSponsor, team, amountPerKm, limit) return sponsoringRepository.save(sponsoring) } @Transactional override fun acceptSponsoring(sponsoring: Sponsoring): Sponsoring { sponsoring.accept() return sponsoringRepository.save(sponsoring) } @Transactional override fun rejectSponsoring(sponsoring: Sponsoring): Sponsoring { sponsoring.reject() return sponsoringRepository.save(sponsoring) } @Transactional override fun withdrawSponsoring(sponsoring: Sponsoring): Sponsoring { sponsoring.withdraw() mailService.sendSponsoringWasWithdrawnEmail(sponsoring) return sponsoringRepository.save(sponsoring) } override fun findByTeamId(teamId: Long) = sponsoringRepository.findByTeamId(teamId) override fun findBySponsorId(sponsorId: Long) = sponsoringRepository.findBySponsorAccountId(sponsorId) override fun findOne(id: Long): Sponsoring? = sponsoringRepository.findOne(id) fun getAmountRaised(sponsoring: Sponsoring): Money { return if (reachedLimit(sponsoring)) { sponsoring.limit } else { calculateAmount(sponsoring) } } fun reachedLimit(sponsoring: Sponsoring): Boolean { return calculateAmount(sponsoring).isGreaterThan(sponsoring.limit) } fun calculateAmount(sponsoring: Sponsoring): Money { val kilometers = teamService.getDistanceForTeam(sponsoring.team!!.id!!) val amountPerKmAsBigDecimal = sponsoring.amountPerKm.numberStripped val total = amountPerKmAsBigDecimal.multiply(BigDecimal.valueOf(kilometers)) return Money.of(total, "EUR") } }
src/main/java/backend/model/sponsoring/SponsoringServiceImpl.kt
1103261194
package com.company.commonbusiness.http.rx import io.reactivex.* import org.reactivestreams.Publisher /** * Author: 李昭鸿 * Time: Create on 2019/2/22 9:55 * Desc: 多种线程调度器处理 */ open class BaseScheduler<T> constructor( private val subscribeOnScheduler: Scheduler, private val observerOnScheduler: Scheduler ) : ObservableTransformer<T, T>, SingleTransformer<T, T>, MaybeTransformer<T, T>, CompletableTransformer, FlowableTransformer<T, T> { override fun apply(upstream: Observable<T>): ObservableSource<T> { return upstream.subscribeOn(subscribeOnScheduler) .unsubscribeOn(subscribeOnScheduler) .observeOn(observerOnScheduler) } override fun apply(upstream: Single<T>): SingleSource<T> { return upstream.subscribeOn(subscribeOnScheduler) .observeOn(observerOnScheduler) } override fun apply(upstream: Maybe<T>): MaybeSource<T> { return upstream.subscribeOn(subscribeOnScheduler) .unsubscribeOn(subscribeOnScheduler) .observeOn(observerOnScheduler) } override fun apply(upstream: Completable): CompletableSource { return upstream.subscribeOn(subscribeOnScheduler) .unsubscribeOn(subscribeOnScheduler) .observeOn(observerOnScheduler) } override fun apply(upstream: Flowable<T>): Publisher<T> { return upstream.subscribeOn(subscribeOnScheduler) .unsubscribeOn(subscribeOnScheduler) .observeOn(observerOnScheduler) } }
CommonBusiness/src/main/java/com/company/commonbusiness/http/rx/BaseScheduler.kt
1923878584
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.collectors.fus.ui import com.intellij.ide.ui.UISettings import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.CollectUsagesException import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator.ensureProperKey import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions /** * @author Konstantin Bulenkov */ class FontSizeInfoUsageCollector : ApplicationUsagesCollector() { @Throws(CollectUsagesException::class) override fun getUsages(): Set<UsageDescriptor> { val scheme = EditorColorsManager.getInstance().globalScheme val ui = UISettings.shadowInstance val usages = mutableSetOf( UsageDescriptor("UI.font.size[${ui.fontSize}]"), UsageDescriptor(ensureProperKey("UI.font.name[${ui.fontFace}]")), UsageDescriptor("Presentation.mode.font.size[${ui.presentationModeFontSize}]") ) if (!scheme.isUseAppFontPreferencesInEditor) { usages += setOf( UsageDescriptor("Editor.font.size[${scheme.editorFontSize}]"), UsageDescriptor(ensureProperKey("Editor.font.name[${scheme.editorFontName}]")) ) } else { val appPrefs = AppEditorFontOptions.getInstance().fontPreferences usages += setOf( UsageDescriptor("IDE.editor.font.size[${appPrefs.getSize(appPrefs.fontFamily)}]"), UsageDescriptor(ensureProperKey("IDE.editor.font.name[${appPrefs.fontFamily}]")) ) } if (!scheme.isUseEditorFontPreferencesInConsole) { usages += setOf( UsageDescriptor("Console.font.size[${scheme.consoleFontSize}]"), UsageDescriptor(ensureProperKey("Console.font.name[${scheme.consoleFontName}]")) ) } val quickDocFontSize = PropertiesComponent.getInstance().getValue("quick.doc.font.size") if (quickDocFontSize != null) { usages += setOf( UsageDescriptor("QuickDoc.font.size[$quickDocFontSize]") ) } return usages } override fun getGroupId(): String { return "ui.fonts" } override fun getData(): FeatureUsageData? { return FeatureUsageData().addOS() } }
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/ui/FontSizeInfoUsageCollector.kt
2507473255
package com.iterable.inbox_customization.customizations import android.os.Bundle import android.text.format.DateUtils import android.view.View import android.widget.TextView import com.iterable.inbox_customization.MainFragment import com.iterable.inbox_customization.R import com.iterable.inbox_customization.util.DataManager import com.iterable.inbox_customization.util.SingleFragmentActivity import com.iterable.iterableapi.IterableInAppMessage import com.iterable.iterableapi.ui.inbox.IterableInboxAdapter import com.iterable.iterableapi.ui.inbox.IterableInboxAdapterExtension import com.iterable.iterableapi.ui.inbox.IterableInboxFragment import java.util.* fun MainFragment.onInboxWithAdditionalFieldsClicked() { DataManager.loadData("inbox-with-additional-fields-messages.json") val intent = SingleFragmentActivity.createIntentWithFragment( activity!!, InboxWithAdditionalFieldsFragment::class.java ) startActivity(intent) } class InboxWithAdditionalFieldsFragment : IterableInboxFragment(), IterableInboxAdapterExtension<InboxWithAdditionalFieldsFragment.ViewHolder> { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setAdapterExtension(this) } override fun createViewHolderExtension(view: View, viewType: Int): ViewHolder? { return ViewHolder(view) } override fun getItemViewType(message: IterableInAppMessage): Int { return 0 } override fun getLayoutForViewType(viewType: Int): Int { return R.layout.additional_fields_cell } override fun onBindViewHolder( viewHolder: IterableInboxAdapter.ViewHolder, holderExtension: ViewHolder?, message: IterableInAppMessage ) { holderExtension?.discountText?.text = message.customPayload.optString("discount") } class ViewHolder(view: View) { var discountText: TextView? = null init { this.discountText = view.findViewById(R.id.discountText) } } }
sample-apps/inbox-customization/app/src/main/java/com/iterable/inbox_customization/customizations/InboxWithAdditionalFields.kt
2121660453
// 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.intellij.build.impl import de.pdark.decentxml.* import io.opentelemetry.api.trace.Span import org.jetbrains.annotations.TestOnly import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.CompatibleBuildRange import java.nio.file.Files import java.time.ZonedDateTime import java.time.format.DateTimeFormatter internal val pluginDateFormat = DateTimeFormatter.ofPattern("yyyyMMdd") private val buildNumberRegex = Regex("(\\d+\\.)+\\d+") fun getCompatiblePlatformVersionRange(compatibleBuildRange: CompatibleBuildRange, buildNumber: String): Pair<String, String> { if (compatibleBuildRange == CompatibleBuildRange.EXACT || !buildNumber.matches(buildNumberRegex)) { return Pair(buildNumber, buildNumber) } val sinceBuild: String val untilBuild: String if (compatibleBuildRange == CompatibleBuildRange.ANY_WITH_SAME_BASELINE) { sinceBuild = buildNumber.substring(0, buildNumber.indexOf(".")) untilBuild = buildNumber.substring(0, buildNumber.indexOf(".")) + ".*" } else { sinceBuild = if (buildNumber.matches(Regex("\\d+\\.\\d+"))) buildNumber else buildNumber.substring(0, buildNumber.lastIndexOf(".")) val end = if ((compatibleBuildRange == CompatibleBuildRange.RESTRICTED_TO_SAME_RELEASE)) { buildNumber.lastIndexOf(".") } else { buildNumber.indexOf(".") } untilBuild = "${buildNumber.substring(0, end)}.*" } return Pair(sinceBuild, untilBuild) } fun patchPluginXml(moduleOutputPatcher: ModuleOutputPatcher, plugin: PluginLayout, releaseDate: String, releaseVersion: String, pluginsToPublish: Set<PluginLayout?>, context: BuildContext) { val moduleOutput = context.getModuleOutputDir(context.findRequiredModule(plugin.mainModule)) val pluginXmlFile = moduleOutput.resolve("META-INF/plugin.xml") if (Files.notExists(pluginXmlFile)) { context.messages.error("plugin.xml not found in ${plugin.mainModule} module: $pluginXmlFile") } val includeInBuiltinCustomRepository = context.productProperties.productLayout.prepareCustomPluginRepositoryForPublishedPlugins && context.proprietaryBuildTools.artifactsServer != null val isBundled = !pluginsToPublish.contains(plugin) val compatibleBuildRange = when { isBundled || plugin.pluginCompatibilityExactVersion || includeInBuiltinCustomRepository -> CompatibleBuildRange.EXACT context.applicationInfo.isEAP -> CompatibleBuildRange.RESTRICTED_TO_SAME_RELEASE else -> CompatibleBuildRange.NEWER_WITH_SAME_BASELINE } val defaultPluginVersion = if (context.buildNumber.endsWith(".SNAPSHOT")) { "${context.buildNumber}.${pluginDateFormat.format(ZonedDateTime.now())}" } else { context.buildNumber } val pluginVersion = plugin.versionEvaluator.evaluate(pluginXmlFile, defaultPluginVersion, context) val sinceUntil = getCompatiblePlatformVersionRange(compatibleBuildRange, context.buildNumber) @Suppress("TestOnlyProblems") val content = try { plugin.pluginXmlPatcher( // using input stream allows us to support BOM doPatchPluginXml(document = Files.newInputStream(pluginXmlFile).use { XMLParser().parse(XMLIOSource(it)) }, pluginModuleName = plugin.mainModule, pluginVersion = pluginVersion, releaseDate = releaseDate, releaseVersion = releaseVersion, compatibleSinceUntil = sinceUntil, toPublish = pluginsToPublish.contains(plugin), retainProductDescriptorForBundledPlugin = plugin.retainProductDescriptorForBundledPlugin, isEap = context.applicationInfo.isEAP, productName = context.applicationInfo.productName), context, ) } catch (e: Throwable) { throw RuntimeException("Could not patch $pluginXmlFile", e) } moduleOutputPatcher.patchModuleOutput(plugin.mainModule, "META-INF/plugin.xml", content) } @TestOnly fun doPatchPluginXml(document: Document, pluginModuleName: String, pluginVersion: String?, releaseDate: String, releaseVersion: String, compatibleSinceUntil: Pair<String, String>, toPublish: Boolean, retainProductDescriptorForBundledPlugin: Boolean, isEap: Boolean, productName: String): String { val rootElement = document.rootElement val ideaVersionElement = getOrCreateTopElement(rootElement, "idea-version", listOf("id", "name")) ideaVersionElement.setAttribute("since-build", compatibleSinceUntil.first) ideaVersionElement.setAttribute("until-build", compatibleSinceUntil.second) val versionElement = getOrCreateTopElement(rootElement, "version", listOf("id", "name")) versionElement.text = pluginVersion val productDescriptor = rootElement.getChild("product-descriptor") if (productDescriptor != null) { if (!toPublish && !retainProductDescriptorForBundledPlugin) { Span.current().addEvent("skip $pluginModuleName <product-descriptor/>") removeTextBeforeElement(productDescriptor) productDescriptor.remove() } else { Span.current().addEvent("patch $pluginModuleName <product-descriptor/>") setProductDescriptorEapAttribute(productDescriptor, isEap) productDescriptor.setAttribute("release-date", releaseDate) productDescriptor.setAttribute("release-version", releaseVersion) } } // patch Database plugin for WebStorm, see WEB-48278 if (toPublish && productDescriptor != null && productDescriptor.getAttributeValue("code") == "PDB" && productName == "WebStorm") { Span.current().addEvent("patch $pluginModuleName for WebStorm") val pluginName = rootElement.getChild("name") check(pluginName.text == "Database Tools and SQL") { "Plugin name for \'$pluginModuleName\' should be \'Database Tools and SQL\'" } pluginName.text = "Database Tools and SQL for WebStorm" val description = rootElement.getChild("description") val replaced = replaceInElementText(description, "IntelliJ-based IDEs", "WebStorm") check(replaced) { "Could not find \'IntelliJ-based IDEs\' in plugin description of $pluginModuleName" } } return document.toXML() } fun getOrCreateTopElement(rootElement: Element, tagName: String, anchors: List<String>): Element { rootElement.getChild(tagName)?.let { return it } val newElement = Element(tagName) val anchor = anchors.asSequence().mapNotNull { rootElement.getChild(it) }.firstOrNull() if (anchor == null) { rootElement.addNode(0, newElement) rootElement.addNode(0, Text("\n ")) } else { val anchorIndex = rootElement.nodeIndexOf(anchor) // should not happen check(anchorIndex >= 0) { "anchor < 0 when getting child index of \'${anchor.name}\' in root element of ${rootElement.toXML()}" } var indent = rootElement.getNode(anchorIndex - 1) indent = if (indent is Text) indent.copy() else Text("") rootElement.addNode(anchorIndex + 1, newElement) rootElement.addNode(anchorIndex + 1, indent) } return newElement } private fun removeTextBeforeElement(element: Element) { val parentElement = element.parentElement ?: throw IllegalStateException("Could not find parent of \'${element.toXML()}\'") val elementIndex = parentElement.nodeIndexOf(element) check(elementIndex >= 0) { "Could not find element index \'${element.toXML()}\' in parent \'${parentElement.toXML()}\'" } if (elementIndex > 0) { val text = parentElement.getNode(elementIndex - 1) if (text is Text) { parentElement.removeNode(elementIndex - 1) } } } @Suppress("SameParameterValue") private fun replaceInElementText(element: Element, oldText: String, newText: String): Boolean { var replaced = false for (node in element.nodes) { if (node is Text) { val textBefore = node.text val text = textBefore.replace(oldText, newText) if (textBefore != text) { replaced = true node.text = text } } } return replaced } private fun setProductDescriptorEapAttribute(productDescriptor: Element, isEap: Boolean) { if (isEap) { productDescriptor.setAttribute("eap", "true") } else { productDescriptor.removeAttribute("eap") } }
platform/build-scripts/src/org/jetbrains/intellij/build/impl/PluginXmlPatcher.kt
4066728649
package com.intellij.ide.starter.community import com.intellij.ide.starter.community.model.ReleaseInfo import com.intellij.ide.starter.ide.IdeDownloader import com.intellij.ide.starter.ide.IdeInstaller import com.intellij.ide.starter.models.IdeInfo import com.intellij.ide.starter.system.OsType import com.intellij.ide.starter.system.SystemInfo import com.intellij.ide.starter.utils.HttpClient import com.intellij.ide.starter.utils.logOutput import java.nio.file.Path import kotlin.io.path.exists object PublicIdeDownloader : IdeDownloader { /** Filter release map: <ProductCode, List of releases> */ private fun findSpecificRelease(releaseInfoMap: Map<String, List<ReleaseInfo>>, filteringParams: ProductInfoRequestParameters): ReleaseInfo { val sorted = releaseInfoMap.values.first().sortedByDescending { it.date } if (filteringParams.majorVersion.isNotBlank()) return sorted.first { it.majorVersion == filteringParams.majorVersion } // find latest release / eap, if no specific params were provided if (filteringParams.versionNumber.isBlank() && filteringParams.buildNumber.isBlank()) return sorted.first() if (filteringParams.versionNumber.isNotBlank()) return sorted.first { it.version == filteringParams.versionNumber } if (filteringParams.buildNumber.isNotBlank()) return sorted.first { it.build == filteringParams.buildNumber } throw NoSuchElementException("Couldn't find specified release by parameters $filteringParams") } override fun downloadIdeInstaller(ideInfo: IdeInfo, installerDirectory: Path): IdeInstaller { val params = ProductInfoRequestParameters(type = ideInfo.productCode, snapshot = ideInfo.buildType, buildNumber = ideInfo.buildNumber, versionNumber = ideInfo.version) val releaseInfoMap = JetBrainsDataServiceClient.getReleases(params) if (releaseInfoMap.size != 1) throw RuntimeException("Only one product can be downloaded at once. Found ${releaseInfoMap.keys}") val possibleBuild: ReleaseInfo = findSpecificRelease(releaseInfoMap, params) val downloadLink: String = when (SystemInfo.getOsType()) { OsType.Linux -> possibleBuild.downloads.linux!!.link OsType.MacOS -> { if (SystemInfo.OS_ARCH == "aarch64") possibleBuild.downloads.macM1!!.link // macM1 else possibleBuild.downloads.mac!!.link } OsType.Windows -> possibleBuild.downloads.windowsZip!!.link else -> throw RuntimeException("Unsupported OS ${SystemInfo.getOsType()}") } val installerFile = installerDirectory.resolve( "${ideInfo.installerFilePrefix}-" + possibleBuild.build.replace(".", "") + ideInfo.installerFileExt ) if (!installerFile.exists()) { logOutput("Downloading $ideInfo ...") HttpClient.download(downloadLink, installerFile) } else logOutput("Installer file $installerFile already exists. Skipping download.") return IdeInstaller(installerFile, possibleBuild.build) } }
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/community/PublicIdeDownloader.kt
2081251866
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.psi.* import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewUtil import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.util.and import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources import org.jetbrains.kotlin.idea.highlighter.markers.resolveDeclarationWithParents import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.refactoring.explicateAsText import org.jetbrains.kotlin.idea.refactoring.getThisLabelName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters import org.jetbrains.kotlin.idea.base.util.useScope import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.OverloadChecker import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.results.TypeSpecificityComparator import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal fun ResolvedCall<*>.noReceivers() = dispatchReceiver == null && extensionReceiver == null internal fun PsiNamedElement.renderDescription(): String { val type = UsageViewUtil.getType(this) if (name == null || name!!.startsWith("<")) return type return "$type '$name'".trim() } internal fun PsiElement.representativeContainer(): PsiNamedElement? = when (this) { is KtDeclaration -> containingClassOrObject ?: getStrictParentOfType<KtNamedDeclaration>() ?: JavaPsiFacade.getInstance(project).findPackage(containingKtFile.packageFqName.asString()) is PsiMember -> containingClass else -> null } internal fun DeclarationDescriptor.canonicalRender(): String = DescriptorRenderer.FQ_NAMES_IN_TYPES.render(this) internal fun checkRedeclarations( declaration: KtNamedDeclaration, newName: String, result: MutableList<UsageInfo>, resolutionFacade: ResolutionFacade = declaration.getResolutionFacade(), descriptor: DeclarationDescriptor = declaration.unsafeResolveToDescriptor(resolutionFacade) ) { fun DeclarationDescriptor.isTopLevelPrivate(): Boolean = this is DeclarationDescriptorWithVisibility && visibility == DescriptorVisibilities.PRIVATE && containingDeclaration is PackageFragmentDescriptor fun isInSameFile(d1: DeclarationDescriptor, d2: DeclarationDescriptor): Boolean = (d1 as? DeclarationDescriptorWithSource)?.source?.getPsi()?.containingFile == (d2 as? DeclarationDescriptorWithSource)?.source ?.getPsi()?.containingFile fun MemberScope.findSiblingsByName(): List<DeclarationDescriptor> { val descriptorKindFilter = when (descriptor) { is ClassifierDescriptor -> DescriptorKindFilter.CLASSIFIERS is VariableDescriptor -> DescriptorKindFilter.VARIABLES is FunctionDescriptor -> DescriptorKindFilter.FUNCTIONS else -> return emptyList() } return getDescriptorsFiltered(descriptorKindFilter) { it.asString() == newName }.filter { it != descriptor } } fun getSiblingsWithNewName(): List<DeclarationDescriptor> { val containingDescriptor = descriptor.containingDeclaration if (descriptor is ValueParameterDescriptor) { return (containingDescriptor as CallableDescriptor).valueParameters.filter { it.name.asString() == newName } } if (descriptor is TypeParameterDescriptor) { val typeParameters = when (containingDescriptor) { is ClassDescriptor -> containingDescriptor.declaredTypeParameters is CallableDescriptor -> containingDescriptor.typeParameters else -> emptyList() } return SmartList<DeclarationDescriptor>().apply { typeParameters.filterTo(this) { it.name.asString() == newName } val containingDeclaration = (containingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() as? KtDeclaration ?: return emptyList() val dummyVar = KtPsiFactory(containingDeclaration.project).createProperty("val foo: $newName") val outerScope = containingDeclaration.getResolutionScope() val context = dummyVar.analyzeInContext(outerScope, containingDeclaration) addIfNotNull(context[BindingContext.VARIABLE, dummyVar]?.type?.constructor?.declarationDescriptor) } } return when (containingDescriptor) { is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope.findSiblingsByName() is PackageFragmentDescriptor -> containingDescriptor.getMemberScope().findSiblingsByName().filter { it != descriptor && (!(descriptor.isTopLevelPrivate() || it.isTopLevelPrivate()) || isInSameFile(descriptor, it)) } else -> { val block = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()?.parent as? KtBlockExpression ?: return emptyList() block.statements.mapNotNull { if (it.name != newName) return@mapNotNull null val isAccepted = when (descriptor) { is ClassDescriptor -> it is KtClassOrObject is VariableDescriptor -> it is KtProperty is FunctionDescriptor -> it is KtNamedFunction else -> false } if (!isAccepted) return@mapNotNull null (it as? KtDeclaration)?.unsafeResolveToDescriptor() } } } } val overloadChecker = when (descriptor) { is PropertyDescriptor, is FunctionDescriptor, is ClassifierDescriptor -> { @OptIn(FrontendInternals::class) val typeSpecificityComparator = resolutionFacade.getFrontendService(descriptor.module, TypeSpecificityComparator::class.java) OverloadChecker(typeSpecificityComparator) } else -> null } for (candidateDescriptor in getSiblingsWithNewName()) { val candidate = (candidateDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() as? KtNamedDeclaration ?: continue if (overloadChecker != null && overloadChecker.isOverloadable(descriptor, candidateDescriptor)) continue val what = candidate.renderDescription() val where = candidate.representativeContainer()?.renderDescription() ?: continue val message = KotlinBundle.message("text.0.already.declared.in.1", what, where).capitalize() result += BasicUnresolvableCollisionUsageInfo(candidate, candidate, message) } } private fun LexicalScope.getRelevantDescriptors( declaration: PsiNamedElement, name: String ): Collection<DeclarationDescriptor> { val nameAsName = Name.identifier(name) return when (declaration) { is KtProperty, is KtParameter, is PsiField -> getAllAccessibleVariables(nameAsName) is KtNamedFunction -> getAllAccessibleFunctions(nameAsName) is KtClassOrObject, is PsiClass -> listOfNotNull(findClassifier(nameAsName, NoLookupLocation.FROM_IDE)) else -> emptyList() } } fun reportShadowing( declaration: PsiNamedElement, elementToBindUsageInfoTo: PsiElement, candidateDescriptor: DeclarationDescriptor, refElement: PsiElement, result: MutableList<UsageInfo> ) { val candidate = DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement ?: return if (declaration.parent == candidate.parent) return val message = KotlinBundle.message( "text.0.will.be.shadowed.by.1", declaration.renderDescription(), candidate.renderDescription() ).capitalize() result += BasicUnresolvableCollisionUsageInfo(refElement, elementToBindUsageInfoTo, message) } // todo: break into smaller functions private fun checkUsagesRetargeting( elementToBindUsageInfosTo: PsiElement, declaration: PsiNamedElement, name: String, isNewName: Boolean, accessibleDescriptors: Collection<DeclarationDescriptor>, originalUsages: MutableList<UsageInfo>, newUsages: MutableList<UsageInfo> ) { val usageIterator = originalUsages.listIterator() while (usageIterator.hasNext()) { val usage = usageIterator.next() val refElement = usage.element as? KtSimpleNameExpression ?: continue val context = refElement.analyze(BodyResolveMode.PARTIAL) val scope = refElement.parentsWithSelf .filterIsInstance<KtElement>() .mapNotNull { context[BindingContext.LEXICAL_SCOPE, it] } .firstOrNull() ?: continue if (scope.getRelevantDescriptors(declaration, name).isEmpty()) { if (declaration !is KtProperty && declaration !is KtParameter) continue if (Fe10KotlinNewDeclarationNameValidator(refElement.parent, refElement, KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE)(name)) continue } val psiFactory = KtPsiFactory(declaration.project) val resolvedCall = refElement.getResolvedCall(context) if (resolvedCall == null) { val typeReference = refElement.getStrictParentOfType<KtTypeReference>() ?: continue val referencedClass = context[BindingContext.TYPE, typeReference]?.constructor?.declarationDescriptor ?: continue val referencedClassFqName = FqName(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(referencedClass)) val newFqName = if (isNewName) referencedClassFqName.parent().child(Name.identifier(name)) else referencedClassFqName val fakeVar = psiFactory.createDeclaration<KtProperty>("val __foo__: ${newFqName.asString()}") val newContext = fakeVar.analyzeInContext(scope, refElement) val referencedClassInNewContext = newContext[BindingContext.TYPE, fakeVar.typeReference!!]?.constructor?.declarationDescriptor val candidateText = referencedClassInNewContext?.canonicalRender() if (referencedClassInNewContext == null || ErrorUtils.isError(referencedClassInNewContext) || referencedClass.canonicalRender() == candidateText || accessibleDescriptors.any { it.canonicalRender() == candidateText } ) { usageIterator.set(UsageInfoWithFqNameReplacement(refElement, declaration, newFqName)) } else { reportShadowing(declaration, elementToBindUsageInfosTo, referencedClassInNewContext, refElement, newUsages) } continue } val callExpression = resolvedCall.call.callElement as? KtExpression ?: continue val fullCallExpression = callExpression.getQualifiedExpressionForSelectorOrThis() val qualifiedExpression = if (resolvedCall.noReceivers()) { val resultingDescriptor = resolvedCall.resultingDescriptor val fqName = resultingDescriptor.importableFqName ?: (resultingDescriptor as? ClassifierDescriptor)?.let { FqName(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(it)) } ?: continue if (fqName.parent().isRoot) { callExpression.copied() } else { psiFactory.createExpressionByPattern("${fqName.parent().asString()}.$0", callExpression) } } else { resolvedCall.getExplicitReceiverValue()?.let { fullCallExpression.copied() } ?: resolvedCall.getImplicitReceiverValue()?.let { implicitReceiver -> val expectedLabelName = implicitReceiver.declarationDescriptor.getThisLabelName() val implicitReceivers = scope.getImplicitReceiversHierarchy() val receiversWithExpectedName = implicitReceivers.filter { it.value.type.constructor.declarationDescriptor?.getThisLabelName() == expectedLabelName } val canQualifyThis = receiversWithExpectedName.isEmpty() || receiversWithExpectedName.size == 1 && (declaration !is KtClassOrObject || expectedLabelName != name) if (canQualifyThis) { if (refElement.parent is KtCallableReferenceExpression) { psiFactory.createExpressionByPattern("${implicitReceiver.explicateAsText()}::$0", callExpression) } else { psiFactory.createExpressionByPattern("${implicitReceiver.explicateAsText()}.$0", callExpression) } } else { val defaultReceiverClassText = implicitReceivers.firstOrNull()?.value?.type?.constructor?.declarationDescriptor?.canonicalRender() val canInsertUnqualifiedThis = accessibleDescriptors.any { it.canonicalRender() == defaultReceiverClassText } if (canInsertUnqualifiedThis) { psiFactory.createExpressionByPattern("this.$0", callExpression) } else { callExpression.copied() } } } ?: continue } val newCallee = if (qualifiedExpression is KtCallableReferenceExpression) { qualifiedExpression.callableReference } else { qualifiedExpression.getQualifiedElementSelector() as? KtSimpleNameExpression ?: continue } if (isNewName) { newCallee.getReferencedNameElement().replace(psiFactory.createNameIdentifier(name)) } qualifiedExpression.parentSubstitute = fullCallExpression.parent val newContext = qualifiedExpression.analyzeInContext(scope, refElement, DelegatingBindingTrace(context, "")) val newResolvedCall = newCallee.getResolvedCall(newContext) val candidateText = newResolvedCall?.candidateDescriptor?.getImportableDescriptor()?.canonicalRender() if (newResolvedCall != null && !accessibleDescriptors.any { it.canonicalRender() == candidateText } && resolvedCall.candidateDescriptor.canonicalRender() != candidateText ) { reportShadowing(declaration, elementToBindUsageInfosTo, newResolvedCall.candidateDescriptor, refElement, newUsages) continue } if (fullCallExpression !is KtQualifiedExpression) { usageIterator.set(UsageInfoWithReplacement(fullCallExpression, declaration, qualifiedExpression)) } } } internal fun checkOriginalUsagesRetargeting( declaration: KtNamedDeclaration, newName: String, originalUsages: MutableList<UsageInfo>, newUsages: MutableList<UsageInfo> ) { val accessibleDescriptors = declaration.getResolutionScope().getRelevantDescriptors(declaration, newName) checkUsagesRetargeting(declaration, declaration, newName, true, accessibleDescriptors, originalUsages, newUsages) } internal fun checkNewNameUsagesRetargeting( declaration: KtNamedDeclaration, newName: String, newUsages: MutableList<UsageInfo> ) { val currentName = declaration.name ?: return val descriptor = declaration.unsafeResolveToDescriptor() if (declaration is KtParameter && !declaration.hasValOrVar()) { val ownerFunction = declaration.ownerFunction val searchScope = (if (ownerFunction is KtPrimaryConstructor) ownerFunction.containingClassOrObject else ownerFunction) ?: return val usagesByCandidate = LinkedHashMap<PsiElement, MutableList<UsageInfo>>() searchScope.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { if (expression.getReferencedName() != newName) return val ref = expression.mainReference val candidate = ref.resolve() as? PsiNamedElement ?: return usagesByCandidate.getOrPut(candidate) { SmartList() }.add(MoveRenameUsageInfo(ref, candidate)) } } ) for ((candidate, usages) in usagesByCandidate) { checkUsagesRetargeting(candidate, declaration, currentName, false, listOf(descriptor), usages, newUsages) usages.filterIsInstanceTo<KtResolvableCollisionUsageInfo, MutableList<UsageInfo>>(newUsages) } return } val operator = declaration.isOperator() for (candidateDescriptor in declaration.getResolutionScope().getRelevantDescriptors(declaration, newName)) { val candidate = DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement ?: continue val searchParameters = KotlinReferencesSearchParameters( candidate, scope = candidate.useScope().restrictToKotlinSources() and declaration.useScope(), kotlinOptions = KotlinReferencesSearchOptions(searchForOperatorConventions = operator) ) val usages = ReferencesSearch.search(searchParameters).mapTo(SmartList<UsageInfo>()) { MoveRenameUsageInfo(it, candidate) } checkUsagesRetargeting(candidate, declaration, currentName, false, listOf(descriptor), usages, newUsages) usages.filterIsInstanceTo<KtResolvableCollisionUsageInfo, MutableList<UsageInfo>>(newUsages) } } internal fun PsiElement?.isOperator(): Boolean { if (this !is KtNamedFunction || !KotlinPsiHeuristics.isPossibleOperator(this)) { return false } val resolveWithParents = resolveDeclarationWithParents(this as KtNamedFunction) return resolveWithParents.overriddenDescriptors.any { val psi = it.source.getPsi() ?: return@any false psi !is KtElement || psi.safeAs<KtNamedFunction>()?.hasModifier(KtTokens.OPERATOR_KEYWORD) == true } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt
1701265288
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data.feedback import com.google.firebase.functions.FirebaseFunctions import com.google.samples.apps.iosched.model.SessionId import com.google.samples.apps.iosched.shared.result.Result import javax.inject.Inject import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume interface FeedbackEndpoint { suspend fun sendFeedback(sessionId: SessionId, responses: Map<String, Int>): Result<Unit> } class DefaultFeedbackEndpoint @Inject constructor( private val functions: FirebaseFunctions ) : FeedbackEndpoint { override suspend fun sendFeedback( sessionId: SessionId, responses: Map<String, Int> ): Result<Unit> { return suspendCancellableCoroutine { continuation -> functions .getHttpsCallable("sendFeedback") .call( hashMapOf( "sessionId" to sessionId, "responses" to responses, "client" to "ANDROID" ) ) .addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(Result.Success(Unit)) } else { continuation.resume(Result.Error(RuntimeException(task.exception))) } } } } }
shared/src/main/java/com/google/samples/apps/iosched/shared/data/feedback/FeedbackEndpoint.kt
2082005691
package com.apollographql.apollo3.ast /** * All the issues that can be collected while analyzing a graphql document */ sealed class Issue( val message: String, val sourceLocation: SourceLocation, val severity: Severity, ) { /** * A grammar error */ class ParsingError(message: String, sourceLocation: SourceLocation) : Issue(message, sourceLocation, Severity.ERROR) /** * A GraphqQL validation error as per the spec */ class ValidationError( message: String, sourceLocation: SourceLocation, severity: Severity = Severity.ERROR, val details: ValidationDetails = ValidationDetails.Other ) : Issue(message, sourceLocation, severity) /** * A deprecated field/enum is used */ class DeprecatedUsage(message: String, sourceLocation: SourceLocation) : Issue(message, sourceLocation, Severity.WARNING) /** * A variable is unused */ class UnusedVariable(message: String, sourceLocation: SourceLocation) : Issue(message, sourceLocation, Severity.WARNING) /** * A fragment has an @include or @skip directive. While this is valid GraphQL, the responseBased codegen does not support that */ class ConditionalFragment(message: String, sourceLocation: SourceLocation) : Issue(message, sourceLocation, Severity.ERROR) /** * Upper case fields are not supported as Kotlin doesn't allow a property name with the same name as a nested class. * If this happens, the easiest solution is to add an alias with a lower case first letter. * * This error is an Apollo Kotlin specific error */ class UpperCaseField(message: String, sourceLocation: SourceLocation) : Issue(message, sourceLocation, Severity.ERROR) enum class Severity { WARNING, ERROR, } } fun List<Issue>.checkNoErrors() { val error = firstOrNull { it.severity == Issue.Severity.ERROR } if (error != null) { throw SourceAwareException( error.message, error.sourceLocation ) } } fun List<Issue>.containsError(): Boolean = any { it.severity == Issue.Severity.ERROR } enum class ValidationDetails { /** * An unknown directive was found. * * In a perfect world everyone uses SDL schemas and we can validate directives but in this world, a lot of users rely * on introspection schemas that do not contain directives. If this happens, we pass them through without validation. */ UnknownDirective, /** * Two type definitions have the same name */ DuplicateTypeName, Other }
apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/Issue.kt
4189529650
/* * Copyright (C) 2009 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 okhttp3.internal.http import okhttp3.OkHttpClient import okhttp3.Protocol import okhttp3.Request object ExternalHttp2Example { @JvmStatic fun main(args: Array<String>) { val client = OkHttpClient.Builder() .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)) .build() val call = client.newCall( Request.Builder() .url("https://www.google.ca/") .build() ) val response = call.execute() try { println(response.code) println("PROTOCOL ${response.protocol}") var line: String? while (response.body.source().readUtf8Line().also { line = it } != null) { println(line) } } finally { response.body.close() } client.connectionPool.evictAll() } }
okhttp/src/jvmTest/java/okhttp3/internal/http/ExternalHttp2Example.kt
3408604895
package org.jetbrains.completion.full.line.local.generation.generation import io.kinference.model.ExecutionContext import org.jetbrains.completion.full.line.local.generation.LapTimer import org.jetbrains.completion.full.line.local.generation.matcher.FullLinePrefixMatcher import org.jetbrains.completion.full.line.local.generation.model.ModelWrapper import org.jetbrains.completion.full.line.local.generation.search.FullLineBeamSearch import org.jetbrains.completion.full.line.local.generation.search.Search import org.jetbrains.completion.full.line.local.tokenizer.Tokenizer import kotlin.math.min import kotlin.math.pow class FullLineGeneration( model: ModelWrapper, tokenizer: Tokenizer, private val loggingCallback: ((String) -> Unit)? = null ) : BaseGeneration<FullLineGenerationConfig>(model, tokenizer) { override val prefixMatcher = FullLinePrefixMatcher(tokenizer) private val eosIds = setOf(tokenizer.encode("\n").last()) internal val oneTokenEosRegex = Regex("\\W+") override fun generate( context: IntArray, prefix: String, config: FullLineGenerationConfig, execContext: ExecutionContext ): List<List<GenerationInfo>> { val terminatedHypotheses: MutableList<Search.Hypothesis> = mutableListOf() val search = FullLineBeamSearch( vocabSize = tokenizer.vocabSize, searchSize = config.numBeams, lenNormBase = config.lenNormBase, lenNormPow = config.lenNormPow ) loggingCallback?.let { it("Prefix is $logItemOpen$prefix$logItemClose") it("Context length is ${context.size}") it("Doing ${config.maxLen} iterations") it("Beam search started") } val timer = loggingCallback?.let { LapTimer() } execContext.checkCancelled.invoke() initState(prefix, config) timer?.lap("initState") initLogProbs(context, execContext) timer?.lap("initLogProbs") sortState(IntArray(search.batchSize)) timer?.lap("sortState") for (i in 0 until config.maxLen) { execContext.checkCancelled.invoke() loggingCallback?.invoke("Performing step $i") search.step(nextLogProbs!!, context) timer?.lap("$i: step") updateState(search.sortMask, search.lastPredictions) timer?.lap("$i: updateState after step") val terminatedIndices = search.hypotheses.terminatedIndices(config.oneTokenMode, prefix) if (terminatedIndices.isNotEmpty()) { val newTerminatedHypotheses = search.dropHypotheses(terminatedIndices) terminatedHypotheses.addAll(newTerminatedHypotheses) if (search.hypotheses.isEmpty()) break timer?.lap("$i: stash terminated hypotheses") } loggingCallback?.invoke("Unterminated variants:\n${search.hypotheses.logString()}") loggingCallback?.invoke("Terminated variants:\n${terminatedHypotheses.logString()}") timer?.lap("$i: logging tokens") // TODO: find out whether we want this line or some other solution if (config.oneTokenMode && terminatedHypotheses.isNotEmpty()) break if (i < config.maxLen - 1) { if (terminatedIndices.isNotEmpty()) { sortState(search.sortMask) timer?.lap("$i: sortState after termination") } updateLogProbs(search.lastPredictions, execContext) timer?.lap("$i: updateLogProbs") } } timer?.let { it.end() it.laps.forEach { lap -> loggingCallback?.invoke("${lap.name} took ${lap.timeMillis} ms") } loggingCallback?.invoke("Beam search ended in ${it.endTime - it.startTime} ms") } resetState() val allHypotheses = if (config.oneTokenMode) terminatedHypotheses else (terminatedHypotheses + search.hypotheses) loggingCallback?.invoke("All returned hypotheses:\n${allHypotheses.logString()}") return listOf(allHypotheses.sortedByDescending { it.score }.map { hyp -> val len = hyp.ids.size // TODO: clean eachStepScore implementation val eachStepScore = hyp.score.pow(1.0 / len) GenerationInfo(List(len) { eachStepScore }, hyp.ids.toList()) }) } private fun List<Search.Hypothesis>.terminatedIndices(terminateByWords: Boolean, prefix: String): List<Int> { return this.mapIndexed { i, it -> val lastTokenId = it.ids.last() if (lastTokenId in eosIds) return@mapIndexed i if (terminateByWords) { val hypothesisText = tokenizer.decode(it.ids) var newSequence = hypothesisText if (prefix.isNotEmpty()) { newSequence = findFirstSuffixLastPrefix(prefix, hypothesisText) } if (newSequence.contains(oneTokenEosRegex) && !newSequence.matches(oneTokenEosRegex)) return@mapIndexed i } return@mapIndexed null }.filterNotNull() } private fun List<Search.Hypothesis>.logString(): String { if (this.isEmpty()) return "No hypotheses" return this.sortedByDescending { it.score }.joinToString("\n") { logItemOpen + tokenizer.decode( it.ids ) + logItemClose + " " + it.score } } private fun findFirstSuffixLastPrefix(first: String, last: String): String { for (len in 1..min(first.length, last.length)) { if (first.regionMatches(first.length - len, last, 0, len)) { return last.substring(len) } } return "" } companion object { private const val logItemOpen = ">>>" private const val logItemClose = "<<<" } }
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/generation/generation/FullLineGeneration.kt
2169292083
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize class GeneralInfo( var productNumber: String? = null, var serial: String? = null, var model: String? = null, var language: String? = null, var firmware: String? = null, var batteryLevel: Int = 0, var timeToEmpty: Int = 0, var timeToFullCharge: Int = 0, var totalCharges: Int = 0, var manufacturingDate: String? = null, var authorizationStatus: Int = 0, var vendor: String? = null ) : Parcelable
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/GeneralInfo.kt
1492453894
package ui.debugmenu import javafx.beans.property.SimpleStringProperty import javafx.collections.ObservableList import javafx.event.ActionEvent import javafx.fxml.FXMLLoader import javafx.scene.Node import javafx.scene.Scene import javafx.scene.control.SplitPane import javafx.stage.Stage import java.io.IOException import java.net.URL import java.util.* import java.util.function.Consumer class DebugMenu(filterList: ObservableList<String>, log: SimpleStringProperty, width: Int, height: Int, notifications: ArrayList<Node>) : Stage() { private var debugController: DebugController? = null init { val loader = FXMLLoader(javaClass.getResource("/debugMenu.fxml")) try { loader.load<Any>() debugController = loader.getController<DebugController>() debugController!!.setLog(log) debugController!!.setFilterList(filterList) notifications.forEach { this.addNotification(it) } val root = loader.getRoot<SplitPane>() scene = Scene(root, width.toDouble(), height.toDouble()) } catch (e: IOException) { e.printStackTrace() } } fun addNotification(notification: Node) { debugController?.addNotification(notification) } }
src/ui/debugmenu/DebugMenu.kt
3729000169
package graphics.scenery.tests.examples.volumes import bdv.util.AxisOrder import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.attribute.material.Material import graphics.scenery.volumes.* import ij.IJ import ij.ImagePlus import net.imglib2.img.Img import net.imglib2.img.display.imagej.ImageJFunctions import net.imglib2.type.numeric.integer.UnsignedShortType import org.joml.Vector3f import tpietzsch.example2.VolumeViewerOptions /** * Volume Ortho View Example using the "BDV Rendering Example loading a RAII" * * @author Jan Tiemann <[email protected]> */ class OrthoViewExample : SceneryBase("Ortho View example", 1280, 720) { lateinit var volume: Volume override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val cam: Camera = DetachedHeadCamera() with(cam) { perspectiveCamera(50.0f, windowWidth, windowHeight) spatial { position = Vector3f(0.0f, 2.0f, 5.0f) } scene.addChild(this) } val shell = Box(Vector3f(10.0f, 10.0f, 10.0f), insideNormals = true) shell.material { cullingMode = Material.CullingMode.None diffuse = Vector3f(0.2f, 0.2f, 0.2f) specular = Vector3f(0.0f) ambient = Vector3f(0.0f) } scene.addChild(shell) Light.createLightTetrahedron<PointLight>(spread = 4.0f, radius = 15.0f, intensity = 0.5f) .forEach { scene.addChild(it) } val origin = Box(Vector3f(0.1f, 0.1f, 0.1f)) origin.material().diffuse = Vector3f(0.8f, 0.0f, 0.0f) scene.addChild(origin) val imp: ImagePlus = IJ.openImage("https://imagej.nih.gov/ij/images/t1-head.zip") val img: Img<UnsignedShortType> = ImageJFunctions.wrapShort(imp) volume = Volume.fromRAI(img, UnsignedShortType(), AxisOrder.DEFAULT, "T1 head", hub, VolumeViewerOptions()) volume.transferFunction = TransferFunction.ramp(0.001f, 0.5f, 0.3f) scene.addChild(volume) val bGrid = BoundingGrid() bGrid.node = volume volume.addChild(bGrid) createOrthoView(volume,"1",hub) } override fun inputSetup() { setupCameraModeSwitching() //inputHandler?.addOrthoViewDragBehavior("2") } companion object { @JvmStatic fun main(args: Array<String>) { OrthoViewExample().main() } } }
src/test/kotlin/graphics/scenery/tests/examples/volumes/OrthoViewExample.kt
1390672978
package com.masahirosaito.spigot.homes.strings import com.masahirosaito.spigot.homes.strings.Strings.COMMAND_NAME import com.masahirosaito.spigot.homes.strings.Strings.HOME_LIMIT_NUM import com.masahirosaito.spigot.homes.strings.Strings.HOME_NAME import com.masahirosaito.spigot.homes.strings.Strings.PERMISSION_NAME import com.masahirosaito.spigot.homes.strings.Strings.PLAYER_NAME import com.masahirosaito.spigot.homes.datas.strings.ErrorStringData import com.masahirosaito.spigot.homes.load import com.masahirosaito.spigot.homes.loadData import com.masahirosaito.spigot.homes.strings.Strings.COMMAND_USAGE import java.io.File object ErrorStrings { lateinit var error: ErrorStringData fun load(folderPath: String) { error = loadData(File(folderPath, "error.json").load(), ErrorStringData::class.java) } fun NO_COMMAND(commandName: String) = error.NO_COMMAND .replace(COMMAND_NAME, commandName) fun NO_CONSOLE_COMMAND() = error.NO_CONSOLE_COMMAND fun NO_PERMISSION(permission: String) = error.NO_PERMISSION .replace(PERMISSION_NAME, permission) fun NO_ONLINE_PLAYER(playerName: String) = error.NO_ONLINE_PLAYER .replace(PLAYER_NAME, playerName) fun NO_OFFLINE_PLAYER(playerName: String) = error.NO_OFFLINE_PLAYER .replace(PLAYER_NAME, playerName) fun NO_VAULT() = error.NO_VAULT fun NO_ECONOMY() = error.NO_ECONOMY fun NO_DEFAULT_HOME(playerName: String) = error.NO_DEFAULT_HOME .replace(PLAYER_NAME, playerName) fun NO_NAMED_HOME(playerName: String, homeName: String) = error.NO_NAMED_HOME .replace(PLAYER_NAME, playerName) .replace(HOME_NAME, homeName) fun NO_HOME(playerName: String) = error.NO_HOME .replace(PLAYER_NAME, playerName) fun HOME_LIMIT(limit: Int) = error.HOME_LIMIT .replace(HOME_LIMIT_NUM, limit.toString()) fun DEFAULT_HOME_IS_PRIVATE(playerName: String) = error.DEFAULT_HOME_IS_PRIVATE .replace(PLAYER_NAME, playerName) fun NAMED_HOME_IS_PRIVATE(playerName: String, homeName: String) = error.NAMED_HOME_IS_PRIVATE .replace(PLAYER_NAME, playerName) .replace(HOME_NAME, homeName) fun NO_RECEIVED_INVITATION() = error.NO_RECEIVED_INVITATION fun ALREADY_HAS_INVITATION(playerName: String) = error.ALREADY_HAS_INVITATION .replace(PLAYER_NAME, playerName) fun NOT_ALLOW_BY_CONFIG() = error.NOT_ALLOW_BY_CONFIG fun ARGUMENT_INCORRECT(commandUsage: String) = error.ARGUMENT_INCORRECT .replace(COMMAND_USAGE, commandUsage) fun INVALID_COMMAND_SENDER() = error.INVALID_COMMAND_SENDER fun ALREADY_EXECUTE_TELEPORT() = error.ALREADY_EXECUTE_TELEPORT }
src/main/kotlin/com/masahirosaito/spigot/homes/strings/ErrorStrings.kt
3664335748
package com.aemtools.codeinsight.osgiservice import com.aemtools.index.model.sortByMods import com.aemtools.index.search.OSGiConfigSearch import com.aemtools.codeinsight.osgiservice.markerinfo.OSGiServiceConfigMarkerInfo import com.aemtools.common.util.isOSGiService import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier /** * @author Dmytro_Troynikov */ class OSGiConfigLineMarker : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? { if (element is PsiIdentifier && element.parent is PsiClass) { val psiClass = element.parent as? PsiClass ?: return null if (psiClass.isOSGiService()) { val fqn = psiClass.qualifiedName ?: return null val configs = OSGiConfigSearch.findConfigsForClass(fqn, element.project, true) if (configs.isEmpty()) { return null } return OSGiServiceConfigMarkerInfo(element, configs.sortByMods()) } } return null } override fun collectSlowLineMarkers(elements: MutableList<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) { } }
aem-intellij-core/src/main/kotlin/com/aemtools/codeinsight/osgiservice/OSGiConfigLineMarker.kt
2961711477
package tests.coding internal val listData = TestData<List<*>>( symmetric = mapOf( emptyList<Any?>() to "[]", listOf(1) to "[1]", listOf(true, "hey", null) to """[true,"hey",null]""", listOf(emptyList<Any?>(), listOf(1)) to "[[],[1]]" ), decodableOnly = mapOf( " [ \t\n\r] " to emptyList<Any?>(), "[ [], [ 1 ] ]" to listOf(emptyList<Any?>(), listOf(1)) ) )
coding/tests-jvm/data/basic/listData.kt
4118668952
package com.aemtools.test.util import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * Require not null delegate demands from underlying supplier to * provide not null value. * If supplier returns __null__ [IllegalArgumentException] will be thrown. * * @author Dmytro Troynikov */ class RequireNotNull<out T>(private val supplier: () -> T?) { operator fun provideDelegate(thisRef: Nothing?, prop: KProperty<*>): ReadOnlyProperty<Nothing?, T> { val result = supplier.invoke() return object : ReadOnlyProperty<Nothing?, T> { override fun getValue(thisRef: Nothing?, property: KProperty<*>): T { if (result == null) { throw IllegalArgumentException("Supplier provided null for ${property.name}") } return result } } } } /** * Require not null delegate * @param supplier supplier of value * @return [RequireNotNull] delegate */ fun <T> notNull(supplier: () -> T?): RequireNotNull<T> = RequireNotNull(supplier)
test-framework/src/main/kotlin/com/aemtools/test/util/Delegates.kt
1088676745
package io.github.ranolp.kubo.telegram.client.objects import com.github.badoualy.telegram.tl.api.TLMessage import io.github.ranolp.kubo.general.objects.Chat import io.github.ranolp.kubo.general.objects.Message import io.github.ranolp.kubo.general.objects.User import io.github.ranolp.kubo.general.side.Side import io.github.ranolp.kubo.telegram.Telegram import java.time.LocalDateTime class TelegramClientMessage(val message: TLMessage) : Message { override val side: Side = Telegram.CLIENT_SIDE override val text: String? get() = message.message override val from: User? get() = TODO("not implemented") override val chat: Chat get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override val whenSended: LocalDateTime get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override fun delete() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun edit(message: String) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/client/objects/TelegramClientMessage.kt
80257344
package com.aemtools.lang.htl.psi.mixin.model import com.aemtools.lang.htl.psi.HtlContextExpression /** * Helper model for htl option. * @author Dmytro Troynikov */ class HtlOptionModel(val contextExpression: HtlContextExpression) { /** * Get name of current option. * * @return name of current option */ fun name(): String { val assignment = contextExpression.assignment val variableName = contextExpression.variableName if (assignment != null) { return assignment.variableName.varName.text } if (variableName != null) { return variableName.varName.text } return "" } }
lang/src/main/kotlin/com/aemtools/lang/htl/psi/mixin/model/HtlOptionModel.kt
4105743639
package jetbrains.buildServer.dotnet.test import jetbrains.buildServer.dotnet.discovery.* import org.testng.Assert import org.testng.annotations.DataProvider import org.testng.annotations.Test class JsonProjectDeserializerTest { @DataProvider fun testDeserializeData(): Array<Array<Any>> { return arrayOf( arrayOf( "/project.json", Solution(listOf(Project("projectPath", emptyList(), listOf(Framework("dnx451"), Framework("dnxcore50")), emptyList(), emptyList()))))) } @Test(dataProvider = "testDeserializeData") fun shouldDeserialize(target: String, expectedSolution: Solution) { // Given val path = "projectPath" val streamFactory = StreamFactoryStub().add(path, this::class.java.getResourceAsStream(target)) val deserializer = JsonProjectDeserializer(ReaderFactoryImpl()) // When val actualSolution = deserializer.deserialize(path, streamFactory) // Then Assert.assertEquals(actualSolution, expectedSolution) } @DataProvider fun testAcceptData(): Array<Array<Any>> { return arrayOf( arrayOf("project.json", true), arrayOf("abc\\project.json", true), arrayOf("abc//project.json", true), arrayOf("abc//ProjecT.JsoN", true), arrayOf("aaaproject.json", false), arrayOf("project.jsonaaa", false), arrayOf("abc\\project.jsonsss", false), arrayOf("project.json10aaa", false), arrayOf("10project.json", false), arrayOf("10rer323project.json", false), arrayOf(".json", false), arrayOf("json", false), arrayOf(" ", false), arrayOf("", false)) } @Test(dataProvider = "testAcceptData") fun shouldAccept(path: String, expectedAccepted: Boolean) { // Given val deserializer = JsonProjectDeserializer(ReaderFactoryImpl()) // When val actualAccepted = deserializer.accept(path) // Then Assert.assertEquals(actualAccepted, expectedAccepted) } }
plugin-dotnet-server/src/test/kotlin/jetbrains/buildServer/dotnet/test/JsonProjectDeserializerTest.kt
4078291268
package main.tut02 import buffer.destroy import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL3 import com.jogamp.opengl.util.glsl.ShaderProgram import extensions.intBufferBig import extensions.toFloatBuffer import glsl.programOf import glsl.shaderCodeOf import main.L import main.SIZE import main.framework.Framework import main.framework.Semantic import vec._4.Vec4 /** * Created by GBarbieri on 21.02.2017. */ fun main(args: Array<String>) { VertexColor_() } class VertexColor_ : Framework("Tutorial 02 - Vertex Colors") { val VERTEX_SHADER = "tut02/vertex-colors.vert" val FRAGMENT_SHADER = "tut02/vertex-colors.frag" var theProgram = 0 val vertexBufferObject = intBufferBig(1) val vao = intBufferBig(1) val vertexData = floatArrayOf( +0.0f, +0.500f, 0.0f, 1.0f, +0.5f, -0.366f, 0.0f, 1.0f, -0.5f, -0.366f, 0.0f, 1.0f, +1.0f, +0.000f, 0.0f, 1.0f, +0.0f, +1.000f, 0.0f, 1.0f, +0.0f, +0.000f, 1.0f, 1.0f) override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArrays(1, vao) glBindVertexArray(vao[0]) } fun initializeProgram(gl: GL3) { theProgram = programOf(gl, this::class.java, "tut02", "vertex-colors.vert", "vertex-colors.frag") } fun initializeVertexBuffer(gl: GL3) = with(gl){ val vertexBuffer = vertexData.toFloatBuffer() glGenBuffers(1, vertexBufferObject) glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject[0]) glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) vertexBuffer.destroy() } override fun display(gl: GL3) = with(gl){ glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0f).put(1, 0f).put(2, 0f).put(3, 0f)) glUseProgram(theProgram) glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject[0]) glEnableVertexAttribArray(Semantic.Attr.POSITION) glEnableVertexAttribArray(Semantic.Attr.COLOR) glVertexAttribPointer(Semantic.Attr.POSITION, 4, GL_FLOAT, false, Vec4.SIZE, 0) glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_FLOAT, false, Vec4.SIZE, Vec4.SIZE * 3.L) glDrawArrays(GL_TRIANGLES, 0, 3) glDisableVertexAttribArray(Semantic.Attr.POSITION) glDisableVertexAttribArray(Semantic.Attr.COLOR) glUseProgram(0) } override fun reshape(gl: GL3, w: Int, h: Int) { gl.glViewport(0, 0, w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(1, vertexBufferObject) glDeleteVertexArrays(1, vao) vertexBufferObject.destroy() vao.destroy() } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> { animator.remove(window) window.destroy() } } } }
src/main/kotlin/main/tut02/vertexColor.kt
2397634898
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.reactive import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail import org.springframework.transaction.support.DefaultTransactionDefinition class TransactionalOperatorExtensionsTests { private val tm = ReactiveTestTransactionManager(false, true) @Test fun commitWithSuspendingFunction() { val operator = TransactionalOperator.create(tm, DefaultTransactionDefinition()) runBlocking { operator.executeAndAwait { delay(1) true } } assertThat(tm.commit).isTrue() assertThat(tm.rollback).isFalse() } @Test fun commitWithEmptySuspendingFunction() { val operator = TransactionalOperator.create(tm, DefaultTransactionDefinition()) runBlocking { operator.executeAndAwait { delay(1) null } } assertThat(tm.commit).isTrue() assertThat(tm.rollback).isFalse() } @Test fun rollbackWithSuspendingFunction() { val operator = TransactionalOperator.create(tm, DefaultTransactionDefinition()) runBlocking { try { operator.executeAndAwait { delay(1) throw IllegalStateException() } } catch (ex: IllegalStateException) { assertThat(tm.commit).isFalse() assertThat(tm.rollback).isTrue() return@runBlocking } fail("") } } @Test fun commitWithFlow() { val operator = TransactionalOperator.create(tm, DefaultTransactionDefinition()) val flow = flow { emit(1) emit(2) emit(3) emit(4) } runBlocking { val list = flow.transactional(operator).toList() assertThat(list).hasSize(4) } assertThat(tm.commit).isTrue() assertThat(tm.rollback).isFalse() } @Test fun rollbackWithFlow() { val operator = TransactionalOperator.create(tm, DefaultTransactionDefinition()) val flow = flow<Int> { delay(1) throw IllegalStateException() } runBlocking { try { flow.transactional(operator).toList() } catch (ex: IllegalStateException) { assertThat(tm.commit).isFalse() assertThat(tm.rollback).isTrue() return@runBlocking } } } }
spring-tx/src/test/kotlin/org/springframework/transaction/reactive/TransactionalOperatorExtensionsTests.kt
1904502867
package v_builders import junit.framework.Assert import org.junit.Test import java.util.HashMap class _36_Extension_Function_Literals { @Test fun testIsOddAndIsEven() { val result = task36() Assert.assertEquals("The functions 'isOdd' and 'isEven' should be implemented correctly", listOf(false, true, true), result) } }
test/v_builders/_36_Extension_Function_Literals.kt
1429354030
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.ui import com.intellij.navigation.TargetPresentation import com.intellij.ui.components.JBLabel import com.intellij.ui.speedSearch.SearchAwareRenderer import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.UIUtil.getListSelectionForeground import org.jetbrains.annotations.ApiStatus.Experimental import java.awt.Component import javax.swing.JList import javax.swing.ListCellRenderer import javax.swing.SwingConstants @Experimental internal abstract class TargetPresentationRightRenderer<T> : ListCellRenderer<T>, SearchAwareRenderer<T> { companion object { private val ourBorder = JBUI.Borders.emptyRight(UIUtil.getListCellHPadding()) } protected abstract fun getPresentation(value: T): TargetPresentation? private val component = JBLabel().apply { border = ourBorder horizontalTextPosition = SwingConstants.LEFT horizontalAlignment = SwingConstants.RIGHT // align icon to the right } final override fun getItemSearchString(item: T): String? = getPresentation(item)?.containerText final override fun getListCellRendererComponent(list: JList<out T>, value: T, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { component.apply { text = "" icon = null background = UIUtil.getListBackground(isSelected) foreground = if (isSelected) getListSelectionForeground(true) else UIUtil.getInactiveTextColor() font = list.font } getPresentation(value)?.let { presentation -> presentation.locationText?.let { locationText -> component.text = locationText component.icon = presentation.locationIcon } } return component } }
platform/lang-impl/src/com/intellij/ide/ui/TargetPresentationRightRenderer.kt
2982105783
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[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 com.vrem.wifianalyzer.wifi.scanner import com.nhaarman.mockitokotlin2.* import com.vrem.wifianalyzer.permission.PermissionService import com.vrem.wifianalyzer.settings.Settings import com.vrem.wifianalyzer.wifi.manager.WiFiManagerWrapper import com.vrem.wifianalyzer.wifi.model.WiFiData import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test class ScannerTest { private val settings: Settings = mock() private val wiFiManagerWrapper: WiFiManagerWrapper = mock() private val updateNotifier1: UpdateNotifier = mock() private val updateNotifier2: UpdateNotifier = mock() private val updateNotifier3: UpdateNotifier = mock() private val transformer: Transformer = mock() private val scanResultsReceiver: ScanResultsReceiver = mock() private val scannerCallback: ScannerCallback = mock() private val permissionService: PermissionService = mock() private val wiFiData: WiFiData = mock() private val periodicScan: PeriodicScan = mock() private val fixture = Scanner(wiFiManagerWrapper, settings, permissionService, transformer) @Before fun setUp() { fixture.periodicScan = periodicScan fixture.scanResultsReceiver = scanResultsReceiver fixture.scannerCallback = scannerCallback fixture.register(updateNotifier1) fixture.register(updateNotifier2) fixture.register(updateNotifier3) } @After fun tearDown() { verifyNoMoreInteractions(settings) verifyNoMoreInteractions(wiFiManagerWrapper) verifyNoMoreInteractions(transformer) verifyNoMoreInteractions(periodicScan) verifyNoMoreInteractions(permissionService) verifyNoMoreInteractions(scanResultsReceiver) verifyNoMoreInteractions(scannerCallback) } @Test fun testStop() { // setup whenever(settings.wiFiOffOnExit()).thenReturn(false) // execute fixture.stop() // validate assertEquals(0, fixture.registered()) verify(settings).wiFiOffOnExit() verify(wiFiManagerWrapper, never()).disableWiFi() verify(periodicScan).stop() verify(scanResultsReceiver).unregister() } @Test fun testStopWithDisableWiFiOnExit() { // setup whenever(settings.wiFiOffOnExit()).thenReturn(true) // execute fixture.stop() // validate assertEquals(0, fixture.registered()) verify(wiFiManagerWrapper).disableWiFi() verify(periodicScan).stop() verify(scanResultsReceiver).unregister() verify(settings).wiFiOffOnExit() } @Test fun testPause() { // execute fixture.pause() // validate verify(periodicScan).stop() verify(scanResultsReceiver).unregister() } @Test fun testResume() { // execute fixture.resume() // validate verify(periodicScan).start() } @Test fun testRunning() { // setup whenever(periodicScan.running).thenReturn(true) // execute val actual = fixture.running() // validate assertTrue(actual) verify(periodicScan).running } @Test fun testRegister() { // setup assertEquals(3, fixture.registered()) // execute fixture.register(updateNotifier2) // validate assertEquals(4, fixture.registered()) } @Test fun testUnregister() { // setup assertEquals(3, fixture.registered()) // execute fixture.unregister(updateNotifier2) // validate assertEquals(2, fixture.registered()) } @Test fun testUpdate() { // setup whenever(transformer.transformToWiFiData()).thenReturn(wiFiData) whenever(permissionService.enabled()).thenReturn(true) // execute fixture.update() // validate assertEquals(wiFiData, fixture.wiFiData()) verify(wiFiManagerWrapper).enableWiFi() verify(permissionService).enabled() verify(scanResultsReceiver).register() verify(wiFiManagerWrapper).startScan() verify(scannerCallback).onSuccess() verify(transformer).transformToWiFiData() verifyUpdateNotifier(1) } @Test fun testUpdateShouldScanResultsOnce() { // setup val expected = 3 whenever(transformer.transformToWiFiData()).thenReturn(wiFiData) whenever(permissionService.enabled()).thenReturn(true) // execute for (i in 0 until expected) { fixture.update() } // validate verify(wiFiManagerWrapper, times(expected)).enableWiFi() verify(permissionService, times(expected)).enabled() verify(scanResultsReceiver, times(expected)).register() verify(wiFiManagerWrapper, times(expected)).startScan() verify(scannerCallback).onSuccess() verify(transformer, times(expected)).transformToWiFiData() verifyUpdateNotifier(expected) } @Test fun testUpdateWithRequirementPermissionDisabled() { // setup whenever(transformer.transformToWiFiData()).thenReturn(wiFiData) whenever(permissionService.enabled()).thenReturn(false) // execute fixture.update() // validate verify(wiFiManagerWrapper).enableWiFi() verify(permissionService).enabled() verify(scanResultsReceiver, never()).register() verify(wiFiManagerWrapper, never()).startScan() verify(scannerCallback, never()).onSuccess() verify(transformer).transformToWiFiData() verifyUpdateNotifier(1) } @Test fun testToggleWhenRunning() { // setup fixture.periodicScan = periodicScan whenever(periodicScan.running).thenReturn(true) // execute fixture.toggle() // validate verify(periodicScan).running verify(periodicScan).stop() } @Test fun testToggleWhenNotRunning() { // setup fixture.periodicScan = periodicScan whenever(periodicScan.running).thenReturn(false) // execute fixture.toggle() // validate verify(periodicScan).running verify(periodicScan).start() } private fun verifyUpdateNotifier(expected: Int) { verify(updateNotifier1, times(expected)).update(wiFiData) verify(updateNotifier2, times(expected)).update(wiFiData) verify(updateNotifier3, times(expected)).update(wiFiData) } }
app/src/test/kotlin/com/vrem/wifianalyzer/wifi/scanner/ScannerTest.kt
817108047
package de.htwdd.htwdresden.utils.extensions import io.realm.Realm import io.realm.RealmModel import io.realm.RealmObject import io.realm.RealmQuery typealias Query<T> = RealmQuery<T>.() -> Unit fun <T: RealmModel> T.queryFirst(query: Query<T>): T? { Realm.getDefaultInstance().use { realm -> val item: T? = realm.where(this.javaClass).withQuery(query).findFirst() return if(item != null && RealmObject.isValid(item)) realm.copyFromRealm(item) else null } } private inline fun <T> T.withQuery(block: (T) -> Unit): T { block(this) return this }
app/src/main/java/de/htwdd/htwdresden/utils/extensions/RealmExtension.kt
347346853
package com.stefano.playground.fastbookmark.utils import android.content.SharedPreferences import android.content.pm.ActivityInfo interface AppPreferences { fun getFavouriteBookmarks(): ActivityInfo? fun getFavouriteBookmarksAsString(): String? fun toString(activityInfo: ActivityInfo?): String? } class AppPreferencesImpl(preferences: SharedPreferences): AppPreferences { private val delimiter = "/" private var preferences: SharedPreferences init { this.preferences = preferences } override fun getFavouriteBookmarks(): ActivityInfo? { val tokens = preferences.getString("pref_list_favourite_sharing_app", null)?.split(delimiter) return if (tokens != null && tokens.isNotEmpty()) { val info = ActivityInfo() info.packageName = tokens.first() info.name = tokens.last() return info } else { null } } override fun getFavouriteBookmarksAsString(): String? { val favouriteBookmarksAppData = getFavouriteBookmarks() return if (favouriteBookmarksAppData == null) { null } else { toString(favouriteBookmarksAppData.packageName, favouriteBookmarksAppData.name) } } override fun toString(activityInfo: ActivityInfo?): String? { return if (activityInfo == null) { null } else { toString(activityInfo.packageName, activityInfo.name) } } private fun toString(packageName: String, activityName: String): String { return "$packageName$delimiter$activityName" } }
app/src/main/kotlin/com/stefano/playground/fastbookmark/utils/AppPreferences.kt
2872314806
package com.yeungeek.videosample import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
VideoSample/app/src/test/java/com/yeungeek/videosample/ExampleUnitTest.kt
2793535971
package nl.dionsegijn.konfetti.core.models data class Vector(var x: Float = 0f, var y: Float = 0f) { fun add(v: Vector) { x += v.x y += v.y } fun addScaled(v: Vector, s: Float) { x += v.x * s y += v.y * s } fun mult(n: Float) { x *= n y *= n } fun div(n: Float) { x /= n y /= n } }
konfetti/core/src/main/java/nl/dionsegijn/konfetti/core/models/Vector.kt
605286170
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.tests import com.intellij.openapi.components.service import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.testFramework.runAll import com.intellij.util.WaitFor import com.intellij.vfs.AsyncVfsEventsPostProcessorImpl import git4idea.config.GitConfigUtil.COMMIT_TEMPLATE import git4idea.repo.GitCommitTemplateTracker import git4idea.repo.GitRepository import git4idea.test.GitPlatformTest import git4idea.test.TestFile import git4idea.test.file import git4idea.test.git import java.io.File class GitCommitTemplateTest : GitPlatformTest() { override fun setUp() { super.setUp() waitForTemplateTrackerReady() } override fun tearDown() { runAll( { git("config --global --unset commit.template", ignoreNonZeroExitCode = true) }, { super.tearDown() } ) } fun `test set commit template`() { val repository = createRepository(projectPath) val templateContent = """ Some Template # comment1 # comment2 """.trimIndent() setupCommitTemplate(repository, "commit_template.txt", templateContent) assertCommitTemplate(repository, templateContent) } fun `test set and change commit template`() { val repository = createRepository(projectPath) val templateContent = """ Local Template # comment1 # comment2 """.trimIndent() val template = setupCommitTemplate(repository, "commit_template.txt", templateContent) assertCommitTemplate(repository, templateContent) val newTemplateContent = """ New Local Template # comment3 # comment4 """.trimIndent() template.write(newTemplateContent) template.file.refresh() assertCommitTemplate(repository, newTemplateContent) } fun `test local commit template override global`() { val repository = createRepository(projectPath) val globalTemplateContent = """ Global Template # comment3 # comment4 """.trimIndent() setupCommitTemplate(repository, "global_commit_template.txt", globalTemplateContent, false) assertCommitTemplate(repository, globalTemplateContent) val localTemplateContent = """ Local Template # comment1 # comment2 """.trimIndent() setupCommitTemplate(repository, "local_commit_template.txt", localTemplateContent) assertCommitTemplate(repository, localTemplateContent) } fun `test commit template in multiple repositories`() { val repo1 = createRepository(createChildDirectory(projectRoot, "root1").path) val repo2 = createRepository(createChildDirectory(projectRoot, "root2").path) val templateContent1 = """ Template for first repository # comment1 # comment2 """.trimIndent() val templateContent2 = """ Template for second repository # comment3 # comment4 """.trimIndent() setupCommitTemplate(repo1, "template1.txt", templateContent1) setupCommitTemplate(repo2, "template2.txt", templateContent2) assertCommitTemplate(repo1, templateContent1) assertCommitTemplate(repo2, templateContent2) } fun `test commit template specified relative to git dir`() { val repository = createRepository(projectPath) val templateContent = """ Some Template # comment1 # comment2 """.trimIndent() repository .file("template.txt") .assertNotExists() .create(templateContent) git.config(repository, "--local", COMMIT_TEMPLATE, "template.txt") repository.repositoryFiles.configFile.refresh() assertCommitTemplate(repository, templateContent) } fun `test not valid commit template specified relative to git dir`() { val repository = createRepository(projectPath) val templateContent = """ Some Template # comment1 # comment2 """.trimIndent() repository .file("template.txt") .assertNotExists() .create(templateContent) val commitTemplateTracker = project.service<GitCommitTemplateTracker>() git.config(repository, "--local", COMMIT_TEMPLATE, "/template.txt") repository.repositoryFiles.configFile.refresh() assertTrue("Commit template exist for $repository", !commitTemplateTracker.exists(repository)) git.config(repository, "--local", COMMIT_TEMPLATE, "template.txt/") repository.repositoryFiles.configFile.refresh() assertTrue("Commit template exist for $repository", !commitTemplateTracker.exists(repository)) } private fun setupCommitTemplate(repository: GitRepository, templateFileName: String, templateContent: String, local: Boolean = true): TestFile { val commitTemplate = repository .file(templateFileName) .assertNotExists() .create(templateContent) val pathToCommitTemplatePath = commitTemplate.file.let { FileUtil.toSystemIndependentName(it.path) } git.config(repository, if (local) "--local" else "--global", COMMIT_TEMPLATE, pathToCommitTemplatePath) if (local) { repository.repositoryFiles.configFile.refresh() } else { //explicit notify because of IDEA-131645 project.service<GitCommitTemplateTracker>().notifyConfigChanged(repository) } return commitTemplate } private fun assertCommitTemplate(repository: GitRepository, expectedTemplateContent: String) { val commitTemplateTracker = project.service<GitCommitTemplateTracker>() assertTrue("Commit template doesn't exist for $repository", commitTemplateTracker.exists(repository)) assertEquals("Commit template content doesn't match $repository", expectedTemplateContent, commitTemplateTracker.getTemplateContent(repository)) } private fun File.refresh() { LocalFileSystem.getInstance().refreshIoFiles(setOf(this)) AsyncVfsEventsPostProcessorImpl.waitEventsProcessed() } private fun waitForTemplateTrackerReady() { object : WaitFor() { override fun condition(): Boolean = project.service<GitCommitTemplateTracker>().isStarted() override fun assertCompleted(message: String?) { if (!condition()) { fail(message) } } }.assertCompleted("Failed to wait ${this::class.simpleName}") } }
plugins/git4idea/tests/git4idea/tests/GitCommitTemplateTest.kt
2339559331
fun box(): String { val plusZero: Any = 0.0 val minusZero: Any = -0.0 if ((minusZero as Double) < (plusZero as Double)) return "fail 0" val plusZeroF: Any = 0.0F val minusZeroF: Any = -0.0F if ((minusZeroF as Float) < (plusZeroF as Float)) return "fail 1" if ((minusZero as Double) != (plusZero as Double)) return "fail 3" if ((minusZeroF as Float) != (plusZeroF as Float)) return "fail 4" return "OK" }
backend.native/tests/external/codegen/box/ieee754/anyToReal.kt
1973710700
package io.github.robwin.web.exception import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus @ResponseStatus(HttpStatus.NOT_FOUND) class HeroNotFoundException(message: String?) : RuntimeException(message)
spring-boot-server/src/main/kotlin/io/github/robwin/web/exception/HeroNotFoundException.kt
3954126266
// WITH_REFLECT // IGNORE_BACKEND: JS, NATIVE abstract class Outer { inner class Inner fun foo(): Inner? = null } fun box(): String { kotlin.test.assertEquals( "class Outer\$Inner", Outer::class.java.declaredMethods.single().genericReturnType.toString()) return "OK" }
backend.native/tests/external/codegen/box/reflection/genericSignature/signatureOfSimpleInnerSimpleOuter.kt
2710711865
package codegen.branching.when_through import kotlin.test.* fun when_through(i: Int): Int { var value = 1 when (i) { 10 -> value = 42 11 -> value = 43 12 -> value = 44 } return value } @Test fun runTest() { if (when_through(2) != 1) throw Error() }
backend.native/tests/codegen/branching/when_through.kt
3687986508
class A { val prop: Int constructor(arg: Boolean) { if (arg) { prop = 1 return } prop = 2 } } fun box(): String { val a1 = A(true) if (a1.prop != 1) return "fail1: ${a1.prop}" val a2 = A(false) if (a2.prop != 2) return "fail2: ${a2.prop}" return "OK" }
backend.native/tests/external/codegen/box/secondaryConstructors/withReturn.kt
2751512616
package au.com.codeka.warworlds.client.game.empire import android.content.Intent import android.net.Uri import android.view.ViewGroup import au.com.codeka.warworlds.client.App import au.com.codeka.warworlds.client.concurrency.Threads import au.com.codeka.warworlds.client.game.empire.SettingsView.PatreonConnectCompleteCallback import au.com.codeka.warworlds.client.game.world.EmpireManager import au.com.codeka.warworlds.client.net.HttpRequest import au.com.codeka.warworlds.client.net.ServerUrl.getUrl import au.com.codeka.warworlds.client.ui.Screen import au.com.codeka.warworlds.client.ui.ScreenContext import au.com.codeka.warworlds.client.ui.ShowInfo import au.com.codeka.warworlds.client.ui.ShowInfo.Companion.builder import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.PatreonBeginRequest import au.com.codeka.warworlds.common.proto.PatreonBeginResponse /** * This screen shows the status of the empire. You can see all your colonies, all your fleets, etc. */ class EmpireScreen : Screen() { private lateinit var context: ScreenContext private lateinit var layout: EmpireLayout override fun onCreate(context: ScreenContext, container: ViewGroup) { super.onCreate(context, container) this.context = context layout = EmpireLayout(context.activity, SettingsCallbacks()) } override fun onShow(): ShowInfo { return builder().view(layout).build() } private inner class SettingsCallbacks : SettingsView.Callback { override fun onPatreonConnectClick( completeCallback: PatreonConnectCompleteCallback) { App.taskRunner.runTask(Runnable { val req = HttpRequest.Builder() .url(getUrl("/accounts/patreon-begin")) .authenticated() .body(PatreonBeginRequest(empire_id = EmpireManager.getMyEmpire().id).encode()) .method(HttpRequest.Method.POST) .build() if (req.responseCode != 200 || req.exception != null) { // TODO: better error handling. log.error("Error starting patreon connect request: %d %s", req.responseCode, req.exception) completeCallback.onPatreonConnectComplete("Unexpected error.") return@Runnable } val resp = req.getBody(PatreonBeginResponse::class.java) if (resp == null) { // TODO: better error handling. log.error("Got an empty response?") completeCallback.onPatreonConnectComplete("Unexpected error.") return@Runnable } val uri = ("https://www.patreon.com/oauth2/authorize?response_type=code" + "&client_id=" + resp.client_id + "&redirect_uri=" + Uri.encode(resp.redirect_uri) + "&state=" + Uri.encode(resp.state)) log.info("Opening URL: %s", uri) App.taskRunner.runTask({ val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) context.activity.startActivity(intent) }, Threads.UI) }, Threads.BACKGROUND) } } companion object { private val log = Log("EmpireScreen") } }
client/src/main/kotlin/au/com/codeka/warworlds/client/game/empire/EmpireScreen.kt
1722368632
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2020 Richard Harrah * * 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 com.tealcube.minecraft.bukkit.mythicdrops.utils import com.squareup.moshi.Moshi import com.tealcube.minecraft.bukkit.mythicdrops.moshi.LevelAdapter import com.tealcube.minecraft.bukkit.mythicdrops.moshi.MythicSettingsInterfaceJsonAdapterFactory object JsonUtil { val moshi: Moshi = Moshi.Builder().add(MythicSettingsInterfaceJsonAdapterFactory).add(LevelAdapter()).build() }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/JsonUtil.kt
1069630732
abstract class Base { abstract val foo: Int } class Derived : Base() { override val foo = <caret> } fun getInt(): Int = 0 fun getString(): String = "" // EXIST: getInt // ABSENT: getString
plugins/kotlin/completion/tests/testData/smart/ImplicitlyTypedOverrideValInitializer.kt
120408345
class Foo { operator fun invoke(a: Any) {} } fun test(f: Foo) { f <caret>{} } // REF: (in Foo).invoke(Any)
plugins/kotlin/idea/tests/testData/resolve/references/invoke/lambdaNoPar.kt
3384206870
// PROBLEM: none inline class InlineClass(val x: Int) fun <caret>takeInline(inlineClass: InlineClass) = 1 val call = takeInline(InlineClass(1))
plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedSymbol/functionWithInlineClass.kt
3941486727
/* * 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 com.example.graygallery.utils import android.graphics.BitmapFactory import okhttp3.ResponseBody fun getBitmapFromResponseBody(responseBody: ResponseBody) = BitmapFactory.decodeStream(responseBody.byteStream())
FileProvider/app/src/main/java/com/example/graygallery/utils/NetworkUtils.kt
277072323
/* * 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 org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.code import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod interface GrCodeMembersProvider<in T : GrTypeDefinition> { fun getCodeMethods(definition: T): Array<GrMethod> fun getCodeFields(definition: T): Array<GrField> fun getCodeInnerClasses(definition: T): Array<GrTypeDefinition> }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/code/GrCodeMembersProvider.kt
597642496
// PROBLEM: none enum class MyEnum(val i: Int) { HELLO(42), WORLD("42") ; constructor<caret>(s: String): this(42) } fun test() { MyEnum.HELLO }
plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedSymbol/enumSecondaryConstructor.kt
565184197
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.collaboration.ui.codereview import com.intellij.ide.ui.AntialiasingType import com.intellij.ui.BrowserHyperlinkListener import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.HTMLEditorKitBuilder import com.intellij.util.ui.JBInsets import org.jetbrains.annotations.Nls import javax.swing.JEditorPane import javax.swing.text.DefaultCaret open class BaseHtmlEditorPane : JEditorPane() { init { editorKit = HTMLEditorKitBuilder().withWordWrapViewFactory().build() isEditable = false isOpaque = false addHyperlinkListener(BrowserHyperlinkListener.INSTANCE) margin = JBInsets.emptyInsets() GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent()) val caret = caret as DefaultCaret caret.updatePolicy = DefaultCaret.NEVER_UPDATE } fun setBody(@Nls body: String) { if (body.isEmpty()) { text = "" } else { text = "<html><body>$body</body></html>" } setSize(Int.MAX_VALUE / 2, Int.MAX_VALUE / 2) } }
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/BaseHtmlEditorPane.kt
2691716358
package io.fotoapparat.routine.focus import io.fotoapparat.hardware.Device import io.fotoapparat.result.FocusResult import kotlinx.coroutines.runBlocking /** * Focuses the camera. */ internal fun Device.focus(): FocusResult = runBlocking { val cameraDevice = awaitSelectedCamera() cameraDevice.autoFocus() }
fotoapparat/src/main/java/io/fotoapparat/routine/focus/FocusRoutine.kt
3463859595
package sealed sealed interface <caret>SealedInterfaceA sealed interface SealedInterfaceB class HierarchyClassA: SealedInterfaceA, SealedInterfaceB
plugins/kotlin/idea/tests/testData/refactoring/moveMultiModule/moveSealedCheckTargetPackageHasNoMembersCrossModule/before/A/src/sealed/SealedHierarchy.kt
954449862
class KotlinClass { fun <caret>a(): Int = extension } fun test() { KotlinClass().a() } val KotlinClass.extension: Int get() = 42
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/expressionBody/delegateToExtensionPropertyWithoutThis.kt
245018070