repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/data/insallationcandidates/Installer.kt | 1 | 4287 | package com.msc.serverbrowser.data.insallationcandidates
import com.msc.serverbrowser.constants.PathConstants
import com.msc.serverbrowser.data.InstallationCandidateCache
import com.msc.serverbrowser.data.properties.AllowCachingDownloadsProperty
import com.msc.serverbrowser.data.properties.ClientPropertiesController
import com.msc.serverbrowser.info
import com.msc.serverbrowser.severe
import com.msc.serverbrowser.util.basic.FileUtility
import com.msc.serverbrowser.util.samp.GTAController
import com.msc.serverbrowser.util.unix.WineUtility
import com.msc.serverbrowser.util.windows.OSUtility
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
/**
* Class for installing SA-MP Versions.
*
* @author Marcel
* @since 22.01.2018
*/
object Installer {
/**
* Installs an [InstallationCandidate].
*
* @param candidate the candidate to be installed.
*/
fun installViaInstallationCandidate(candidate: InstallationCandidate) {
// RetrievePath (includes isDownload if necessary, otherwise cache path)
try {
info("Installing $candidate.")
val installer = getInstallerPathAndDownloadIfNecessary(candidate)
val gtaPath = GTAController.gtaPath!!
// Check whether its an installer or a zip
if (candidate.url.endsWith(".exe")) {
val windowsStyleGtaPath = GTAController.windowsStyleGtaPath
runNullSoftInstaller(installer, windowsStyleGtaPath!!)
info("Ran installer: $installer")
} else {
FileUtility.unzip(installer, gtaPath)
info("Unzipped installation files: $installer")
}
// In case the cache wasn't use, we don't want to keep the temporary file.
if (installer == PathConstants.TEMP_INSTALLER_EXE || installer == PathConstants.TEMP_INSTALLER_EXE) {
Files.delete(Paths.get(installer))
info("Deleted temporary installation files: $installer")
}
} catch (exception: IOException) {
severe("Error installing SA-MP.", exception)
}
}
@Throws(IOException::class)
private fun getInstallerPathAndDownloadIfNecessary(candidate: InstallationCandidate): String {
if (InstallationCandidateCache.isVersionCached(candidate)) {
val path = InstallationCandidateCache.getPathForCachedVersion(candidate)
if (path.isPresent) {
info("Using cached version for candidate '$candidate'.")
return path.get()
}
}
if (candidate.isDownload) {
val isExecutable = candidate.url.endsWith(".exe")
val outputPath = if (isExecutable) PathConstants.TEMP_INSTALLER_EXE else PathConstants.TEMP_INSTALLER_ZIP
info("Downloading file for candidate '$candidate'.")
FileUtility.downloadFile(candidate.url, outputPath)
if (ClientPropertiesController.getProperty(AllowCachingDownloadsProperty)) {
info("Adding file for candidate '$candidate' to cache.")
InstallationCandidateCache.addCandidateToCache(candidate, outputPath)
}
return outputPath
}
return candidate.url
}
private fun runNullSoftInstaller(installerPath: String, gtaPath: String) {
try {
// cmd /c allows elevation of the command instead of retrieving an severe
// /S starts a silent installation
// /D specifies the installation target folder
val installerProcess = if (OSUtility.isWindows.not()) {
WineUtility.createWineRunner(listOf("cmd", "/c", installerPath, "/S", "/D=$gtaPath")).start()
} else {
Runtime.getRuntime().exec("cmd /c $installerPath /S /D=$gtaPath")
}
// Waiting until the installer has finished, in order to be able to give proper GUI responses.
installerProcess.waitFor()
} catch (exception: IOException) {
severe("Error using installer: $installerPath", exception)
} catch (exception: InterruptedException) {
severe("Error using installer: $installerPath", exception)
}
}
}
| mpl-2.0 | 9755b881d7d7b062b40fbd6876a60d29 | 39.828571 | 117 | 0.658269 | 4.866061 | false | false | false | false |
Mindera/skeletoid | kt-extensions/src/main/java/com/mindera/skeletoid/kt/extensions/utils/String.kt | 1 | 706 | package com.mindera.skeletoid.kt.extensions.utils
fun String.removeSpaces() = this.replace(" ", "")
fun String.digits() = this.map(Character::getNumericValue)
fun String?.removeCharacters(charactersToRemove: String): String? {
return this?.replace("[$charactersToRemove]".toRegex(), "") ?: this
}
fun String.matchesEntireRegex(regex: Regex): Boolean {
return regex.matchEntire(this)?.value?.isNotEmpty() == true
}
fun String.isEmailValid(): Boolean {
return this.isNotBlank() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
fun String?.nullIfBlank(): String? = if (isNullOrBlank()) null else this
fun String?.nullIfEmpty(): String? = if (isNullOrEmpty()) null else this
| mit | 95950f5aa88a29125542c82dea5e03a8 | 32.619048 | 91 | 0.728045 | 4.034286 | false | false | false | false |
googlecodelabs/android-people | app/src/main/java/com/example/android/people/ui/main/MainFragment.kt | 2 | 2179 | /*
* 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.example.android.people.ui.main
import android.os.Bundle
import android.transition.TransitionInflater
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.android.people.R
import com.example.android.people.databinding.MainFragmentBinding
import com.example.android.people.getNavigationController
import com.example.android.people.ui.viewBindings
/**
* The main chat list screen.
*/
class MainFragment : Fragment(R.layout.main_fragment) {
private val binding by viewBindings(MainFragmentBinding::bind)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
exitTransition = TransitionInflater.from(context).inflateTransition(R.transition.slide_top)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navigationController = getNavigationController()
navigationController.updateAppBar(false)
val viewModel: MainViewModel by viewModels()
val contactAdapter = ContactAdapter { id ->
navigationController.openChat(id, null)
}
viewModel.contacts.observe(viewLifecycleOwner, Observer { contacts ->
contactAdapter.submitList(contacts)
})
binding.contacts.run {
layoutManager = LinearLayoutManager(view.context)
setHasFixedSize(true)
adapter = contactAdapter
}
}
}
| apache-2.0 | acb955b6df2c2e28ebb5fd0ab6ad3ec2 | 35.932203 | 99 | 0.741625 | 4.778509 | false | false | false | false |
Heiner1/AndroidAPS | rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.kt | 1 | 3951 | package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks
import android.content.Context
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData
import info.nightscout.androidaps.utils.Round.isSame
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import kotlin.math.roundToLong
/**
* This class is intended to be run by the Service, for the Service. Not intended for clients to run.
*/
class InitializePumpManagerTask(injector: HasAndroidInjector, private val context: Context) : ServiceTask(injector) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var rileyLinkServiceData: RileyLinkServiceData
@Inject lateinit var rileyLinkUtil: RileyLinkUtil
override fun run() {
if (!isRileyLinkDevice) return
var lastGoodFrequency: Double
if (rileyLinkServiceData.lastGoodFrequency == null) {
lastGoodFrequency = sp.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0)
lastGoodFrequency = (lastGoodFrequency * 1000.0).roundToLong() / 1000.0
rileyLinkServiceData.lastGoodFrequency = lastGoodFrequency
} else lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency ?: 0.0
val rileyLinkCommunicationManager = pumpDevice?.rileyLinkService?.deviceCommunicationManager
if (activePlugin.activePump.manufacturer() === ManufacturerType.Medtronic) {
if (lastGoodFrequency > 0.0 && rileyLinkCommunicationManager?.isValidFrequency(lastGoodFrequency) == true) {
rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkReady)
aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to $lastGoodFrequency MHz")
rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency)
if (rileyLinkCommunicationManager.tryToConnectToDevice()) rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorReady)
else {
rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.NoContactWithDevice)
rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump, context)
}
} else rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump, context)
} else {
if (!isSame(lastGoodFrequency, RileyLinkTargetFrequency.Omnipod.scanFrequencies[0])) {
lastGoodFrequency = RileyLinkTargetFrequency.Omnipod.scanFrequencies[0]
lastGoodFrequency = (lastGoodFrequency * 1000.0).roundToLong() / 1000.0
rileyLinkServiceData.lastGoodFrequency = lastGoodFrequency
}
rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkReady)
rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod // TODO shouldn't be needed
aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to $lastGoodFrequency MHz")
rileyLinkCommunicationManager?.setRadioFrequencyForPump(lastGoodFrequency)
rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorReady)
}
}
} | agpl-3.0 | 3577cd73d8ff40288216e1709c90d448 | 60.75 | 152 | 0.766894 | 5.525874 | false | false | false | false |
treelzebub/zinepress | app/src/main/java/net/treelzebub/zinepress/Constants.kt | 1 | 417 | package net.treelzebub.zinepress
/**
* Created by Tre Murillo on 1/2/16
*/
object Constants {
const val CONSUMER_KEY = "49756-f2c439a8fa6256da0bc3710a"
const val BASE_URL = "https://getpocket.com"
const val AUTHORIZE_URL = "$BASE_URL/auth/authorize"
const val REDIRECT_URI = "oauth://zinepress.treelzebub.net"
const val CONTENT_TYPE_ARTICLE = "article"
}
| gpl-2.0 | af9166589c5765a872d0d4bee13f079a | 25.0625 | 71 | 0.642686 | 3.362903 | false | false | false | false |
realm/realm-java | realm/realm-library/src/androidTest/kotlin/io/realm/entities/SetContainerClass.kt | 1 | 3358 | /*
* Copyright 2021 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.entities
import io.realm.RealmAny
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.RealmSet
import io.realm.annotations.PrimaryKey
import org.bson.types.Decimal128
import org.bson.types.ObjectId
import java.util.*
open class SetContainerClass : RealmObject() {
val myRealmModelNoPkSet = RealmSet<Owner>()
val myRealmModelSet = RealmSet<DogPrimaryKey>()
val myBooleanSet = RealmSet<Boolean>()
val myStringSet = RealmSet<String>()
val myIntSet = RealmSet<Int>()
val myFloatSet = RealmSet<Float>()
val myLongSet = RealmSet<Long>()
val myShortSet = RealmSet<Short>()
val myDoubleSet = RealmSet<Double>()
val myByteSet = RealmSet<Byte>()
val myBinarySet = RealmSet<ByteArray>()
val myDateSet = RealmSet<Date>()
val myObjectIdSet = RealmSet<ObjectId>()
val myUUIDSet = RealmSet<UUID>()
val myDecimal128Set = RealmSet<Decimal128>()
val myRealmAnySet = RealmSet<RealmAny>()
val myRealmModelNoPkList = RealmList<Owner>()
val myRealmModelList = RealmList<DogPrimaryKey>()
val myBooleanList = RealmList<Boolean>()
val myStringList = RealmList<String>()
val myIntList = RealmList<Int>()
val myFloatList = RealmList<Float>()
val myLongList = RealmList<Long>()
val myShortList = RealmList<Short>()
val myDoubleList = RealmList<Double>()
val myByteList = RealmList<Byte>()
val myBinaryList = RealmList<ByteArray>()
val myDateList = RealmList<Date>()
val myObjectIdList = RealmList<ObjectId>()
val myUUIDList = RealmList<UUID>()
val myDecimal128List = RealmList<Decimal128>()
val myRealmAnyList = RealmList<RealmAny>()
companion object {
const val CLASS_NAME = "SetContainerClass"
}
}
open class SetContainerMigrationClass : RealmObject() {
@PrimaryKey
var id: String? = ""
val myRealmModelSet = RealmSet<StringOnly>()
val myBooleanSet = RealmSet<Boolean>()
val myStringSet = RealmSet<String>()
val myIntSet = RealmSet<Int>()
val myFloatSet = RealmSet<Float>()
val myLongSet = RealmSet<Long>()
val myShortSet = RealmSet<Short>()
val myDoubleSet = RealmSet<Double>()
val myByteSet = RealmSet<Byte>()
val myBinarySet = RealmSet<ByteArray>()
val myDateSet = RealmSet<Date>()
val myObjectIdSet = RealmSet<ObjectId>()
val myUUIDSet = RealmSet<UUID>()
val myDecimal128Set = RealmSet<Decimal128>()
val myRealmAnySet = RealmSet<RealmAny>()
companion object {
const val CLASS_NAME = "SetContainerMigrationClass"
}
}
open class SetContainerAfterMigrationClass : RealmObject() {
@PrimaryKey
var id: String? = ""
companion object {
const val CLASS_NAME = "SetContainerAfterMigrationClass"
}
}
| apache-2.0 | 76eda31da51d02ecb090377c48c12750 | 31.601942 | 75 | 0.706373 | 4.218593 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/data/proto/CheckProtoTest.kt | 1 | 976 | package arcs.core.data.proto
import arcs.core.data.AccessPath
import arcs.core.data.Check
import arcs.core.data.HandleConnectionSpec
import arcs.core.data.HandleMode
import arcs.core.data.InformationFlowLabel
import arcs.core.data.TypeVariable
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class CheckProtoTest {
@Test
fun roundTrip_assert() {
val connectionSpec = HandleConnectionSpec(
name = "connectionSpec",
direction = HandleMode.Read,
type = TypeVariable("a")
)
val check = Check(
accessPath = AccessPath("particleSpec", connectionSpec),
predicate = InformationFlowLabel.Predicate.Label(
InformationFlowLabel.SemanticTag("label")
)
)
val encoded = check.encode()
val decoded = encoded.decode(mapOf("connectionSpec" to connectionSpec))
assertThat(decoded).isEqualTo(check)
}
}
| bsd-3-clause | af0a8b58e77431a0bd0738db709c1d29 | 26.885714 | 75 | 0.741803 | 4.033058 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AnnotationClassConversion.kt | 6 | 2862 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.conversions
import org.jetbrains.kotlin.j2k.ast.Nullability
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.toExpression
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.JKJavaArrayType
import org.jetbrains.kotlin.nj2k.types.isArrayType
import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType
import org.jetbrains.kotlin.nj2k.types.updateNullabilityRecursively
class AnnotationClassConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKClass) return recurse(element)
if (element.classKind != JKClass.ClassKind.ANNOTATION) return recurse(element)
val javaAnnotationMethods =
element.classBody.declarations
.filterIsInstance<JKJavaAnnotationMethod>()
val constructor = JKKtPrimaryConstructor(
JKNameIdentifier(""),
javaAnnotationMethods.map { it.asKotlinAnnotationParameter() },
JKStubExpression(),
JKAnnotationList(),
emptyList(),
JKVisibilityModifierElement(Visibility.PUBLIC),
JKModalityModifierElement(Modality.FINAL)
)
element.modality = Modality.FINAL
element.classBody.declarations += constructor
element.classBody.declarations -= javaAnnotationMethods
return recurse(element)
}
private fun JKJavaAnnotationMethod.asKotlinAnnotationParameter(): JKParameter {
val type = returnType.type
.updateNullabilityRecursively(Nullability.NotNull)
.replaceJavaClassWithKotlinClassType(symbolProvider)
val initializer = this::defaultValue.detached().toExpression(symbolProvider)
val isVarArgs = type is JKJavaArrayType && name.value == "value"
return JKParameter(
JKTypeElement(
if (!isVarArgs) type else (type as JKJavaArrayType).type,
returnType::annotationList.detached()
),
JKNameIdentifier(name.value),
isVarArgs = isVarArgs,
initializer =
if (type.isArrayType()
&& initializer !is JKKtAnnotationArrayInitializerExpression
&& initializer !is JKStubExpression
) {
JKKtAnnotationArrayInitializerExpression(initializer)
} else initializer,
annotationList = this::annotationList.detached(),
).also { parameter ->
parameter.trailingComments += trailingComments
parameter.leadingComments += leadingComments
}
}
} | apache-2.0 | 2f54a4616314a2ee056d7d8689fbeb8c | 44.444444 | 120 | 0.693222 | 5.770161 | false | false | false | false |
theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/database/feed/model/FeedGroupSubscriptionEntity.kt | 4 | 1628 | 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"
}
}
| gpl-3.0 | f7515f2cde31f26a3f8abe337f428f06 | 33.638298 | 113 | 0.710074 | 4.573034 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/fragments/AdjustTripFragment.kt | 2 | 3279 | 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)
}
}
| mit | 84ebc5dc1c9739e8b096fe111938f581 | 32.15625 | 88 | 0.653553 | 4.843427 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/notifications/utils/FormattableContentClickHandler.kt | 1 | 6504 | 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)
}
}
| gpl-2.0 | dab8739cc1151cf46c6a20eb8a73430e | 39.397516 | 118 | 0.660363 | 5.141502 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt | 1 | 32443 | // 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()
}
}
| apache-2.0 | 68bf3296ce86cdfab9783bc1ddb9d9ae | 47.64018 | 164 | 0.633943 | 6.584737 | false | false | false | false |
michaelkourlas/voipms-sms-client | voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/utils/network.kt | 1 | 2375 | /*
* 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())
}
}
}
| apache-2.0 | 6f191714283b8357c77f5c46eb411b66 | 33.42029 | 79 | 0.713684 | 4.481132 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/imageloader/GlideImageLoader.kt | 1 | 1594 | 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)
}
}
| apache-2.0 | 1611b244b6deda9ce9cd708282c5b970 | 32.208333 | 130 | 0.744668 | 4.904615 | false | false | false | false |
hzsweers/CatchUp | services/slashdot/src/main/kotlin/io/sweers/catchup/service/slashdot/SlashdotService.kt | 1 | 5053 | /*
* 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)
}
}
}
| apache-2.0 | c8e55493da70683efbd3009ddb0e1ac3 | 30.385093 | 88 | 0.723135 | 4.440246 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspections/naming/property/test.kt | 3 | 872 | 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
}
}
| apache-2.0 | c2212da22df98b9772c466bac94f5644 | 13.533333 | 42 | 0.587156 | 3.241636 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHECloneDialogExtension.kt | 2 | 3523 | // 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()
} | apache-2.0 | e308410197cb5fe062062d8984040f91 | 40.952381 | 140 | 0.795629 | 4.666225 | false | false | false | false |
DeskChan/DeskChan | src/main/kotlin/info/deskchan/core/PluginProperties.kt | 2 | 2162 | 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))
}
}
} | lgpl-3.0 | 47becbd8e909f76f4cf97a20b7ad7460 | 30.808824 | 93 | 0.554117 | 4.858427 | false | true | false | false |
binaryroot/AndroidArchitecture | app/src/main/java/com/androidarchitecture/data/auth/AuthorizationService.kt | 1 | 1648 | 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
}
}
| mit | 37ffb4be3237456689ab813b0524f382 | 30.09434 | 90 | 0.635922 | 5.198738 | false | true | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/test/java/com/doctoror/particleswallpaper/userprefs/data/DefaultSceneSettingsTest.kt | 1 | 5148 | /*
* 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)
}
| apache-2.0 | 063a5c35b7f8bd9239d64412ded567b0 | 26.978261 | 92 | 0.660839 | 4.771084 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/track/TrackManager.kt | 2 | 1133 | 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 }
}
| apache-2.0 | bdadbf8ae1188380632ece87136b5aa7 | 28.051282 | 81 | 0.718447 | 3.486154 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/OrcTypes.kt | 4 | 13149 | /*
* 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."
}
}
| bsd-3-clause | 629704404605b30ecd1f0486ef219115 | 44.65625 | 158 | 0.741577 | 5.23031 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/Page.kt | 1 | 491 | 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()
}
| apache-2.0 | ccc5da597f879a2ee59b12826d27afff | 36.769231 | 108 | 0.725051 | 5.010204 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/program/internal/ProgramIndicatorCall.kt | 1 | 3989 | /*
* 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()
}
}
| bsd-3-clause | be214408bb7988579e62aa3980bb7344 | 42.835165 | 107 | 0.682878 | 4.800241 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/diamond/Diamond4.kt | 1 | 1104 | 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()
}
| unlicense | de9d06f9e3b64a19449d19319a7012a0 | 25.926829 | 70 | 0.451993 | 3.942857 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/model/sponsoring/SponsoringServiceImpl.kt | 1 | 7389 | 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")
}
}
| agpl-3.0 | cbc2f64d3f8022e52a42bf1e8577456f | 43.957317 | 189 | 0.642208 | 4.628374 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/ui/FontSizeInfoUsageCollector.kt | 1 | 2559 | // 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()
}
}
| apache-2.0 | 548ee2e44526e3c97a31e09ddcecffad | 40.274194 | 140 | 0.741305 | 4.704044 | false | false | false | false |
google/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/PluginXmlPatcher.kt | 4 | 8596 | // 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")
}
} | apache-2.0 | 3239d4b88fd0c334f04fe9073a7637f1 | 42.419192 | 135 | 0.701605 | 4.957324 | false | false | false | false |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/community/PublicIdeDownloader.kt | 2 | 3109 | 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)
}
} | apache-2.0 | 53a04df0b0d492c276a7ae746e6ebba2 | 46.846154 | 132 | 0.721454 | 4.911532 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt | 1 | 20784 | // 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
}
} | apache-2.0 | 28604ff11b7594d36ed863f4903ecc08 | 50.44802 | 158 | 0.717523 | 5.89617 | false | false | false | false |
apollographql/apollo-android | apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/Issue.kt | 1 | 2499 | 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
}
| mit | ddd07fd4e848e59eae8b316ba51a6bb9 | 29.108434 | 128 | 0.713485 | 4.551913 | false | false | false | false |
square/okhttp | okhttp/src/jvmTest/java/okhttp3/internal/http/ExternalHttp2Example.kt | 2 | 1385 | /*
* 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()
}
}
| apache-2.0 | a20b23bc2fddcb788cde5e3eb893fdc3 | 29.108696 | 80 | 0.677978 | 4.00289 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/GeneralInfo.kt | 1 | 623 | /*
* 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 | mit | 9e0ecd675303f6ad53a7b42b964c47fb | 23.96 | 44 | 0.678973 | 3.708333 | false | false | false | false |
BrianErikson/PushLocal-Desktop | src/ui/debugmenu/DebugMenu.kt | 1 | 1273 | 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)
}
}
| apache-2.0 | 7a8bb6aaec2d452308187f02f2d811ee | 32.5 | 147 | 0.704635 | 4.697417 | false | false | false | false |
scenerygraphics/scenery | src/test/kotlin/graphics/scenery/tests/examples/volumes/OrthoViewExample.kt | 1 | 2518 | 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()
}
}
}
| lgpl-3.0 | 14b081a0c479807da967c06008734aad | 31.282051 | 115 | 0.654091 | 3.670554 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/strings/ErrorStrings.kt | 1 | 3087 | 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
}
| apache-2.0 | ef26024c7489ba6204ac5314dced4baf | 32.923077 | 92 | 0.641399 | 4.257931 | false | false | false | false |
RanolP/Kubo | Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/client/objects/TelegramClientMessage.kt | 1 | 1253 | 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.
}
} | mit | a5fde6c6b014c8d086ee122ea2c14a42 | 42.241379 | 123 | 0.731844 | 4.276451 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-server/src/test/kotlin/jetbrains/buildServer/dotnet/test/JsonProjectDeserializerTest.kt | 1 | 2204 | 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)
}
} | apache-2.0 | ee1872f7301c56db803fb27cb3fe06df | 35.147541 | 158 | 0.608439 | 4.963964 | false | true | false | false |
xranby/modern-jogl-examples | src/main/kotlin/main/tut02/vertexColor.kt | 1 | 3093 | 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()
}
}
}
}
| mit | 2e54e95e5209116c99a053b1c39a995f | 26.864865 | 105 | 0.646621 | 3.638824 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/ide/ui/TargetPresentationRightRenderer.kt | 2 | 2050 | // 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
}
}
| apache-2.0 | d49b428868365ff760248b1ac7fedad9 | 37.679245 | 140 | 0.692195 | 5.189873 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/scanner/ScannerTest.kt | 1 | 7391 | /*
* 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)
}
} | gpl-3.0 | 50816d37f1f5b39a3b9ee45fe97dbd81 | 31.421053 | 95 | 0.66838 | 5.241844 | false | true | false | false |
stefanodacchille/fast-bookmark | app/src/main/kotlin/com/stefano/playground/fastbookmark/utils/AppPreferences.kt | 1 | 1494 | 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"
}
} | mit | 61bc6a73ac3e224f524cdf747855cd4c | 27.207547 | 97 | 0.720214 | 4.94702 | false | false | false | false |
DanielMartinus/Konfetti | konfetti/core/src/main/java/nl/dionsegijn/konfetti/core/models/Vector.kt | 1 | 382 | 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
}
}
| isc | 84294a1c98f39dcb598bb5cd6e70af53 | 15.608696 | 57 | 0.41623 | 2.96124 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/ieee754/anyToReal.kt | 5 | 443 | 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"
} | apache-2.0 | 00e69af5f5554a53f922af3a0618aaa7 | 28.6 | 70 | 0.61851 | 3.30597 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/codegen/branching/when_through.kt | 1 | 274 | 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()
} | apache-2.0 | 4ba4c8c8a15dbd83df4be6b29a28a02d | 14.277778 | 41 | 0.591241 | 3.078652 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/withReturn.kt | 5 | 334 | 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"
}
| apache-2.0 | 1835fe277fa5c3f144fa4c90182b0177 | 17.555556 | 48 | 0.452096 | 2.955752 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/empire/EmpireScreen.kt | 1 | 3085 | 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")
}
} | mit | 3f7cbe7bb2c26b8602e724be810a7a7b | 39.077922 | 99 | 0.700162 | 4.180217 | false | false | false | false |
smmribeiro/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/BaseHtmlEditorPane.kt | 9 | 1155 | // 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)
}
} | apache-2.0 | 41f07ff933a9dc92ada8535b835047c5 | 30.243243 | 120 | 0.748052 | 4.325843 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringStateChanges.kt | 4 | 7645 | // 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 com.jetbrains.python.refactoring.suggested
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.intellij.refactoring.suggested.SuggestedRefactoringState
import com.intellij.refactoring.suggested.SuggestedRefactoringStateChanges
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport
import com.intellij.refactoring.suggested.range
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.ParamHelper
internal class PySuggestedRefactoringStateChanges(support: PySuggestedRefactoringSupport) : SuggestedRefactoringStateChanges(support) {
override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? {
return findStateChanges(declaration).signature(declaration, prevState)
}
override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> {
return findStateChanges(declaration).parameterMarkerRanges(declaration)
}
override fun updateState(state: SuggestedRefactoringState, declaration: PsiElement): SuggestedRefactoringState {
return findStateChanges(declaration).updateNewState(state, declaration, super.updateState(state, declaration))
}
override fun guessParameterIdByMarkers(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? {
return super.guessParameterIdByMarkers(markerRange, prevState) ?:
// findStateChanges(prevState.declaration) can't be used here since !prevState.declaration.isValid
sequenceOf(ChangeSignatureStateChanges(this), RenameStateChanges)
.mapNotNull { it.guessParameterIdByMarker(markerRange, prevState) }
.firstOrNull()
}
private fun findStateChanges(declaration: PsiElement): StateChangesInternal {
return sequenceOf(ChangeSignatureStateChanges(this), RenameStateChanges).first { it.isApplicable(declaration) }
}
private interface StateChangesInternal {
fun isApplicable(declaration: PsiElement): Boolean
fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature?
fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?>
fun updateNewState(prevState: SuggestedRefactoringState,
declaration: PsiElement,
newState: SuggestedRefactoringState): SuggestedRefactoringState = newState
fun guessParameterIdByMarker(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? = null
}
private class ChangeSignatureStateChanges(private val mainStateChanges: PySuggestedRefactoringStateChanges) : StateChangesInternal {
companion object {
private val DISAPPEARED_RANGES =
Key.create<Map<RangeMarker, Any>>("PySuggestedRefactoringStateChanges.ChangeSignature.DISAPPEARED_RANGES")
}
override fun isApplicable(declaration: PsiElement): Boolean = PySuggestedRefactoringSupport.isAvailableForChangeSignature(declaration)
override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? {
val signature = createSignatureData(declaration as PyFunction) ?: return null
return if (prevState == null) signature
else mainStateChanges.matchParametersWithPrevState(signature, declaration, prevState)
}
override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> {
return (declaration as PyFunction).parameterList.parameters.map(this::getParameterMarker)
}
override fun updateNewState(prevState: SuggestedRefactoringState,
declaration: PsiElement,
newState: SuggestedRefactoringState): SuggestedRefactoringState {
val initialSignature = prevState.oldSignature
val prevSignature = prevState.newSignature
val newSignature = newState.newSignature
val idsPresent = newSignature.parameters.map { it.id }.toSet()
val disappearedRanges = (prevState.additionalData[DISAPPEARED_RANGES] ?: emptyMap())
.filter { it.key.isValid && it.value !in idsPresent }
.toMutableMap()
prevSignature.parameters
.asSequence()
.map { it.id }
.filter { id -> id !in idsPresent && initialSignature.parameterById(id) != null }
.mapNotNull { id -> prevState.parameterMarkers.firstOrNull { it.parameterId == id } }
.filter { it.rangeMarker.isValid }
.associateByTo(disappearedRanges, { it.rangeMarker }, { it.parameterId })
return newState.withAdditionalData(DISAPPEARED_RANGES, disappearedRanges)
}
override fun guessParameterIdByMarker(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? {
val disappearedRanges = prevState.additionalData[DISAPPEARED_RANGES] ?: return null
return disappearedRanges.entries.firstOrNull { it.key.isValid && it.key.range == markerRange }?.value
}
private fun createSignatureData(function: PyFunction): SuggestedRefactoringSupport.Signature? {
val name = function.name ?: return null
val parametersData = function.parameterList.parameters.map { createParameterData(it) ?: return null }
return SuggestedRefactoringSupport.Signature.create(name, PyTypingTypeProvider.ANY, parametersData, null)
}
private fun getParameterMarker(parameter: PyParameter): TextRange? {
val asNamed = parameter.asNamed
if (asNamed != null) {
if (asNamed.isPositionalContainer) return getChildRange(parameter, PyTokenTypes.MULT)
if (asNamed.isKeywordContainer) return getChildRange(parameter, PyTokenTypes.EXP)
}
return PsiTreeUtil.skipWhitespacesForward(parameter)
?.takeIf { it.elementType == PyTokenTypes.COMMA || it.elementType == PyTokenTypes.RPAR }
?.textRange
}
private fun getChildRange(element: PsiElement, type: IElementType): TextRange? = element.node.findChildByType(type)?.textRange
private fun createParameterData(parameter: PyParameter): SuggestedRefactoringSupport.Parameter? {
val name = when (parameter) {
is PySlashParameter -> PySlashParameter.TEXT
is PySingleStarParameter -> PySingleStarParameter.TEXT
is PyNamedParameter -> ParamHelper.getNameInSignature(parameter)
else -> return null
}
return SuggestedRefactoringSupport.Parameter(
Any(),
name,
PyTypingTypeProvider.ANY,
PySuggestedRefactoringSupport.ParameterData(parameter.defaultValueText)
)
}
}
private object RenameStateChanges : StateChangesInternal {
override fun isApplicable(declaration: PsiElement): Boolean = PySuggestedRefactoringSupport.isAvailableForRename(declaration)
override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): SuggestedRefactoringSupport.Signature? {
val name = (declaration as PsiNameIdentifierOwner).name ?: return null
return SuggestedRefactoringSupport.Signature.create(name, null, emptyList(), null)
}
override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> = emptyList()
}
} | apache-2.0 | 84eaa154e637d45bfad92f0bddf3cfbd | 48.012821 | 140 | 0.763113 | 5.535844 | false | false | false | false |
leafclick/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt | 1 | 7493 | // 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 org.jetbrains.builtInWebServer
import com.google.common.base.Function
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SmartList
import com.intellij.util.io.exists
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
import kotlin.streams.asSequence
private const val cacheSize: Long = 4096 * 4
/**
* Implement [WebServerRootsProvider] to add your provider
*/
class WebServerPathToFileManager(private val project: Project) {
val pathToInfoCache: Cache<String, PathInfo> = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()!!
// time to expire should be greater than pathToFileCache
private val virtualFileToPathInfo = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>()
internal val pathToExistShortTermCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()!!
/**
* https://youtrack.jetbrains.com/issue/WEB-25900
*
* Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search
* (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir)
*/
internal val parentToSuitableRoot = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, List<SuitableRoot>>(
CacheLoader.from(Function { path ->
val suitableRoots = SmartList<SuitableRoot>()
var moduleQualifier: String? = null
val modules = runReadAction { ModuleManager.getInstance(project).modules }
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
for (root in rootProvider.getRoots(module.rootManager)) {
if (root.findChild(path!!) != null) {
if (moduleQualifier == null) {
moduleQualifier = getModuleNameQualifier(project, module)
}
suitableRoots.add(SuitableRoot(root, moduleQualifier))
}
}
}
}
suitableRoots
}))!!
init {
ApplicationManager.getApplication().messageBus.connect (project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
if (event is VFileContentChangeEvent) {
val file = event.file
for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) {
if (rootsProvider.isClearCacheOnFileContentChanged(file)) {
clearCache()
break
}
}
}
else {
clearCache()
break
}
}
}
})
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
clearCache()
}
})
}
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<WebServerPathToFileManager>()
}
private fun clearCache() {
pathToInfoCache.invalidateAll()
virtualFileToPathInfo.invalidateAll()
pathToExistShortTermCache.invalidateAll()
parentToSuitableRoot.invalidateAll()
}
@JvmOverloads
fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? {
return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile()
}
@JvmOverloads
fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? {
var pathInfo = pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
if (pathToExistShortTermCache.getIfPresent(path) == false) {
return null
}
pathInfo = doFindByRelativePath(path, pathQuery)
if (cacheResult) {
if (pathInfo != null && pathInfo.isValid) {
pathToInfoCache.put(path, pathInfo)
}
else {
pathToExistShortTermCache.put(path, false)
}
}
}
return pathInfo
}
fun getPath(file: VirtualFile): String? = getPathInfo(file)?.path
fun getPathInfo(child: VirtualFile): PathInfo? {
var result = virtualFileToPathInfo.getIfPresent(child)
if (result == null) {
result = WebServerRootsProvider.EP_NAME.extensions().asSequence().map { it.getPathInfo(child, project) }.find { it != null }
if (result != null) {
virtualFileToPathInfo.put(child, result)
}
}
return result
}
internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? {
val result = WebServerRootsProvider.EP_NAME.extensions().asSequence().map { it.resolve(path, project, pathQuery) }.find { it != null } ?: return null
result.file?.let {
virtualFileToPathInfo.put(it, result)
}
return result
}
fun getResolver(path: String): FileResolver = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER
}
interface FileResolver {
fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo?
}
private val RELATIVE_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
// WEB-17691 built-in server doesn't serve files it doesn't have in the project tree
// temp:// reports isInLocalFileSystem == true, but it is not true
if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") {
return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) }
}
val file = Paths.get(root.path, path)
return if (file.exists()) {
PathInfo(file, null, root, moduleName, isLibrary)
}
else {
null
}
}
}
private val EMPTY_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
val file = findIndexFile(root) ?: return null
return PathInfo(null, file, root, moduleName, isLibrary)
}
}
internal val defaultPathQuery = PathQuery() | apache-2.0 | af3806445611c36e477a19f68f4a09ff | 38.650794 | 165 | 0.70746 | 4.697806 | false | false | false | false |
leafclick/intellij-community | plugins/devkit/devkit-core/src/util/ExtensionLocator.kt | 1 | 4674 | // 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 org.jetbrains.idea.devkit.util
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.UsageSearchContext
import com.intellij.psi.util.ClassUtil
import com.intellij.psi.xml.XmlTag
import com.intellij.util.SmartList
import com.intellij.util.xml.DomManager
import org.jetbrains.idea.devkit.dom.Extension
import org.jetbrains.idea.devkit.dom.ExtensionPoint
import java.util.*
fun locateExtensionsByPsiClass(psiClass: PsiClass): List<ExtensionCandidate> {
return findExtensionsByClassName(psiClass.project, ClassUtil.getJVMClassName(psiClass) ?: return emptyList())
}
fun locateExtensionsByExtensionPoint(extensionPoint: ExtensionPoint): List<ExtensionCandidate> {
return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, null).findCandidates()
}
fun locateExtensionsByExtensionPointAndId(extensionPoint: ExtensionPoint, extensionId: String): ExtensionLocator {
return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, extensionId)
}
internal fun processExtensionDeclarations(name: String, project: Project, strictMatch: Boolean = true, callback: (Extension, XmlTag) -> Boolean) {
val scope = PluginRelatedLocatorsUtils.getCandidatesScope(project)
PsiSearchHelper.getInstance(project).processElementsWithWord(
{ element, offsetInElement ->
val elementAtOffset = (element as? XmlTag)?.findElementAt(offsetInElement) ?: return@processElementsWithWord true
if (strictMatch) {
if (!elementAtOffset.textMatches(name)) {
return@processElementsWithWord true
}
}
else if (!StringUtil.contains(elementAtOffset.text, name)) {
return@processElementsWithWord true
}
val extension = DomManager.getDomManager(project).getDomElement(element) as? Extension ?: return@processElementsWithWord true
callback(extension, element)
}, scope, name, UsageSearchContext.IN_FOREIGN_LANGUAGES, /* case-sensitive = */ true)
}
private fun findExtensionsByClassName(project: Project, className: String): List<ExtensionCandidate> {
val result = Collections.synchronizedList(SmartList<ExtensionCandidate>())
val smartPointerManager by lazy { SmartPointerManager.getInstance(project) }
processExtensionsByClassName(project, className) { tag, _ ->
result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(tag)))
true
}
return result
}
internal inline fun processExtensionsByClassName(project: Project, className: String, crossinline processor: (XmlTag, ExtensionPoint) -> Boolean) {
processExtensionDeclarations(className, project) { extension, tag ->
extension.extensionPoint?.let { processor(tag, it) } ?: true
}
}
internal class ExtensionByExtensionPointLocator(private val project: Project,
extensionPoint: ExtensionPoint,
private val extensionId: String?) : ExtensionLocator() {
private val pointQualifiedName = extensionPoint.effectiveQualifiedName
private fun processCandidates(processor: (XmlTag) -> Boolean) {
// We must search for the last part of EP name, because for instance 'com.intellij.console.folding' extension
// may be declared as <extensions defaultExtensionNs="com"><intellij.console.folding ...
val epNameToSearch = StringUtil.substringAfterLast(pointQualifiedName, ".") ?: return
processExtensionDeclarations(epNameToSearch, project, false /* not strict match */) { extension, tag ->
val ep = extension.extensionPoint ?: return@processExtensionDeclarations true
if (ep.effectiveQualifiedName == pointQualifiedName && (extensionId == null || extensionId == extension.id.stringValue)) {
// stop after the first found candidate if ID is specified
processor(tag) && extensionId == null
}
else {
true
}
}
}
override fun findCandidates(): List<ExtensionCandidate> {
val result = Collections.synchronizedList(SmartList<ExtensionCandidate>())
val smartPointerManager by lazy { SmartPointerManager.getInstance(project) }
processCandidates {
result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(it)))
}
return result
}
}
sealed class ExtensionLocator {
abstract fun findCandidates(): List<ExtensionCandidate>
} | apache-2.0 | 8f77c2e5333c497d32b7562236fd666a | 46.704082 | 147 | 0.759735 | 5.19911 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/editors/PackageScopeTableCellEditor.kt | 1 | 3070 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors
import com.intellij.ui.components.editors.JBComboBoxTableCellEditorComponent
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.AbstractTableCellEditor
import com.jetbrains.packagesearch.intellij.plugin.ui.components.ComboBoxTableCellEditorComponent
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeViewModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PopupMenuListItemCellRenderer
import java.awt.Component
import javax.swing.JTable
internal object PackageScopeTableCellEditor : AbstractTableCellEditor() {
private val comboBoxEditor = JBComboBoxTableCellEditorComponent()
override fun getCellEditorValue(): Any? = comboBoxEditor.editorValue
override fun getTableCellEditorComponent(table: JTable, value: Any, isSelected: Boolean, row: Int, column: Int): Component =
when (val scopeViewModel = value as ScopeViewModel<*>) {
is ScopeViewModel.InstalledPackage -> {
val availableScopes = scopeViewModel.packageModel.usageInfo
.flatMap { it.availableScopes }
val scopeViewModels = (availableScopes + scopeViewModel.installedScopes)
.distinct()
.sorted()
.map { scopeViewModel.copy(selectedScope = it) }
createComboBoxEditor(table, scopeViewModels, scopeViewModel.selectedScope)
}
is ScopeViewModel.InstallablePackage -> {
val scopeViewModels = scopeViewModel.availableScopes
.distinct()
.sorted()
.map { scopeViewModel.copy(selectedScope = it) }
createComboBoxEditor(table, scopeViewModels, scopeViewModel.selectedScope)
}
}.apply {
table.colors.applyTo(this, isSelected = true)
setCell(row, column)
}
private fun createComboBoxEditor(
table: JTable,
scopeViewModels: List<ScopeViewModel<*>>,
selectedScope: PackageScope
): ComboBoxTableCellEditorComponent<*> {
require(table is JBTable) { "The packages list table is expected to be a JBTable, but was a ${table::class.qualifiedName}" }
val selectedViewModel = scopeViewModels.find { it.selectedScope == selectedScope }
val cellRenderer = PopupMenuListItemCellRenderer(selectedViewModel, table.colors) { it.selectedScope.displayName }
return ComboBoxTableCellEditorComponent(table, cellRenderer).apply {
options = scopeViewModels
value = selectedViewModel
isShowBelowCell = false
isForcePopupMatchCellWidth = false
}
}
}
| apache-2.0 | db13b78005ad2b509e457b1fef797207 | 47.730159 | 139 | 0.709772 | 5.531532 | false | false | false | false |
kivensolo/UiUsingListView | database/src/main/java/com/kingz/database/entity/CookiesEntity.kt | 1 | 657 | package com.kingz.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import java.io.Serializable
/**
* author:ZekeWang
* date:2021/5/11
* description:网络请求的Cookie表
* @since DataBase v3
*/
@Entity(tableName = "http_cookie", primaryKeys = ["id"])
class CookiesEntity(
@ColumnInfo(name = "id")
var id: Int = 0,
@ColumnInfo(name = "url", defaultValue = "")
var url: String = "",
@ColumnInfo(name = "cookies", defaultValue = "")
var cookies: String = ""
) : Serializable {
override fun toString(): String {
return "CookiesEntity(id=$id, url='$url', cookies='$cookies')"
}
} | gpl-2.0 | fc11175106fbaa903669b6fc394379ed | 24.6 | 70 | 0.655712 | 3.651429 | false | false | false | false |
bjansen/pebble-intellij | src/main/kotlin/com/github/bjansen/intellij/pebble/editor/PebbleTypedHandler.kt | 1 | 6447 | package com.github.bjansen.intellij.pebble.editor
import com.github.bjansen.intellij.pebble.lang.PebbleFileViewProvider
import com.github.bjansen.intellij.pebble.psi.PebbleFile
import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.tokens
import com.github.bjansen.pebble.parser.PebbleLexer
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil.insertStringAtCaret
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import java.util.regex.Pattern
/**
* Automatically close delimiters.
*/
// TODO This doesn't support custom delimiters
class PebbleTypedHandler : TypedHandlerDelegate() {
private val tagNamePattern: Pattern = Pattern.compile("\\{%\\s+(\\w+).*")
private val tagsThatCanBeClosed = mapOf(
"autoescape" to "endautoescape",
"block" to "endblock",
"cache" to "endcache",
"filter" to "endfilter",
"for" to "endfor",
"if" to "endif",
"macro" to "endmacro",
"parallel" to "endparallel"
)
override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {
if (file.viewProvider !is PebbleFileViewProvider) {
return TypedHandlerDelegate.Result.CONTINUE
}
if (c != '}' && c != '#' && c != '{') {
return TypedHandlerDelegate.Result.CONTINUE
}
val offset = editor.caretModel.offset
val charBefore = getCharAt(editor.document, offset - 1)
val charAfter = getCharAt(editor.document, offset)
val buf = StringBuilder()
var caretShift = 2
if (charBefore == '{' && (c == '#' || c == '{')) {
// autoclose the comment
buf.append(c).append(" ")
if (needsClosingDelimiter(editor, offset, c)) {
buf.append(" ").append(if (c == '#') c else '}')
if (charAfter != '}') {
buf.append('}')
}
}
}
if (charBefore == '%' && c == '}') {
val closingTag = tagsThatCanBeClosed[findOpeningTagName(editor)]
if (closingTag != null) {
buf.append("}{% ").append(closingTag).append(" %}")
}
caretShift = 1
}
if (buf.isEmpty()) {
return TypedHandlerDelegate.Result.CONTINUE
}
insertStringAtCaret(editor, buf.toString(), true, caretShift)
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.commitDocument(editor.document)
return TypedHandlerDelegate.Result.STOP
}
private fun findOpeningTagName(editor: Editor): String? {
var offset = editor.caretModel.offset
while (offset > 0) {
if (getCharAt(editor.document, offset) == '%' && getCharAt(editor.document, offset - 1) == '{') {
val tag = editor.document.text.substring(offset-1 until editor.caretModel.offset)
val matcher = tagNamePattern.matcher(tag)
if (matcher.matches()) {
return matcher.group(1)
}
}
offset--
}
return null
}
private fun needsClosingDelimiter(editor: Editor, afterOffset: Int, openingChar: Char): Boolean {
val closingChar = if (openingChar == '{') '}' else openingChar
val docCharSequence = editor.document.charsSequence
for (offset in afterOffset until docCharSequence.length) {
val nextChar = if (offset + 1 < docCharSequence.length)
docCharSequence[offset + 1]
else '\u0000'
val currChar = docCharSequence[offset]
if (currChar == '{' && nextChar == openingChar) {
return true
}
if (currChar != closingChar || nextChar != '}') {
continue
}
return false
}
return true
}
private fun getCharAt(document: Document, offset: Int): Char {
if (offset >= document.textLength || offset < 0) {
return '\u0000'
}
return document.charsSequence[offset]
}
}
class PebbleEnterBetweenTagsHandler : EnterHandlerDelegateAdapter() {
override fun preprocessEnter(file: PsiFile, editor: Editor, caretOffset: Ref<Int>, caretAdvance: Ref<Int>,
dataContext: DataContext, originalHandler: EditorActionHandler?): EnterHandlerDelegate.Result {
if (file is PebbleFile && betweenMatchingTags(editor, caretOffset.get())) {
editor.document.insertString(caretOffset.get(), "\n")
}
return EnterHandlerDelegate.Result.Continue
}
private fun betweenMatchingTags(editor: Editor, offset: Int): Boolean {
if (offset < 2) {
return false
}
val chars = editor.document.charsSequence
if (chars[offset - 1] != '}' || chars[offset - 2] != '%') {
return false
}
val highlighter = (editor as EditorEx).highlighter
val iterator = highlighter.createIterator(offset - 1)
if (iterator.tokenType !== tokens[PebbleLexer.TAG_CLOSE]) {
return false
}
iterator.advance()
if (!iterator.atEnd() && iterator.tokenType === tokens[PebbleLexer.TAG_OPEN]) {
// see if it's an "endXXX" tag
do {
iterator.advance()
} while (!iterator.atEnd() && iterator.tokenType === TokenType.WHITE_SPACE)
return !iterator.atEnd()
&& iterator.tokenType === tokens[PebbleLexer.ID_NAME]
&& chars.substring(iterator.start..iterator.end).startsWith("end")
}
return false
}
}
| mit | 4581decb0226085e8fa0ae7b77a8da97 | 35.219101 | 128 | 0.612223 | 4.757934 | false | false | false | false |
androidx/androidx | navigation/navigation-runtime/src/main/java/androidx/navigation/NavHost.kt | 3 | 2752 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation
import androidx.annotation.IdRes
/**
* A host is a single context or container for navigation via a [NavController].
*
* It is strongly recommended to construct the nav controller by instantiating a
* [NavHostController], which offers additional APIs specifically for a NavHost.
* The NavHostController should still only be externally accessible as a [NavController],
* rather than directly exposing it as a [NavHostController].
*
* Navigation hosts must:
*
* * Handle [saving][NavController.saveState] and
* [restoring][NavController.restoreState] their controller's state
* * Call [Navigation.setViewNavController] on their root view
* * Route system Back button events to the NavController either by manually calling
* [NavController.popBackStack] or by calling
* [NavHostController.setOnBackPressedDispatcher]
* when constructing the NavController.
*
* Optionally, a navigation host should consider calling:
*
* * Call [NavHostController.setLifecycleOwner] to associate the
* NavController with a specific Lifecycle.
* * Call [NavHostController.setViewModelStore] to enable usage of
* [NavController.getViewModelStoreOwner] and navigation graph scoped ViewModels.
*/
public interface NavHost {
/**
* The [navigation controller][NavController] for this navigation host.
*/
public val navController: NavController
}
/**
* Construct a new [NavGraph]
*/
@Suppress("Deprecation")
@Deprecated(
"Use routes to create your NavGraph instead",
ReplaceWith(
"createGraph(startDestination = startDestination.toString(), route = id.toString()) " +
"{ builder.invoke() }"
)
)
public inline fun NavHost.createGraph(
@IdRes id: Int = 0,
@IdRes startDestination: Int,
builder: NavGraphBuilder.() -> Unit
): NavGraph = navController.createGraph(id, startDestination, builder)
/**
* Construct a new [NavGraph]
*/
public inline fun NavHost.createGraph(
startDestination: String,
route: String? = null,
builder: NavGraphBuilder.() -> Unit
): NavGraph = navController.createGraph(startDestination, route, builder)
| apache-2.0 | 8b2e869be3b43daa98239e5b060113ef | 34.74026 | 95 | 0.739826 | 4.688245 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/conventionNameCalls/ReplaceCallWithBinaryOperatorInspection.kt | 3 | 11922 | // 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.inspections.conventionNameCalls
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.inspections.KotlinEqualsBetweenInconvertibleTypesInspection
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.conventionNameCalls.isAnyEquals
import org.jetbrains.kotlin.idea.intentions.isOperatorOrCompatible
import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getLastParentOfTypeInRow
import org.jetbrains.kotlin.resolve.calls.util.getFirstArgumentExpression
import org.jetbrains.kotlin.resolve.calls.util.getReceiverExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.smartcasts.getKotlinTypeWithPossibleSmartCastToFP
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.isNullabilityFlexible
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.util.OperatorNameConventions
class ReplaceCallWithBinaryOperatorInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
private fun IElementType.inverted(): KtSingleValueToken? = when (this) {
KtTokens.LT -> KtTokens.GT
KtTokens.GT -> KtTokens.LT
KtTokens.GTEQ -> KtTokens.LTEQ
KtTokens.LTEQ -> KtTokens.GTEQ
else -> null
}
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
val calleeExpression = element.callExpression?.calleeExpression as? KtSimpleNameExpression ?: return false
if (operation(calleeExpression) == null) return false
val context = element.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = element.callExpression?.getResolvedCall(context) ?: return false
if (!resolvedCall.isReallySuccess()) return false
if (resolvedCall.call.typeArgumentList != null) return false
val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return false
if ((resolvedCall.getArgumentMapping(argument) as ArgumentMatch).valueParameter.index != 0) return false
if (!element.isReceiverExpressionWithValue()) return false
val (expressionToBeReplaced, newExpression) = getReplacementExpression(element) ?: return false
val newContext = newExpression.analyzeAsReplacement(expressionToBeReplaced, context)
return newContext.diagnostics.noSuppression().forElement(newExpression).isEmpty()
}
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
override fun inspectionHighlightType(element: KtDotQualifiedExpression): ProblemHighlightType {
val calleeExpression = element.callExpression?.calleeExpression as? KtSimpleNameExpression
val identifier = calleeExpression?.getReferencedNameAsName()
if (identifier == OperatorNameConventions.EQUALS) {
val context = element.analyze(BodyResolveMode.PARTIAL)
if (element.receiverExpression.getType(context)?.isNullabilityFlexible() == true) {
return ProblemHighlightType.INFORMATION
}
}
val isFloatingPointNumberEquals = calleeExpression?.isFloatingPointNumberEquals() ?: false
return if (isFloatingPointNumberEquals) {
ProblemHighlightType.INFORMATION
} else if (identifier == OperatorNameConventions.EQUALS || identifier == OperatorNameConventions.COMPARE_TO) {
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
} else {
ProblemHighlightType.INFORMATION
}
}
override fun inspectionText(element: KtDotQualifiedExpression) = KotlinBundle.message("call.replaceable.with.binary.operator")
override val defaultFixText: String get() = KotlinBundle.message("replace.with.binary.operator")
override fun fixText(element: KtDotQualifiedExpression): String {
val calleeExpression = element.callExpression?.calleeExpression as? KtSimpleNameExpression ?: return defaultFixText
if (calleeExpression.isFloatingPointNumberEquals()) {
return KotlinBundle.message("replace.total.order.equality.with.ieee.754.equality")
}
val operation = operation(calleeExpression) ?: return defaultFixText
return KotlinBundle.message("replace.with.0", operation.value)
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val (expressionToBeReplaced, newExpression) = getReplacementExpression(element) ?: return
expressionToBeReplaced.replace(newExpression)
}
private fun getReplacementExpression(element: KtDotQualifiedExpression): Pair<KtExpression, KtExpression>? {
val callExpression = element.callExpression ?: return null
val calleeExpression = callExpression.calleeExpression as? KtSimpleNameExpression ?: return null
val operation = operation(calleeExpression) ?: return null
val argument = callExpression.valueArguments.single().getArgumentExpression() ?: return null
val receiver = element.receiverExpression
val factory = KtPsiFactory(element)
return when (operation) {
KtTokens.EXCLEQ -> {
val prefixExpression = element.getWrappingPrefixExpressionIfAny() ?: return null
val newExpression = factory.createExpressionByPattern("$0 != $1", receiver, argument, reformat = false)
prefixExpression to newExpression
}
in OperatorConventions.COMPARISON_OPERATIONS -> {
val binaryParent = element.parent as? KtBinaryExpression ?: return null
val newExpression = factory.createExpressionByPattern("$0 ${operation.value} $1", receiver, argument, reformat = false)
binaryParent to newExpression
}
else -> {
val newExpression = factory.createExpressionByPattern("$0 ${operation.value} $1", receiver, argument, reformat = false)
element to newExpression
}
}
}
private fun PsiElement.getWrappingPrefixExpressionIfAny() =
(getLastParentOfTypeInRow<KtParenthesizedExpression>() ?: this).parent as? KtPrefixExpression
private fun operation(calleeExpression: KtSimpleNameExpression): KtSingleValueToken? {
val identifier = calleeExpression.getReferencedNameAsName()
val dotQualified = calleeExpression.parent.parent as? KtDotQualifiedExpression ?: return null
val isOperatorOrCompatible by lazy {
(calleeExpression.resolveToCall()?.resultingDescriptor as? FunctionDescriptor)?.isOperatorOrCompatible == true
}
return when (identifier) {
OperatorNameConventions.EQUALS -> {
if (!dotQualified.isAnyEquals()) return null
with(KotlinEqualsBetweenInconvertibleTypesInspection) {
val receiver = dotQualified.receiverExpression
val argument = dotQualified.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()
if (dotQualified.analyze(BodyResolveMode.PARTIAL).isInconvertibleTypes(receiver, argument)) return null
}
val prefixExpression = dotQualified.getWrappingPrefixExpressionIfAny()
if (prefixExpression != null && prefixExpression.operationToken == KtTokens.EXCL) KtTokens.EXCLEQ
else KtTokens.EQEQ
}
OperatorNameConventions.COMPARE_TO -> {
if (!isOperatorOrCompatible) return null
// callee -> call -> DotQualified -> Binary
val binaryParent = dotQualified.parent as? KtBinaryExpression ?: return null
val notZero = when {
binaryParent.right?.text == "0" -> binaryParent.left
binaryParent.left?.text == "0" -> binaryParent.right
else -> return null
}
if (notZero != dotQualified) return null
val token = binaryParent.operationToken as? KtSingleValueToken ?: return null
if (token in OperatorConventions.COMPARISON_OPERATIONS) {
if (notZero == binaryParent.left) token else token.inverted()
} else {
null
}
}
else -> {
if (!isOperatorOrCompatible) return null
OperatorConventions.BINARY_OPERATION_NAMES.inverse()[identifier]
}
}
}
private fun KtDotQualifiedExpression.isFloatingPointNumberEquals(): Boolean {
val resolvedCall = resolveToCall() ?: return false
val resolutionFacade = getResolutionFacade()
val context = analyze(resolutionFacade, BodyResolveMode.PARTIAL)
val declarationDescriptor = containingDeclarationForPseudocode?.resolveToDescriptorIfAny()
val dataFlowValueFactory = resolutionFacade.dataFlowValueFactory
val defaultType: (KotlinType, Set<KotlinType>) -> KotlinType = { givenType, stableTypes -> stableTypes.firstOrNull() ?: givenType }
val receiverType = resolvedCall.getReceiverExpression()?.getKotlinTypeWithPossibleSmartCastToFP(
context, declarationDescriptor, languageVersionSettings, dataFlowValueFactory, defaultType
) ?: return false
val argumentType = resolvedCall.getFirstArgumentExpression()?.getKotlinTypeWithPossibleSmartCastToFP(
context, declarationDescriptor, languageVersionSettings, dataFlowValueFactory, defaultType
) ?: return false
return receiverType.isFpType() && argumentType.isNumericType() ||
argumentType.isFpType() && receiverType.isNumericType()
}
private fun KtSimpleNameExpression.isFloatingPointNumberEquals(): Boolean {
val dotQualified = parent.parent as? KtDotQualifiedExpression ?: return false
return dotQualified.isFloatingPointNumberEquals()
}
private fun KotlinType.isFpType(): Boolean {
return isFloat() || isDouble()
}
private fun KotlinType.isNumericType(): Boolean {
return isFpType() || isByte() || isShort() || isInt() || isLong()
}
}
| apache-2.0 | ddf037f6fb6ba9eff411758ede1fa730 | 53.940092 | 158 | 0.728569 | 5.955045 | false | false | false | false |
jwren/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarMainWidgetComponent.kt | 1 | 5727 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.execution.runToolbar.data.RWSlotManagerState
import com.intellij.execution.runToolbar.data.RWStateListener
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeFrame
import java.awt.event.ContainerEvent
import java.awt.event.ContainerListener
import javax.swing.SwingUtilities
class RunToolbarMainWidgetComponent(val presentation: Presentation, place: String, group: ActionGroup) :
FixWidthSegmentedActionToolbarComponent(place, group) {
companion object {
private val LOG = Logger.getInstance(RunToolbarMainWidgetComponent::class.java)
private var counter: MutableMap<Project, Int> = mutableMapOf()
}
override fun logNeeded(): Boolean = RunToolbarProcess.logNeeded
private var project: Project? = null
set(value) {
if(field == value) return
field?.let {
remove(it)
}
field = value
field?.let {
add(it)
}
}
private var popupController: RunToolbarPopupController? = null
private val componentListener = object : ContainerListener {
override fun componentAdded(e: ContainerEvent) {
rebuildPopupControllerComponent()
}
override fun componentRemoved(e: ContainerEvent) {
rebuildPopupControllerComponent()
}
}
private val managerStateListener = object : RWStateListener {
override fun stateChanged(state: RWSlotManagerState) {
updateState()
}
}
private var state: RunToolbarMainSlotState? = null
private fun updateState() {
state = project?.let {
val slotManager = RunToolbarSlotManager.getInstance(it)
val value = when (slotManager.getState()) {
RWSlotManagerState.SINGLE_MAIN -> {
RunToolbarMainSlotState.PROCESS
}
RWSlotManagerState.SINGLE_PLAIN,
RWSlotManagerState.MULTIPLE -> {
if(isOpened) RunToolbarMainSlotState.CONFIGURATION else RunToolbarMainSlotState.INFO
}
RWSlotManagerState.INACTIVE -> {
RunToolbarMainSlotState.CONFIGURATION
}
RWSlotManagerState.MULTIPLE_WITH_MAIN -> {
if(isOpened) RunToolbarMainSlotState.PROCESS else RunToolbarMainSlotState.INFO
}
}
value
}
if(RunToolbarProcess.logNeeded) LOG.info("MAIN SLOT state updated: $state RunToolbar")
}
override fun traceState(lastIds: List<String>, filteredIds: List<String>, ides: List<String>) {
if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT state: ${state} new filtered: ${filteredIds}} visible: $ides RunToolbar")
}
internal var isOpened = false
set(value) {
if(field == value) return
field = value
if(RunToolbarProcess.logNeeded) LOG.info("MAIN SLOT isOpened: $isOpened RunToolbar")
updateState()
if (RunToolbarProcess.isExperimentalUpdatingEnabled) {
forceUpdate()
}
}
override fun isSuitableAction(action: AnAction): Boolean {
return state?.let {
if(action is RTBarAction) {
action.checkMainSlotVisibility(it)
} else true
} ?: true
}
override fun addNotify() {
super.addNotify()
(SwingUtilities.getWindowAncestor(this) as? IdeFrame)?.project?.let {
project = it
RUN_CONFIG_WIDTH = RunToolbarSettings.getInstance(it).getRunConfigWidth()
}
}
override fun updateWidthHandler() {
super.updateWidthHandler()
project?.let {
RunToolbarSettings.getInstance(it).setRunConfigWidth(RUN_CONFIG_WIDTH)
}
}
private fun rebuildPopupControllerComponent() {
popupController?.let {
it.updateControllerComponents(components.filter{it is PopupControllerComponent}.toMutableList())
}
}
override fun removeNotify() {
project = null
super.removeNotify()
}
private fun add(project: Project) {
popupController = RunToolbarPopupController(project, this)
val value = counter.getOrDefault(project, 0) + 1
counter[project] = value
val slotManager = RunToolbarSlotManager.getInstance(project)
DataManager.registerDataProvider(component, DataProvider { key ->
when {
RunToolbarData.RUN_TOOLBAR_DATA_KEY.`is`(key) -> {
slotManager.mainSlotData
}
RunToolbarData.RUN_TOOLBAR_POPUP_STATE_KEY.`is`(key) -> {
isOpened
}
RunToolbarData.RUN_TOOLBAR_MAIN_STATE.`is`(key) -> {
state
}
else -> null
}
})
if (value == 1) {
slotManager.stateListeners.addListener(managerStateListener)
slotManager.active = true
}
rebuildPopupControllerComponent()
addContainerListener(componentListener)
}
private fun remove(project: Project) {
RunToolbarSlotManager.getInstance(project).stateListeners.removeListener(managerStateListener)
counter[project]?.let {
val value = maxOf(it - 1, 0)
counter[project] = value
if (value == 0) {
RunToolbarSlotManager.getInstance(project).active = false
counter.remove(project)
}
}
removeContainerListener(componentListener)
popupController?.let {
if(!Disposer.isDisposed(it)) {
Disposer.dispose(it)
}
}
popupController = null
state = null
}
}
| apache-2.0 | 29aca7c681e3dbc99fd996a94b4ea318 | 28.828125 | 158 | 0.698621 | 4.828836 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowLeftToolbar.kt | 1 | 3303 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.toolWindow
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.impl.AbstractDroppableStripe
import com.intellij.openapi.wm.impl.LayoutData
import com.intellij.openapi.wm.impl.SquareStripeButton
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.Point
import java.awt.Rectangle
import javax.swing.JComponent
import javax.swing.JPanel
internal class ToolWindowLeftToolbar : ToolWindowToolbar() {
private class StripeV2(private val toolBar: ToolWindowLeftToolbar,
override val anchor: ToolWindowAnchor) : AbstractDroppableStripe(VerticalFlowLayout(0, 0)) {
override val isNewStripes: Boolean
get() = true
override fun getButtonFor(toolWindowId: String) = toolBar.getButtonFor(toolWindowId)
override fun getToolWindowFor(component: JComponent) = (component as SquareStripeButton).toolWindow
override fun tryDroppingOnGap(data: LayoutData, gap: Int, insertOrder: Int) {
toolBar.tryDroppingOnGap(data, gap, dropRectangle) {
layoutDragButton(data, gap)
}
}
override fun toString() = "StripeNewUi(anchor=$anchor)"
}
private val topPane = StripeV2(this, ToolWindowAnchor.LEFT)
private val bottomPane = StripeV2(this, ToolWindowAnchor.BOTTOM)
val moreButton = MoreSquareStripeButton(this)
init {
border = JBUI.Borders.customLine(JBUI.CurrentTheme.ToolWindow.borderColor(), 1, 0, 0, 1)
topPane.background = JBUI.CurrentTheme.ToolWindow.background()
bottomPane.background = JBUI.CurrentTheme.ToolWindow.background()
val topWrapper = JPanel(BorderLayout())
topWrapper.add(topPane, BorderLayout.NORTH)
add(topWrapper, BorderLayout.NORTH)
add(bottomPane, BorderLayout.SOUTH)
}
override fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe {
return when (anchor) {
ToolWindowAnchor.LEFT -> topPane
ToolWindowAnchor.BOTTOM -> bottomPane
ToolWindowAnchor.TOP -> bottomPane
else -> throw IllegalArgumentException("Wrong anchor $anchor")
}
}
fun initMoreButton() {
topPane.parent?.add(moreButton, BorderLayout.CENTER)
}
override fun getStripeFor(screenPoint: Point): AbstractDroppableStripe? {
if (!isVisible || !moreButton.isVisible) {
return null
}
val moreButtonRect = Rectangle(moreButton.locationOnScreen, moreButton.size)
if (Rectangle(topPane.locationOnScreen, topPane.size).contains(screenPoint) ||
topPane.getButtons().isEmpty() && moreButtonRect.contains(screenPoint)) {
return topPane
}
else if (!moreButtonRect.contains(screenPoint) &&
Rectangle(locationOnScreen, size).also { JBInsets.removeFrom(it, insets) }.contains(screenPoint)) {
return bottomPane
}
else {
return null
}
}
override fun reset() {
topPane.reset()
bottomPane.reset()
}
override fun getButtonFor(toolWindowId: String): StripeButtonManager? {
return topPane.getButtons().find { it.id == toolWindowId } ?: bottomPane.getButtons().find { it.id == toolWindowId }
}
} | apache-2.0 | 769beac3550dfc32a64c70789469ad07 | 34.913043 | 120 | 0.737511 | 4.518468 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/Kate.kt | 1 | 4420 | package alraune
import pieces100.*
import vgrechka.*
abstract class Kate<Fields : BunchOfFields>(
val modalTitle: String,
val submitButtonTitle: String = AlText.ok,
val submitButtonLevel: AlButtonStyle = AlButtonStyle.Primary,
val cancelButtonTitle: String = AlText.changedMind)
: Dancer<ShitWithContext<ModalShit, Context1>> {
abstract fun setInitialFields(fs: Fields)
abstract fun makeFields(): Fields
abstract fun serveGivenValidFields(fs: Fields)
abstract fun ooModalBody(fs: Fields)
open fun serveOkButtonForScrewedState() {imf("Hey little bitch, override me")}
open fun decorateModal(it: ComposeModalContent) {it.blueLeftMargin()}
var modalContentDomid by notNull<String>()
override fun dance() : ShitWithContext<ModalShit, Context1> {
val fields = useFields(makeFields(), FieldSource.Initial())
setInitialFields(fields)
return _modalWithScripts(fields)
}
class Problems(
val errors: Boolean = false,
val midAirComparisonPageHref: String? = null,
val shitRemoved: Boolean = false)
fun _modalWithScripts(fieldsToRender: Fields, problems: Problems = Problems()): ShitWithContext<ModalShit, Context1> {
modalContentDomid = uuid_insideIgnoreWhenCheckingForStaleness()
return composeModalWithScripts {
it.modalDialogDomid = modalContentDomid
it.title = modalTitle
decorateModal(it)
if (problems.shitRemoved) {
it.body = div().with {
oo(composeRedTriangleBanner("Эту хрень уже удалили. Поздно укакался"))
oo(div("У тебя теперь остается тупо один вариант..."))
}
it.footer = !ButtonBarWithTicker()
.tickerLocation(Rightness.Left)
.addSubmitFormButton(MinimalButtonShit(t("TOTE", "Я обламываюсь"), AlButtonStyle.Primary,
freakingServant {serveOkButtonForScrewedState()}))
}
else {
it.body = div().with {
if (problems.errors)
oo(composeFixErrorsBelowBanner())
problems.midAirComparisonPageHref?.let {
oo(composeMidAirCollisionBanner(
toTheRightOfMessage = ComposeChevronLink(t("TOTE", "Сравнить"), it).WithLeftMargin().newTab()))
}
ooModalBody(fieldsToRender)
}
it.footer = !ButtonBarWithTicker()
.tickerLocation(Rightness.Left)
.addSubmitFormButton(when {
problems.midAirComparisonPageHref != null ->
MinimalButtonShit(t("TOTE", "Затереть и сохранить мое"), AlButtonStyle.Danger,
freakingServant {
rctx0.al.forceOverwriteStale = true
serve()
})
else -> MinimalButtonShit(submitButtonTitle, submitButtonLevel,
freakingServant {serve()})
})
.addCloseModalButton(cancelButtonTitle)
}
}
}
fun serve() {
val fs = useFields(makeFields(), FieldSource.Post())
fun notFuckingOk(problems: Problems) {
val currentModalContentDomid = modalContentDomid
val newMWS = _modalWithScripts(fs, problems)
btfEval(jsReplaceElement(currentModalContentDomid,
newMWS.shit.modalContent,
newMWS.context.onDomReadyPlusOnShown()))
btfEval(jsScrollModalToTop())
}
if (anyFieldErrors(fs)) {
notFuckingOk(Problems(errors = true))
} else {
try {
serveGivenValidFields(fs)
} catch (mac: MidAirCollision) {
if (mac.midAirComparisonPageHref != null)
notFuckingOk(Problems(midAirComparisonPageHref = mac.midAirComparisonPageHref))
else
throw mac
} catch (e: ShitRemovedCollision) {
notFuckingOk(Problems(shitRemoved = true))
}
}
}
}
| apache-2.0 | 6df1038d3350c085d7459362196028cd | 37.855856 | 123 | 0.571528 | 5.165269 | false | false | false | false |
jwren/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/QuickPopupsLesson.kt | 5 | 2310 | // 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 training.learn.lesson.general.assistance
import com.intellij.codeInsight.documentation.QuickDocUtil
import com.intellij.codeInsight.hint.ImplementationViewComponent
import org.assertj.swing.timing.Timeout
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.ui.LearningUiUtil
import java.util.concurrent.TimeUnit
class QuickPopupsLesson(private val sample: LessonSample) :
KLesson("CodeAssistance.QuickPopups", LessonsBundle.message("quick.popups.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
task("QuickJavaDoc") {
text(LessonsBundle.message("quick.popups.show.documentation", action(it)))
triggerOnQuickDocumentationPopup()
restoreIfModifiedOrMoved(sample)
test { actions(it) }
}
task {
text(LessonsBundle.message("quick.popups.press.escape", action("EditorEscape")))
stateCheck { previous.ui?.isShowing != true }
restoreIfModifiedOrMoved()
test {
invokeActionViaShortcut("ESCAPE")
}
}
task("QuickImplementations") {
text(LessonsBundle.message("quick.popups.show.implementation", action(it)))
triggerUI().component { _: ImplementationViewComponent -> true }
restoreIfModifiedOrMoved()
test {
actions(it)
val delay = Timeout.timeout(3, TimeUnit.SECONDS)
LearningUiUtil.findShowingComponentWithTimeout(project, ImplementationViewComponent::class.java, delay)
Thread.sleep(500)
invokeActionViaShortcut("ESCAPE")
}
}
}
private fun TaskRuntimeContext.checkDocComponentClosed(): Boolean {
val activeDocComponent = QuickDocUtil.getActiveDocComponent(project)
return activeDocComponent == null || !activeDocComponent.isShowing
}
override val suitableTips = listOf("CtrlShiftIForLookup", "CtrlShiftI", "QuickJavaDoc")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("quick.popups.help.link"),
LessonUtil.getHelpLink("using-code-editor.html#quick_popups")),
)
} | apache-2.0 | a68608e5709e89d50bbfbbbd723c7ce1 | 36.885246 | 140 | 0.739827 | 4.863158 | false | false | false | false |
JetBrains/kotlin-native | performance/ring/src/main/kotlin/org/jetbrains/ring/EulerBenchmark.kt | 4 | 7010 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
fun fibonacci(): Sequence<Int> {
var a = 0
var b = 1
fun next(): Int {
val res = a + b
a = b
b = res
return res
}
return generateSequence { next() }
}
fun Any.isPalindrome() = toString() == toString().reversed()
inline fun IntRange.sum(predicate: (Int) -> Boolean): Int {
var sum = 0
for (i in this) if (predicate(i)) sum += i
return sum
}
inline fun Sequence<Int>.sum(predicate: (Int) -> Boolean): Int {
var sum = 0
for (i in this) if (predicate(i)) sum += i
return sum
}
/**
* A class tests decisions of various Euler problems
*
* NB: all tests here work slower than Java, probably because of all these functional wrappers
*/
open class EulerBenchmark {
//Benchmark
fun problem1bySequence() = (1..BENCHMARK_SIZE).asSequence().sum( { it % 3 == 0 || it % 5 == 0} )
//Benchmark
fun problem1() = (1..BENCHMARK_SIZE).sum( { it % 3 == 0 || it % 5 == 0} )
//Benchmark
fun problem2() = fibonacci().takeWhile { it < BENCHMARK_SIZE }.sum { it % 2 == 0 }
//Benchmark
fun problem4(): Long {
val s: Long = BENCHMARK_SIZE.toLong()
val maxLimit = (s-1)*(s-1)
val minLimit = (s/10)*(s/10)
val maxDiv = BENCHMARK_SIZE-1
val minDiv = BENCHMARK_SIZE/10
for (i in maxLimit downTo minLimit) {
if (!i.isPalindrome()) continue;
for (j in minDiv..maxDiv) {
if (i % j == 0L) {
val res = i / j
if (res in minDiv.toLong()..maxDiv.toLong()) {
return i
}
}
}
}
return -1
}
private val veryLongNumber = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
"""
//Benchmark
fun problem8(): Long {
val productSize = when(BENCHMARK_SIZE) {
in 1..10 -> 4
in 11..1000 -> 8
else -> 13
}
val digits: MutableList<Int> = ArrayList()
for (digit in veryLongNumber) {
if (digit in '0'..'9') {
digits.add(digit.toInt() - '0'.toInt())
}
}
var largest = 0L
for (i in 0..digits.size -productSize-1) {
var product = 1L
for (j in 0..productSize-1) {
product *= digits[i+j]
}
if (product > largest) largest = product
}
return largest
}
//Benchmark
fun problem9(): Long {
val BENCHMARK_SIZE = BENCHMARK_SIZE // Looks awful but removes all implicit getSize() calls
for (c in BENCHMARK_SIZE/3..BENCHMARK_SIZE-3) {
val c2 = c.toLong() * c.toLong()
for (b in (BENCHMARK_SIZE-c)/2..c-1) {
if (b+c >= BENCHMARK_SIZE)
break
val a = BENCHMARK_SIZE - b - c
if (a >= b)
continue
val b2 = b.toLong() * b.toLong()
val a2 = a.toLong() * a.toLong()
if (c2 == b2 + a2) {
return a.toLong() * b.toLong() * c.toLong()
}
}
}
return -1L
}
data class Children(val left: Int, val right: Int)
//Benchmark
fun problem14(): List<Int> {
// Simplified problem is solved here: it's not allowed to leave the interval [0..BENCHMARK_SIZE) inside a number chain
val BENCHMARK_SIZE = BENCHMARK_SIZE
// Build a tree
// index is produced from first & second
val tree = Array(BENCHMARK_SIZE, { i -> Children(i*2, if (i>4 && (i+2) % 6 == 0) (i-1)/3 else 0)})
// Find longest chain by DFS
fun dfs(begin: Int): List<Int> {
if (begin == 0 || begin >= BENCHMARK_SIZE)
return listOf()
val left = dfs(tree[begin].left)
val right = dfs(tree[begin].right)
return listOf(begin) + if (left.size > right.size) left else right
}
return dfs(1)
}
data class Way(val length: Int, val next: Int)
//Benchmark
fun problem14full(): List<Int> {
val BENCHMARK_SIZE = BENCHMARK_SIZE
// Previous achievements: map (number) -> (length, next)
val map: MutableMap<Int, Way> = HashMap()
// Starting point
map.put(1, Way(0, 0))
// Check all other numbers
var bestNum = 0
var bestLen = 0
fun go(begin: Int): Way {
val res = map[begin]
if (res != null)
return res
val next = if (begin % 2 == 0) begin/2 else 3*begin+1
val childRes = go(next)
val myRes = Way(childRes.length + 1, next)
map[begin] = myRes
return myRes
}
for (i in 2..BENCHMARK_SIZE-1) {
val res = go(i)
if (res.length > bestLen) {
bestLen = res.length
bestNum = i
}
}
fun unroll(begin: Int): List<Int> {
if (begin == 0)
return listOf()
val next = map[begin]?.next ?: 0
return listOf(begin) + unroll(next)
}
return unroll(bestNum)
}
}
| apache-2.0 | 13972e9957796a49a80760dcb0338bc2 | 32.380952 | 126 | 0.570471 | 3.714891 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ArtifactsOrderEntityImpl.kt | 2 | 7972 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactsOrderEntityImpl(val dataSource: ArtifactsOrderEntityData) : ArtifactsOrderEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val orderOfArtifacts: List<String>
get() = dataSource.orderOfArtifacts
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ArtifactsOrderEntityData?) : ModifiableWorkspaceEntityBase<ArtifactsOrderEntity, ArtifactsOrderEntityData>(
result), ArtifactsOrderEntity.Builder {
constructor() : this(ArtifactsOrderEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactsOrderEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isOrderOfArtifactsInitialized()) {
error("Field ArtifactsOrderEntity#orderOfArtifacts should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override fun afterModification() {
val collection_orderOfArtifacts = getEntityData().orderOfArtifacts
if (collection_orderOfArtifacts is MutableWorkspaceList<*>) {
collection_orderOfArtifacts.cleanModificationUpdateAction()
}
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ArtifactsOrderEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.orderOfArtifacts != dataSource.orderOfArtifacts) this.orderOfArtifacts = dataSource.orderOfArtifacts.toMutableList()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
private val orderOfArtifactsUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("orderOfArtifacts")
}
override var orderOfArtifacts: MutableList<String>
get() {
val collection_orderOfArtifacts = getEntityData().orderOfArtifacts
if (collection_orderOfArtifacts !is MutableWorkspaceList) return collection_orderOfArtifacts
if (diff == null || modifiable.get()) {
collection_orderOfArtifacts.setModificationUpdateAction(orderOfArtifactsUpdater)
}
else {
collection_orderOfArtifacts.cleanModificationUpdateAction()
}
return collection_orderOfArtifacts
}
set(value) {
checkModificationAllowed()
getEntityData(true).orderOfArtifacts = value
orderOfArtifactsUpdater.invoke(value)
}
override fun getEntityClass(): Class<ArtifactsOrderEntity> = ArtifactsOrderEntity::class.java
}
}
class ArtifactsOrderEntityData : WorkspaceEntityData<ArtifactsOrderEntity>() {
lateinit var orderOfArtifacts: MutableList<String>
fun isOrderOfArtifactsInitialized(): Boolean = ::orderOfArtifacts.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ArtifactsOrderEntity> {
val modifiable = ArtifactsOrderEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactsOrderEntity {
return getCached(snapshot) {
val entity = ArtifactsOrderEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): ArtifactsOrderEntityData {
val clonedEntity = super.clone()
clonedEntity as ArtifactsOrderEntityData
clonedEntity.orderOfArtifacts = clonedEntity.orderOfArtifacts.toMutableWorkspaceList()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactsOrderEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ArtifactsOrderEntity(orderOfArtifacts, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ArtifactsOrderEntityData
if (this.entitySource != other.entitySource) return false
if (this.orderOfArtifacts != other.orderOfArtifacts) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ArtifactsOrderEntityData
if (this.orderOfArtifacts != other.orderOfArtifacts) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + orderOfArtifacts.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + orderOfArtifacts.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.orderOfArtifacts?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | 8eae3d037f3aff72b7fafebd14938f12 | 34.431111 | 131 | 0.743979 | 5.669986 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/newProject/steps/PyAddExistingSdkPanel.kt | 2 | 8331 | // 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.jetbrains.python.newProject.steps
import com.intellij.execution.ExecutionException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PathMappingSettings
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.UIUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PySdkBundle
import com.jetbrains.python.Result
import com.jetbrains.python.remote.PyProjectSynchronizer
import com.jetbrains.python.remote.PyProjectSynchronizerProvider
import com.jetbrains.python.remote.PythonSshInterpreterManager
import com.jetbrains.python.sdk.PythonSdkUtil
import com.jetbrains.python.sdk.add.PyAddSdkPanel
import com.jetbrains.python.sdk.associatedModulePath
import com.jetbrains.python.sdk.sdkSeemsValid
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.JComboBox
import javax.swing.JComponent
/**
* @author vlan
*/
class PyAddExistingSdkPanel(project: Project?,
module: Module?,
existingSdks: List<Sdk>,
newProjectPath: String?,
preferredSdk: Sdk?) : PyAddSdkPanel() {
override val panelName: String get() = PyBundle.message("python.add.sdk.panel.name.previously.configured.interpreter")
/**
* Path mappings of current synchronizer.
* Once set, [remotePathField] will be updated on any change of local path passed through mappings
*/
private var defaultMappings: List<PathMappingSettings.PathMapping>? = null
override val sdk: Sdk?
get() = sdkComboBox.selectedItem as? Sdk
/**
* Either a [ComboBox] with "Add Interpreter" link component for targets-based UI or a combobox of the legacy [PythonSdkChooserCombo].
*
* The rollback to the latter option is possible by switching off *python.use.targets.api* registry key.
*/
private val sdkComboBox: JComboBox<*>
private val addSdkChangedListener: (Runnable) -> Unit
val remotePath: String?
get() = if (remotePathField.mainPanel.isVisible) remotePathField.textField.text else null
override var newProjectPath: String? = newProjectPath
set(value) {
field = value
updateRemotePathIfNeeded()
}
private val remotePathField = PyRemotePathField().apply {
addActionListener {
val currentSdk = sdk ?: return@addActionListener
if (!PythonSdkUtil.isRemote(currentSdk)) return@addActionListener
textField.text = currentSdk.chooseRemotePath(parent) ?: return@addActionListener
}
}
init {
layout = BorderLayout()
val sdksForNewProject = existingSdks.filter { it.associatedModulePath == null }
val interpreterComponent: JComponent
if (Registry.`is`("python.use.targets.api")) {
val preselectedSdk = sdksForNewProject.firstOrNull { it == preferredSdk }
val pythonSdkComboBox = createPythonSdkComboBox(sdksForNewProject, preselectedSdk)
pythonSdkComboBox.addActionListener { update() }
interpreterComponent = pythonSdkComboBox.withAddInterpreterLink(project, module)
sdkComboBox = pythonSdkComboBox
addSdkChangedListener = { runnable ->
sdkComboBox.addActionListener { runnable.run() }
}
}
else {
val legacySdkChooser = PythonSdkChooserCombo(project, module,
sdksForNewProject) {
it != null && it == preferredSdk
}.apply {
if (SystemInfo.isMac && !UIUtil.isUnderDarcula()) {
putClientProperty("JButton.buttonType", null)
}
addChangedListener {
update()
}
}
interpreterComponent = legacySdkChooser
sdkComboBox = legacySdkChooser.comboBox
addSdkChangedListener = { runnable ->
legacySdkChooser.addChangedListener { runnable.run() }
}
}
val formPanel = FormBuilder.createFormBuilder()
.addLabeledComponent(PySdkBundle.message("python.interpreter.label"), interpreterComponent)
.addComponent(remotePathField.mainPanel)
.panel
add(formPanel, BorderLayout.NORTH)
update()
}
override fun validateAll(): List<ValidationInfo> =
listOf(validateSdkChooserField(),
validateRemotePathField())
.filterNotNull()
override fun addChangeListener(listener: Runnable) {
addSdkChangedListener(listener)
remotePathField.addTextChangeListener { listener.run() }
}
private fun validateSdkChooserField(): ValidationInfo? {
val selectedSdk = sdk
val message = when {
selectedSdk == null -> PyBundle.message("python.sdk.no.interpreter.selection")
! selectedSdk.sdkSeemsValid -> PyBundle.message("python.sdk.choose.valid.interpreter")
else -> return null
}
return ValidationInfo(message, sdkComboBox)
}
private fun validateRemotePathField(): ValidationInfo? {
val path = remotePath
return when {
path != null && path.isBlank() -> ValidationInfo(PyBundle.message("python.new.project.remote.path.not.provided"))
else -> null
}
}
private fun update() {
val synchronizer = sdk?.projectSynchronizer
remotePathField.mainPanel.isVisible = synchronizer != null
if (synchronizer != null) {
val defaultRemotePath = synchronizer.getDefaultRemotePath()
synchronizer.getAutoMappings()?.let {
when (it) {
is Result.Success -> defaultMappings = it.result
is Result.Failure -> {
remotePathField.textField.text = it.error
remotePathField.setReadOnly(true)
return
}
}
}
assert(defaultRemotePath == null || defaultMappings == null) { "Can't have both: default mappings and default value" }
assert(!(defaultRemotePath?.isEmpty() ?: false)) { "Mappings are empty" }
val textField = remotePathField.textField
if (defaultRemotePath != null && StringUtil.isEmpty(textField.text)) {
textField.text = defaultRemotePath
}
}
// DefaultMappings revokes user ability to change mapping by her self, so field is readonly
remotePathField.setReadOnly(defaultMappings != null)
updateRemotePathIfNeeded()
}
/**
* Remote path should be updated automatically if [defaultMappings] are set.
* See [PyProjectSynchronizer.getAutoMappings].
*/
private fun updateRemotePathIfNeeded() {
val path = newProjectPath ?: return
val mappings = defaultMappings ?: return
remotePathField.textField.text = mappings.find { it.canReplaceLocal(path) }?.mapToRemote(path) ?: "?"
}
companion object {
private val Sdk.projectSynchronizer: PyProjectSynchronizer?
get() = PyProjectSynchronizerProvider.getSynchronizer(this)
private fun Sdk.chooseRemotePath(owner: Component): String? {
val remoteManager = PythonSshInterpreterManager.Factory.getInstance() ?: return null
val (supplier, panel) = try {
remoteManager.createServerBrowserForm(this) ?: return null
}
catch (e: Exception) {
when (e) {
is ExecutionException, is InterruptedException -> {
Logger.getInstance(PyAddExistingSdkPanel::class.java).warn("Failed to create server browse button", e)
JBPopupFactory.getInstance()
.createMessage(PyBundle.message("remote.interpreter.remote.server.permissions"))
.show(owner)
return null
}
else -> throw e
}
}
panel.isVisible = true
val wrapper = object : DialogWrapper(true) {
init {
init()
}
override fun createCenterPanel() = panel
}
return if (wrapper.showAndGet()) supplier.get() else null
}
}
}
| apache-2.0 | 552e8897178ec097c7a22345868fac60 | 36.696833 | 140 | 0.702077 | 4.852068 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/types/typesUtils.kt | 1 | 10710 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.types
import com.intellij.psi.*
import com.intellij.psi.impl.compiled.ClsMethodImpl
import com.intellij.psi.impl.source.PsiAnnotationMethodImpl
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.utils.fqname.fqName
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.util.getParameterDescriptor
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.j2k.ast.Nullability
import org.jetbrains.kotlin.j2k.ast.Nullability.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.nj2k.JKSymbolProvider
import org.jetbrains.kotlin.nj2k.symbols.JKClassSymbol
import org.jetbrains.kotlin.nj2k.symbols.JKMethodSymbol
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.JKVarianceTypeParameterType.Variance
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
fun JKType.asTypeElement(annotationList: JKAnnotationList = JKAnnotationList()) =
JKTypeElement(this, annotationList)
fun JKClassSymbol.asType(nullability: Nullability = Default): JKClassType =
JKClassType(this, emptyList(), nullability)
val PsiType.isKotlinFunctionalType: Boolean
get() {
val fqName = safeAs<PsiClassType>()?.resolve()?.kotlinFqName ?: return false
return functionalTypeRegex.matches(fqName.asString())
}
fun PsiParameter.typeFqName(): FqName? = this.getParameterDescriptor()?.type?.fqName
fun KtParameter.typeFqName(): FqName? = this.descriptor?.type?.fqName
private val functionalTypeRegex = """(kotlin\.jvm\.functions|kotlin)\.Function[\d+]""".toRegex()
fun KtTypeReference.toJK(typeFactory: JKTypeFactory): JKType? =
analyze(BodyResolveMode.PARTIAL)
.get(BindingContext.TYPE, this)
?.let { typeFactory.fromKotlinType(it) }
infix fun JKJavaPrimitiveType.isStrongerThan(other: JKJavaPrimitiveType) =
jvmPrimitiveTypesPriority.getValue(this.jvmPrimitiveType.primitiveType) >
jvmPrimitiveTypesPriority.getValue(other.jvmPrimitiveType.primitiveType)
private val jvmPrimitiveTypesPriority =
mapOf(
PrimitiveType.BOOLEAN to -1,
PrimitiveType.CHAR to 0,
PrimitiveType.BYTE to 1,
PrimitiveType.SHORT to 2,
PrimitiveType.INT to 3,
PrimitiveType.LONG to 4,
PrimitiveType.FLOAT to 5,
PrimitiveType.DOUBLE to 6
)
fun JKType.applyRecursive(transform: (JKType) -> JKType?): JKType =
transform(this) ?: when (this) {
is JKTypeParameterType -> this
is JKClassType ->
JKClassType(
classReference,
parameters.map { it.applyRecursive(transform) },
nullability
)
is JKNoType -> this
is JKJavaVoidType -> this
is JKJavaPrimitiveType -> this
is JKJavaArrayType -> JKJavaArrayType(type.applyRecursive(transform), nullability)
is JKContextType -> JKContextType
is JKJavaDisjunctionType ->
JKJavaDisjunctionType(disjunctions.map { it.applyRecursive(transform) }, nullability)
is JKStarProjectionType -> this
else -> this
}
inline fun <reified T : JKType> T.updateNullability(newNullability: Nullability): T =
if (nullability == newNullability) this
else when (this) {
is JKTypeParameterType -> JKTypeParameterType(identifier, newNullability)
is JKClassType -> JKClassType(classReference, parameters, newNullability)
is JKNoType -> this
is JKJavaVoidType -> this
is JKJavaPrimitiveType -> this
is JKJavaArrayType -> JKJavaArrayType(type, newNullability)
is JKContextType -> JKContextType
is JKJavaDisjunctionType -> this
else -> this
} as T
@Suppress("UNCHECKED_CAST")
fun <T : JKType> T.updateNullabilityRecursively(newNullability: Nullability): T =
applyRecursive { type ->
when (type) {
is JKTypeParameterType -> JKTypeParameterType(type.identifier, newNullability)
is JKClassType ->
JKClassType(
type.classReference,
type.parameters.map { it.updateNullabilityRecursively(newNullability) },
newNullability
)
is JKJavaArrayType -> JKJavaArrayType(type.type.updateNullabilityRecursively(newNullability), newNullability)
else -> null
}
} as T
fun JKType.isStringType(): Boolean =
(this as? JKClassType)?.classReference?.isStringType() == true
fun JKClassSymbol.isStringType(): Boolean =
fqName == CommonClassNames.JAVA_LANG_STRING
|| fqName == StandardNames.FqNames.string.asString()
fun JKJavaPrimitiveType.toLiteralType(): JKLiteralExpression.LiteralType? =
when (this) {
JKJavaPrimitiveType.CHAR -> JKLiteralExpression.LiteralType.CHAR
JKJavaPrimitiveType.BOOLEAN -> JKLiteralExpression.LiteralType.BOOLEAN
JKJavaPrimitiveType.INT -> JKLiteralExpression.LiteralType.INT
JKJavaPrimitiveType.LONG -> JKLiteralExpression.LiteralType.LONG
JKJavaPrimitiveType.DOUBLE -> JKLiteralExpression.LiteralType.DOUBLE
JKJavaPrimitiveType.FLOAT -> JKLiteralExpression.LiteralType.FLOAT
else -> null
}
fun JKType.asPrimitiveType(): JKJavaPrimitiveType? =
if (this is JKJavaPrimitiveType) this
else when (fqName) {
StandardNames.FqNames._char.asString(), CommonClassNames.JAVA_LANG_CHARACTER -> JKJavaPrimitiveType.CHAR
StandardNames.FqNames._boolean.asString(), CommonClassNames.JAVA_LANG_BOOLEAN -> JKJavaPrimitiveType.BOOLEAN
StandardNames.FqNames._int.asString(), CommonClassNames.JAVA_LANG_INTEGER -> JKJavaPrimitiveType.INT
StandardNames.FqNames._long.asString(), CommonClassNames.JAVA_LANG_LONG -> JKJavaPrimitiveType.LONG
StandardNames.FqNames._float.asString(), CommonClassNames.JAVA_LANG_FLOAT -> JKJavaPrimitiveType.FLOAT
StandardNames.FqNames._double.asString(), CommonClassNames.JAVA_LANG_DOUBLE -> JKJavaPrimitiveType.DOUBLE
StandardNames.FqNames._byte.asString(), CommonClassNames.JAVA_LANG_BYTE -> JKJavaPrimitiveType.BYTE
StandardNames.FqNames._short.asString(), CommonClassNames.JAVA_LANG_SHORT -> JKJavaPrimitiveType.SHORT
else -> null
}
fun JKJavaPrimitiveType.isNumberType() =
this == JKJavaPrimitiveType.INT ||
this == JKJavaPrimitiveType.LONG ||
this == JKJavaPrimitiveType.FLOAT ||
this == JKJavaPrimitiveType.DOUBLE
fun JKJavaPrimitiveType.kotlinName() =
jvmPrimitiveType.javaKeywordName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.US) else it.toString() }
val primitiveTypes =
listOf(
JvmPrimitiveType.BOOLEAN,
JvmPrimitiveType.CHAR,
JvmPrimitiveType.BYTE,
JvmPrimitiveType.SHORT,
JvmPrimitiveType.INT,
JvmPrimitiveType.FLOAT,
JvmPrimitiveType.LONG,
JvmPrimitiveType.DOUBLE
)
fun JKType.arrayFqName(): String =
if (this is JKJavaPrimitiveType)
PrimitiveType.valueOf(jvmPrimitiveType.name).arrayTypeFqName.asString()
else StandardNames.FqNames.array.asString()
fun JKClassSymbol.isArrayType(): Boolean =
fqName in arrayFqNames
private val arrayFqNames = buildList {
JKJavaPrimitiveType.ALL.mapTo(this) { PrimitiveType.valueOf(it.jvmPrimitiveType.name).arrayTypeFqName.asString() }
add(StandardNames.FqNames.array.asString())
}
fun JKType.isArrayType() =
when (this) {
is JKClassType -> classReference.isArrayType()
is JKJavaArrayType -> true
else -> false
}
fun JKType.isUnit(): Boolean =
fqName == StandardNames.FqNames.unit.asString()
val JKType.isCollectionType: Boolean
get() = fqName in collectionFqNames
val JKType.fqName: String?
get() = safeAs<JKClassType>()?.classReference?.fqName
private val collectionFqNames = setOf(
StandardNames.FqNames.mutableIterator.asString(),
StandardNames.FqNames.mutableList.asString(),
StandardNames.FqNames.mutableCollection.asString(),
StandardNames.FqNames.mutableSet.asString(),
StandardNames.FqNames.mutableMap.asString(),
StandardNames.FqNames.mutableMapEntry.asString(),
StandardNames.FqNames.mutableListIterator.asString()
)
fun JKType.arrayInnerType(): JKType? =
when (this) {
is JKJavaArrayType -> type
is JKClassType ->
if (this.classReference.isArrayType()) this.parameters.singleOrNull()
else null
else -> null
}
fun JKMethodSymbol.isAnnotationMethod(): Boolean =
when (val target = target) {
is JKJavaAnnotationMethod, is PsiAnnotationMethodImpl -> true
is ClsMethodImpl -> target.containingClass?.isAnnotationType == true
else -> false
}
fun JKClassSymbol.isInterface(): Boolean {
return when (val target = target) {
is PsiClass -> target.isInterface
is KtClass -> target.isInterface()
is JKClass -> target.classKind == JKClass.ClassKind.INTERFACE
else -> false
}
}
fun JKType.isInterface(): Boolean =
(this as? JKClassType)?.classReference?.isInterface() ?: false
fun JKType.replaceJavaClassWithKotlinClassType(symbolProvider: JKSymbolProvider): JKType =
applyRecursive { type ->
if (type is JKClassType && type.classReference.fqName == "java.lang.Class") {
JKClassType(
symbolProvider.provideClassSymbol(StandardNames.FqNames.kClass.toSafe()),
type.parameters.map { it.replaceJavaClassWithKotlinClassType(symbolProvider) },
NotNull
)
} else null
}
fun JKLiteralExpression.isNull(): Boolean =
this.type == JKLiteralExpression.LiteralType.NULL
fun JKParameter.determineType(symbolProvider: JKSymbolProvider): JKType =
if (isVarArgs) {
val typeParameters =
if (type.type is JKJavaPrimitiveType) emptyList() else listOf(JKVarianceTypeParameterType(Variance.OUT, type.type))
JKClassType(symbolProvider.provideClassSymbol(type.type.arrayFqName()), typeParameters, NotNull)
} else type.type | apache-2.0 | 97916a835108880aa57102f91c0c3f45 | 39.418868 | 127 | 0.719795 | 5.051887 | false | false | false | false |
smmribeiro/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/AddModuleDirectiveTest.kt | 18 | 3635 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.codeInsight.daemon.quickFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddUsesDirectiveFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiJavaModule
class AddModuleDirectiveTest : LightJava9ModulesCodeInsightFixtureTestCase() {
fun testNewRequires() = doRequiresTest(
"module M { }",
"module M {\n" +
" requires M2;\n" +
"}")
fun testRequiresAfterOther() = doRequiresTest(
"module M {\n" +
" requires other;\n" +
"}",
"module M {\n" +
" requires other;\n" +
" requires M2;\n" +
"}")
fun testNoDuplicateRequires() = doRequiresTest(
"module M { requires M2; }",
"module M { requires M2; }")
fun testRequiresInIncompleteModule() = doRequiresTest(
"module M {",
"module M {\n" +
" requires M2;")
fun testNewExports() = doExportsTest(
"module M { }",
"module M {\n" +
" exports pkg.m;\n" +
"}")
fun testExportsAfterOther() = doExportsTest(
"module M {\n" +
" exports pkg.other;\n" +
"}",
"module M {\n" +
" exports pkg.other;\n" +
" exports pkg.m;\n" +
"}")
fun testNoNarrowingExports() = doExportsTest(
"module M { exports pkg.m; }",
"module M { exports pkg.m; }")
fun testNoDuplicateExports() = doExportsTest(
"module M { exports pkg.m to M1, M2; }",
"module M { exports pkg.m to M1, M2; }")
fun testNoExportsToUnnamed() = doExportsTest(
"module M { exports pkg.m to M1; }",
"module M { exports pkg.m to M1; }",
target = "")
fun testExportsExtendsOther() = doExportsTest(
"module M {\n" +
" exports pkg.m to M1;\n" +
"}",
"module M {\n" +
" exports pkg.m to M1, M2;\n" +
"}")
fun testExportsExtendsIncompleteOther() = doExportsTest(
"module M {\n" +
" exports pkg.m to M1\n" +
"}",
"module M {\n" +
" exports pkg.m to M1, M2\n" +
"}")
fun testNewUses() = doUsesTest(
"module M { }",
"module M {\n" +
" uses pkg.m.C;\n" +
"}")
fun testUsesAfterOther() = doUsesTest(
"module M {\n" +
" uses pkg.m.B;\n" +
"}",
"module M {\n" +
" uses pkg.m.B;\n" +
" uses pkg.m.C;\n" +
"}")
fun testNoDuplicateUses() = doUsesTest(
"module M { uses pkg.m.C; }",
"module M { uses pkg.m.C; }")
private fun doRequiresTest(text: String, expected: String) = doTest(text, { AddRequiresDirectiveFix(it, "M2") }, expected)
private fun doExportsTest(text: String, expected: String, target: String = "M2") = doTest(text, { AddExportsDirectiveFix(it, "pkg.m", target) }, expected)
private fun doUsesTest(text: String, expected: String) = doTest(text, { AddUsesDirectiveFix(it, "pkg.m.C") }, expected)
private fun doTest(text: String, fix: (PsiJavaModule) -> IntentionAction, expected: String) {
val file = myFixture.configureByText("module-info.java", text) as PsiJavaFile
val action = fix(file.moduleDeclaration!!)
WriteCommandAction.writeCommandAction(file).run<RuntimeException> { action.invoke(project, editor, file) }
assertEquals(expected, file.text)
}
} | apache-2.0 | 5ab73cfa85e2465dddcba58f6b520d07 | 31.756757 | 156 | 0.641265 | 3.624128 | false | true | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/browser/ChangesFilterer.kt | 1 | 11232 | // 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 com.intellij.openapi.vcs.changes.ui.browser
import com.intellij.diff.DiffContentFactory
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.trimExpandText
import com.intellij.diff.lang.DiffIgnoredRangeProvider
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.ByteBackedContentRevision
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ui.ChangesComparator
import com.intellij.util.ModalityUiUtil
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.update.DisposableUpdate
import com.intellij.util.ui.update.MergingUpdateQueue
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NotNull
class ChangesFilterer(val project: Project?, val listener: Listener) : Disposable {
companion object {
@JvmField
val DATA_KEY: DataKey<ChangesFilterer> = DataKey.create("com.intellij.openapi.vcs.changes.ui.browser.ChangesFilterer")
}
private val LOCK = Any()
private val updateQueue = MergingUpdateQueue("ChangesFilterer", 300, true, MergingUpdateQueue.ANY_COMPONENT, this)
private var progressIndicator: ProgressIndicator = EmptyProgressIndicator()
private var rawChanges: List<Change>? = null
private var activeFilter: Filter? = null
private var processedChanges: List<Change>? = null
private var pendingChanges: List<Change>? = null
private var filteredOutChanges: List<Change>? = null
override fun dispose() {
resetFilter()
}
@RequiresEdt
fun setChanges(changes: List<Change>?) {
val oldChanges = rawChanges
if (oldChanges == null && changes == null) return
if (oldChanges != null && changes != null && ContainerUtil.equalsIdentity(oldChanges, changes)) return
rawChanges = changes?.toList()
if (activeFilter != null) {
restartLoading()
}
}
@RequiresEdt
fun getFilteredChanges(): FilteredState {
synchronized(LOCK) {
val processed = processedChanges
val pending = pendingChanges
val filteredOut = filteredOutChanges
return when {
processed != null && pending != null && filteredOut != null -> FilteredState.create(processed, pending, filteredOut)
else -> FilteredState.create(rawChanges ?: emptyList())
}
}
}
@RequiresEdt
fun getProgress(): Float {
val pendingCount = synchronized(LOCK) { pendingChanges?.size }
val totalCount = rawChanges?.size
if (pendingCount == null || totalCount == null || totalCount == 0) return 1.0f
return (1.0f - pendingCount.toFloat() / totalCount).coerceAtLeast(0.0f)
}
@NotNull
fun hasActiveFilter(): Boolean = activeFilter != null
fun clearFilter() = setFilter(null)
private fun setFilter(filter: Filter?) {
activeFilter = filter
restartLoading()
}
private fun restartLoading() {
val indicator = resetFilter()
val filter = activeFilter
val changesToFilter = rawChanges
if (filter == null || changesToFilter == null) {
updatePresentation()
return
}
val changes = changesToFilter.sortedWith(ChangesComparator.getInstance(false))
// Work around expensive removeAt(0) with double reversion
val pending = changes.asReversed().asSequence().map { Change(it.beforeRevision, it.afterRevision, FileStatus.OBSOLETE) }
.toMutableList().asReversed()
val processed = mutableListOf<Change>()
val filteredOut = mutableListOf<Change>()
synchronized(LOCK) {
processedChanges = processed
pendingChanges = pending
filteredOutChanges = filteredOut
}
updatePresentation()
ApplicationManager.getApplication().executeOnPooledThread {
ProgressManager.getInstance().runProcess(
{ filterChanges(changes, filter, pending, processed, filteredOut) },
indicator)
}
}
private fun filterChanges(changes: List<Change>,
filter: Filter,
pending: MutableList<Change>,
processed: MutableList<Change>,
filteredOut: MutableList<Change>) {
queueUpdatePresentation()
val filteredChanges = filter.acceptBulk(this, changes)
if (filteredChanges != null) {
synchronized(LOCK) {
ProgressManager.checkCanceled()
pending.clear()
processed.addAll(filteredChanges)
val filteredOutSet = changes.toMutableSet()
filteredOutSet.removeAll(filteredChanges)
filteredOut.addAll(filteredOutSet)
}
updatePresentation()
return
}
for (change in changes) {
ProgressManager.checkCanceled()
val accept = filter.accept(this, change)
synchronized(LOCK) {
ProgressManager.checkCanceled()
pending.removeAt(0)
if (accept) {
processed.add(change)
}
else {
filteredOut.add(change)
}
}
queueUpdatePresentation()
}
updatePresentation()
}
private fun queueUpdatePresentation() {
updateQueue.queue(DisposableUpdate.createDisposable(updateQueue, "update") {
updatePresentation()
})
}
private fun updatePresentation() {
ModalityUiUtil.invokeLaterIfNeeded(
ModalityState.any()) {
updateQueue.cancelAllUpdates()
listener.updateChanges()
}
}
private fun resetFilter(): ProgressIndicator {
synchronized(LOCK) {
processedChanges = null
pendingChanges = null
filteredOutChanges = null
progressIndicator.cancel()
progressIndicator = EmptyProgressIndicator()
return progressIndicator
}
}
private interface Filter {
fun isAvailable(filterer: ChangesFilterer): Boolean = true
fun accept(filterer: ChangesFilterer, change: Change): Boolean
fun acceptBulk(filterer: ChangesFilterer, changes: List<Change>): Collection<Change>? = null
@Nls
fun getText(): String
@Nls
fun getDescription(): String? = null
}
private object MovesOnlyFilter : Filter {
override fun getText(): String = VcsBundle.message("action.filter.moved.files.text")
override fun acceptBulk(filterer: ChangesFilterer, changes: List<Change>): Collection<Change>? {
for (epFilter in BulkMovesOnlyChangesFilter.EP_NAME.extensionList) {
val filteredChanges = epFilter.filter(filterer.project, changes)
if (filteredChanges != null) {
return filteredChanges
}
}
return null
}
override fun accept(filterer: ChangesFilterer, change: Change): Boolean {
val bRev = change.beforeRevision ?: return true
val aRev = change.afterRevision ?: return true
if (bRev.file == aRev.file) return true
if (bRev is ByteBackedContentRevision && aRev is ByteBackedContentRevision) {
val bytes1 = bRev.contentAsBytes ?: return true
val bytes2 = aRev.contentAsBytes ?: return true
return !bytes1.contentEquals(bytes2)
}
else {
val content1 = bRev.content ?: return true
val content2 = aRev.content ?: return true
return content1 != content2
}
}
}
private object NonImportantFilter : Filter {
override fun getText(): String = VcsBundle.message("action.filter.non.important.files.text")
override fun isAvailable(filterer: ChangesFilterer): Boolean = filterer.project != null
override fun accept(filterer: ChangesFilterer, change: Change): Boolean {
val project = filterer.project
val bRev = change.beforeRevision ?: return true
val aRev = change.afterRevision ?: return true
val content1 = bRev.content ?: return true
val content2 = aRev.content ?: return true
val diffContent1 = DiffContentFactory.getInstance().create(project, content1, bRev.file)
val diffContent2 = DiffContentFactory.getInstance().create(project, content2, aRev.file)
val provider = DiffIgnoredRangeProvider.EP_NAME.extensions.find {
it.accepts(project, diffContent1) &&
it.accepts(project, diffContent2)
}
if (provider == null) return content1 != content2
val ignoredRanges1 = provider.getIgnoredRanges(project, content1, diffContent1)
val ignoredRanges2 = provider.getIgnoredRanges(project, content2, diffContent2)
val ignored1 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges1)
val ignored2 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges2)
val range = trimExpandText(content1, content2, 0, 0, content1.length, content2.length, ignored1, ignored2)
return !range.isEmpty
}
}
interface Listener {
fun updateChanges()
}
class FilteredState private constructor(val changes: List<Change>, val pending: List<Change>, val filteredOut: List<Change>) {
companion object {
@JvmStatic
fun create(changes: List<Change>): FilteredState = create(changes, emptyList(), emptyList())
fun create(changes: List<Change>, pending: List<Change>, filteredOut: List<Change>): FilteredState =
FilteredState(changes.toList(), pending.toList(), filteredOut.toList())
}
}
class FilterGroup : DefaultActionGroup(), Toggleable, DumbAware {
init {
isPopup = true
templatePresentation.text = VcsBundle.message("action.filter.filter.by.text")
templatePresentation.icon = AllIcons.General.Filter
}
override fun update(e: AnActionEvent) {
val filterer = e.getData(DATA_KEY)
if (filterer == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = filterer.rawChanges != null
Toggleable.setSelected(e.presentation, filterer.activeFilter != null)
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
val filterer = e?.getData(DATA_KEY) ?: return AnAction.EMPTY_ARRAY
return listOf(MovesOnlyFilter, NonImportantFilter)
.filter { it.isAvailable(filterer) }
.map { ToggleFilterAction(filterer, it) }
.toTypedArray()
}
override fun disableIfNoVisibleChildren(): Boolean = false
}
private class ToggleFilterAction(val filterer: ChangesFilterer, val filter: Filter)
: ToggleAction(filter.getText(), filter.getDescription(), null), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean = filterer.activeFilter == filter
override fun setSelected(e: AnActionEvent, state: Boolean) {
filterer.setFilter(if (state) filter else null)
}
}
}
| apache-2.0 | 29da78eebab46ea3e2a494b3792cdb4e | 33.56 | 140 | 0.705751 | 4.824742 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/StringExtensions.kt | 1 | 651 | package ch.rmy.android.framework.extensions
import androidx.annotation.IntRange
import ch.rmy.android.framework.utils.localization.StaticLocalizable
fun String.truncate(@IntRange(from = 1) maxLength: Int) =
if (length > maxLength) substring(0, maxLength - 1) + "…" else this
fun String.replacePrefix(oldPrefix: String, newPrefix: String) =
runIf(startsWith(oldPrefix)) {
"$newPrefix${removePrefix(oldPrefix)}"
}
fun <T : CharSequence> T.takeUnlessEmpty(): T? =
takeUnless { it.isEmpty() }
fun ByteArray.toHexString() =
joinToString("") { "%02x".format(it) }
fun String.toLocalizable() =
StaticLocalizable(this)
| mit | 15f0c961c9e3b6f786236ebf0b300435 | 29.904762 | 71 | 0.716487 | 3.6875 | false | false | false | false |
alexstyl/Memento-Namedays | memento/src/main/java/com/alexstyl/specialdates/TimeOfDay.kt | 3 | 1175 | package com.alexstyl.specialdates
import org.joda.time.LocalTime
data class TimeOfDay(private val dateTime: LocalTime) {
constructor(hour: Int, minute: Int) : this(LocalTime(hour, minute))
val hours: Int
get() = dateTime.hourOfDay
val minutes: Int
get() = dateTime.minuteOfHour
override fun toString(): String {
val hour = hours
val str = StringBuilder()
if (isOneDigit(hour)) {
str.append(ZERO)
}
str.append(hour)
.append(SEPARATOR)
val minute = minutes
if (isOneDigit(minute)) {
str.append(ZERO)
}
str.append(minute)
return str.toString()
}
private fun isOneDigit(value: Int): Boolean {
return value < 10
}
fun toMillis(): Long {
return dateTime.millisOfDay.toLong()
}
fun isAfter(timeOfDay: TimeOfDay): Boolean {
return dateTime.isAfter(timeOfDay.dateTime)
}
companion object {
private const val ZERO = "0"
private const val SEPARATOR = ":"
fun now(): TimeOfDay {
return TimeOfDay(LocalTime.now())
}
}
}
| mit | 372d9b6b05ad584c646e1bf43e779412 | 21.596154 | 71 | 0.577021 | 4.53668 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/importwallet/PasswordController.kt | 1 | 4459 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 12/3/19.
* Copyright (c) 2019 breadwallet LLC
*
* 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.breadwallet.ui.importwallet
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import com.breadwallet.databinding.ControllerImportPasswordBinding
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.changehandlers.DialogChangeHandler
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.flowbind.editorActions
import com.breadwallet.ui.flowbind.textChanges
import com.breadwallet.ui.importwallet.PasswordController.E
import com.breadwallet.ui.importwallet.PasswordController.F
import com.breadwallet.ui.importwallet.PasswordController.M
import com.spotify.mobius.Next.dispatch
import com.spotify.mobius.Next.next
import com.spotify.mobius.Update
import drewcarlson.mobius.flow.subtypeEffectHandler
import dev.zacsweers.redacted.annotations.Redacted
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
class PasswordController(
args: Bundle? = null
) : BaseMobiusController<M, E, F>(args) {
init {
overridePopHandler(DialogChangeHandler())
overridePushHandler(DialogChangeHandler())
}
override val defaultModel = M.DEFAULT
override val update = Update<M, E, F> { model, event ->
when (event) {
is E.OnPasswordChanged -> next(model.copy(password = event.password))
E.OnConfirmClicked -> dispatch(setOf(F.Confirm(model.password)))
E.OnCancelClicked -> dispatch(setOf(F.Cancel))
}
}
override val flowEffectHandler
get() = subtypeEffectHandler<F, E> {
addConsumerSync(Main, ::handleConfirm)
addActionSync<F.Cancel>(Main, ::handleCancel)
}
private val binding by viewBinding(ControllerImportPasswordBinding::inflate)
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return with(binding) {
merge(
inputPassword.editorActions()
.filter { it == EditorInfo.IME_ACTION_DONE }
.map { E.OnConfirmClicked },
inputPassword.textChanges().map { E.OnPasswordChanged(it) },
buttonConfirm.clicks().map { E.OnConfirmClicked },
buttonCancel.clicks().map { E.OnCancelClicked }
)
}
}
private fun handleConfirm(effect: F.Confirm) {
findListener<Listener>()?.onPasswordConfirmed(effect.password)
router.popController(this)
}
private fun handleCancel() {
findListener<Listener>()?.onPasswordCancelled()
router.popController(this)
}
interface Listener {
fun onPasswordConfirmed(password: String)
fun onPasswordCancelled()
}
data class M(@Redacted val password: String = "") {
companion object {
val DEFAULT = M()
}
}
sealed class E {
data class OnPasswordChanged(
@Redacted val password: String
) : E()
object OnConfirmClicked : E()
object OnCancelClicked : E()
}
sealed class F {
data class Confirm(
@Redacted val password: String
) : F()
object Cancel : F()
}
}
| mit | cb1eb8dfbcf5ab1240966cea605093f3 | 35.252033 | 81 | 0.698587 | 4.587449 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/app/PrefPool.kt | 1 | 1061 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.ui.app
import android.content.Context
import android.content.SharedPreferences
internal object PrefPool {
private var pref: SharedPreferences? = null
private const val PREFERENCE_NAME = "main_preference"
fun getSharedPref(context: Context): SharedPreferences {
if (pref == null) {
pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
}
return pref!!
}
} | apache-2.0 | d448ef839616f9d92ba353f8587383a4 | 31.181818 | 86 | 0.721018 | 4.313008 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/plugins/RecyclerPicker/RecyclerPickerLayoutManager.kt | 1 | 3207 | package cx.ring.plugins.RecyclerPicker
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView.Recycler
class RecyclerPickerLayoutManager(
context: Context?,
orientation: Int,
reverseLayout: Boolean,
private val listener: ItemSelectedListener
) : LinearLayoutManager(context, orientation, reverseLayout) {
private var recyclerView: RecyclerView? = null
override fun onAttachedToWindow(view: RecyclerView) {
super.onAttachedToWindow(view)
recyclerView = view
// Smart snapping
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)
}
override fun onLayoutCompleted(state: RecyclerView.State) {
super.onLayoutCompleted(state)
scaleDownView()
}
override fun scrollHorizontallyBy(
dx: Int, recycler: Recycler,
state: RecyclerView.State
): Int {
val scrolled = super.scrollHorizontallyBy(dx, recycler, state)
return if (orientation == VERTICAL) {
0
} else {
scaleDownView()
scrolled
}
}
override fun onScrollStateChanged(state: Int) {
super.onScrollStateChanged(state)
// When scroll stops we notify on the selected item
if (state == RecyclerView.SCROLL_STATE_IDLE) {
// Find the closest child to the recyclerView center --> this is the selected item.
val recyclerViewCenterX = recyclerViewCenterX
var minDistance = recyclerView!!.width
var position = -1
for (i in 0 until recyclerView!!.childCount) {
val child = recyclerView!!.getChildAt(i)
val childCenterX = getDecoratedLeft(child) + (getDecoratedRight(child) - getDecoratedLeft(child)) / 2
val newDistance = Math.abs(childCenterX - recyclerViewCenterX)
if (newDistance < minDistance) {
minDistance = newDistance
position = recyclerView!!.getChildLayoutPosition(child)
}
}
listener.onItemSelected(position)
}
}
private val recyclerViewCenterX: Int
private get() = recyclerView!!.width / 2 + recyclerView!!.left
private fun scaleDownView() {
val mid = width / 2.0f
for (i in 0 until childCount) {
// Calculating the distance of the child from the center
val child = getChildAt(i)
val childMid = (getDecoratedLeft(child!!) + getDecoratedRight(child)) / 2.0f
val distanceFromCenter = Math.abs(mid - childMid)
// The scaling formula
var k = Math.sqrt((distanceFromCenter / width).toDouble()).toFloat()
k *= 1.5f
val scale = 1 - k * 0.66f
// Set scale to view
child.scaleX = scale
child.scaleY = scale
}
}
interface ItemSelectedListener {
fun onItemSelected(position: Int)
fun onItemClicked(position: Int)
}
} | gpl-3.0 | 8cecd20cac1b6890bf77d9eeade08e66 | 33.869565 | 117 | 0.631431 | 5.248773 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/kotlin/com/gmail/blueboxware/libgdxplugin/json/TestQuoteHandling.kt | 1 | 1958 | package com.gmail.blueboxware.libgdxplugin.json
import com.gmail.blueboxware.libgdxplugin.LibGDXCodeInsightFixtureTestCase
import com.gmail.blueboxware.libgdxplugin.filetypes.json.LibGDXJsonFileType
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
/*
* Copyright 2021 Blue Box Ware
*
* 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.
*/
class TestQuoteHandling : LibGDXCodeInsightFixtureTestCase() {
fun testDoubleQuote1() = doTest(
"<caret>",
"\"\""
)
fun testDoubleQuote2() = doTest(
"\"<caret>\"",
"\"\""
)
fun testDoubleQuoteAtEndOfUnquotedString() = doTest(
"[foo<caret>]",
"[foo\"]"
)
fun testSingleQuote() = doTest(
"<caret>",
"'",
'\''
)
fun testBackSpaceInQuotes() = doTest(
"\"<caret>\"",
"",
'\b'
)
fun testBackSpaceInQuotesInUnquotedString() = doTest(
"foo\"<caret>\"bar",
"foo\"bar",
'\b'
)
fun testDoubleQuoteInUnquotedString() = doTest(
"foo<caret>bar",
"foo\"bar"
)
fun doTest(source: String, expected: String, char: Char = '\"') {
myFixture.configureByText(LibGDXJsonFileType.INSTANCE, source)
if (char == '\b') {
LightPlatformCodeInsightTestCase.backspace(editor, project)
} else {
myFixture.type(char)
}
myFixture.checkResult(expected)
}
}
| apache-2.0 | 4d12e241012df1fa715ff5804f6a86fb | 25.459459 | 75 | 0.636364 | 4.511521 | false | true | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/assetsInCode/findUsages/FindUsagesWithTags2.kt | 1 | 620 | import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets
@GDXAssets(atlasFiles = arrayOf(""), skinFiles = ["src\\findUsages/findUsagesWithTags2.skin"])
val s: Skin = Skin()
object O {
@GDXAssets(atlasFiles = arrayOf(""), skinFiles = arrayOf("src\\findUsages\\findUsagesWithTags1.skin", "src/findUsages/findUsagesWithTags2.skin"))
val skin: Skin = Skin()
}
fun f() {
val c = s.get("toggle", TextButton.TextButtonStyle::class.java)
val d = O.skin.has("toggle", TextButton.TextButtonStyle::class.java)
} | apache-2.0 | d7dcef4a4088fc177dad509cb9bbbc06 | 37.8125 | 147 | 0.748387 | 3.522727 | false | false | false | false |
AdamMc331/CashCaretaker | app/src/main/java/com/androidessence/cashcaretaker/core/di/KoinViewModelModule.kt | 1 | 1277 | package com.androidessence.cashcaretaker.core.di
import com.androidessence.cashcaretaker.ui.accountlist.AccountListViewModel
import com.androidessence.cashcaretaker.ui.addaccount.AddAccountViewModel
import com.androidessence.cashcaretaker.ui.addtransaction.AddTransactionViewModel
import com.androidessence.cashcaretaker.ui.transactionlist.TransactionListViewModel
import com.androidessence.cashcaretaker.ui.transfer.AddTransferViewModel
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.dsl.module
val viewModelModule = module {
viewModel {
AccountListViewModel(
repository = get(),
analyticsTracker = get()
)
}
viewModel {
AddTransactionViewModel(
repository = get(),
analyticsTracker = get()
)
}
viewModel {
AddTransferViewModel(
repository = get(),
analyticsTracker = get()
)
}
viewModel {
AddAccountViewModel(
repository = get(),
analyticsTracker = get()
)
}
viewModel { (accountName: String) ->
TransactionListViewModel(
accountName = accountName,
repository = get(),
analyticsTracker = get()
)
}
}
| mit | ccd7712d69b1c0577d5d25c4d7ee5661 | 26.170213 | 83 | 0.653093 | 5.434043 | false | false | false | false |
jonnyzzz/TeamCity.Node | server/src/main/java/com/jonnyzzz/teamcity/plugins/node/server/BowerRunType.kt | 1 | 2994 | /*
* Copyright 2013-2017 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.server
import jetbrains.buildServer.requirements.Requirement
import jetbrains.buildServer.requirements.RequirementType
import jetbrains.buildServer.serverSide.PropertiesProcessor
import com.jonnyzzz.teamcity.plugins.node.common.BowerBean
import com.jonnyzzz.teamcity.plugins.node.common.NodeBean
import com.jonnyzzz.teamcity.plugins.node.common.BowerExecutionMode
/*
* Copyright 2000-2013 Eugene Petrenko
*
* 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.
*/
/**
* Created by Victor Mosin ([email protected])
* Date: 01.02.17 9:15
*/
class BowerRunType : RunTypeBase() {
private val bean = BowerBean()
override fun getType(): String = bean.runTypeName
override fun getDisplayName(): String = "Bower"
override fun getDescription(): String = "Executes Bower tasks"
override fun getEditJsp(): String = "bower.edit.jsp"
override fun getViewJsp(): String = "bower.view.jsp"
override fun getRunnerPropertiesProcessor(): PropertiesProcessor = PropertiesProcessor { arrayListOf() }
override fun describeParameters(parameters: Map<String, String>): String
= "Run targets: ${bean.parseCommands(parameters[bean.targets]).joinToString(", ")}"
override fun getDefaultRunnerProperties(): MutableMap<String, String>
= hashMapOf(bean.bowerMode to bean.bowerModeDefault.value)
override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> {
val result = arrayListOf<Requirement>()
result.addAll(super.getRunnerSpecificRequirements(runParameters))
result.add(Requirement(NodeBean().nodeJSConfigurationParameter, null, RequirementType.EXISTS))
if (bean.parseMode(runParameters[bean.bowerMode]) == BowerExecutionMode.GLOBAL) {
result.add(Requirement(bean.bowerConfigurationParameter, null, RequirementType.EXISTS))
}
return result
}
}
| apache-2.0 | 626d3c3738ebff57f4dc369ec15d2a37 | 38.92 | 108 | 0.763861 | 4.345428 | false | false | false | false |
industrial-data-space/trusted-connector | ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/ConfigApi.kt | 1 | 10355 | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api
import de.fhg.aisec.ids.api.Constants
import de.fhg.aisec.ids.api.conm.ConnectionManager
import de.fhg.aisec.ids.api.endpointconfig.EndpointConfigManager
import de.fhg.aisec.ids.api.router.RouteManager
import de.fhg.aisec.ids.api.settings.ConnectionSettings
import de.fhg.aisec.ids.api.settings.ConnectorConfig
import de.fhg.aisec.ids.api.settings.Settings
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import io.swagger.annotations.Authorization
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.TreeMap
import java.util.function.Consumer
import java.util.regex.Pattern
import java.util.stream.Collectors
import javax.ws.rs.BadRequestException
import javax.ws.rs.Consumes
import javax.ws.rs.GET
import javax.ws.rs.POST
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
/**
* REST API interface for configurations in the connector.
*
*
* The API will be available at http://localhost:8181/cxf/api/v1/config/<method>.
*
* @author Julian Schuette ([email protected])
* @author Gerd Brost ([email protected])
* @author Michael Lux ([email protected])
</method> */
@Component
@Path("/config")
@Api(value = "Connector Configuration", authorizations = [Authorization(value = "oauth2")])
class ConfigApi {
@Autowired
private lateinit var settings: Settings
@Autowired
private lateinit var routeManager: RouteManager
@Autowired(required = false)
private var connectionManager: ConnectionManager? = null
@Autowired(required = false)
private var endpointConfigManager: EndpointConfigManager? = null
@GET
@ApiOperation(value = "Retrieves the current configuration", response = ConnectorConfig::class)
@Path("/connectorConfig")
@Produces(
MediaType.APPLICATION_JSON
)
@AuthorizationRequired
fun get(): ConnectorConfig {
return settings.connectorConfig
}
@POST // @OPTIONS
@Path("/connectorConfig")
@ApiOperation(value = "Sets the overall configuration of the connector")
@ApiResponses(
ApiResponse(
code = 500,
message = "_No valid preferences received_: If incorrect configuration parameter is provided"
)
)
@Consumes(
MediaType.APPLICATION_JSON
)
@AuthorizationRequired
fun set(config: ConnectorConfig?): String {
if (config == null) {
throw BadRequestException("No valid preferences received!")
}
settings.connectorConfig = config
return "OK"
}
/**
* Save connection configuration of a particular connection.
*
* @param connection The name of the connection
* @param conSettings The connection configuration of the connection
*/
@POST
@Path("/connectionConfigs/{con}")
@ApiOperation(value = "Save connection configuration of a particular connection")
@ApiResponses(
ApiResponse(
code = 500,
message = "_No valid connection settings received!_: If incorrect connection settings parameter is provided"
)
)
@Consumes(
MediaType.APPLICATION_JSON
)
@AuthorizationRequired
fun setConnectionConfigurations(
@PathParam("con") connection: String,
conSettings: ConnectionSettings?
): Response {
return conSettings?.let {
// connection has format "<route_id> - host:port"
// store only "host:port" in database to make connection available in other parts of the application
// where rout_id is not available
val m = CONNECTION_CONFIG_PATTERN.matcher(connection)
if (!m.matches()) {
// GENERAL_CONFIG has changed
settings.setConnectionSettings(connection, it)
} else {
// specific endpoint config has changed
settings.setConnectionSettings(m.group(1), it)
// notify EndpointConfigurationListeners that some endpointConfig has changed
endpointConfigManager?.notify(m.group(1))
}
Response.ok().build()
} ?: Response.serverError().entity("No valid connection settings received!").build()
}
/**
* Sends configuration of a connection
*
* @param connection Connection identifier
* @return The connection configuration of the requested connection
*/
@GET
@Path("/connectionConfigs/{con}")
@ApiOperation(value = "Sends configuration of a connection", response = ConnectionSettings::class)
@Produces(
MediaType.APPLICATION_JSON
)
@AuthorizationRequired
fun getConnectionConfigurations(@PathParam("con") connection: String): ConnectionSettings {
return settings.getConnectionSettings(connection)
} // add endpoint configurations// For every currently available endpoint, go through all preferences and check
// if the id is already there. If not, create empty config.
// create missing endpoint configurations
// add route id before host identifier for web console view
// Set of all connection configurations, properly ordered
// Load all existing entries
// Assert global configuration entry
// add all available endpoints
/**
* Sends configurations of all connections
*
* @return Map of connection names/configurations
*/
@get:AuthorizationRequired
@get:Produces(MediaType.APPLICATION_JSON)
@get:ApiResponses(
ApiResponse(
code = 200,
message = "Map of connections and configurations",
response = ConnectionSettings::class,
responseContainer = "Map"
)
)
@get:ApiOperation(value = "Retrieves configurations of all connections")
@get:Path("/connectionConfigs")
@get:GET
val allConnectionConfigurations: Map<String, ConnectionSettings>
get() {
val connectionManager = connectionManager ?: return emptyMap()
// Set of all connection configurations, properly ordered
val allSettings: MutableMap<String, ConnectionSettings> = TreeMap(
Comparator { o1: String, o2: String ->
when (Constants.GENERAL_CONFIG) {
o1 -> {
return@Comparator -1
}
o2 -> {
return@Comparator 1
}
else -> {
return@Comparator o1.compareTo(o2)
}
}
}
)
// Load all existing entries
allSettings.putAll(settings.allConnectionSettings)
// Assert global configuration entry
allSettings.putIfAbsent(Constants.GENERAL_CONFIG, ConnectionSettings())
val routeInputs = routeManager
.routes
.mapNotNull { it.id }
.associateWith { routeManager.getRouteInputUris(it) }
// add all available endpoints
for (endpoint in connectionManager.listAvailableEndpoints()) {
// For every currently available endpoint, go through all preferences and check
// if the id is already there. If not, create empty config.
val hostIdentifier = endpoint.host + ":" + endpoint.port
// create missing endpoint configurations
if (allSettings.keys.stream().noneMatch { anObject: String? -> hostIdentifier == anObject }) {
allSettings[hostIdentifier] = ConnectionSettings()
}
}
// add route id before host identifier for web console view
val retAllSettings: MutableMap<String, ConnectionSettings> = HashMap()
for ((key, value) in allSettings) {
if (key == Constants.GENERAL_CONFIG) {
retAllSettings[key] = value
} else {
var endpointIdentifiers = routeInputs
.entries
.stream()
.filter { (_, value1) ->
value1.stream().anyMatch { u: String -> u.startsWith("idsserver://$key") }
}
.map { (key1) -> "$key1 - $key" }
.collect(Collectors.toList())
if (endpointIdentifiers.isEmpty()) {
endpointIdentifiers = listOf("<no route found> - $key")
}
// add endpoint configurations
endpointIdentifiers.forEach(
Consumer { endpointIdentifier: String ->
if (retAllSettings.keys.stream()
.noneMatch { anObject: String? -> endpointIdentifier == anObject }
) {
retAllSettings[endpointIdentifier] = value
}
}
)
}
}
return retAllSettings
}
companion object {
private val CONNECTION_CONFIG_PATTERN = Pattern.compile(".* - ([^ ]+)$")
}
}
| apache-2.0 | aeedeecdd0f9c31ae7988f3d9f4b1365 | 37.494424 | 120 | 0.612265 | 5.172328 | false | true | false | false |
maxlord/kotlin-android-app | app/src/main/kotlin/ru/maxlord/kotlinandroidapp/base/BaseFragment.kt | 1 | 2730 | package ru.maxlord.kotlinandroidapp.base
import android.content.SharedPreferences
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.trello.rxlifecycle.components.RxFragment
import ru.maxlord.kotlinandroidapp.activity.base.BaseActivity
import ru.maxlord.kotlinandroidapp.activity.base.BaseNoActionBarActivity
import ru.maxlord.kotlinandroidapp.activity.splash.Splash
import ru.maxlord.kotlinandroidapp.annotation.ConfigPrefs
import javax.inject.Inject
/**
*
* @author Lord (Kuleshov M.V.)
* @since 11.01.16
*/
abstract class BaseFragment: RxFragment() {
// @Bind(R.id.toolbar)
protected var toolbar: Toolbar? = null
lateinit var prefs: SharedPreferences
@Inject
fun setSharedPreferences(@ConfigPrefs prefs: SharedPreferences) {
this.prefs = prefs
}
private var component: FragmentSubComponent? = null
fun getComponent(): FragmentSubComponent {
return component!!
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(getLayoutRes(), container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (activity is BaseActivity) {
val activity = activity as BaseActivity
this.component = activity.getComponent().plus(FragmentModule(this))
inject()
} else if (activity is BaseNoActionBarActivity) {
val activity = activity as BaseNoActionBarActivity
this.component = activity.getComponent().plus(FragmentModule(this))
inject()
} else if (activity is Splash) {
val activity = activity as Splash
this.component = activity.getComponent().plus(FragmentModule(this))
inject()
}
if (toolbar != null) {
toolbar!!.title = activity.title
}
loadData()
}
/**
* @return
*/
@LayoutRes protected abstract fun getLayoutRes(): Int
protected abstract fun inject()
override fun onViewCreated(v: View?, savedInstanceState: Bundle?) {
super.onViewCreated(v, savedInstanceState)
initControls(v)
onRestoreInstanceState(savedInstanceState)
}
protected open fun onRestoreInstanceState(savedInstanceState: Bundle?) {
}
protected open fun initControls(v: View?) {
}
open fun loadData() {
}
protected fun releaseDatabaseHelper() {
// OpenHelperManager.releaseHelper()
}
}
| mit | d805e58b58aee505c9a8a8ab92a23e1b | 26.575758 | 116 | 0.692674 | 5.027624 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/utils/TranslateCommand.kt | 1 | 1618 | package net.perfectdreams.loritta.morenitta.commands.vanilla.utils
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.escapeMentions
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.utils.translate.GoogleTranslateUtils
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.LorittaBot
class TranslateCommand(loritta: LorittaBot) : AbstractCommand(loritta, "traduzir", listOf("translate"), net.perfectdreams.loritta.common.commands.CommandCategory.UTILS) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.translate.description")
override fun getExamplesKey() = LocaleKeyData("commands.command.translate.examples")
// TODO: Fix Usage
override suspend fun run(context: CommandContext, locale: BaseLocale) {
if (context.args.size >= 2) {
val strLang = context.args[0]
context.args[0] = "" // Super workaround
val text = context.args.joinToString(" ")
try {
val translatedText = GoogleTranslateUtils.translate(text, "auto", strLang)
context.reply(
LorittaReply(
translatedText!!.escapeMentions(),
"\uD83D\uDDFA"
)
)
} catch (e: Exception) {
logger.warn(e) { "Error while translating $text to $strLang!" }
}
} else {
context.explain()
}
}
} | agpl-3.0 | 3f0ac764970d728cb4bbeef238e84a0d | 39.475 | 170 | 0.727441 | 4.314667 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/com/myflightbook/android/ActViewProperties.kt | 1 | 14613 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
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.myflightbook.android
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.SparseArray
import android.view.*
import android.widget.BaseExpandableListAdapter
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.myflightbook.android.webservices.AuthToken
import com.myflightbook.android.webservices.CustomPropertyTypesSvc
import com.myflightbook.android.webservices.CustomPropertyTypesSvc.Companion.cachedPropertyTypes
import com.myflightbook.android.webservices.FlightPropertiesSvc
import kotlinx.coroutines.launch
import model.CustomPropertyType
import model.DBCache
import model.DecimalEdit
import model.DecimalEdit.CrossFillDelegate
import model.FlightProperty
import model.FlightProperty.Companion.crossProduct
import model.FlightProperty.Companion.distillList
import model.FlightProperty.Companion.fromDB
import model.FlightProperty.Companion.refreshPropCache
import model.FlightProperty.Companion.rewritePropertiesForFlight
import java.util.*
class ActViewProperties : FixedExpandableListActivity(), PropertyEdit.PropertyListener,
CrossFillDelegate {
private var mrgfpIn = arrayOf<FlightProperty>()
private var mRgfpall: Array<FlightProperty>? = null
private var mRgcpt: Array<CustomPropertyType>? = null
private var mRgexpandedgroups: BooleanArray? = null
private var mIdflight: Long = -1
private var mIdexistingid = 0
private var mXfillvalue = 0.0
private var mXfilltachstart = 0.0
private fun refreshPropertyTypes(fAllowCache : Boolean = true) {
val act = this as Activity
lifecycleScope.launch {
ActMFBForm.doAsync<CustomPropertyTypesSvc, Array<CustomPropertyType>?>(act,
CustomPropertyTypesSvc(),
getString(R.string.prgCPT),
{ s -> s.getCustomPropertyTypes(AuthToken.m_szAuthToken, fAllowCache, act) },
{ _, result ->
if (result != null && result.isNotEmpty()) {
mRgcpt = result
// Refresh the CPT's for each item in the full array
if (mRgfpall != null) {
refreshPropCache()
for (fp in mRgfpall!!) fp.refreshPropType()
}
populateList()
}
}
)
}
}
private fun deleteProperty(fp : FlightProperty, idExisting: Int) {
val act = this as Activity
lifecycleScope.launch {
ActMFBForm.doAsync<FlightPropertiesSvc, Any?>(
act,
FlightPropertiesSvc(),
getString(R.string.prgDeleteProp),
{ s-> s.deletePropertyForFlight(AuthToken.m_szAuthToken, idExisting, fp.idProp, act) },
{ _, _ ->
val alNew = ArrayList<FlightProperty>()
for (fp2 in mrgfpIn) if (fp2.idProp != fp.idProp) alNew.add(fp)
mrgfpIn = alNew.toTypedArray()
}
)
}
}
private inner class ExpandablePropertyListAdapter(
val mContext: Context?,
val mGroups: ArrayList<String>?,
val mChildren: ArrayList<ArrayList<FlightProperty>?>?
) : BaseExpandableListAdapter() {
private val mCachedviews: SparseArray<View> = SparseArray()
override fun getGroupCount(): Int {
assert(mGroups != null)
return mGroups!!.size
}
override fun getChildrenCount(groupPos: Int): Int {
assert(mChildren != null)
return mChildren!![groupPos]!!.size
}
override fun getGroup(i: Int): Any {
assert(mGroups != null)
return mGroups!![i]
}
override fun getChild(groupPos: Int, childPos: Int): Any {
assert(mChildren != null)
return mChildren!![groupPos]!![childPos]
}
override fun getGroupId(groupPos: Int): Long {
return groupPos.toLong()
}
override fun getChildId(groupPos: Int, childPos: Int): Long {
assert(mChildren != null)
// return childPos;
return mChildren!![groupPos]!![childPos].idPropType.toLong()
}
override fun hasStableIds(): Boolean {
return false
}
override fun getGroupView(
groupPosition: Int,
isExpanded: Boolean,
convertViewIn: View?,
parent: ViewGroup
): View {
assert(mGroups != null)
var convertView = convertViewIn
if (convertView == null) {
assert(mContext != null)
val infalInflater =
(mContext!!.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater)
convertView = infalInflater.inflate(R.layout.grouprow, parent, false)
}
val tv = convertView?.findViewById<TextView>(R.id.propertyGroup)
tv?.text = mGroups!![groupPosition]
return convertView!!
}
override fun getChildView(
groupPosition: Int, childPosition: Int, isLastChild: Boolean,
convertViewIn: View?, parent: ViewGroup
): View {
val fp = getChild(groupPosition, childPosition) as FlightProperty
// ignore passed-in value of convert view; keep these all around all the time.
var convertView = mCachedviews[fp.getCustomPropertyType()!!.idPropType]
if (convertView == null) {
assert(mContext != null)
val infalInflater =
(mContext!!.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater)
convertView = infalInflater.inflate(R.layout.cptitem, parent, false)
mCachedviews.put(fp.getCustomPropertyType()!!.idPropType, convertView)
}
val pe: PropertyEdit = convertView.findViewById(R.id.propEdit)
// only init if it's not already set up - this avoids focus back-and-forth with edittext
val fpExisting = pe.flightProperty
if (fpExisting == null || fpExisting.idPropType != fp.idPropType) pe.initForProperty(
fp,
fp.idPropType,
this@ActViewProperties,
if (fp.idPropType == CustomPropertyType.idPropTypeTachStart) (
object: CrossFillDelegate {
override fun crossFillRequested(sender: DecimalEdit?) {
if (mXfilltachstart > 0 && sender != null) sender.doubleValue = mXfilltachstart
}
}) else this@ActViewProperties)
return convertView
}
override fun isChildSelectable(i: Int, i1: Int): Boolean {
return false
}
override fun onGroupExpanded(groupPosition: Int) {
super.onGroupExpanded(groupPosition)
if (mRgexpandedgroups != null) mRgexpandedgroups!![groupPosition] = true
}
override fun onGroupCollapsed(groupPosition: Int) {
super.onGroupCollapsed(groupPosition)
if (mRgexpandedgroups != null) mRgexpandedgroups!![groupPosition] = false
}
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.expandablelist)
val tvSearch = findViewById<TextView>(R.id.txtSearchProp)
tvSearch.setHint(R.string.hintSearchProperties)
tvSearch.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
populateList()
}
override fun afterTextChanged(editable: Editable) {}
})
val i = intent
mIdflight = i.getLongExtra(ActNewFlight.PROPSFORFLIGHTID, -1)
if (mIdflight >= 0) {
// initialize the flightprops from the db
mrgfpIn = fromDB(mIdflight)
}
mIdexistingid = i.getIntExtra(ActNewFlight.PROPSFORFLIGHTEXISTINGID, 0)
mXfillvalue = i.getDoubleExtra(ActNewFlight.PROPSFORFLIGHTCROSSFILLVALUE, 0.0)
mXfilltachstart = i.getDoubleExtra(ActNewFlight.TACHFORCROSSFILLVALUE, 0.0)
val cptSvc = CustomPropertyTypesSvc()
if (cptSvc.getCacheStatus() === DBCache.DBCacheStatus.VALID) {
mRgcpt = cachedPropertyTypes
populateList()
} else
refreshPropertyTypes()
val srl = findViewById<SwipeRefreshLayout>(R.id.swiperefresh)
srl?.setOnRefreshListener {
srl.isRefreshing = false
refreshProps()
}
}
public override fun onPause() {
super.onPause()
if (currentFocus != null) currentFocus!!.clearFocus() // force any in-progress edit to commit, particularly for properties.
updateProps()
}
private fun updateProps() {
val rgfpUpdated = distillList(mRgfpall)
rewritePropertiesForFlight(mIdflight, rgfpUpdated)
}
private fun containsWords(szTargetIn: String, rgTerms: Array<String>): Boolean {
var szTarget = szTargetIn
szTarget = szTarget.uppercase(Locale.getDefault())
for (s in rgTerms) {
if (s.isNotEmpty() && !szTarget.contains(s)) return false
}
return true
}
private fun populateList() {
// get the cross product of property types with existing properties
if (mRgcpt == null) mRgcpt = cachedPropertyTypes // try to avoid passing null
if (mRgfpall == null) mRgfpall = crossProduct(mrgfpIn, mRgcpt)
// This maps the headers to the individual sub-lists.
val headers = HashMap<String, String>()
val childrenMaps = HashMap<String, ArrayList<FlightProperty>?>()
// Keep a list of the keys in order
val alKeys = ArrayList<String>()
var szKeyLast: String? = ""
val szRestrict =
(findViewById<View>(R.id.txtSearchProp) as EditText).text.toString().uppercase(
Locale.getDefault()
)
val rgTerms = szRestrict.split("\\s+".toRegex()).toTypedArray()
// slice and dice into headers/first names
for (fp in mRgfpall!!) {
if (!containsWords(fp.labelString(), rgTerms)) continue
// get the section for this property
val szKey =
if (fp.getCustomPropertyType()!!.isFavorite) getString(R.string.lblPreviouslyUsed) else fp.labelString()
.substring(0, 1).uppercase(
Locale.getDefault()
)
if (szKey.compareTo(szKeyLast!!) != 0) {
alKeys.add(szKey)
szKeyLast = szKey
}
if (!headers.containsKey(szKey)) headers[szKey] = szKey
// Get the array-list for that key, creating it if necessary
val alProps: ArrayList<FlightProperty>? = if (childrenMaps.containsKey(szKey)) childrenMaps[szKey] else ArrayList()
assert(alProps != null)
alProps!!.add(fp)
childrenMaps[szKey] = alProps
}
// put the above into arrayLists, but in the order that the keys were encountered. .values() is an undefined order.
val headerList = ArrayList<String>()
val childrenList = ArrayList<ArrayList<FlightProperty>?>()
for (s in alKeys) {
headerList.add(headers[s]!!)
childrenList.add(childrenMaps[s])
}
if (mRgexpandedgroups == null)
mRgexpandedgroups = BooleanArray(alKeys.size)
else if (mRgexpandedgroups!!.size != alKeys.size) {
mRgexpandedgroups = BooleanArray(alKeys.size)
if (mRgexpandedgroups!!.size <= 5) // autoexpand if fewer than 5 groups.
Arrays.fill(mRgexpandedgroups!!, true)
}
val mAdapter = ExpandablePropertyListAdapter(this, headerList, childrenList)
setListAdapter(mAdapter)
for (i in mRgexpandedgroups!!.indices) if (mRgexpandedgroups!![i]) this.expandableListView!!.expandGroup(i)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.propertylistmenu, menu)
return true
}
private fun refreshProps() {
updateProps() // preserve current user edits
refreshPropertyTypes(false)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuBackToFlight -> {
updateProps()
finish()
}
R.id.menuRefreshProperties -> refreshProps()
else -> return super.onOptionsItemSelected(
item
)
}
return true
}
private fun deleteDefaultedProperty(fp: FlightProperty) {
for (f in mrgfpIn) if (f.idPropType == fp.idPropType && f.idProp > 0)
deleteProperty(fp, mIdexistingid)
}
//region Property update delegates
override fun updateProperty(id: Int, fp: FlightProperty) {
if (mIdexistingid > 0 && fp.isDefaultValue()) deleteDefaultedProperty(fp)
}
override fun dateOfFlightShouldReset(dt: Date) {}
//region DecimalEdit cross-fill
override fun crossFillRequested(sender: DecimalEdit?) {
sender!!.doubleValue = mXfillvalue
} //endregion
} | gpl-3.0 | fcff8909d47c32c80ac41d75dd4284a5 | 38.928962 | 131 | 0.622186 | 5.011317 | false | false | false | false |
christophpickl/kpotpourri | github4k/src/main/kotlin/com/github/christophpickl/kpotpourri/github/internal/GithubApiImpl.kt | 1 | 4844 | package com.github.christophpickl.kpotpourri.github.internal
import com.github.christophpickl.kpotpourri.github.AssetUpload
import com.github.christophpickl.kpotpourri.github.CreateReleaseRequest
import com.github.christophpickl.kpotpourri.github.CreateReleaseResponse
import com.github.christophpickl.kpotpourri.github.Github4kException
import com.github.christophpickl.kpotpourri.github.GithubApi
import com.github.christophpickl.kpotpourri.github.Issue
import com.github.christophpickl.kpotpourri.github.Milestone
import com.github.christophpickl.kpotpourri.github.RepositoryConfig
import com.github.christophpickl.kpotpourri.github.State
import com.github.christophpickl.kpotpourri.github.Tag
import com.github.christophpickl.kpotpourri.http4k.BaseUrlConfig
import com.github.christophpickl.kpotpourri.http4k.ServerConfig
import com.github.christophpickl.kpotpourri.http4k.StatusFamily
import com.github.christophpickl.kpotpourri.http4k.buildHttp4k
import com.github.christophpickl.kpotpourri.http4k.get
import com.github.christophpickl.kpotpourri.http4k.patch
import com.github.christophpickl.kpotpourri.http4k.post
import mu.KotlinLogging.logger
@Suppress("KDocMissingDocumentation")
internal class GithubApiImpl(
private val config: RepositoryConfig,
connection: ServerConfig
) : GithubApi {
companion object {
private val GITHUB_MIMETYPE = "application/vnd.github.v3+json"
}
private val log = logger {}
private fun ServerConfig.toBaseUrlConfig() = BaseUrlConfig(
protocol = protocol,
hostName = hostName,
port = port,
path = "/repos/${config.repositoryOwner}/${config.repositoryName}"
)
private val http4k = buildHttp4k {
baseUrlBy(connection.toBaseUrlConfig())
basicAuth(config.username, config.password)
addHeader("Accept" to GITHUB_MIMETYPE)
enforceStatusFamily(StatusFamily.Success_2)
}
override fun listOpenMilestones(): List<Milestone> {
log.debug("listOpenMilestones()")
// state defaults to "open"
return http4k.get<Array<MilestoneJson>>("/milestones")
.map { it.toMilestone() }
.sortedBy { it.version }
}
override fun listIssues(milestone: Milestone): List<Issue> {
log.debug("listIssues(milestone={})", milestone)
return http4k.get<Array<IssueJson>>("/issues") {
addQueryParam("state" to "all")
addQueryParam("milestone" to milestone.number)
}
.map { it.toIssue() }
.sortedBy { it.number }
}
override fun listTags() =
http4k.get<Array<Tag>>("/tags")
.toList()
.sortedBy(Tag::name)
override fun close(milestone: Milestone) {
if (milestone.state == State.Closed) {
throw Github4kException("Milestone already closed: $milestone")
}
val response = http4k.patch<UpdateMilestoneResponseJson>("/milestones/${milestone.number}") {
requestBody(UpdateMilestoneRequestJson(state = State.Closed.jsonValue))
}
if (response.state != State.Closed.jsonValue) {
throw Github4kException("Failed to close milestone: $milestone")
}
}
override fun createNewRelease(createRequest: CreateReleaseRequest) =
http4k.post<CreateReleaseResponse>("/releases") {
requestBody(createRequest)
}
override fun listReleases(): List<CreateReleaseResponse> =
http4k.get<Array<CreateReleaseResponse>>("/releases")
.toList()
.sortedBy { it.name }
override fun uploadReleaseAsset(upload: AssetUpload) {
// "upload_url": "https://uploads.github.com/repos/christophpickl/gadsu_release_playground/releases/5934443/assets{?name,label}",
val uploadUrl = http4k.get<SingleReleaseJson>("/releases/${upload.releaseId}").upload_url.removeSuffix("{?name,label}")
log.debug { "Upload URL for github assets: $uploadUrl" }
// "https://uploads.github.com/repos/christophpickl/gadsu_release_playground/releases/5934443/assets{?name,label}"
val response = http4k.post<AssetUploadResponse>(uploadUrl) {
addHeader("Content-Type" to upload.contentType)
addQueryParam("name" to upload.fileName)
requestBytesBody(upload.bytes, upload.contentType)
disableBaseUrl()
}
log.debug { "Uploaded asset: $response" }
if (response.state != "uploaded") {
throw Github4kException("Upload failed for ${upload.fileName}! ($upload, $response)")
}
}
override fun toString() = "${this.javaClass.simpleName}[config=$config]"
}
@JsonData internal data class SingleReleaseJson(
val upload_url: String
)
| apache-2.0 | 8cb66d26565c5dfd47b872103fe94b80 | 39.033058 | 137 | 0.68559 | 4.539831 | false | true | false | false |
TouK/bubble | bubble/src/main/java/pl/touk/android/bubble/coordinates/CoordinatesCalculator.kt | 1 | 2684 | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pl.touk.android.bubble.coordinates
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
class CoordinatesCalculator {
companion object {
private val PITCH_POSITION = 1
private val ROLL_POSITION = 2
private val SENSOR_RESULTS_SIZE = 3
private val ORIENTATION_COORDINATES_RESULT_SIZE = 3
private val ROTATION_MATRIX_SIZE = 9
}
private val magneticSensorValues: FloatArray = FloatArray(SENSOR_RESULTS_SIZE)
private val accelerometerSensorValues: FloatArray = FloatArray(SENSOR_RESULTS_SIZE)
private val rotationMatrix: FloatArray = FloatArray(ROTATION_MATRIX_SIZE)
private val orientationCoordinates: FloatArray = FloatArray(ORIENTATION_COORDINATES_RESULT_SIZE)
public fun calculate(sensorEvent: SensorEvent): Coordinates {
cacheEventData(sensorEvent)
SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerSensorValues, magneticSensorValues);
SensorManager.getOrientation(rotationMatrix, orientationCoordinates);
val pitch = orientationCoordinates[PITCH_POSITION]
val roll = orientationCoordinates[ROLL_POSITION]
return Coordinates(pitch, roll)
}
private fun cacheEventData(sensorEvent: SensorEvent) {
if (sensorEvent.sensor.type == Sensor.TYPE_ACCELEROMETER) {
System.arraycopy(sensorEvent.values, 0, accelerometerSensorValues, 0, SENSOR_RESULTS_SIZE);
} else if (sensorEvent.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) {
System.arraycopy(sensorEvent.values, 0, magneticSensorValues, 0, SENSOR_RESULTS_SIZE);
}
}
internal fun calculateAverage(coordinates: List<Coordinates>): Coordinates {
var averagePitch = 0f
var averageRoll = 0f
val size = coordinates.size().toFloat()
coordinates.forEach {
averagePitch += it.pitch
averageRoll += it.roll
}
return Coordinates(averagePitch / size, averageRoll / size)
}
} | apache-2.0 | 99deeaca3d65f7c4077e0084aaf87636 | 36.816901 | 111 | 0.714232 | 4.784314 | false | false | false | false |
Shynixn/PetBlocks | petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/persistence/entity/AIFlyRidingEntity.kt | 1 | 1849 | package com.github.shynixn.petblocks.core.logic.persistence.entity
import com.github.shynixn.petblocks.api.business.annotation.YamlSerialize
import com.github.shynixn.petblocks.api.persistence.entity.AIFlyRiding
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class AIFlyRidingEntity : AIBaseEntity(), AIFlyRiding {
/**
* Name of the type.
*/
override var type: String = "fly-riding"
/**
* Riding speed.
*/
@YamlSerialize(value = "speed", orderNumber = 1)
override var ridingSpeed: Double = 1.0
/**
* Riding offset from ground.
*/
@YamlSerialize(value = "offset-y", orderNumber = 2)
override var ridingYOffSet: Double = 1.0
} | apache-2.0 | b1a72942b15a41deea9de71763be7147 | 36.755102 | 81 | 0.721471 | 4.14574 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/automatic_machines/TileRenders.kt | 2 | 23246 | package com.cout970.magneticraft.features.automatic_machines
import com.cout970.magneticraft.api.conveyorbelt.IConveyorBelt
import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBoxStorage
import com.cout970.magneticraft.api.pneumatic.PneumaticBox
import com.cout970.magneticraft.misc.RegisterRenderer
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.resource
import com.cout970.magneticraft.misc.vector.*
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.tilerenderers.*
import com.cout970.modelloader.api.*
import com.cout970.modelloader.api.animation.AnimatedModel
import com.cout970.modelloader.api.formats.gltf.GltfAnimationBuilder
import com.cout970.modelloader.api.util.TRSTransformation
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.client.renderer.block.model.ItemCameraTransforms
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.item.ItemSkull
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.Vec3d
import net.minecraftforge.client.ForgeHooksClient
/**
* Created by cout970 on 2017/08/10.
*/
@RegisterRenderer(TileFeedingTrough::class)
object TileRendererFeedingTrough : BaseTileRenderer<TileFeedingTrough>() {
override fun init() {
createModel(Blocks.feedingTrough)
}
override fun render(te: TileFeedingTrough) {
val item = te.invModule.inventory[0]
val level = when {
item.count > 32 -> 4
item.count > 16 -> 3
item.count > 8 -> 2
item.count > 0 -> 1
else -> 0
}
Utilities.rotateFromCenter(te.facing, 90f)
renderModel("default")
if (level > 0) {
Utilities.rotateFromCenter(EnumFacing.NORTH, 90f)
stackMatrix {
renderSide(level, item)
rotate(180f, 0.0f, 1.0f, 0.0f)
translate(-1.0, 0.0, -2.0)
renderSide(level, item)
}
}
}
private fun renderSide(level: Int, item: ItemStack) {
if (level >= 1) {
pushMatrix()
transform(Vec3d(2.0, 1.1, 6.0),
Vec3d(90.0, 0.0, 0.0),
Vec3d(0.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
pushMatrix()
transform(Vec3d(7.5, 1.5, 7.0),
Vec3d(90.0, 30.0, 0.0),
Vec3d(0.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
}
if (level >= 2) {
pushMatrix()
transform(Vec3d(0.0, 2.0, 12.0),
Vec3d(90.0, -30.0, 0.0),
Vec3d(16.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
pushMatrix()
transform(Vec3d(16.5, 2.5, 12.5),
Vec3d(90.0, -30.0, 0.0),
Vec3d(16.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
}
if (level >= 3) {
pushMatrix()
transform(Vec3d(1.0, 1.0, 7.0),
Vec3d(-10.0, 22.0, 4.0),
Vec3d(0.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
pushMatrix()
transform(Vec3d(0.0, 1.0, 15.0),
Vec3d(10.0, -22.0, -4.0),
Vec3d(16.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
pushMatrix()
transform(Vec3d(-2.5, -2.0, -4.0),
Vec3d(20.0, -90.0, 5.0),
Vec3d(0.0, 0.0, 8.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
}
if (level >= 4) {
pushMatrix()
transform(Vec3d(5.0, 0.0, 4.5),
Vec3d(-10.0, 0.0, 0.0),
Vec3d(0.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
pushMatrix()
transform(Vec3d(7.0, 0.0, 11.0),
Vec3d(14.0, 0.0, 0.0),
Vec3d(0.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
pushMatrix()
transform(Vec3d(12.0, 0.0, 10.0),
Vec3d(14.0, 0.0, 0.0),
Vec3d(0.0, 0.0, 0.0),
Vec3d(1.0, 1.0, 1.0))
renderItem(item)
popMatrix()
}
}
private fun transform(pos: Vec3d, rot: Vec3d, rotPos: Vec3d, scale: Vec3d) {
translate(PIXEL * 16, 0.0, 0.0)
rotate(0, -90, 0)
translate(pos.xd * PIXEL, pos.yd * PIXEL, pos.zd * PIXEL)
translate(rotPos.xd * PIXEL, rotPos.yd * PIXEL, rotPos.zd * PIXEL)
rotate(rot.xd, rot.yd, rot.zd)
translate(-rotPos.xd * PIXEL, -rotPos.yd * PIXEL, -rotPos.zd * PIXEL)
translate(PIXEL * 4, 0.0, 0.0)
GlStateManager.scale(scale.xd, scale.yd, scale.zd)
}
private fun rotate(x: Number, y: Number, z: Number) {
rotate(z, 0f, 0f, 1f)
rotate(y, 0f, 1f, 0f)
rotate(x, 1f, 0f, 0f)
}
private fun renderItem(stack: ItemStack) {
Minecraft.getMinecraft().renderItem.renderItem(stack, ItemCameraTransforms.TransformType.GROUND)
}
}
@RegisterRenderer(TileInserter::class)
object TileRendererInserter : BaseTileRenderer<TileInserter>() {
override fun init() {
val item = FilterNotString("item")
createModel(Blocks.inserter,
ModelSelector("animation0", item, FilterRegex("animation0", FilterTarget.ANIMATION)),
ModelSelector("animation1", item, FilterRegex("animation1", FilterTarget.ANIMATION)),
ModelSelector("animation2", item, FilterRegex("animation2", FilterTarget.ANIMATION)),
ModelSelector("animation3", item, FilterRegex("animation3", FilterTarget.ANIMATION)),
ModelSelector("animation4", item, FilterRegex("animation4", FilterTarget.ANIMATION)),
ModelSelector("animation5", item, FilterRegex("animation5", FilterTarget.ANIMATION)),
ModelSelector("animation6", item, FilterRegex("animation6", FilterTarget.ANIMATION)),
ModelSelector("animation7", item, FilterRegex("animation7", FilterTarget.ANIMATION)),
ModelSelector("animation8", item, FilterRegex("animation8", FilterTarget.ANIMATION)),
ModelSelector("animation9", item, FilterRegex("animation9", FilterTarget.ANIMATION))
)
}
override fun render(te: TileInserter) {
Utilities.rotateFromCenter(te.facing, 180f)
val mod = te.inserterModule
val transition = mod.transition
val extra = if (mod.moving) ticks else 0f
time = ((mod.animationTime + extra) / mod.maxAnimationTime).coerceAtMost(1f).toDouble() * 20 * 0.33
renderModel(transition.animation)
val item = te.inventory[0]
if (item.isEmpty) return
// animation0 is used to get the articulated node because Transition.ROTATING discards the
// info about translation/rotation of the inner nodes
val cache0 = getModel("animation0") as? AnimationRenderCache ?: return
val cache1 = getModel(transition.animation) as? AnimationRenderCache ?: return
val node = cache0.model.rootNodes.firstOrNull() ?: return
val anim = cache1.model
val localTime = ((time / 20.0) % cache1.model.length.toDouble()).toFloat()
val trs = getGlobalTransform(item, anim, node, localTime)
pushMatrix()
ForgeHooksClient.multiplyCurrentGlMatrix(trs.matrix.apply { transpose() })
translate(0.0, (-7.5).px, 0.0)
if (!Minecraft.getMinecraft().renderItem.shouldRenderItemIn3D(item) || item.item is ItemSkull) {
// 2D item
scale(0.75)
} else {
// 3D block
rotate(180f, 0f, 1f, 0f)
translate(0.0, (-1.9).px, 0.0)
scale(0.9)
}
Minecraft.getMinecraft().renderItem.renderItem(item, ItemCameraTransforms.TransformType.GROUND)
popMatrix()
}
fun getGlobalTransform(item: ItemStack, anim: AnimatedModel, node: AnimatedModel.Node, localTime: Float): TRSTransformation {
val trs = anim.getTransform(node, localTime)
if (node.children.isEmpty()) return trs
return trs * getGlobalTransform(item, anim, node.children[0], localTime)
}
}
@RegisterRenderer(TileConveyorBelt::class)
object TileRendererConveyorBelt : BaseTileRenderer<TileConveyorBelt>() {
var belt: IRenderCache? = null
var beltUp: IRenderCache? = null
var beltDown: IRenderCache? = null
var cornerBelt: IRenderCache? = null
override fun init() {
createModel(Blocks.conveyorBelt, listOf(
ModelSelector("back_legs", FilterRegex("back_leg.*")),
ModelSelector("front_legs", FilterRegex("front_leg.*")),
ModelSelector("lateral_left", FilterRegex("lateral_left")),
ModelSelector("lateral_right", FilterRegex("lateral_right")),
ModelSelector("panel_left", FilterRegex("panel_left")),
ModelSelector("panel_right", FilterRegex("panel_right"))
), "base")
createModel(Blocks.conveyorBelt, listOf(
ModelSelector("corner", FilterNotRegex("support.*")),
ModelSelector("corner_supports", FilterRegex("support.*"))
), "corner_base")
createModel(Blocks.conveyorBelt, listOf(
ModelSelector("up", FilterNotRegex("support.*")),
ModelSelector("up_supports", FilterRegex("support.*"))
), "up_base", false)
createModel(Blocks.conveyorBelt, listOf(
ModelSelector("down", FilterNotRegex("support.*")),
ModelSelector("down_supports", FilterRegex("support.*"))
), "down_base", false)
val anim = modelOf(Blocks.conveyorBelt, "anim")
val cornerAnim = modelOf(Blocks.conveyorBelt, "corner_anim")
val upAnim = modelOf(Blocks.conveyorBelt, "up_anim")
val downAnim = modelOf(Blocks.conveyorBelt, "down_anim")
//cleaning
cornerBelt?.close()
belt?.close()
beltUp?.close()
beltDown?.close()
val beltModel = ModelLoaderApi.getModelEntry(anim) ?: return
val cornerBeltModel = ModelLoaderApi.getModelEntry(cornerAnim) ?: return
val beltUpModel = ModelLoaderApi.getModelEntry(upAnim) ?: return
val beltDownModel = ModelLoaderApi.getModelEntry(downAnim) ?: return
val texture = resource("blocks/machines/conveyor_belt_anim")
belt = updateTexture(beltModel, texture)
cornerBelt = updateTexture(cornerBeltModel, texture)
beltUp = updateTexture(beltUpModel, texture)
beltDown = updateTexture(beltDownModel, texture)
}
override fun render(te: TileConveyorBelt) {
Utilities.rotateFromCenter(te.facing)
renderStaticParts(te)
val limit = Config.conveyorBeltItemRenderLimit
if (Minecraft.getMinecraft().player.getDistanceSq(te.pos) <= limit * limit) {
renderDynamicParts(te.conveyorModule, ticks)
}
// translate(0f, 12.5 * PIXEL, 0f)
//debug hitboxes
// renderHitboxes(te)
}
// debug
fun renderHitboxes(te: TileConveyorBelt) {
te.conveyorModule.boxes.forEach {
Utilities.renderBox(it.getHitBox())
}
}
// debug bitmaps
fun renderBitmap(te: TileConveyorBelt, x: Double, y: Double, z: Double) {
stackMatrix {
translate(x, y + 1f, z)
Utilities.rotateFromCenter(te.facing)
Utilities.renderBox((vec3Of(1, 0, 0) * PIXEL).createAABBUsing(vec3Of(2, 1, 1) * PIXEL),
vec3Of(0, 1, 0))
Utilities.renderBox((vec3Of(0, 0, 1) * PIXEL).createAABBUsing(vec3Of(1, 1, 2) * PIXEL),
vec3Of(0, 0, 1))
val bitmap2 = te.conveyorModule.generateGlobalBitMap()
for (i in 0 until 16) {
for (j in 0 until 16) {
val color = if (!bitmap2[i, j]) vec3Of(1, 1, 1) else vec3Of(0, 0, 1)
val h = if (bitmap2[i, j]) 1 else 0
Utilities.renderBox(
vec3Of(i, h, j) * PIXEL createAABBUsing vec3Of(i + 1, h, j + 1) * PIXEL, color)
}
}
}
}
fun renderDynamicParts(mod: IConveyorBelt, partialTicks: Float) {
bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
mod.boxes.forEach { box ->
stackMatrix {
val boxPos = box.position + if (box.locked) 0f else partialTicks
val pos = box.getPos(partialTicks)
val y = when (mod.level) {
1 -> boxPos / 16.0
-1 -> 1.0 - boxPos / 16.0
else -> 0.0
}
translate(pos.xd, 13.5 * PIXEL + y, pos.zd)
Utilities.renderItem(box.item, mod.facing)
}
}
}
fun renderStaticParts(te: TileConveyorBelt) {
val mod = te.conveyorModule
if (mod.isUp) {
stackMatrix {
Utilities.rotateFromCenter(EnumFacing.NORTH, 180f)
beltUp?.render()
renderModel("up")
if (mod.hasBlockDown()) {
renderModel("up_supports")
}
}
} else if (mod.isDown) {
beltDown?.render()
renderModel("down")
if (mod.hasBlockDown()) {
renderModel("down_supports")
}
} else if (mod.isCorner) {
stackMatrix {
if (mod.hasRight()) {
rotate(90f, 0f, 1f, 0f)
scale(-1f, 1f, 1f)
GlStateManager.cullFace(GlStateManager.CullFace.FRONT)
cornerBelt?.render()
renderModel("corner")
if (mod.hasBlockDown()) {
renderModel("corner_supports")
}
GlStateManager.cullFace(GlStateManager.CullFace.BACK)
} else {
translate(1f, 0f, 0f)
rotate(-90f, 0f, 1f, 0f)
cornerBelt?.render()
renderModel("corner")
if (mod.hasBlockDown()) {
renderModel("corner_supports")
}
}
}
} else {
belt?.render()
renderModel("default")
if (mod.hasLeft()) {
renderModel("lateral_left")
} else {
renderModel("panel_left")
}
if (mod.hasRight()) {
renderModel("lateral_right")
} else {
renderModel("panel_right")
}
if (!mod.hasBlockDown()) return
if (mod.hasBack()) {
stackMatrix {
translate(0f, 0f, PIXEL)
renderModel("back_legs")
}
} else {
renderModel("back_legs")
}
if (!mod.hasFront()) {
renderModel("front_legs")
}
}
}
private fun updateTexture(model: ModelEntry, texture: ResourceLocation): IRenderCache {
val raw = model.raw
val textureMap = Minecraft.getMinecraft().textureMapBlocks
val animTexture = textureMap.getAtlasSprite(texture.toString())
return when (raw) {
is Model.Mcx -> {
val finalModel = ModelTransform.updateModelUvs(raw.data, animTexture)
TextureModelCache(TextureMap.LOCATION_BLOCKS_TEXTURE, ModelCache { ModelUtilities.renderModel(finalModel) })
}
is Model.Gltf -> {
val finalModel = ModelTransform.updateModelUvs(raw.data, animTexture)
val anim = GltfAnimationBuilder().buildPlain(finalModel)
AnimationRenderCache(anim) { 0.0 }
}
else -> error("Invalid type: $raw, ${raw::class.java}")
}
}
}
@RegisterRenderer(TilePneumaticTube::class)
object TileRendererPneumaticTube : BaseTileRenderer<TilePneumaticTube>() {
override fun init() {
createModel(Blocks.pneumaticTube, listOf(
ModelSelector("center_full", FilterString("center_full")),
ModelSelector("north", FilterString("north")),
ModelSelector("south", FilterString("south")),
ModelSelector("east", FilterString("east")),
ModelSelector("west", FilterString("west")),
ModelSelector("up", FilterString("up")),
ModelSelector("down", FilterString("down")),
ModelSelector("center_north_h", FilterString("center_north_h")),
ModelSelector("center_south_h", FilterString("center_south_h")),
ModelSelector("center_east_h", FilterString("center_east_h")),
ModelSelector("center_west_h", FilterString("center_west_h")),
ModelSelector("center_up_h", FilterString("center_up_h")),
ModelSelector("center_down_h", FilterString("center_down_h")),
ModelSelector("center_north_v", FilterString("center_north_v")),
ModelSelector("center_south_v", FilterString("center_south_v")),
ModelSelector("center_east_v", FilterString("center_east_v")),
ModelSelector("center_west_v", FilterString("center_west_v")),
ModelSelector("center_up_v", FilterString("center_up_v")),
ModelSelector("center_down_v", FilterString("center_down_v"))
))
}
override fun render(te: TilePneumaticTube) {
val d = te.down()
val u = te.up()
val n = te.north()
val s = te.south()
val w = te.west()
val e = te.east()
GlStateManager.disableCull()
when {
n && s && !e && !w && !u && !d -> {
renderModel("center_east_h")
renderModel("center_west_h")
renderModel("center_up_h")
renderModel("center_down_h")
}
!n && !s && e && w && !u && !d -> {
renderModel("center_north_h")
renderModel("center_south_h")
renderModel("center_up_v")
renderModel("center_down_v")
}
!n && !s && !e && !w && u && d -> {
renderModel("center_north_v")
renderModel("center_south_v")
renderModel("center_east_v")
renderModel("center_west_v")
}
else -> renderModel("center_full")
}
if (n) renderModel("north")
if (s) renderModel("south")
if (e) renderModel("east")
if (w) renderModel("west")
if (u) renderModel("up")
if (d) renderModel("down")
GlStateManager.enableCull()
renderItems(te.flow)
}
fun renderItems(flow: PneumaticBoxStorage) {
flow.getItems().forEach { box ->
val percent = if (!box.isOutput) {
1 - ((box.progress.toFloat() + ticks * 16) / PneumaticBox.MAX_PROGRESS)
} else {
(box.progress.toFloat() + ticks * 16) / PneumaticBox.MAX_PROGRESS
}
val offset = vec3Of(8.px, 7.px, 8.px) + box.side.toVector3() * 0.5 * percent
stackMatrix {
translate(offset)
Utilities.renderTubeItem(box.item)
}
}
}
}
@RegisterRenderer(TilePneumaticRestrictionTube::class)
object TileRendererPneumaticRestrictionTube : BaseTileRenderer<TilePneumaticRestrictionTube>() {
override fun init() {
createModel(Blocks.pneumaticRestrictionTube, listOf(
ModelSelector("center_full", FilterString("center_full")),
ModelSelector("north", FilterString("north")),
ModelSelector("south", FilterString("south")),
ModelSelector("east", FilterString("east")),
ModelSelector("west", FilterString("west")),
ModelSelector("up", FilterString("up")),
ModelSelector("down", FilterString("down")),
ModelSelector("center_north_h", FilterString("center_north_h")),
ModelSelector("center_south_h", FilterString("center_south_h")),
ModelSelector("center_east_h", FilterString("center_east_h")),
ModelSelector("center_west_h", FilterString("center_west_h")),
ModelSelector("center_up_h", FilterString("center_up_h")),
ModelSelector("center_down_h", FilterString("center_down_h")),
ModelSelector("center_north_v", FilterString("center_north_v")),
ModelSelector("center_south_v", FilterString("center_south_v")),
ModelSelector("center_east_v", FilterString("center_east_v")),
ModelSelector("center_west_v", FilterString("center_west_v")),
ModelSelector("center_up_v", FilterString("center_up_v")),
ModelSelector("center_down_v", FilterString("center_down_v"))
))
}
override fun render(te: TilePneumaticRestrictionTube) {
val d = te.down()
val u = te.up()
val n = te.north()
val s = te.south()
val w = te.west()
val e = te.east()
GlStateManager.disableCull()
when {
n && s && !e && !w && !u && !d -> {
renderModel("center_east_h")
renderModel("center_west_h")
renderModel("center_up_h")
renderModel("center_down_h")
}
!n && !s && e && w && !u && !d -> {
renderModel("center_north_h")
renderModel("center_south_h")
renderModel("center_up_v")
renderModel("center_down_v")
}
!n && !s && !e && !w && u && d -> {
renderModel("center_north_v")
renderModel("center_south_v")
renderModel("center_east_v")
renderModel("center_west_v")
}
else -> renderModel("center_full")
}
if (n) renderModel("north")
if (s) renderModel("south")
if (e) renderModel("east")
if (w) renderModel("west")
if (u) renderModel("up")
if (d) renderModel("down")
GlStateManager.enableCull()
TileRendererPneumaticTube.renderItems(te.flow)
}
} | gpl-2.0 | 30a7f8ae122d44cd460a34c5c01fe22f | 35.551887 | 129 | 0.546158 | 4.284187 | false | false | false | false |
mcmacker4/PBR-Test | src/main/kotlin/net/upgaming/pbrengine/models/Model.kt | 1 | 4991 | package net.upgaming.pbrengine.models
import net.upgaming.pbrengine.util.toFloatBuffer
import org.joml.Vector2f
import org.joml.Vector3f
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.*
import org.lwjgl.opengl.GL30.*
import java.io.File
import java.nio.file.Files
class Model(val vao: Int, val vertexCount: Int) {
object Loader {
private val vaos = arrayListOf<Int>()
private val vbos = arrayListOf<Int>()
fun load(data: Data): Model {
val vao = createVAO()
glBindVertexArray(vao)
storeDataInAttributeArray(0, 3, data.vertices)
storeDataInAttributeArray(1, 3, data.normals)
storeDataInAttributeArray(2, 2, data.texCoords)
glBindVertexArray(0)
return Model(vao, data.vertices.size / 3)
}
fun loadVerticesOnly(vertices: FloatArray): Model {
val vao = createVAO()
glBindVertexArray(vao)
storeDataInAttributeArray(0, 3, vertices)
glBindVertexArray(0)
return Model(vao, vertices.size / 3)
}
private fun storeDataInAttributeArray(index: Int, size: Int, data: FloatArray) {
val buffer = data.toFloatBuffer()
val vbo = createVBO()
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW)
glVertexAttribPointer(index, size, GL_FLOAT, false, 0, 0)
glEnableVertexAttribArray(index)
glBindBuffer(GL_ARRAY_BUFFER, 0)
}
private fun createVAO(): Int {
val vao = glGenVertexArrays()
vaos.add(vao)
return vao
}
private fun createVBO(): Int {
val vbo = glGenBuffers()
vbos.add(vbo)
return vbo
}
fun cleanUp() {
vbos.forEach(::glDeleteBuffers)
vaos.forEach(::glDeleteVertexArrays)
}
}
object OBJLoader {
val vertices = arrayListOf<Vector3f>()
val normals = arrayListOf<Vector3f>()
val texCoords = arrayListOf<Vector2f>()
val ordVertices = arrayListOf<Vector3f>()
val ordNormals = arrayListOf<Vector3f>()
val ordTexCoords = arrayListOf<Vector2f>()
fun load(name: String): Model {
clear()
val path = "res/models/$name.obj"
File(path).forEachLine {
val parts = it.split(" ")
when {
it.startsWith("v ") -> {
vertices.add(Vector3f(
parts[1].toFloat(),
parts[2].toFloat(),
parts[3].toFloat()
))
}
it.startsWith("vn ") -> {
normals.add(Vector3f(
parts[1].toFloat(),
parts[2].toFloat(),
parts[3].toFloat()
))
}
it.startsWith("vt ") -> {
texCoords.add(Vector2f(
parts[1].toFloat(),
parts[2].toFloat()
))
}
it.startsWith("f ") -> {
for(i in 1..3) {
val ind = parts[i].split("/")
ordVertices.add(vertices[ind[0].toInt() - 1])
ordNormals.add(normals[ind[2].toInt() - 1])
ordTexCoords.add(texCoords[ind[1].toInt() - 1])
}
}
}
}
val verticesArray = FloatArray(ordVertices.size * 3)
val normalsArray = FloatArray(ordNormals.size * 3)
val texCoordsArray = FloatArray(ordTexCoords.size * 2)
var count = 0
ordVertices.forEach {
verticesArray[count++] = it.x
verticesArray[count++] = it.y
verticesArray[count++] = it.z
}
count = 0
ordNormals.forEach {
normalsArray[count++] = it.x
normalsArray[count++] = it.y
normalsArray[count++] = it.z
}
count = 0
ordTexCoords.forEach {
texCoordsArray[count++] = it.x
texCoordsArray[count++] = it.y
}
return Model.Loader.load(Data(verticesArray, normalsArray, texCoordsArray))
}
private fun clear() {
vertices.clear()
normals.clear()
ordVertices.clear()
ordNormals.clear()
}
}
class Data(val vertices: FloatArray, val normals: FloatArray, val texCoords: FloatArray)
} | apache-2.0 | edda4a5c1704a9f8975e53f12dcbb0bf | 32.959184 | 92 | 0.481467 | 4.966169 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/management/gallery/GalleryManagementFragment.kt | 1 | 3194 | package com.example.android.eyebody.management.gallery
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import java.io.File
import android.support.v7.widget.RecyclerView
import android.widget.Toast
import com.example.android.eyebody.R
import com.example.android.eyebody.gallery.Photo
import com.example.android.eyebody.gallery.PhotoFrameActivity
import com.example.android.eyebody.management.BasePageFragment
/**
* Created by YOON on 2017-11-11
* Modified by Yeji on 2017-12-24
*/
class GalleryManagementFragment : BasePageFragment() {
var photoList = ArrayList<Photo>()
lateinit var galleryView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
pageNumber = arguments.getInt(ARG_PAGE_NUMBER)
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view = inflater!!.inflate(R.layout.fragment_management_gallery, container, false)
galleryView = view.findViewById(R.id.galleryView)
//photoList에 값 채워넣기(이미지 불러오기)
LoadPhotos()
//RecyclerView
galleryView.hasFixedSize()
galleryView.adapter = GalleryManagementAdapter(activity, this, photoList)
return view
}
companion object {
private val ARG_PAGE_NUMBER = "param1"
fun newInstance(pn : Int) : GalleryManagementFragment {
val fragment = GalleryManagementFragment()
val args = Bundle()
args.putInt(ARG_PAGE_NUMBER, pn)
fragment.arguments = args
return fragment
}
}
fun LoadPhotos(){
var state: String = Environment.getExternalStorageState() //외부저장소(SD카드)가 마운트되었는지 확인
if (Environment.MEDIA_MOUNTED.equals(state)) {
//디렉토리 생성
var filedir: String = activity.getExternalFilesDir(null).toString() + "/gallery_body" //Android/data/com.example.android.eyebody/files/gallery_body
var file: File = File(filedir)
if (!file.exists()) {
if (!file.mkdirs()) {
//EXCEPTION 디렉토리가 만들어지지 않음
}
}
for (f in file.listFiles()) {
//TODO 이미지 파일이 아닌경우 예외처리
//TODO 이미지를 암호화해서 저장해놓고 불러올 때만 복호화 하기
photoList.add(Photo(f))
}
} else{
//TODO EXCEPTION 외부저장소가 마운트되지 않아서 파일을 읽고 쓸 수 없음
}
}
fun itemViewClicked(itemView: View, pos: Int){
var intent = Intent(activity, PhotoFrameActivity::class.java)
intent.putExtra("photoList", photoList)
intent.putExtra("pos", pos);
startActivity(intent)
}
fun itemViewLongClicked(itemView: View, pos: Int): Boolean{
return true
}
} | mit | 072f2be2d8eb2fa0c6ef84a788ccf64d | 31.714286 | 160 | 0.646169 | 3.983936 | false | false | false | false |
google/horologist | network-awareness/src/main/java/com/google/android/horologist/networks/ui/DataUsageTimeText.kt | 1 | 2348 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.wear.compose.foundation.CurvedTextStyle
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.TimeText
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.DataUsageReport
import com.google.android.horologist.networks.data.NetworkType
import com.google.android.horologist.networks.data.Networks
@ExperimentalHorologistNetworksApi
@Composable
public fun DataUsageTimeText(
showData: Boolean,
networkStatus: Networks,
networkUsage: DataUsageReport?,
modifier: Modifier = Modifier,
pinnedNetworks: Set<NetworkType> = setOf()
) {
val style = CurvedTextStyle(MaterialTheme.typography.caption1)
val context = LocalContext.current
if (showData) {
TimeText(
modifier = modifier,
startCurvedContent = {
curveDataUsage(
networkStatus = networkStatus,
networkUsage = networkUsage,
style = style,
context = context,
pinnedNetworks = pinnedNetworks
)
},
startLinearContent = {
LinearDataUsage(
networkStatus = networkStatus,
networkUsage = networkUsage,
style = MaterialTheme.typography.caption1,
context = context
)
}
)
} else {
TimeText(modifier = modifier)
}
}
| apache-2.0 | 6ac1de99d0218a24965d03b9d3c7ce2a | 34.575758 | 79 | 0.676746 | 5.149123 | false | false | false | false |
Ekito/koin | koin-projects/koin-core/src/main/kotlin/org/koin/core/scope/Scope.kt | 1 | 13478 | /*
* Copyright 2017-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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.core.scope
import org.koin.core.Koin
import org.koin.core.component.KoinApiExtension
import org.koin.core.definition.BeanDefinition
import org.koin.core.definition.indexKey
import org.koin.core.error.ClosedScopeException
import org.koin.core.error.MissingPropertyException
import org.koin.core.error.NoBeanDefFoundException
import org.koin.core.logger.Level
import org.koin.core.parameter.DefinitionParameters
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
import org.koin.core.registry.InstanceRegistry
import org.koin.core.time.measureDurationForResult
import org.koin.ext.getFullName
import kotlin.reflect.KClass
data class Scope(
val id: ScopeID,
@KoinApiExtension
val _scopeDefinition: ScopeDefinition,
private val _koin: Koin
) {
@PublishedApi
internal val _linkedScope: ArrayList<Scope> = arrayListOf()
@PublishedApi
internal val _instanceRegistry = InstanceRegistry(_koin, this)
@PublishedApi
internal var _source: Any? = null
val closed: Boolean
get() = _closed
private val _callbacks = arrayListOf<ScopeCallback>()
private var _closed: Boolean = false
private var _parameters: DefinitionParameters? = null
val logger = _koin.logger
internal fun create(links: List<Scope>) {
_instanceRegistry.create(_scopeDefinition.definitions)
_linkedScope.addAll(links)
}
inline fun <reified T : Any> getSource(): T = _source as? T ?: error(
"Can't use Scope source for ${T::class.getFullName()} - source is:$_source")
@KoinApiExtension
fun setSource(t: Any?) {
_source = t
}
/**
* Add parent Scopes to allow instance resolution
* i.e: linkTo(scopeC) - allow to resolve instance to current scope and scopeC
*
* @param scopes - Scopes to link with
*/
fun linkTo(vararg scopes: Scope) {
if (!_scopeDefinition.isRoot) {
_linkedScope.addAll(scopes)
} else {
error("Can't add scope link to a root scope")
}
}
/**
* Remove linked scope
*/
fun unlink(vararg scopes: Scope) {
if (!_scopeDefinition.isRoot) {
_linkedScope.removeAll(scopes)
} else {
error("Can't remove scope link to a root scope")
}
}
/**
* Lazy inject a Koin instance
* @param qualifier
* @param scope
* @param parameters
*
* @return Lazy instance of type T
*/
@JvmOverloads
inline fun <reified T : Any> inject(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): Lazy<T> =
lazy(LazyThreadSafetyMode.NONE) { get<T>(qualifier, parameters) }
/**
* Lazy inject a Koin instance if available
* @param qualifier
* @param scope
* @param parameters
*
* @return Lazy instance of type T or null
*/
@JvmOverloads
inline fun <reified T : Any> injectOrNull(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): Lazy<T?> =
lazy(LazyThreadSafetyMode.NONE) { getOrNull<T>(qualifier, parameters) }
/**
* Get a Koin instance
* @param qualifier
* @param scope
* @param parameters
*/
@JvmOverloads
inline fun <reified T : Any> get(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): T {
return get(T::class, qualifier, parameters)
}
/**
* Get a Koin instance if available
* @param qualifier
* @param scope
* @param parameters
*
* @return instance of type T or null
*/
@JvmOverloads
inline fun <reified T : Any> getOrNull(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): T? {
return getOrNull(T::class, qualifier, parameters)
}
/**
* Get a Koin instance if available
* @param qualifier
* @param scope
* @param parameters
*
* @return instance of type T or null
*/
@JvmOverloads
fun <T : Any> getOrNull(
clazz: KClass<T>,
qualifier: Qualifier? = null,
parameters: ParametersDefinition? = null
): T? {
return try {
get(clazz, qualifier, parameters)
} catch (e: ClosedScopeException) {
_koin._logger.debug("Koin.getOrNull - scope closed - no instance found for ${clazz.getFullName()} on scope ${toString()}")
null
} catch (e: NoBeanDefFoundException) {
_koin._logger.debug("Koin.getOrNull - no instance found for ${clazz.getFullName()} on scope ${toString()}")
null
}
}
/**
* Get a Koin instance
* @param clazz
* @param qualifier
* @param parameters
*
* @return instance of type T
*/
fun <T : Any> get(
clazz: KClass<T>,
qualifier: Qualifier? = null,
parameters: ParametersDefinition? = null
): T {
return if (_koin._logger.isAt(Level.DEBUG)) {
val qualifierString = qualifier?.let { " with qualifier '$qualifier'" } ?: ""
_koin._logger.debug("+- '${clazz.getFullName()}'$qualifierString")
val (instance: T, duration: Double) = measureDurationForResult {
resolveInstance<T>(qualifier, clazz, parameters)
}
_koin._logger.debug("|- '${clazz.getFullName()}' in $duration ms")
return instance
} else {
resolveInstance(qualifier, clazz, parameters)
}
}
/**
* Get a Koin instance
* @param java class
* @param qualifier
* @param parameters
*
* @return instance of type T
*/
@JvmOverloads
fun <T : Any> get(
clazz: Class<T>,
qualifier: Qualifier? = null,
parameters: ParametersDefinition? = null
): T {
val kClass = clazz.kotlin
return get(kClass, qualifier, parameters)
}
@Suppress("UNCHECKED_CAST")
private fun <T : Any> resolveInstance(
qualifier: Qualifier?,
clazz: KClass<T>,
parameters: ParametersDefinition?
): T {
if (_closed) {
throw ClosedScopeException("Scope '$id' is closed")
}
val indexKey = indexKey(clazz, qualifier)
return _instanceRegistry.resolveInstance(indexKey, parameters)
?: run {
_koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope")
getFromSource(clazz)
}
?: run {
_koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope's source")
_parameters?.getOrNull<T>(clazz)
}
?: run {
_koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in injected parameters")
findInOtherScope<T>(clazz, qualifier, parameters)
}
?: run {
_koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in linked scopes")
throwDefinitionNotFound(qualifier, clazz)
}
}
@Suppress("UNCHECKED_CAST")
private fun <T> getFromSource(clazz: KClass<*>): T? {
return if (clazz.isInstance(_source)) _source as? T else null
}
private fun <T : Any> findInOtherScope(
clazz: KClass<T>,
qualifier: Qualifier?,
parameters: ParametersDefinition?
): T? {
var instance: T? = null
for (scope in _linkedScope) {
instance = scope.getOrNull<T>(
clazz,
qualifier,
parameters
)
if (instance != null) break
}
return instance
}
private fun throwDefinitionNotFound(
qualifier: Qualifier?,
clazz: KClass<*>
): Nothing {
val qualifierString = qualifier?.let { " & qualifier:'$qualifier'" } ?: ""
throw NoBeanDefFoundException(
"No definition found for class:'${clazz.getFullName()}'$qualifierString. Check your definitions!")
}
internal fun createEagerInstances() {
if (_scopeDefinition.isRoot) {
_instanceRegistry.createEagerInstances()
}
}
/**
* Declare a component definition from the given instance
* This result of declaring a scoped/single definition of type T, returning the given instance
* (single definition of the current scope is root)
*
* @param instance The instance you're declaring.
* @param qualifier Qualifier for this declaration
* @param secondaryTypes List of secondary bound types
* @param override Allows to override a previous declaration of the same type (default to false).
*/
inline fun <reified T : Any> declare(
instance: T,
qualifier: Qualifier? = null,
secondaryTypes: List<KClass<*>>? = null,
override: Boolean = false
) = synchronized(this) {
val definition = _scopeDefinition.saveNewDefinition(instance, qualifier, secondaryTypes, override)
_instanceRegistry.saveDefinition(definition, override = true)
}
/**
* Get current Koin instance
*/
fun getKoin() = _koin
/**
* Get Scope
* @param scopeID
*/
fun getScope(scopeID: ScopeID) = getKoin().getScope(scopeID)
/**
* Register a callback for this Scope Instance
*/
fun registerCallback(callback: ScopeCallback) {
_callbacks += callback
}
/**
* Get a all instance for given inferred class (in primary or secondary type)
*
* @return list of instances of type T
*/
inline fun <reified T : Any> getAll(): List<T> = getAll(T::class)
/**
* Get a all instance for given class (in primary or secondary type)
* @param clazz T
*
* @return list of instances of type T
*/
fun <T : Any> getAll(clazz: KClass<*>): List<T> = _instanceRegistry.getAll(clazz)
/**
* Get instance of primary type P and secondary type S
* (not for scoped instances)
*
* @return instance of type S
*/
inline fun <reified S, reified P> bind(noinline parameters: ParametersDefinition? = null): S {
val secondaryType = S::class
val primaryType = P::class
return bind(primaryType, secondaryType, parameters)
}
/**
* Get instance of primary type P and secondary type S
* (not for scoped instances)
*
* @return instance of type S
*/
fun <S> bind(
primaryType: KClass<*>,
secondaryType: KClass<*>,
parameters: ParametersDefinition?
): S {
return _instanceRegistry.bind(primaryType, secondaryType, parameters)
?: throw NoBeanDefFoundException(
"No definition found to bind class:'${primaryType.getFullName()}' & secondary type:'${secondaryType.getFullName()}'. Check your definitions!")
}
/**
* Retrieve a property
* @param key
* @param defaultValue
*/
fun getProperty(key: String, defaultValue: String): String = _koin.getProperty(key, defaultValue)
/**
* Retrieve a property
* @param key
*/
fun getPropertyOrNull(key: String): String? = _koin.getProperty(key)
/**
* Retrieve a property
* @param key
*/
fun getProperty(key: String): String = _koin.getProperty(key)
?: throw MissingPropertyException("Property '$key' not found")
/**
* Close all instances from this scope
*/
fun close() = synchronized(this) {
clear()
_koin._scopeRegistry.deleteScope(this)
}
internal fun clear() {
_closed = true
_source = null
if (_koin._logger.isAt(Level.DEBUG)) {
_koin._logger.info("closing scope:'$id'")
}
// call on close from callbacks
_callbacks.forEach { it.onScopeClose(this) }
_callbacks.clear()
_instanceRegistry.close()
}
override fun toString(): String {
return "['$id']"
}
fun dropInstance(beanDefinition: BeanDefinition<*>) {
_instanceRegistry.dropDefinition(beanDefinition)
}
fun loadDefinition(beanDefinition: BeanDefinition<*>) {
_instanceRegistry.createDefinition(beanDefinition)
}
fun addParameters(parameters: DefinitionParameters) {
_parameters = parameters
}
fun clearParameters() {
_parameters = null
}
}
typealias ScopeID = String
| apache-2.0 | 498dc9ad99257131ab12ef46f33084f4 | 30.127021 | 166 | 0.596453 | 4.696167 | false | false | false | false |
KazuCocoa/DroidTestHelper | droidtesthelperlib/src/main/java/com/kazucocoa/droidtesthelperlib/HandleAnimations.kt | 1 | 2813 | package com.kazucocoa.droidtesthelperlib
import android.content.Intent
import android.os.IBinder
import android.util.Log
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.Arrays
class HandleAnimations {
private val DISABLE = 0.0f
private val ENABLE = 1.0f
private lateinit var setAnimationScalesMethod: Method
private lateinit var getAnimationScalesMethod: Method
private lateinit var windowManagerObject: Any
private fun animationHandler() {
try {
val asInterface = Class.forName("android.view.IWindowManager\$Stub").getDeclaredMethod("asInterface", IBinder::class.java)
val getService = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String::class.java)
val windowManagerClazz = Class.forName("android.view.IWindowManager")
setAnimationScalesMethod = Class.forName("android.view.IWindowManager").getDeclaredMethod("setAnimationScales", FloatArray::class.java)
getAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("getAnimationScales")
windowManagerObject = asInterface.invoke(null, getService.invoke(null, "window") as IBinder)
} catch (e: Exception) {
throw RuntimeException("Failed to access animation methods", e)
}
}
private fun disableAnimations() {
try {
setAnimationScaleWith(DISABLE)
} catch (e: Exception) {
Log.e(TAG, "Failed to disable animations", e)
}
}
fun enableAnimations() {
try {
setAnimationScaleWith(ENABLE)
} catch (e: Exception) {
Log.e(TAG, "Failed to enable animations", e)
}
}
@Throws(InvocationTargetException::class, IllegalAccessException::class)
private fun setAnimationScaleWith(scaleFactor: Float) {
(getAnimationScalesMethod.invoke(windowManagerObject) as FloatArray).let {
Arrays.fill(it, scaleFactor)
setAnimationScalesMethod.invoke(windowManagerObject, it)
}
}
companion object {
private val TAG = HandleAnimations::class.java.simpleName
private const val animationExtra = "ANIMATION"
fun hasExtraRegardingAnimation(intent: Intent): Boolean {
return intent.hasExtra(animationExtra)
}
fun enableAnimationsWithIntent(intent: Intent) {
val enableAnimation = intent.getBooleanExtra(animationExtra, false)
val handleAnimations = HandleAnimations()
handleAnimations.animationHandler()
if (enableAnimation) {
handleAnimations.enableAnimations()
} else {
handleAnimations.disableAnimations()
}
}
}
}
| mit | f382de9348db6f6f67ee8e152ce9d037 | 31.333333 | 147 | 0.671525 | 5.133212 | false | false | false | false |
MyDogTom/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/naming/ClassNaming.kt | 1 | 1028 | package io.gitlab.arturbosch.detekt.rules.style.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.SubRule
import org.jetbrains.kotlin.psi.KtClassOrObject
class ClassNaming(config: Config = Config.empty) : SubRule<KtClassOrObject>(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
debt = Debt.FIVE_MINS)
private val classPattern = Regex(valueOrDefault(CLASS_PATTERN, "^[A-Z$][a-zA-Z$]*$"))
override fun apply(element: KtClassOrObject) {
if (!element.identifierName().matches(classPattern)) {
report(CodeSmell(
issue.copy(description = "Class and Object names should match the pattern: $classPattern"),
Entity.from(element)))
}
}
companion object {
const val CLASS_PATTERN = "classPattern"
}
}
| apache-2.0 | c16a7c0be3904cb1683dd9a20eb8f35f | 34.448276 | 96 | 0.771401 | 3.607018 | false | true | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/calendar/CalendarAttendee.kt | 1 | 871 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.calendar
/**
* Calendar attendee.
*
* @author moshe.w
*/
class CalendarAttendee {
var id: Long = 0
var eventId: Long = 0
var email: String? = null
var name: String? = null
var status: Int = 0
var type: Int = 0
}
| apache-2.0 | dccfeabdf4ed06c3387cb7d157c40dd8 | 27.096774 | 75 | 0.699196 | 3.941176 | false | false | false | false |
tkiapril/Weisseliste | src/main/kotlin/kotlin/sql/vendors/Mysql.kt | 1 | 5206 | package kotlin.sql.vendors
import java.util.*
import kotlin.sql.*
/**
* User: Andrey.Tarashevskiy
* Date: 08.05.2015
*/
internal object MysqlDialect : VendorDialect() {
override @Synchronized fun tableColumns(): Map<String, List<Pair<String, Boolean>>> {
val tables = HashMap<String, List<Pair<String, Boolean>>>()
val rs = Session.get().connection.createStatement().executeQuery(
"SELECT DISTINCT TABLE_NAME, COLUMN_NAME, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${getDatabase()}'")
while (rs.next()) {
val tableName = rs.getString("TABLE_NAME")!!
val columnName = rs.getString("COLUMN_NAME")!!
val nullable = rs.getBoolean("IS_NULLABLE")
tables[tableName] = (tables[tableName]?.plus(listOf(columnName to nullable)) ?: listOf(columnName to nullable))
}
return tables
}
override @Synchronized fun columnConstraints(vararg tables: Table): Map<Pair<String, String>, List<ForeignKeyConstraint>> {
val constraints = HashMap<Pair<String, String>, MutableList<ForeignKeyConstraint>>()
val tableNames = tables.map { it.tableName }
fun inTableList(): String {
if (tables.isNotEmpty()) {
return " AND ku.TABLE_NAME IN ${tableNames.joinToString("','", prefix = "('", postfix = "')")}"
}
return ""
}
val rs = Session.get().connection.createStatement().executeQuery(
"SELECT\n" +
" rc.CONSTRAINT_NAME,\n" +
" ku.TABLE_NAME,\n" +
" ku.COLUMN_NAME,\n" +
" ku.REFERENCED_TABLE_NAME,\n" +
" ku.REFERENCED_COLUMN_NAME,\n" +
" rc.DELETE_RULE\n" +
"FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n" +
" INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku\n" +
" ON ku.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA AND rc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME\n" +
"WHERE ku.TABLE_SCHEMA = '${getDatabase()}' ${inTableList()}")
while (rs.next()) {
val refereeTableName = rs.getString("TABLE_NAME")!!
if (refereeTableName !in tableNames) continue
val refereeColumnName = rs.getString("COLUMN_NAME")!!
val constraintName = rs.getString("CONSTRAINT_NAME")!!
val refTableName = rs.getString("REFERENCED_TABLE_NAME")!!
val refColumnName = rs.getString("REFERENCED_COLUMN_NAME")!!
val constraintDeleteRule = ReferenceOption.valueOf(rs.getString("DELETE_RULE")!!.replace(" ", "_"))
constraints.getOrPut(Pair(refereeTableName, refereeColumnName), {arrayListOf()}).add(ForeignKeyConstraint(constraintName, refereeTableName, refereeColumnName, refTableName, refColumnName, constraintDeleteRule))
}
return constraints
}
override @Synchronized fun existingIndices(vararg tables: Table): Map<String, List<Index>> {
val constraints = HashMap<String, MutableList<Index>>()
val rs = Session.get().connection.createStatement().executeQuery(
"""SELECT ind.* from (
SELECT
TABLE_NAME, INDEX_NAME, GROUP_CONCAT(column_name ORDER BY seq_in_index) AS `COLUMNS`, NON_UNIQUE
FROM INFORMATION_SCHEMA.STATISTICS s
WHERE table_schema = '${getDatabase()}' and INDEX_NAME <> 'PRIMARY'
GROUP BY 1, 2) ind
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
on kcu.TABLE_NAME = ind.TABLE_NAME
and kcu.COLUMN_NAME = ind.columns
and TABLE_SCHEMA = '${getDatabase()}'
and kcu.REFERENCED_TABLE_NAME is not NULL
WHERE kcu.COLUMN_NAME is NULL;
""")
while (rs.next()) {
val tableName = rs.getString("TABLE_NAME")!!
val indexName = rs.getString("INDEX_NAME")!!
val columnsInIndex = rs.getString("COLUMNS")!!.split(',')
val isUnique = rs.getInt("NON_UNIQUE") == 0
constraints.getOrPut(tableName, { arrayListOf() }).add(Index(indexName, tableName, columnsInIndex, isUnique))
}
return constraints
}
override fun getDatabase(): String {
return Session.get().connection.catalog
}
override fun <T : String?> ExpressionWithColumnType<T>.match(pattern: String, mode: MatchMode?): Op<Boolean> = MATCH(this, pattern, mode ?: MysqlMatchMode.STRICT)
private class MATCH(val expr: ExpressionWithColumnType<*>, val pattern: String, val mode: MatchMode): Op<Boolean>() {
override fun toSQL(queryBuilder: QueryBuilder): String {
return "MATCH(${expr.toSQL(queryBuilder)}) AGAINST ('$pattern' ${mode.mode()})"
}
}
}
enum class MysqlMatchMode(val operator: String): MatchMode {
STRICT("IN BOOLEAN MODE"),
NATURAL_LANGUAGE("IN NATURAL LANGUAGE MODE");
override fun mode() = operator
} | agpl-3.0 | 28fa4e314c48b26e648b5ac173cf4398 | 43.127119 | 222 | 0.587975 | 4.71558 | false | false | false | false |
nosix/vue-kotlin | vuekt/src/main/kotlin/org/musyozoku/vuekt/util.kt | 1 | 859 | @file:Suppress("unused", "UnsafeCastFromDynamic", "NOTHING_TO_INLINE")
package org.musyozoku.vuekt
/**
* JavaScript native `this`
*/
external val `this`: dynamic
/**
* Typed JavaScript native `this`
*/
inline fun <T : Any> thisAs(): T = `this`
/**
* Type of `void 0`
*/
external interface Void
/**
* Constant of `void 0`
*/
val void: Void = js("void 0")
/**
* `{ [propertyName: String]: T }`
*/
external interface JsonOf<T>
inline operator fun <T> JsonOf<T>.get(propertyName: String): T = this.asDynamic()[propertyName]
inline operator fun <T> JsonOf<T>.set(propertyName: String, value: T) {
this.asDynamic()[propertyName] = value
}
/**
* `T | Array<T>`
*/
external interface OneOrMany<T>
inline fun <T> OneOrMany(value: T): OneOrMany<T> = value.asDynamic()
inline fun <T> OneOrMany(value: Array<T>): OneOrMany<T> = value.asDynamic()
| apache-2.0 | c0c9f13c1a9c5b28fa9ca0aa33e5fc99 | 19.95122 | 95 | 0.661234 | 3.193309 | false | false | false | false |
vovagrechka/k2php | k2php/src/org/jetbrains/kotlin/js/translate/callTranslator/CallInfo.kt | 2 | 8839 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.callTranslator
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.js.backend.ast.JsBlock
import org.jetbrains.kotlin.js.backend.ast.JsConditional
import org.jetbrains.kotlin.js.backend.ast.JsExpression
import org.jetbrains.kotlin.js.backend.ast.JsLiteral
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.reference.CallArgumentTranslator
import org.jetbrains.kotlin.js.translate.reference.ReferenceTranslator
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils.getReceiverParameterForReceiver
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.isSafeCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
interface CallInfo {
val context: TranslationContext
val resolvedCall: ResolvedCall<out CallableDescriptor>
val dispatchReceiver: JsExpression?
val extensionReceiver: JsExpression?
fun constructSafeCallIfNeeded(result: JsExpression): JsExpression
}
abstract class AbstractCallInfo : CallInfo {
override fun toString(): String {
val location = DiagnosticUtils.atLocation(callableDescriptor)
val name = callableDescriptor.name.asString()
return "callableDescriptor: $name at $location; dispatchReceiver: $dispatchReceiver; extensionReceiver: $extensionReceiver"
}
}
// if value == null, it is get access
class VariableAccessInfo(callInfo: CallInfo, val value: JsExpression? = null) : AbstractCallInfo(), CallInfo by callInfo
class FunctionCallInfo(
callInfo: CallInfo,
val argumentsInfo: CallArgumentTranslator.ArgumentsInfo
) : AbstractCallInfo(), CallInfo by callInfo
/**
* no receivers - extensionOrDispatchReceiver = null, extensionReceiver = null
* this - extensionOrDispatchReceiver = this, extensionReceiver = null
* receiver - extensionOrDispatchReceiver = receiver, extensionReceiver = null
* both - extensionOrDispatchReceiver = this, extensionReceiver = receiver
*/
class ExplicitReceivers(val extensionOrDispatchReceiver: JsExpression?, val extensionReceiver: JsExpression? = null)
fun TranslationContext.getCallInfo(
resolvedCall: ResolvedCall<out CallableDescriptor>,
extensionOrDispatchReceiver: JsExpression?
): CallInfo {
return createCallInfo(resolvedCall, ExplicitReceivers(extensionOrDispatchReceiver))
}
// two receiver need only for FunctionCall in VariableAsFunctionResolvedCall
fun TranslationContext.getCallInfo(
resolvedCall: ResolvedCall<out FunctionDescriptor>,
explicitReceivers: ExplicitReceivers
): FunctionCallInfo {
val argsBlock = JsBlock()
val argumentsInfo = CallArgumentTranslator.translate(resolvedCall, explicitReceivers.extensionOrDispatchReceiver, this, argsBlock)
val explicitReceiversCorrected =
if (!argsBlock.isEmpty && explicitReceivers.extensionOrDispatchReceiver != null) {
val receiverOrThisRef = cacheExpressionIfNeeded(explicitReceivers.extensionOrDispatchReceiver)
var receiverRef = explicitReceivers.extensionReceiver
if (receiverRef != null) {
receiverRef = defineTemporary(explicitReceivers.extensionReceiver!!)
}
ExplicitReceivers(receiverOrThisRef, receiverRef)
}
else {
explicitReceivers
}
this.addStatementsToCurrentBlockFrom(argsBlock)
val callInfo = createCallInfo(resolvedCall, explicitReceiversCorrected)
return FunctionCallInfo(callInfo, argumentsInfo)
}
private fun boxIfNeedeed(v: ReceiverValue?, d: ReceiverParameterDescriptor?, r: JsExpression?): JsExpression? {
if (r != null && v != null && KotlinBuiltIns.isCharOrNullableChar(v.type) &&
(d == null || !KotlinBuiltIns.isCharOrNullableChar(d.type))) {
return JsAstUtils.charToBoxedChar(r)
}
return r
}
private fun TranslationContext.getDispatchReceiver(receiverValue: ReceiverValue): JsExpression {
return getDispatchReceiver(getReceiverParameterForReceiver(receiverValue))
}
private fun TranslationContext.createCallInfo(
resolvedCall: ResolvedCall<out CallableDescriptor>,
explicitReceivers: ExplicitReceivers
): CallInfo {
val receiverKind = resolvedCall.explicitReceiverKind
// I'm not sure if it's a proper code, and why it should work. Just copied similar logic from ExpressionCodegen.generateConstructorCall.
// See box/classes/inner/instantiateInDerived.kt
// TODO: revisit this code later, write more tests (or borrow them from JVM backend)
fun getDispatchReceiver(): JsExpression? {
val receiverValue = resolvedCall.dispatchReceiver ?: return null
return when (receiverKind) {
DISPATCH_RECEIVER, BOTH_RECEIVERS -> explicitReceivers.extensionOrDispatchReceiver
else -> getDispatchReceiver(receiverValue)
}
}
fun getExtensionReceiver(): JsExpression? {
val receiverValue = resolvedCall.extensionReceiver ?: return null
return when (receiverKind) {
EXTENSION_RECEIVER -> explicitReceivers.extensionOrDispatchReceiver
BOTH_RECEIVERS -> explicitReceivers.extensionReceiver
else -> getDispatchReceiver(receiverValue)
}
}
var dispatchReceiver = getDispatchReceiver()
// if (dispatchReceiver.toString().contains("myFuckingDir")) {
// "break on me"
// }
var extensionReceiver = getExtensionReceiver()
var notNullConditional: JsConditional? = null
if (resolvedCall.call.isSafeCall()) {
when (resolvedCall.explicitReceiverKind) {
BOTH_RECEIVERS, EXTENSION_RECEIVER -> {
notNullConditional = TranslationUtils.notNullConditional(extensionReceiver!!, JsLiteral.NULL, this)
extensionReceiver = notNullConditional.thenExpression
}
else -> {
notNullConditional = TranslationUtils.notNullConditional(dispatchReceiver!!, JsLiteral.NULL, this)
dispatchReceiver = notNullConditional.thenExpression
}
}
}
if (dispatchReceiver == null) {
val container = resolvedCall.resultingDescriptor.containingDeclaration
if (DescriptorUtils.isObject(container)) {
dispatchReceiver = ReferenceTranslator.translateAsValueReference(container, this)
}
}
dispatchReceiver = boxIfNeedeed(resolvedCall.dispatchReceiver,
resolvedCall.candidateDescriptor.dispatchReceiverParameter,
dispatchReceiver)
extensionReceiver = boxIfNeedeed(resolvedCall.extensionReceiver,
resolvedCall.candidateDescriptor.extensionReceiverParameter,
extensionReceiver)
return object : AbstractCallInfo(), CallInfo {
override val context: TranslationContext = this@createCallInfo
override val resolvedCall: ResolvedCall<out CallableDescriptor> = resolvedCall
override val dispatchReceiver: JsExpression? = dispatchReceiver
override val extensionReceiver: JsExpression? = extensionReceiver
val notNullConditionalForSafeCall: JsConditional? = notNullConditional
override fun constructSafeCallIfNeeded(result: JsExpression): JsExpression {
if (notNullConditionalForSafeCall == null) {
return result
}
else {
notNullConditionalForSafeCall.thenExpression = result
return notNullConditionalForSafeCall
}
}
}
}
| apache-2.0 | c66a5e4717735f8b4e715ac572541af4 | 43.417085 | 140 | 0.732323 | 5.747074 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/endpointDoclet/src/main/kotlin/nl/adaptivity/ws/doclet/mdGen.kt | 1 | 9531 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.ws.doclet
import java.io.Writer
/**
* Created by pdvrieze on 11/04/16.
*/
interface Table {
var targetWidth: Int
fun row(block: Row.()->Unit)
}
inline fun Row.col(c: CharSequence) {
col {text(c)}
}
interface Row {
/** Create a simple column */
fun col(block: Cell.()->Unit)
/** Create a paragraph column that does word wrapping*/
fun parcol(block: Cell.()->Unit)
}
interface Cell : FlowContent {
val width: Int
}
interface FlowContent {
fun text(c:CharSequence)
fun link(target:CharSequence, label:CharSequence?=null)
}
interface OutputGenerator: FlowContent {
fun heading1(s:CharSequence)
fun heading2(s:CharSequence)
fun heading3(s:CharSequence)
fun appendln(s:CharSequence)
fun appendln()
fun table(vararg columns:String, block: Table.()->Unit)
}
fun Writer.markDown(block: OutputGenerator.()->Unit) = this.use { MdGen(it).block() }
private class MdTable(val columns: Array<out String>) : Table {
fun appendTo(out: Appendable) {
val foldable = BooleanArray(columns.size)
val desiredColWidths = rows.fold(columns.map { it.length }.toTypedArray()) { array, row ->
row.cells.forEachIndexed { i, cell ->
if (cell.wrapped) {
foldable[i]=true
} else {
array[i] = Math.max(array[i], cell.width)
}
}
array
}
val foldableCount = foldable.count()
if (foldableCount>0) {
val totalExtra = targetWidth - (columns.size * 3 + 1) - desiredColWidths.sum()
if (totalExtra>0) { // Slightly complicated to handle rounding errors
var seenColumns = 0
var usedSpace = 0
foldable.forEachIndexed { i, foldable ->
if (foldable) {
++seenColumns
val extraSpace = (totalExtra * seenColumns / foldableCount) - usedSpace
desiredColWidths[i]+=extraSpace
usedSpace+=extraSpace
}
}
}
}
columns.mapIndexed { i, h -> "$h${' '.pad(desiredColWidths[i]-h.length)}" }.joinTo(out, " | ", "| ", " |")
out.appendln()
desiredColWidths.joinTo(out, "-|-", "|-", "-|") { '-'.pad(it) }
out.appendln()
rows.forEach { row ->
if (row.cells.count { it.wrapped }>0) {
val lines= row.cells.mapIndexed { i, cell -> // Make the cells into lists of lines
val escapedText = Escaper('|').apply { cell.appendTo(this) }
if (foldable[i]) {
escapedText.wordWrap(desiredColWidths[i])
} else {
sequenceOf(escapedText)
}
}.asSequence().flip()
lines.forEach { line ->
line.mapIndexed { i, part -> if (part==null) ' '.pad(desiredColWidths[i]) else "$part${' '.pad(desiredColWidths[i]-part.length)}" }
.joinTo(out, " | ", "| ", " |")
out.appendln()
}
} else {
row.cells.mapIndexed { i, cell ->
val text = Escaper('|').apply{ cell.appendTo(this) }
"$text${' '.pad(desiredColWidths[i]-text.length)}"
}.joinTo(out," | ", "| ", " |")
out.appendln()
}
}
}
private class Escaper(val escapeChar:Char='\\', vararg val escapedChars:Char): Appendable, CharSequence {
private val buffer= StringBuilder()
override val length: Int get() = buffer.length
override fun get(index: Int): Char = buffer.get(index)
override fun subSequence(startIndex: Int, endIndex: Int) = buffer.subSequence(startIndex, endIndex)
override fun append(csq: CharSequence?): Appendable = append(csq, 0, csq?.length?:4)
override fun append(csq: CharSequence?, start: Int, end: Int): Appendable {
if (csq==null) return append("null", start, end)
csq.forEach { append(it) }
return this
}
override fun append(c: Char): Appendable {
if (c==escapeChar || escapedChars.contains(c)) {
buffer.append(escapeChar)
}
buffer.append(c)
return this
}
override fun toString() = buffer.toString()
override fun equals(other: Any?) = buffer.equals(other)
override fun hashCode() = buffer.hashCode()
}
private val rows = mutableListOf<MdRow>()
override var targetWidth:Int = 100
override fun row(block: Row.() -> Unit) {
rows.add(MdRow(columns.size).apply { block() })
}
}
fun CharSequence.wordWrap(maxWidth:Int) : Sequence<CharSequence> {
val result = mutableListOf<CharSequence>()
var start=0
var lastWordEnd=0
forEachIndexed { i, c ->
when (c) {
'\n', '\r', ' ' -> lastWordEnd=i
',', '.', '!', '?' -> lastWordEnd=i+1
}
if ((start<=lastWordEnd && i-start>=maxWidth) || c=='\n' || c=='\r') { // don't wrap if the word is too long
result.add(subSequence(start, lastWordEnd))
start = lastWordEnd
while(start<length && get(start)==' ') { start++ }// start after any spaces
}
}
if (lastWordEnd<length) {
val last = subSequence(start, length)
if (! last.isBlank()) { result.add(last) }
}
return result.asSequence()
}
private class FlipIterator<T>(inSeq:Sequence<Sequence<T>>):Iterator<Sequence<T?>> {
val innerSequences:List<Iterator<T>> = inSeq.map{it.iterator()}.toList()
override fun hasNext() = innerSequences.any { it.hasNext() }
override fun next(): Sequence<T?> {
return innerSequences.asSequence().map { if (it.hasNext()) it.next() else null }
}
}
fun <T> Sequence<Sequence<T>>.flip():Sequence<Sequence<T?>> = object:Sequence<Sequence<T?>> {
override fun iterator(): Iterator<Sequence<T?>> = FlipIterator<T>(this@flip)
}
private fun Char.pad(count:Int):CharSequence = object:CharSequence {
override val length: Int = if(count>0) count else 0
override fun get(index: Int) = this@pad
override fun subSequence(startIndex: Int, endIndex: Int) = [email protected](endIndex-startIndex)
override fun toString(): String = StringBuilder(length).append(this).toString()
}
private class MdRow(val colCount:Int):Row {
val cells = mutableListOf<MdCell>()
override fun col(block: Cell.() -> Unit) { cells.add(MdCell().apply { block() }) }
override fun parcol(block: Cell.() -> Unit) { cells.add(MdCell(true).apply { block() }) }
}
private class MdCell(val wrapped:Boolean=false):Cell {
private val buffer = StringBuilder()
override fun text(c: CharSequence) {
buffer.append(c.normalize())
}
override fun link(target: CharSequence, label: CharSequence?) = buffer._link(target, label)
fun appendTo(a:Appendable) { a.append(buffer) }
override val width: Int get() = buffer.length
}
private class StripNewLines(val orig:CharSequence):CharSequence {
override val length:Int get() = orig.length
override fun get(index: Int) = orig.get(index).let{ when (it) {
'\n', '\r', '\t' -> ' '
else -> it
} }
override fun subSequence(startIndex: Int, endIndex: Int):CharSequence {
val subSequence = orig.subSequence(startIndex, endIndex)
return subSequence.normalize()
}
override fun toString(): String {
return StringBuilder(length).append(this).toString()
}
}
fun CharSequence?.normalize():CharSequence = StringBuilder(this?.length?:0).apply {
this@normalize?.forEach { c ->
when(c) {
in '\u0000'..'\u001f', ' ', '\u00a0' -> if (length>0 && last()!=' ') append(' ')
else -> append(c)
}
}
}
fun CharSequence.tidy():CharSequence = StringBuilder(this.length).apply {
var addNewLines:Int=0
[email protected] { c ->
when(c) {
'\u000a', '\u000d' -> addNewLines ++
in '\u0000'..'\u0009', '\u000b', '\u000c', in '\u000e'..'\u001f', ' ', '\u00a0' -> if (length>0 && last()!=' ') append(' ')
else -> {
if (addNewLines>1){ appendln(); appendln() };
addNewLines=0;
append(c)
}
}
}
}
private fun Appendable._link(target:CharSequence, label: CharSequence?) {
if (label!=null) {
append("[$label]($target)")
} else if(target.startsWith('#')) {
append("[${target.substring(1)}]($target)")
} else {
append("<$target>")
}
}
private class MdGen(val out: Appendable): OutputGenerator {
override fun heading1(s: CharSequence) { out.appendln("# $s") }
override fun heading2(s: CharSequence) { out.appendln("## $s") }
override fun heading3(s: CharSequence) { out.appendln("### $s") }
override fun text(s: CharSequence) { out.appendln(s.tidy().wordWrap(WORDWRAP)) }
override fun appendln(s: CharSequence) { out.appendln(s) }
override fun appendln() { out.appendln() }
override fun link(target: CharSequence, label: CharSequence?) = out._link(target, label)
override fun table(vararg columns: String, block: Table.() -> Unit) {
MdTable(columns).apply { this.block() }.appendTo(out)
}
}
/**
* Append each of the charSequences in the parameters as a new line.
*
* @param seq The sequence of items to append.
*/
fun Appendable.appendln(seq: Sequence<CharSequence>) {
seq.forEach { appendln(it) }
}
| lgpl-3.0 | d39e80af1215a24cfee388828011c154 | 29.745161 | 141 | 0.63561 | 3.730333 | false | false | false | false |
toxxmeister/BLEacon | library/src/main/java/de/troido/bleacon/beaconno/BeaconnoScanner.kt | 1 | 2451 | package de.troido.bleacon.beaconno
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Handler
import de.troido.bleacon.ble.HandledBleActor
import de.troido.bleacon.ble.obtainScanner
import de.troido.bleacon.config.scan.scanSettings
import de.troido.bleacon.data.BleDeserializer
import de.troido.bleacon.data.UndefinedDeserializer
import de.troido.bleacon.scanner.BeaconMetaData
/**
* Example usage:
* ```
* BeaconnoScanner(
* context,
* bleFilter(uuid16 = Uuid16.fromString("17CF")),
* Int16Deserializer,
* UUID16_TRANSFORM,
* scanSettings()
* ) { scanner, device ->
* device.connect(
* context,
* bleConnectionCallback(
* Uuid16.fromString("23FF").toUuid(),
* Uuid16.fromString("4566").toUuid()
* ) { writer ->
* writer.write("Hello ${device.data}!".toByteArray())
* }
* )
* Log.d("Beaconno", "Found a beaconno with ${device.data}!")
* }
* ```
*/
class BeaconnoScanner<T>(context: Context,
filter: ScanFilter,
deserializer: BleDeserializer<T> = UndefinedDeserializer(),
dataTransform: (ByteArray) -> ByteArray,
private val settings: ScanSettings = scanSettings(),
handler: Handler = Handler(),
private val listener: OnBeaconno<T>
) : HandledBleActor(handler) {
private val scanner = obtainScanner()
private val filters = listOf(filter)
private val callback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
result.scanRecord
?.let {
BeaconnoDevice(context, deserializer, dataTransform, it,
BeaconMetaData(result.device, result.rssi, it.txPowerLevel))
}
?.let { listener(this@BeaconnoScanner, it) }
}
}
override fun start() {
handler.post { scanner.startScan(filters, settings, callback) }
}
override fun stop() {
handler.post { scanner.stopScan(callback) }
}
}
| apache-2.0 | 457ecc72179f1e00f149658fee3a2cea | 34.014286 | 99 | 0.596083 | 4.489011 | false | false | false | false |
matkoniecz/StreetComplete | app/src/test/java/de/westnordost/streetcomplete/data/elementfilter/filters/CombineFiltersTest.kt | 1 | 1175 | package de.westnordost.streetcomplete.data.elementfilter.filters
import de.westnordost.streetcomplete.testutils.any
import de.westnordost.streetcomplete.testutils.mock
import de.westnordost.streetcomplete.testutils.on
import org.junit.Assert.*
import org.junit.Test
class CombineFiltersTest {
@Test fun `does not match if one doesn't match`() {
val f1: ElementFilter = mock()
on(f1.matches(any())).thenReturn(true)
val f2: ElementFilter = mock()
on(f2.matches(any())).thenReturn(false)
assertFalse(CombineFilters(f1, f2).matches(null))
}
@Test fun `does match if all match`() {
val f1: ElementFilter = mock()
on(f1.matches(any())).thenReturn(true)
val f2: ElementFilter = mock()
on(f2.matches(any())).thenReturn(true)
assertTrue(CombineFilters(f1, f2).matches(null))
}
@Test fun `concatenates OQL`() {
val f1: ElementFilter = mock()
on(f1.toOverpassQLString()).thenReturn("hell")
val f2: ElementFilter = mock()
on(f2.toOverpassQLString()).thenReturn("o")
assertEquals("hello", CombineFilters(f1, f2).toOverpassQLString())
}
}
| gpl-3.0 | 7e5e955fd5648a8e704299a5de94a5a6 | 33.558824 | 74 | 0.666383 | 3.942953 | false | true | false | false |
WijayaPrinting/wp-javafx | openpss-client-android/src/com/hendraanggrian/openpss/ui/login/PasswordDialogFragment.kt | 1 | 3874 | package com.hendraanggrian.openpss.ui.login
import android.app.Dialog
import android.content.Context.INPUT_METHOD_SERVICE
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.View.OnFocusChangeListener
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import com.hendraanggrian.bundler.Extra
import com.hendraanggrian.bundler.bindExtras
import com.hendraanggrian.bundler.extrasOf
import com.hendraanggrian.openpss.BuildConfig2
import com.hendraanggrian.openpss.R
import com.hendraanggrian.openpss.R2
import com.hendraanggrian.openpss.api.OpenPSSApi
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.openpss.ui.BaseDialogFragment
import com.hendraanggrian.openpss.ui.TextDialogFragment
import com.hendraanggrian.openpss.ui.main.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class PasswordDialogFragment : BaseDialogFragment() {
@Extra lateinit var loginName: String
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
bindExtras()
val editText = EditText(context).apply {
if (BuildConfig2.DEBUG) setText(Employee.DEFAULT_PASSWORD)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
onFocusChangeListener = OnFocusChangeListener { view, _ ->
view.post {
val inputMethodManager =
context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}
val manager = openpssActivity.supportFragmentManager
val dialog = AlertDialog.Builder(context!!)
.setTitle(getString(R2.string.password))
.setView(FrameLayout(context!!).apply {
addView(editText)
val medium = context.resources.getDimensionPixelSize(R.dimen.padding_medium)
val large = context.resources.getDimensionPixelSize(R.dimen.padding_large)
(editText.layoutParams as ViewGroup.MarginLayoutParams).setMargins(
large,
medium,
large,
medium
)
})
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(getString(R2.string.login)) { _, _ ->
runBlocking {
runCatching {
val login = withContext(Dispatchers.IO) {
OpenPSSApi.login(loginName, editText.text)
}
if (login == Employee.NOT_FOUND) error(getString(R2.string.login_failed))
startActivity(
Intent(context, MainActivity::class.java).putExtras(
extrasOf<MainActivity>(
login.name,
login.isAdmin,
login.id.value
)
)
)
openpssActivity.finish()
}.onFailure {
if (BuildConfig2.DEBUG) it.printStackTrace()
TextDialogFragment()
.args(extrasOf<TextDialogFragment>(it.message.toString()))
.show(manager)
}
}
}
.create()
dialog.setOnShowListener { editText.requestFocus() }
return dialog
}
}
| apache-2.0 | 674408fd8c5aac26a7b18044f529b81a | 42.044444 | 97 | 0.602994 | 5.63901 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/world/archetype/LanternWorldArchetypeBuilder.kt | 1 | 8713 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.world.archetype
import org.lanternpowered.server.catalog.AbstractCatalogBuilder
import org.lanternpowered.server.world.LanternWorldProperties
import org.lanternpowered.server.world.dimension.LanternDimensionType
import org.lanternpowered.api.key.NamespacedKey
import org.spongepowered.api.data.persistence.DataContainer
import org.spongepowered.api.entity.living.player.gamemode.GameMode
import org.spongepowered.api.entity.living.player.gamemode.GameModes
import org.spongepowered.api.world.SerializationBehavior
import org.spongepowered.api.world.SerializationBehaviors
import org.spongepowered.api.world.WorldArchetype
import org.spongepowered.api.world.difficulty.Difficulties
import org.spongepowered.api.world.difficulty.Difficulty
import org.spongepowered.api.world.dimension.DimensionType
import org.spongepowered.api.world.dimension.DimensionTypes
import org.spongepowered.api.world.gen.GeneratorModifierType
import org.spongepowered.api.world.gen.GeneratorModifierTypes
import org.spongepowered.api.world.storage.WorldProperties
class LanternWorldArchetypeBuilder : AbstractCatalogBuilder<WorldArchetype, WorldArchetype.Builder>(), WorldArchetype.Builder {
private lateinit var gameMode: GameMode
private lateinit var difficulty: Difficulty
private lateinit var portalAgentType: LanternPortalAgentType<*>
private lateinit var serializationBehavior: SerializationBehavior
private lateinit var dimensionType: LanternDimensionType
// If not specified, fall back to dimension default
private var generatorModifier: GeneratorModifierType = GeneratorModifierTypes.NONE.get()
private var generatorSettings: DataContainer? = null
private var keepSpawnLoaded: Boolean? = null
private var waterEvaporates: Boolean? = null // Non-sponge property
private var allowPlayerRespawns: Boolean? = null // Non-sponge property
private var buildHeight = 0 // Non-sponge property
private var hardcore = false
private var enabled = false
private var loadOnStartup = false
private var generateStructures = true
private var commandEnabled = false
private var pvpEnabled = false
private var generateSpawnOnLoad = false
private var generateBonusChest = false
private var seedProvider: SeedProvider = SeedProvider.Random
init {
reset()
}
override fun from(archetype: WorldArchetype) = apply {
archetype as LanternWorldArchetype
this.difficulty = archetype.difficulty
this.hardcore = archetype.isHardcore
this.enabled = archetype.isEnabled
this.gameMode = archetype.gameMode
this.keepSpawnLoaded = archetype.keepSpawnLoaded
this.dimensionType = archetype.dimensionType
this.generatorModifier = archetype.generatorModifier
this.generatorSettings = archetype.generatorSettings
this.generateStructures = archetype.areStructuresEnabled()
this.commandEnabled = archetype.areCommandsEnabled()
this.waterEvaporates = archetype.waterEvaporates
this.buildHeight = archetype.buildHeight
this.allowPlayerRespawns = archetype.allowPlayerRespawns
this.pvpEnabled = archetype.isPVPEnabled
this.generateSpawnOnLoad = archetype.doesGenerateSpawnOnLoad()
this.generateBonusChest = archetype.doesGenerateBonusChest()
this.seedProvider = archetype.seedProvider
}
override fun from(properties: WorldProperties) = apply {
properties as LanternWorldProperties
this.difficulty = properties.difficulty
this.hardcore = properties.isHardcore
this.enabled = properties.isEnabled
this.gameMode = properties.gameMode
this.keepSpawnLoaded = properties.doesKeepSpawnLoaded()
this.seedProvider = SeedProvider.Constant(properties.seed)
this.dimensionType = properties.dimensionType
this.generatorModifier = properties.generatorModifierType
this.generatorSettings = properties.generatorSettings.copy()
this.generateStructures = properties.areStructuresEnabled()
this.waterEvaporates = properties.doesWaterEvaporate
this.buildHeight = properties.maxBuildHeight
this.pvpEnabled = properties.isPVPEnabled
this.generateSpawnOnLoad = properties.doesGenerateSpawnOnLoad()
this.generateBonusChest = properties.doesGenerateBonusChest()
}
override fun enabled(state: Boolean) = apply { this.enabled = state }
override fun loadOnStartup(state: Boolean) = apply { this.loadOnStartup = state }
override fun keepSpawnLoaded(state: Boolean) = apply { this.keepSpawnLoaded = state }
override fun generateSpawnOnLoad(state: Boolean) = apply { this.generateSpawnOnLoad = state }
override fun seed(seed: Long) = apply { this.seedProvider = SeedProvider.Constant(seed) }
override fun randomSeed() = apply { this.seedProvider = SeedProvider.Random }
override fun gameMode(gameMode: GameMode) = apply { this.gameMode = gameMode }
override fun generatorModifierType(modifier: GeneratorModifierType) = apply { this.generatorModifier = modifier }
override fun dimensionType(type: DimensionType) = apply { this.dimensionType = type as LanternDimensionType }
override fun difficulty(difficulty: Difficulty) = apply { this.difficulty = difficulty }
override fun generateStructures(state: Boolean) = apply { this.generateStructures = state }
override fun hardcore(enabled: Boolean) = apply { this.hardcore = enabled }
override fun generatorSettings(settings: DataContainer) = apply { this.generatorSettings = settings }
override fun pvpEnabled(enabled: Boolean) = apply { this.pvpEnabled = enabled }
override fun commandsEnabled(enabled: Boolean) = apply { this.commandEnabled = enabled }
override fun serializationBehavior(behavior: SerializationBehavior) = apply { this.serializationBehavior = behavior }
override fun generateBonusChest(enabled: Boolean) = apply { this.generateBonusChest = enabled }
fun waterEvaporates(evaporates: Boolean) = apply { this.waterEvaporates = evaporates }
fun allowPlayerRespawns(allow: Boolean) = apply { this.allowPlayerRespawns = allow }
fun buildHeight(buildHeight: Int) = apply {
check(buildHeight <= 256) { "the build height cannot be greater then 256" }
this.buildHeight = buildHeight
}
override fun build(key: NamespacedKey): WorldArchetype {
return LanternWorldArchetype(key,
allowPlayerRespawns = this.allowPlayerRespawns,
buildHeight = this.buildHeight,
commandsEnabled = this.commandEnabled,
difficulty = this.difficulty,
dimensionType = this.dimensionType,
enabled = this.enabled,
gameMode = this.gameMode,
generateStructures = this.generateStructures,
generateSpawnOnLoad = this.generateSpawnOnLoad,
generateBonusChest = this.generateBonusChest,
generatorSettings = this.generatorSettings,
generatorModifier = this.generatorModifier,
hardcore = this.hardcore,
keepSpawnLoaded = this.keepSpawnLoaded,
loadsOnStartup = this.loadOnStartup,
seedProvider = this.seedProvider,
serializationBehavior = this.serializationBehavior,
portalAgentType = this.portalAgentType,
pvpEnabled = this.pvpEnabled,
waterEvaporates = this.waterEvaporates
)
}
override fun reset() = apply {
this.gameMode = GameModes.SURVIVAL.get()
this.difficulty = Difficulties.NORMAL.get()
this.hardcore = false
this.keepSpawnLoaded = null
this.loadOnStartup = false
this.generateSpawnOnLoad = true
this.enabled = true
this.generateStructures = true
this.commandEnabled = true
this.dimensionType = DimensionTypes.OVERWORLD.get() as LanternDimensionType
this.seedProvider = SeedProvider.Random
this.generatorModifier = GeneratorModifierTypes.NONE.get()
this.generatorSettings = null
this.waterEvaporates = null
this.buildHeight = 256
this.serializationBehavior = SerializationBehaviors.AUTOMATIC.get()
this.generateBonusChest = false
}
}
| mit | 882efd6875927332a2eb72fbd7074aad | 49.953216 | 127 | 0.733846 | 5.255127 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/util/TokenCreationWrapper.kt | 1 | 6699 | package com.mercadopago.android.px.internal.util
import com.mercadopago.android.px.addons.ESCManagerBehaviour
import com.mercadopago.android.px.addons.model.EscDeleteReason
import com.mercadopago.android.px.internal.callbacks.TaggedCallback
import com.mercadopago.android.px.internal.extensions.isNotNullNorEmpty
import com.mercadopago.android.px.internal.repository.CardTokenRepository
import com.mercadopago.android.px.model.*
import com.mercadopago.android.px.model.exceptions.CardTokenException
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.model.exceptions.MercadoPagoErrorWrapper
import com.mercadopago.android.px.tracking.internal.model.Reason
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
internal class TokenCreationWrapper private constructor(builder: Builder) {
private val cardTokenRepository: CardTokenRepository
private val escManagerBehaviour: ESCManagerBehaviour
private val card: Card?
private val token: Token?
private val paymentMethod: PaymentMethod
private val reason: Reason
init {
cardTokenRepository = builder.cardTokenRepository
escManagerBehaviour = builder.escManagerBehaviour
card = builder.card
token = builder.token
paymentMethod = builder.paymentMethod!!
reason = builder.reason!!
}
suspend fun createToken(cvv: String): Token {
return if (escManagerBehaviour.isESCEnabled) {
createTokenWithEsc(cvv)
} else {
createTokenWithoutEsc(cvv)
}
}
suspend fun createTokenWithEsc(cvv: String): Token {
return if (card != null) {
SavedESCCardToken.createWithSecurityCode(card.id!!, cvv).run {
validateSecurityCode(card)
createESCToken(this).apply { lastFourDigits = card.lastFourDigits }
}
} else {
SavedESCCardToken.createWithSecurityCode(token!!.cardId, cvv).run {
validateCVVFromToken(cvv)
createESCToken(this)
}
}
}
suspend fun createTokenWithoutEsc(cvv: String) =
SavedCardToken(card!!.id, cvv).run {
validateSecurityCode(card)
createToken(this)
}
suspend fun cloneToken(cvv: String) = putCVV(cvv, doCloneToken().id)
@Throws(CardTokenException::class)
fun validateCVVFromToken(cvv: String): Boolean {
if (token?.firstSixDigits.isNotNullNorEmpty()) {
CardToken.validateSecurityCode(cvv, paymentMethod, token!!.firstSixDigits)
} else if (!CardToken.validateSecurityCode(cvv)) {
throw CardTokenException(CardTokenException.INVALID_FIELD)
}
return true
}
private suspend fun createESCToken(savedESCCardToken: SavedESCCardToken): Token {
return suspendCoroutine {cont ->
cardTokenRepository
.createToken(savedESCCardToken).enqueue(object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
if (Reason.ESC_CAP == reason) { // Remove previous esc for tracking purpose
escManagerBehaviour.deleteESCWith(savedESCCardToken.cardId, EscDeleteReason.ESC_CAP, null)
}
cardTokenRepository.clearCap(savedESCCardToken.cardId) { cont.resume(token) }
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
private suspend fun createToken(savedCardToken: SavedCardToken): Token {
return suspendCoroutine {cont ->
cardTokenRepository
.createToken(savedCardToken).enqueue(object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
cont.resume(token)
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
private suspend fun doCloneToken(): Token {
return suspendCoroutine {cont ->
cardTokenRepository.cloneToken(token!!.id)
.enqueue(object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
cont.resume(token)
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
private suspend fun putCVV(cvv: String, tokenId: String): Token {
return suspendCoroutine {cont ->
cardTokenRepository.putSecurityCode(cvv, tokenId).enqueue(
object : TaggedCallback<Token>(ApiUtil.RequestOrigin.CREATE_TOKEN) {
override fun onSuccess(token: Token) {
cont.resume(token)
}
override fun onFailure(error: MercadoPagoError) {
cont.resumeWithException(MercadoPagoErrorWrapper(error))
}
})
}
}
class Builder(val cardTokenRepository: CardTokenRepository, val escManagerBehaviour: ESCManagerBehaviour) {
var card: Card? = null
private set
var token: Token? = null
private set
var paymentMethod: PaymentMethod? = null
private set
var reason: Reason? = Reason.NO_REASON
private set
fun with(card: Card) = apply {
this.card = card
this.paymentMethod = card.paymentMethod
}
fun with(token: Token) = apply { this.token = token }
fun with(paymentMethod: PaymentMethod) = apply { this.paymentMethod = paymentMethod }
fun with(paymentRecovery: PaymentRecovery) = apply {
card = paymentRecovery.card
token = paymentRecovery.token
paymentMethod = paymentRecovery.paymentMethod
reason = Reason.from(paymentRecovery)
}
fun build(): TokenCreationWrapper {
check(!(token == null && card == null)) { "Token and card can't both be null" }
checkNotNull(paymentMethod) { "Payment method not set" }
return TokenCreationWrapper(this)
}
}
} | mit | 9e371b3b8d050e1007372b8e6fad4736 | 37.953488 | 124 | 0.625019 | 5.3592 | false | false | false | false |
PaulWoitaschek/Voice | playback/src/main/kotlin/voice/playback/PlayerController.kt | 1 | 2507 | package voice.playback
import android.content.ComponentName
import android.content.Context
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.session.MediaControllerCompat
import voice.data.Chapter
import voice.logging.core.Logger
import voice.playback.misc.Decibel
import voice.playback.session.PlaybackService
import voice.playback.session.forcedNext
import voice.playback.session.forcedPrevious
import voice.playback.session.pauseWithRewind
import voice.playback.session.playPause
import voice.playback.session.setGain
import voice.playback.session.setPosition
import voice.playback.session.setVolume
import voice.playback.session.skipSilence
import javax.inject.Inject
import kotlin.time.Duration
class PlayerController
@Inject constructor(
private val context: Context,
) {
private var _controller: MediaControllerCompat? = null
private val callback = object : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
super.onConnected()
Logger.v("onConnected")
_controller = MediaControllerCompat(context, browser.sessionToken)
}
override fun onConnectionSuspended() {
super.onConnectionSuspended()
Logger.v("onConnectionSuspended")
_controller = null
}
override fun onConnectionFailed() {
super.onConnectionFailed()
Logger.d("onConnectionFailed")
_controller = null
}
}
private val browser: MediaBrowserCompat = MediaBrowserCompat(
context,
ComponentName(context, PlaybackService::class.java),
callback,
null,
)
init {
browser.connect()
}
fun setPosition(time: Long, id: Chapter.Id) = execute { it.setPosition(time, id) }
fun skipSilence(skip: Boolean) = execute { it.skipSilence(skip) }
fun fastForward() = execute { it.fastForward() }
fun rewind() = execute { it.rewind() }
fun previous() = execute { it.forcedPrevious() }
fun next() = execute { it.forcedNext() }
fun play() = execute { it.play() }
fun playPause() = execute { it.playPause() }
fun pauseWithRewind(rewind: Duration) = execute { it.pauseWithRewind(rewind) }
fun setSpeed(speed: Float) = execute { it.setPlaybackSpeed(speed) }
fun setGain(gain: Decibel) = execute { it.setGain(gain) }
fun setVolume(volume: Float) = execute {
require(volume in 0F..1F)
it.setVolume(volume)
}
private inline fun execute(action: (MediaControllerCompat.TransportControls) -> Unit) {
_controller?.transportControls?.let(action)
}
}
| gpl-3.0 | 96cc5f49799484acc0520089818c2d49 | 26.855556 | 89 | 0.737934 | 4.278157 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.