repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/bean/PageInterceptorBean.kt | 1 | 977 | package com.xiaojinzi.component.bean
import com.xiaojinzi.component.anno.support.CheckClassNameAnno
import com.xiaojinzi.component.impl.RouterInterceptor
/**
* [.stringInterceptor] 和 [.classInterceptor] 必须有一个是有值的
*/
@CheckClassNameAnno
class PageInterceptorBean constructor(
/**
* 优先级
*/
val priority: Int,
val stringInterceptor: String? = null,
val classInterceptor: Class<out RouterInterceptor>? = null,
) {
constructor(
priority: Int,
stringInterceptor: String? = null,
) : this(
priority = priority,
stringInterceptor = stringInterceptor,
classInterceptor = null,
)
constructor(
priority: Int,
classInterceptor: Class<out RouterInterceptor>? = null,
) : this(
priority = priority,
stringInterceptor = null,
classInterceptor = classInterceptor,
)
} | apache-2.0 | 7cdda67daad4057a7c824468813061c3 | 25.444444 | 67 | 0.6204 | 4.684729 | false | false | false | false |
nevi-me/turf-kotlin | src/main/kotlin/za/co/movinggauteng/turfkotlin/measurement/Distance.kt | 1 | 882 | package za.co.movinggauteng.turfkotlin.measurement
import za.co.movinggauteng.turfkotlin.geojson.Point
import za.co.movinggauteng.turfkotlin.geojson.getCoord
import za.co.movinggauteng.turfkotlin.helpers.Factors
import za.co.movinggauteng.turfkotlin.helpers.Units
import java.lang.StrictMath.*
/**
* Created by Neville on 25 Feb 2017.
*/
fun distance(start: Point, end: Point, units: Units = Units.TURF_KILOMETERS) : Double {
val coordinates1 = start.getCoord()
val coordinates2 = end.getCoord()
val dLat = toRadians(coordinates2.second - coordinates1.second)
val dLon = toRadians(coordinates2.first - coordinates1.first)
val lat1 = toRadians(coordinates1.second)
val lat2 = toRadians(coordinates2.second)
val a = pow(sin(dLat/2), 2.0) + pow(sin(dLon/2), 2.0) * cos(lat1) * cos(lat2)
return 2 * Factors[units]!! * atan2(sqrt(a), sqrt(1-a))
} | apache-2.0 | 46d8bb0fc7f98c1374ea4754b685ba1f | 32.961538 | 87 | 0.734694 | 3.010239 | false | false | false | false |
jitsi/jicofo | jicofo-selector/src/main/kotlin/org/jitsi/jicofo/bridge/RegionBasedBridgeSelectionStrategy.kt | 1 | 6300 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.jicofo.bridge
import org.jitsi.jicofo.JicofoConfig
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.LoggerImpl
/**
* Implements a [BridgeSelectionStrategy] which attempts to select bridges in the participant's region.
*
* Specifically, it implements the following algorithm:
*
* (Happy case 1): If there is a non-overloaded bridge in the conference
* and in the region: use the least loaded of them.
* (Happy case 1A): If there is a non-overloaded bridge in the conference
* and in the region's group: use the least loaded of them.
* (Happy case 2): If there is a non-overloaded bridge in the region,
* and the conference has no bridges in the region: use the least loaded bridge
* in the region.
* (Happy case 2A): If there is a non-overloaded bridge in the region's group,
* and the conference has no bridges in the region's group: use the least loaded bridge
* in the region's group.
*
* (Split case 1): If there is a non-overloaded bridge in the region, the
* conference has bridges in the region but all are overloaded: Use the least
* loaded of the bridges in the region.
* (Split case 1A): If there is a non-overloaded bridge in the region's group, the
* conference has bridges in the region's group but all are overloaded: Use the least
* loaded of the bridges in the region.
*
* (Overload case 1): If all bridges in the region's group are overloaded, and the
* conference has a bridge in the region's group: use the least loaded conference
* bridge in the region's group.
* (Overload case 2): If all bridges in the region's group are overloaded, and the
* conference has no bridges in the region's group: use the least loaded bridge in
* the region's group.
*
* (No-region-match case 1): If there are no bridges in the region's group, and the
* conference has a non-overloaded bridge: use the least loaded conference bridge.
* (No-region-match case 2): If there are no bridges in the region's group and all
* conference bridges are overloaded: use the least loaded bridge.
*
*/
class RegionBasedBridgeSelectionStrategy : BridgeSelectionStrategy() {
/**
* Map a region to the set of all regions in its group (including itself).
*/
val localRegion = JicofoConfig.config.localRegion()
override fun doSelect(
bridges: List<Bridge>,
conferenceBridges: Map<Bridge, ConferenceBridgeProperties>,
participantProperties: ParticipantProperties
): Bridge? {
if (bridges.isEmpty()) {
return null
}
val participantRegion = participantProperties.region
var region = participantRegion ?: localRegion
if (localRegion != null) {
val regionGroup = getRegionGroup(region)
if (conferenceBridges.isEmpty() && region != localRegion) {
// Selecting an initial bridge for a participant not in the local region. This is most likely because
// exactly one of the first two participants in the conference is not in the local region, and we're
// selecting for it first. I.e. there is another participant in the local region which will be
// subsequently invited.
if (regionGroup.contains(localRegion)) {
// With the above assumption, there are two participants in the local region group. Therefore,
// they will use the same bridge. Prefer to use a bridge in the local region.
region = localRegion
}
}
// If there are no bridges in the participant region or region group, select from the local region instead.
if (bridges.none { regionGroup.contains(it.region) }) {
region = localRegion
}
}
return notLoadedAlreadyInConferenceInRegion(bridges, conferenceBridges, participantProperties, region)
?: notLoadedAlreadyInConferenceInRegionGroup(bridges, conferenceBridges, participantProperties, region)
?: notLoadedInRegion(bridges, conferenceBridges, participantProperties, region)
?: notLoadedInRegionGroup(bridges, conferenceBridges, participantProperties, region)
?: leastLoadedAlreadyInConferenceInRegion(bridges, conferenceBridges, participantProperties, region)
?: leastLoadedAlreadyInConferenceInRegionGroup(bridges, conferenceBridges, participantProperties, region)
?: leastLoadedInRegion(bridges, conferenceBridges, participantProperties, region)
?: leastLoadedInRegionGroup(bridges, conferenceBridges, participantProperties, region)
?: nonLoadedAlreadyInConference(bridges, conferenceBridges, participantProperties)
?: leastLoaded(bridges, conferenceBridges, participantProperties)
}
override fun toString(): String {
return "${javaClass.simpleName} with region groups: ${BridgeConfig.config.regionGroups}"
}
override fun select(
bridges: List<Bridge>,
conferenceBridges: Map<Bridge, ConferenceBridgeProperties>,
participantProperties: ParticipantProperties,
allowMultiBridge: Boolean
): Bridge? {
if (!allowMultiBridge) {
logger.warn(
"Octo is disabled, but the selection strategy is RegionBased. Enable octo in jicofo.conf to " +
"allow use of multiple bridges in a conference."
)
}
return super.select(bridges, conferenceBridges, participantProperties, allowMultiBridge)
}
companion object {
private val logger: Logger = LoggerImpl(RegionBasedBridgeSelectionStrategy::class.java.name)
}
}
| apache-2.0 | bfdc6cf4e1e881bc66f6ec9007fe8e20 | 48.606299 | 119 | 0.699048 | 4.801829 | false | false | false | false |
oldergod/red | app/src/main/java/com/benoitquenaudon/tvfoot/red/app/domain/matches/MatchesBindingModel.kt | 1 | 1974 | package com.benoitquenaudon.tvfoot.red.app.domain.matches
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import javax.inject.Inject
class MatchesBindingModel @Inject constructor(private val adapter: MatchesAdapter) {
var refreshLoading = ObservableBoolean(false)
var hasError = ObservableBoolean(false)
var hasData = ObservableBoolean(false)
var nextPageLoading = false
var hasMore = true
var loadingSpecificMatches = false
var errorMessage = ObservableField<String>()
var currentPage = 0
private set
var areTagsLoaded = ObservableBoolean(false)
var hasActiveFilters = ObservableBoolean(false)
fun updateFromState(state: MatchesViewState) {
currentPage = state.currentPage
areTagsLoaded.set(state.tags.isNotEmpty())
hasActiveFilters.set(
state.filteredBroadcasters.isNotEmpty() ||
state.filteredCompetitions.isNotEmpty() ||
state.filteredTeams.isNotEmpty())
nextPageLoading = state.nextPageLoading
hasError.set(state.error != null)
hasMore = state.hasMore
loadingSpecificMatches = state.teamMatchesLoading
if (hasError.get()) {
val error = checkNotNull(state.error) { "state error is null" }
errorMessage.set(error.toString())
}
val matchesDisplayables = state.matchesItemDisplayables(
nextPageLoading = state.nextPageLoading,
loadingSpecificMatches = loadingSpecificMatches,
filteredBroadcasters = state.filteredBroadcasters,
filteredCompetitions = state.filteredCompetitions,
filteredTeams = state.filteredTeams
)
refreshLoading.set(state.refreshLoading ||
(matchesDisplayables.isEmpty() && state.teamMatchesLoading))
hasData.set(matchesDisplayables.isNotEmpty() ||
state.refreshLoading ||
state.nextPageLoading ||
state.teamMatchesLoading)
if (hasData.get()) {
adapter.setMatchesItems(matchesDisplayables)
}
}
}
| apache-2.0 | 3e22658438bf31901d3529cde6e5cb77 | 34.890909 | 84 | 0.737589 | 4.779661 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/suggestededits/SuggestedEditsCardView.kt | 1 | 2797 | package org.wikipedia.feed.suggestededits
import android.content.Context
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.tabs.TabLayoutMediator
import org.wikipedia.WikipediaApp
import org.wikipedia.databinding.ViewSuggestedEditsCardBinding
import org.wikipedia.feed.view.CardFooterView
import org.wikipedia.feed.view.DefaultFeedCardView
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.util.L10nUtil
import org.wikipedia.views.PositionAwareFragmentStateAdapter
class SuggestedEditsCardView(context: Context) : DefaultFeedCardView<SuggestedEditsCard>(context), CardFooterView.Callback {
interface Callback {
fun onSeCardFooterClicked()
}
private val binding = ViewSuggestedEditsCardBinding.inflate(LayoutInflater.from(context), this, true)
override var card: SuggestedEditsCard? = null
set(value) {
field = value
value?.let {
header(it)
updateContents(it)
}
}
override var callback: FeedAdapter.Callback? = null
set(value) {
field = value
binding.headerView.setCallback(value)
}
override fun onFooterClicked() {
callback?.onSeCardFooterClicked()
}
private fun updateContents(card: SuggestedEditsCard) {
setUpPagerWithSECards(card)
binding.cardFooter.setFooterActionText(card.footerActionText(), null)
binding.cardFooter.callback = this
}
private fun setUpPagerWithSECards(card: SuggestedEditsCard) {
binding.seCardsPager.adapter = SECardsPagerAdapter(context as AppCompatActivity, card)
binding.seCardsPager.offscreenPageLimit = 3
L10nUtil.setConditionalLayoutDirection(binding.seCardsPager, WikipediaApp.instance.wikiSite.languageCode)
L10nUtil.setConditionalLayoutDirection(binding.seCardsIndicatorLayout, WikipediaApp.instance.wikiSite.languageCode)
TabLayoutMediator(binding.seCardsIndicatorLayout, binding.seCardsPager) { _, _ -> }.attach()
}
private fun header(card: SuggestedEditsCard) {
binding.headerView.setTitle(card.title())
.setCard(card)
.setLangCode(null)
.setCallback(callback)
}
class SECardsPagerAdapter(activity: AppCompatActivity, private val card: SuggestedEditsCard) : PositionAwareFragmentStateAdapter(activity) {
override fun getItemCount(): Int {
return 3 // description, caption, image tags
}
override fun createFragment(position: Int): Fragment {
return SuggestedEditsCardItemFragment.newInstance(card.age, card.summaryList?.getOrNull(position), card.imageTagsPage)
}
}
}
| apache-2.0 | c645cc98238ea1d82371feb05b4b1b0d | 37.847222 | 144 | 0.726493 | 4.915641 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/fragments/PlatformFragment.kt | 1 | 4935 | /*
* Copyright (c) 2017. ThanksMister LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thanksmister.iot.mqtt.alarmpanel.ui.fragments
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.thanksmister.iot.mqtt.alarmpanel.BaseFragment
import com.thanksmister.iot.mqtt.alarmpanel.R
import com.thanksmister.iot.mqtt.alarmpanel.ui.Configuration
import com.thanksmister.iot.mqtt.alarmpanel.utils.DialogUtils
import kotlinx.android.synthetic.main.fragment_platform.*
import timber.log.Timber
import javax.inject.Inject
import android.widget.CheckBox
import com.baviux.homeassistant.HassWebView
class PlatformFragment : BaseFragment(){
@Inject lateinit var configuration: Configuration
@Inject lateinit var dialogUtils: DialogUtils
private var listener: OnPlatformFragmentListener? = null
interface OnPlatformFragmentListener {
fun navigateAlarmPanel()
fun setPagingEnabled(value: Boolean)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnPlatformFragmentListener) {
listener = context
} else {
throw RuntimeException(context!!.toString() + " must implement OnPlatformFragmentListener")
}
}
override fun onResume() {
super.onResume()
loadWebPage()
if (configuration.platformBar) {
settingsContainer.visibility = View.VISIBLE;
checkbox_hide.isChecked = false
} else {
settingsContainer.visibility = View.GONE;
checkbox_hide.isChecked = true
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(dialogUtils)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button_alarm.setOnClickListener({
if(listener != null) {
webView.closeMoreInfoDialog()
listener!!.navigateAlarmPanel()
}
})
button_refresh.setOnClickListener({
loadWebPage()
})
checkbox_hide.setOnClickListener { v ->
if ((v as CheckBox).isChecked) {
settingsContainer.visibility = View.GONE;
} else {
settingsContainer.visibility = View.VISIBLE;
}
configuration.platformBar = !v.isChecked
}
}
private fun loadWebPage() {
if (configuration.hasPlatformModule() && !TextUtils.isEmpty(configuration.webUrl) && webView != null) {
webView.loadUrl(configuration.webUrl)
webView.setAdjustBackKeyBehavior(configuration.adjustBackBehavior)
webView.setHideAdminMenuItems(configuration.hideAdminMenu)
webView.setOnFinishEventHandler { button_alarm.callOnClick() }
webView.setMoreInfoDialogHandler(object : HassWebView.IMoreInfoDialogHandler{
override fun onShowMoreInfoDialog() {
listener!!.setPagingEnabled(false)
}
override fun onHideMoreInfoDialog() {
listener!!.setPagingEnabled(true)
}
})
} else if (webView != null) {
webView.loadUrl("about:blank")
}
}
override fun onBackPressed() : Boolean{
if (webView == null) {
return super.onBackPressed()
}
val handled = webView.onBackPressed()
// If HassWebView doesn't handle it -> ensure no hass dialog is shown and paging is restored
if (!handled){
webView.closeMoreInfoDialog()
}
return handled;
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_platform, container, false)
}
override fun onDetach() {
super.onDetach()
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*/
fun newInstance(): PlatformFragment {
return PlatformFragment()
}
}
}// Required empty public constructor | apache-2.0 | 655c1aace0d5b53ddb475235f725d6be | 32.578231 | 116 | 0.656535 | 4.857283 | false | true | false | false |
RobertoArtiles/KittenGIFs | app/src/main/java/com/the_roberto/kittengifs/model/kittens/KittensManager.kt | 1 | 3020 | package com.the_roberto.kittengifs.model.kittens
import android.content.Context
import com.the_roberto.kittengifs.EventsTracker
import com.the_roberto.kittengifs.R
import com.the_roberto.kittengifs.dagger.ForApplication
import com.the_roberto.kittengifs.giphy.GiphyService
import com.the_roberto.kittengifs.giphy.SearchGifResponse
import com.the_roberto.kittengifs.model.Settings
import com.the_roberto.kittengifs.model.event.KittenFailedEvent
import com.the_roberto.kittengifs.model.event.KittenLoadedEvent
import okhttp3.OkHttpClient
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class KittensManager @Inject constructor(@ForApplication val context: Context, val settings: Settings, val eventBus: EventBus) {
private var service: GiphyService
private val random = Random()
init {
val client = OkHttpClient.Builder().addNetworkInterceptor { chain ->
val request = chain.request()
val url = request.url()
.newBuilder()
.addQueryParameter("api_key", context.getString(R.string.api_key))
.addQueryParameter("rating", "g")
.build()
val newRequest = request.newBuilder().url(url).build()
return@addNetworkInterceptor chain.proceed(newRequest)
}.build()
val restAdapter = Retrofit.Builder()
.client(client)
.baseUrl("http://api.giphy.com/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build()
service = restAdapter.create(GiphyService::class.java)
}
fun loadNextKitten() {
service.getGifs("kitten", random.nextInt(Math.max(1, settings.getMaxOffset())).toLong(), 1)
.enqueue(object : Callback<SearchGifResponse> {
override fun onResponse(call: Call<SearchGifResponse>, response: Response<SearchGifResponse>) {
if (response.isSuccessful) {
val original = response.body().data?.get(0)?.images?.original!!
eventBus.post(KittenLoadedEvent(original.url!!, original.mp4!!))
settings.setLastOpenedKitten(original.mp4)
settings.setKittenToShareUrl(original.url)
settings.setMaxOffset(response.body().pagination?.totalCount)
} else {
eventBus.post(KittenFailedEvent())
}
}
override fun onFailure(call: Call<SearchGifResponse>, error: Throwable) {
EventsTracker.trackFailedKitten()
eventBus.post(KittenFailedEvent())
}
})
}
} | apache-2.0 | 6da58bfff2b94ec23ddf33f71136869c | 40.958333 | 128 | 0.631126 | 4.886731 | false | false | false | false |
colesadam/hill-lists | app/src/main/java/uk/colessoft/android/hilllist/dao/HillDetailDao.kt | 1 | 2570 | package uk.colessoft.android.hilllist.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.Transaction
import androidx.sqlite.db.SimpleSQLiteQuery
import uk.colessoft.android.hilllist.domain.HillDetail
@Dao
abstract class HillDetailDao {
val hillQuery: String
get() {
return """SELECT DISTINCT h_id, latitude, longitude,Metres,Feet,
name,notes,dateClimbed,b_id from hills
JOIN typeslink ON typeslink.hill_id = h_id
LEFT JOIN bagging ON b_id = h_id
JOIN hilltypes ON typeslink.type_Id = ht_id"""
}
@Query("SELECT DISTINCT h_id, latitude, longitude,Metres,Feet,name,notes,dateClimbed,b_id from hills JOIN typeslink ON typeslink.hill_id = h_id LEFT JOIN bagging ON b_id = h_id JOIN hilltypes ON typeslink.type_Id = ht_id")
abstract fun getHills(): LiveData<List<HillDetail>>
@Transaction
@Query("SELECT * FROM hills WHERE h_id = :hillId")
abstract fun getHillDetail(hillId: Long): LiveData<HillDetail>
@RawQuery
abstract fun getHillsRaw(query: SimpleSQLiteQuery): LiveData<List<HillDetail>>
fun getHills(groupId: String?, country: CountryClause?, moreFilters: String?): LiveData<List<HillDetail>> {
return getHillsRaw(
SimpleSQLiteQuery("$hillQuery " + whereClause(groupId, country, moreFilters)
+ " order by " + HillsOrder.HEIGHT_DESC.sql, arrayOf()))
}
private fun whereClause(groupId: String?, country: CountryClause?, moreFilters: String?): String {
if ("T100" == groupId) return "WHERE " + getT100(moreFilters)
fun groupClause(groupId: String?): String {
return groupId?.split(",")?.fold("") { currentValue, result ->
currentValue + "title = '$result' OR "
}?.trim { it <= ' ' }?.dropLast(3) ?: ""
}
if (groupId != null || country != null || moreFilters != null) {
return "WHERE " + addToWhere(moreFilters,
addToWhere(country?.sql,
addToWhere(groupClause(groupId), "")
)
).removeSuffix(" AND ")
} else return ""
}
private fun getT100(moreFilters: String?): String {
return addToWhere(moreFilters, "T100='1'")
}
private fun addToWhere(filter: String?, where: String): String {
return (if ("" != where && !filter.isNullOrEmpty())
"$where AND " else where) + (filter ?: "")
}
} | mit | bcf2814ce18096fcaf026c1f78bedbf7 | 35.728571 | 226 | 0.62607 | 4.066456 | false | false | false | false |
mightyfrog/S4FD | app/src/main/java/org/mightyfrog/android/s4fd/details/tabcontents/attacks/AttacksFragment.kt | 1 | 3445 | package org.mightyfrog.android.s4fd.details.tabcontents.attacks
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Surface
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.mightyfrog.android.s4fd.R
import org.mightyfrog.android.s4fd.compare.CompareActivity
import org.mightyfrog.android.s4fd.data.KHCharacter
import org.mightyfrog.android.s4fd.data.Move
import org.mightyfrog.android.s4fd.details.tabcontents.BaseFragment
import java.util.*
/**
* @author Shigehiro Soejima
*/
class AttacksFragment : BaseFragment(), AttacksContract.View {
private lateinit var attackPresenter: AttacksPresenter
private val listener = object : OnItemClickListener {
override fun onItemClick(name: String) {
attackPresenter.compare(name)
}
}
private val adapter = AttacksAdapter(ArrayList(0), listener)
companion object {
fun newInstance(b: Bundle): AttacksFragment = AttacksFragment().apply {
arguments = b
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AttacksPresenter(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_tab_content, container, false)?.apply {
val rv = findViewById<RecyclerView>(R.id.recyclerView)
rv.adapter = adapter
val glm = GridLayoutManager(context, 2)
glm.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (surfaceRotation == Surface.ROTATION_0 || surfaceRotation == Surface.ROTATION_180) 2 else 1
}
}
rv.layoutManager = glm
rv.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
arguments?.apply {
attackPresenter.loadMoves(getInt("id"))
}
}
override fun showComparison(name: String, charToCompare: KHCharacter?) {
Intent(activity, CompareActivity::class.java).apply {
putExtra("name", name)
putExtra("ownerId", arguments?.getInt("id"))
putExtra("charToCompareId", charToCompare?.id)
startActivity(this)
// activity.overridePendingTransition(R.anim.slide_in_up, 0)
}
}
override fun showMoves(list: List<Move>) {
adapter.update(list)
}
override fun showErrorMessage(msg: String) {
activity?.apply {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
}
override fun showErrorMessage(resId: Int) {
showErrorMessage(getString(resId))
}
override fun setPresenter(presenter: AttacksPresenter) {
attackPresenter = presenter
}
fun setCharToCompare(char: KHCharacter?) { // hmmm...
attackPresenter.setCharToCompare(char)
}
interface OnItemClickListener {
fun onItemClick(name: String)
}
} | apache-2.0 | f20990437e2f129f8fc4ca301aab4041 | 32.134615 | 121 | 0.685341 | 4.778086 | false | false | false | false |
Omico/CurrentActivity | ui/monitor/src/main/kotlin/me/omico/currentactivity/ui/monitor/MonitorUi.kt | 1 | 4030 | /*
* This file is part of CurrentActivity.
*
* Copyright (C) 2022 Omico
*
* CurrentActivity 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.
*
* CurrentActivity 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 CurrentActivity. If not, see <https://www.gnu.org/licenses/>.
*/
package me.omico.currentactivity.ui.monitor
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import me.omico.currentactivity.shizuku.ShizukuBinderStatus
import me.omico.currentactivity.shizuku.ShizukuPermissionStatus
import me.omico.currentactivity.shizuku.ShizukuStatus
import me.omico.currentactivity.ui.rememberCurrentActivityText
import me.omico.currentactivity.ui.rememberShizukuStatus
import rikka.shizuku.Shizuku
@Composable
fun MonitorUi() {
val shizukuStatus by rememberShizukuStatus(requestPermissionAfterChecked = true)
Box(
modifier = run {
Modifier
.fillMaxSize()
.padding(horizontal = 16.dp)
},
) {
Card(
modifier = Modifier.fillMaxSize(),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.7f),
),
) {
Crossfade(
modifier = run {
Modifier
.fillMaxSize()
.clickable {
when (shizukuStatus) {
is ShizukuPermissionStatus.Denied -> Shizuku.requestPermission(0)
else -> return@clickable
}
}
},
targetState = shizukuStatus,
) { status ->
when (status) {
is ShizukuStatus.Initializing -> MonitorText(text = "Initializing...")
is ShizukuBinderStatus.BinderDead -> MonitorText(text = "Binder dead")
is ShizukuBinderStatus.BinderReceived -> MonitorText(text = "Binder received")
is ShizukuBinderStatus.WaitingForBinder -> MonitorText(text = "Waiting for binder...")
is ShizukuStatus.ShizukuManagerNotFound -> MonitorText(text = "Shizuku manager not found")
is ShizukuPermissionStatus.Denied -> MonitorText(text = "Permission denied")
is ShizukuPermissionStatus.Granted -> CurrentActivityMonitorText()
}
}
}
}
}
@Composable
private fun MonitorText(
contentAlignment: Alignment = Alignment.Center,
text: String,
) {
Box(
modifier = run {
Modifier
.fillMaxSize()
.padding(horizontal = 16.dp)
},
contentAlignment = contentAlignment,
content = { Text(text = text) },
)
}
@Composable
private fun CurrentActivityMonitorText() {
val text by rememberCurrentActivityText()
MonitorText(
contentAlignment = Alignment.CenterStart,
text = text,
)
}
| gpl-3.0 | f840321015acc4f1d174ce35cb982bc6 | 36.314815 | 110 | 0.650124 | 4.648212 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/translations/inspections/MissingFormatInspection.kt | 1 | 1898 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.inspections
import com.demonwav.mcdev.translations.identification.TranslationInstance
import com.demonwav.mcdev.translations.identification.TranslationInstance.Companion.FormattingError
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiReferenceExpression
class MissingFormatInspection : TranslationInspection() {
override fun getStaticDescription() = "Detects missing format arguments for translations"
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitReferenceExpression(expression: PsiReferenceExpression) {
visit(expression)
}
override fun visitLiteralExpression(expression: PsiLiteralExpression) {
visit(expression, ChangeTranslationQuickFix("Use a different translation"))
}
private fun visit(expression: PsiExpression, vararg quickFixes: LocalQuickFix) {
val result = TranslationInstance.find(expression)
if (result != null && result.formattingError == FormattingError.MISSING) {
holder.registerProblem(
expression,
"There are missing formatting arguments to satisfy '${result.text}'",
ProblemHighlightType.GENERIC_ERROR,
*quickFixes
)
}
}
}
}
| mit | 7c96dd95460975c44d28740d6492d304 | 36.96 | 99 | 0.724974 | 5.615385 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/info/translatorgroup/TranslatorGroupInfoFragment.kt | 1 | 3818 | package me.proxer.app.info.translatorgroup
import android.content.ClipData
import android.content.ClipboardManager
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.getSystemService
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.gojuno.koptional.rxjava2.filterSome
import com.gojuno.koptional.toOptional
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseContentFragment
import me.proxer.app.util.extension.linkClicks
import me.proxer.app.util.extension.linkLongClicks
import me.proxer.app.util.extension.linkify
import me.proxer.app.util.extension.toAppDrawable
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import me.proxer.app.util.extension.toast
import me.proxer.library.entity.info.TranslatorGroup
import me.proxer.library.enums.Country
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
/**
* @author Ruben Gees
*/
class TranslatorGroupInfoFragment : BaseContentFragment<TranslatorGroup>(R.layout.fragment_translator_group) {
companion object {
fun newInstance() = TranslatorGroupInfoFragment().apply {
arguments = bundleOf()
}
}
override val viewModel by viewModel<TranslatorGroupInfoViewModel> { parametersOf(id) }
override val hostingActivity: TranslatorGroupActivity
get() = activity as TranslatorGroupActivity
private val id: String
get() = hostingActivity.id
private var name: String?
get() = hostingActivity.name
set(value) {
hostingActivity.name = value
}
private val languageRow: ViewGroup by bindView(R.id.languageRow)
private val language: ImageView by bindView(R.id.language)
private val linkRow: ViewGroup by bindView(R.id.linkRow)
private val link: TextView by bindView(R.id.link)
private val descriptionContainer: ViewGroup by bindView(R.id.descriptionContainer)
private val description: TextView by bindView(R.id.description)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
link.linkClicks()
.map { it.toPrefixedUrlOrNull().toOptional() }
.filterSome()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe { showPage(it) }
link.linkLongClicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
val title = getString(R.string.clipboard_title)
requireContext().getSystemService<ClipboardManager>()?.setPrimaryClip(
ClipData.newPlainText(title, it.toString())
)
requireContext().toast(R.string.clipboard_status)
}
}
override fun showData(data: TranslatorGroup) {
super.showData(data)
name = data.name
if (data.country == Country.NONE) {
languageRow.isGone = true
} else {
languageRow.isVisible = true
language.setImageDrawable(data.country.toAppDrawable(requireContext()))
}
if (data.link?.toString().isNullOrBlank()) {
linkRow.isGone = true
} else {
linkRow.isVisible = true
link.text = data.link.toString().linkify(mentions = false)
}
if (data.description.isBlank()) {
descriptionContainer.isGone = true
} else {
descriptionContainer.isVisible = true
description.text = data.description
}
}
}
| gpl-3.0 | 34e3b2f98a2a10f326e42dce71ee5c2f | 33.089286 | 110 | 0.698009 | 4.661783 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mcp/version/McpVersion.kt | 1 | 4416 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.version
import com.demonwav.mcdev.platform.mcp.McpVersionPair
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.fromJson
import com.demonwav.mcdev.util.sortVersions
import com.google.gson.Gson
import java.io.IOException
import java.net.URL
import kotlin.math.min
class McpVersion private constructor(private val map: Map<String, Map<String, List<Int>>>) {
val versions: List<SemanticVersion> by lazy {
sortVersions(map.keys)
}
data class McpVersionSet(val goodVersions: List<McpVersionPair>, val badVersions: List<McpVersionPair>)
private fun getSnapshot(version: SemanticVersion): McpVersionSet {
return get(version, "snapshot")
}
private fun getStable(version: SemanticVersion): McpVersionSet {
return get(version, "stable")
}
private operator fun get(version: SemanticVersion, type: String): McpVersionSet {
val good = ArrayList<McpVersionPair>()
val bad = ArrayList<McpVersionPair>()
val keySet = map.keys
for (mcVersion in keySet) {
val versions = map[mcVersion]
if (versions != null) {
versions[type]?.let { vers ->
val mcVersionParsed = SemanticVersion.parse(mcVersion)
val pairs = vers.map { McpVersionPair("${type}_$it", mcVersionParsed) }
if (mcVersionParsed.startsWith(version)) {
good.addAll(pairs)
} else {
bad.addAll(pairs)
}
}
}
}
return McpVersionSet(good, bad)
}
fun getMcpVersionList(version: SemanticVersion): List<McpVersionEntry> {
val limit = 50
val result = ArrayList<McpVersionEntry>(limit * 4)
val majorVersion = version.take(2)
val stable = getStable(majorVersion)
val snapshot = getSnapshot(majorVersion)
fun mapTopTo(source: List<McpVersionPair>, dest: MutableList<McpVersionEntry>, limit: Int, isRed: Boolean) {
val tempList = ArrayList(source).apply { sortDescending() }
for (i in 0 until min(limit, tempList.size)) {
dest += McpVersionEntry(tempList[i], isRed)
}
}
mapTopTo(stable.goodVersions, result, limit, false)
mapTopTo(snapshot.goodVersions, result, limit, false)
// If we're already at the limit we don't need to go through the bad list
if (result.size >= limit) {
return result.subList(0, min(limit, result.size))
}
// The bad pairs don't match the current MC version, but are still available to the user
// We will color them red
mapTopTo(stable.badVersions, result, limit, true)
mapTopTo(snapshot.badVersions, result, limit, true)
return result.subList(0, min(limit, result.size))
}
companion object {
fun downloadData(): McpVersion? {
val bspkrsMappings = try {
val bspkrsText = URL("https://maven.minecraftforge.net/de/oceanlabs/mcp/versions.json").readText()
Gson().fromJson<MutableMap<String, MutableMap<String, MutableList<Int>>>>(bspkrsText)
} catch (ignored: IOException) {
mutableMapOf()
}
val tterragMappings = try {
val tterragText = URL("https://assets.tterrag.com/temp_mappings.json").readText()
Gson().fromJson<MutableMap<String, MutableMap<String, MutableList<Int>>>>(tterragText)
} catch (ignored: IOException) {
emptyMap()
}
// Merge the temporary mappings list into the main one, temporary solution for 1.16
tterragMappings.forEach { (mcVersion, channels) ->
val existingChannels = bspkrsMappings.getOrPut(mcVersion, ::mutableMapOf)
channels.forEach { (channelName, newVersions) ->
val existingVersions = existingChannels.getOrPut(channelName, ::mutableListOf)
existingVersions.addAll(newVersions)
}
}
return if (bspkrsMappings.isEmpty()) null else McpVersion(bspkrsMappings)
}
}
}
| mit | ffaba192b67c360f70263db453f1f4e7 | 35.495868 | 116 | 0.616395 | 4.576166 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/messages/dto/MessagesGetLongPollHistoryResponse.kt | 1 | 2666 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.messages.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.groups.dto.GroupsGroupFull
import com.vk.sdk.api.users.dto.UsersUserFull
import kotlin.Boolean
import kotlin.Int
import kotlin.collections.List
/**
* @param history
* @param messages
* @param credentials
* @param profiles
* @param groups
* @param chats
* @param newPts - Persistence timestamp
* @param fromPts
* @param more - Has more
* @param conversations
*/
data class MessagesGetLongPollHistoryResponse(
@SerializedName("history")
val history: List<List<Int>>? = null,
@SerializedName("messages")
val messages: MessagesLongpollMessages? = null,
@SerializedName("credentials")
val credentials: MessagesLongpollParams? = null,
@SerializedName("profiles")
val profiles: List<UsersUserFull>? = null,
@SerializedName("groups")
val groups: List<GroupsGroupFull>? = null,
@SerializedName("chats")
val chats: List<MessagesChat>? = null,
@SerializedName("new_pts")
val newPts: Int? = null,
@SerializedName("from_pts")
val fromPts: Int? = null,
@SerializedName("more")
val more: Boolean? = null,
@SerializedName("conversations")
val conversations: List<MessagesConversation>? = null
)
| mit | 6bd9cf48155c67f0754ace806528b253 | 37.085714 | 81 | 0.693548 | 4.384868 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/widgets/dto/WidgetsWidgetComment.kt | 1 | 3189 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.widgets.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.base.dto.BaseBoolInt
import com.vk.sdk.api.base.dto.BaseLikesInfo
import com.vk.sdk.api.base.dto.BaseRepostsInfo
import com.vk.sdk.api.users.dto.UsersUserFull
import com.vk.sdk.api.wall.dto.WallCommentAttachment
import com.vk.sdk.api.wall.dto.WallPostSource
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param date - Date when the comment has been added in Unixtime
* @param fromId - Comment author ID
* @param id - Comment ID
* @param postType - Post type
* @param text - Comment text
* @param toId - Wall owner
* @param attachments
* @param canDelete - Information whether current user can delete the comment
* @param comments
* @param likes
* @param media
* @param postSource
* @param reposts
* @param user
*/
data class WidgetsWidgetComment(
@SerializedName("date")
val date: Int,
@SerializedName("from_id")
val fromId: Int,
@SerializedName("id")
val id: Int,
@SerializedName("post_type")
val postType: Int,
@SerializedName("text")
val text: String,
@SerializedName("to_id")
val toId: Int,
@SerializedName("attachments")
val attachments: List<WallCommentAttachment>? = null,
@SerializedName("can_delete")
val canDelete: BaseBoolInt? = null,
@SerializedName("comments")
val comments: WidgetsCommentReplies? = null,
@SerializedName("likes")
val likes: BaseLikesInfo? = null,
@SerializedName("media")
val media: WidgetsCommentMedia? = null,
@SerializedName("post_source")
val postSource: WallPostSource? = null,
@SerializedName("reposts")
val reposts: BaseRepostsInfo? = null,
@SerializedName("user")
val user: UsersUserFull? = null
)
| mit | 97cc1415e57b3a6a734382c5e7a9f8c4 | 36.081395 | 81 | 0.696457 | 4.141558 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/stack/topbar/titlebar/TitleSubTitleLayout.kt | 1 | 3528 | package com.reactnativenavigation.views.stack.topbar.titlebar
import android.content.Context
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.RestrictTo
import com.reactnativenavigation.options.Alignment
import com.reactnativenavigation.options.FontOptions
import com.reactnativenavigation.options.parsers.TypefaceLoader
private const val DEFAULT_TITLE_FONT_SIZE_DP = 18f
private const val DEFAULT_SUBTITLE_FONT_SIZE_DP = 14f
class TitleSubTitleLayout(context: Context) : LinearLayout(context) {
private val titleTextView = SingleLineTextView(context, DEFAULT_TITLE_FONT_SIZE_DP)
private val subTitleTextView = SingleLineTextView(context, DEFAULT_SUBTITLE_FONT_SIZE_DP)
init {
this.orientation = VERTICAL
this.setVerticalGravity(Gravity.CENTER_VERTICAL)
this.addView(titleTextView, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply { gravity = Gravity.START or Gravity.CENTER_VERTICAL })
this.addView(subTitleTextView, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply {
gravity = Gravity.START or Gravity.CENTER_VERTICAL
weight = 1f
})
}
fun setSubTitleAlignment(alignment: Alignment) {
if (alignment == Alignment.Center) {
(this.subTitleTextView.layoutParams as LayoutParams).gravity = Gravity.CENTER
} else {
(this.subTitleTextView.layoutParams as LayoutParams).gravity = Gravity.START or Gravity.CENTER_VERTICAL
}
}
fun setTitleAlignment(alignment: Alignment) {
if (alignment == Alignment.Center) {
(this.titleTextView.layoutParams as LayoutParams).gravity = Gravity.CENTER
} else {
(this.titleTextView.layoutParams as LayoutParams).gravity = Gravity.START or Gravity.CENTER_VERTICAL
}
}
fun setTitleFontSize(size: Float) = titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, size)
fun setSubtitleFontSize(size: Float) = subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, size)
fun setSubtitleTextColor(@ColorInt color: Int) = this.subTitleTextView.setTextColor(color)
fun setTitleTextColor(@ColorInt color: Int) = this.titleTextView.setTextColor(color)
fun setTitleTypeface(typefaceLoader: TypefaceLoader, font: FontOptions) {
titleTextView.typeface = font.getTypeface(typefaceLoader, titleTextView.typeface)
}
fun setSubtitleTypeface(typefaceLoader: TypefaceLoader, font: FontOptions) {
subTitleTextView.typeface = font.getTypeface(typefaceLoader, subTitleTextView.typeface)
}
fun setTitle(title: CharSequence?) {
this.titleTextView.text = title
}
fun setSubtitle(subTitle: CharSequence?) {
this.subTitleTextView.text = subTitle
if (subTitle.isNullOrEmpty()) {
this.subTitleTextView.visibility = View.GONE
} else {
this.subTitleTextView.visibility = View.VISIBLE
}
}
fun getTitle() = (this.titleTextView.text ?: "").toString()
fun clear() {
this.titleTextView.text = null
setSubtitle(null)
}
@RestrictTo(RestrictTo.Scope.TESTS)
fun getTitleTxtView(): TextView {
return this.titleTextView
}
@RestrictTo(RestrictTo.Scope.TESTS)
fun getSubTitleTxtView(): TextView {
return this.subTitleTextView
}
} | mit | 2976c0b6f940510fe5b69e800e10c5ea | 36.542553 | 164 | 0.725907 | 4.716578 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz/ui/delegate/StepQuizDelegate.kt | 2 | 7883 | package org.stepik.android.view.step_quiz.ui.delegate
import android.os.Build
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.core.view.updateMargins
import androidx.core.view.updateMarginsRelative
import com.google.android.material.button.MaterialButton
import org.stepic.droid.R
import org.stepik.android.domain.step_quiz.model.StepQuizLessonData
import org.stepik.android.model.DiscountingPolicyType
import org.stepik.android.model.ReviewStrategyType
import org.stepik.android.model.Step
import org.stepik.android.model.Submission
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.model.ReplyResult
import org.stepik.android.view.step_quiz.mapper.StepQuizFeedbackMapper
import org.stepik.android.view.step_quiz.model.StepQuizFeedbackState
import org.stepik.android.view.step_quiz.resolver.StepQuizFormResolver
import ru.nobird.android.view.base.ui.extension.toPx
class StepQuizDelegate(
private val step: Step,
private val stepQuizLessonData: StepQuizLessonData,
private val stepQuizFormDelegate: StepQuizFormDelegate,
private val stepQuizFeedbackBlocksDelegate: StepQuizFeedbackBlocksDelegate,
private val stepQuizActionButton: MaterialButton,
private val stepRetryButton: MaterialButton,
private val stepQuizDiscountingPolicy: TextView,
private val stepQuizReviewTeacherMessage: TextView?,
private val onNewMessage: (StepQuizFeature.Message) -> Unit,
/**
* If null so there is no next action will be shown
*/
private val onNextClicked: (() -> Unit)? = null
) {
private val context = stepQuizActionButton.context
private val stepQuizFeedbackMapper = StepQuizFeedbackMapper()
private var currentState: StepQuizFeature.State.AttemptLoaded? = null
init {
stepQuizActionButton.setOnClickListener { onActionButtonClicked() }
stepRetryButton.setOnClickListener { onNewMessage(StepQuizFeature.Message.CreateAttemptClicked(step)) }
}
fun onActionButtonClicked() {
val state = currentState ?: return
if (StepQuizFormResolver.isSubmissionInTerminalState(state)) {
if (StepQuizFormResolver.canMoveToNextStep(step, stepQuizLessonData, state) && onNextClicked != null) {
onNextClicked.invoke()
} else {
onNewMessage(StepQuizFeature.Message.CreateAttemptClicked(step))
}
} else {
val replyResult = stepQuizFormDelegate.createReply()
when (replyResult.validation) {
is ReplyResult.Validation.Success ->
onNewMessage(StepQuizFeature.Message.CreateSubmissionClicked(step, replyResult.reply))
is ReplyResult.Validation.Error ->
stepQuizFeedbackBlocksDelegate.setState(StepQuizFeedbackState.Validation(replyResult.validation.message))
}
}
}
fun setState(state: StepQuizFeature.State.AttemptLoaded) {
currentState = state
stepQuizFeedbackBlocksDelegate.setState(stepQuizFeedbackMapper.mapToStepQuizFeedbackState(step.block?.name, state))
stepQuizFormDelegate.setState(state)
if (StepQuizFormResolver.canOnlyRetry(step, stepQuizLessonData, state)) {
stepQuizActionButton.isVisible = false
stepRetryButton.setText(R.string.step_quiz_action_button_try_again)
stepRetryButton.updateLayoutParams<ViewGroup.MarginLayoutParams> {
width = ViewGroup.LayoutParams.MATCH_PARENT
updateMargins(right = 0)
updateMarginsRelative(end = 0)
}
} else {
stepQuizActionButton.isVisible = true
stepQuizActionButton.isEnabled = StepQuizFormResolver.isQuizActionEnabled(state)
stepQuizActionButton.text = resolveQuizActionButtonText(state)
stepRetryButton.text = null
stepRetryButton.updateLayoutParams<ViewGroup.MarginLayoutParams> {
width = context.resources.getDimensionPixelOffset(R.dimen.step_submit_button_height)
updateMargins(right = 16.toPx())
if (Build.VERSION.SDK_INT >= 17) {
updateMarginsRelative(end = 16.toPx())
}
}
}
stepRetryButton.isVisible =
StepQuizFormResolver.canMoveToNextStep(step, stepQuizLessonData, state) ||
StepQuizFormResolver.canOnlyRetry(step, stepQuizLessonData, state)
val isNeedShowDiscountingPolicy =
state.restrictions.discountingPolicyType != DiscountingPolicyType.NoDiscount &&
(state.submissionState as? StepQuizFeature.SubmissionState.Loaded)?.submission?.status != Submission.Status.CORRECT
stepQuizDiscountingPolicy.isVisible = isNeedShowDiscountingPolicy
stepQuizDiscountingPolicy.text = resolveQuizDiscountingPolicyText(state)
stepQuizReviewTeacherMessage?.isVisible = step.actions?.doReview != null && stepQuizLessonData.isTeacher
step.instructionType?.let { instructionType ->
@StringRes
val stringRes =
when (instructionType) {
ReviewStrategyType.PEER ->
R.string.step_quiz_review_teacher_peer_message
ReviewStrategyType.INSTRUCTOR ->
R.string.step_quiz_review_teacher_instructor_message
}
stepQuizReviewTeacherMessage?.text = context.getString(stringRes)
}
}
private fun resolveQuizActionButtonText(state: StepQuizFeature.State.AttemptLoaded): String =
with(state.restrictions) {
if (StepQuizFormResolver.isSubmissionInTerminalState(state)) {
when {
StepQuizFormResolver.canMoveToNextStep(step, stepQuizLessonData, state) && onNextClicked != null ->
context.getString(R.string.next)
maxSubmissionCount in 0 until submissionCount ->
context.getString(R.string.step_quiz_action_button_no_submissions)
else ->
context.getString(R.string.step_quiz_action_button_try_again)
}
} else {
if (maxSubmissionCount > submissionCount) {
val submissionsLeft = maxSubmissionCount - submissionCount
context.getString(
R.string.step_quiz_action_button_submit_with_counter,
context.resources.getQuantityString(R.plurals.submissions, submissionsLeft, submissionsLeft)
)
} else {
context.getString(R.string.step_quiz_action_button_submit)
}
}
}
private fun resolveQuizDiscountingPolicyText(state: StepQuizFeature.State.AttemptLoaded): String? =
with(state.restrictions) {
when (discountingPolicyType) {
DiscountingPolicyType.Inverse ->
context.getString(R.string.discount_policy_inverse_title)
DiscountingPolicyType.FirstOne, DiscountingPolicyType.FirstThree -> {
val remainingSubmissionCount = discountingPolicyType.numberOfTries() - state.restrictions.submissionCount
if (remainingSubmissionCount > 0) {
context.resources.getQuantityString(R.plurals.discount_policy_first_n, remainingSubmissionCount, remainingSubmissionCount)
} else {
context.getString(R.string.discount_policy_no_way)
}
}
else ->
null
}
}
} | apache-2.0 | 6f9e8a2295a46680acea15ab1ad2a69c | 44.051429 | 146 | 0.670811 | 5.33717 | false | false | false | false |
M4R1KU/releasr | backend/src/main/kotlin/me/mkweb/releasr/web/auth/JwtAuthenticationFilter.kt | 1 | 1349 | package me.mkweb.releasr.web.auth
import me.mkweb.releasr.web.auth.exception.JwtTokenMissingException
import me.mkweb.releasr.web.auth.model.JwtAuthenticationToken
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.GenericFilterBean
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
class JwtAuthenticationFilter(private val authenticationManager: AuthenticationManager) : GenericFilterBean() {
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
val header = (request!! as HttpServletRequest).getHeader("Authorization")
if (header == null || !header.startsWith("Bearer ")) {
throw JwtTokenMissingException("No JWT token found in request headers")
}
val authToken = header.substring(7)
val authRequest = JwtAuthenticationToken(authToken)
val authentication = authenticationManager.authenticate(authRequest)
SecurityContextHolder.getContext().authentication = authentication
chain!!.doFilter(request, response)
SecurityContextHolder.getContext().authentication = null
}
} | mit | 52e01761e8c52a474798ed97c92440e9 | 41.1875 | 111 | 0.782061 | 5.332016 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectSimpleGame/core/src/me/liuqingwen/game/screens/MainMenuScreen.kt | 1 | 2510 | package me.liuqingwen.game.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.*
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import me.liuqingwen.game.AbstractScreen
import me.liuqingwen.game.ScreenManager
import me.liuqingwen.game.ScreenType
import kotlin.math.atan
/**
* Created by Qingwen on 2018-2018-7-15, project: ProjectGDXGame.
*
* @Author: Qingwen
* @DateTime: 2018-7-15
* @Package: me.liuqingwen.game in project: ProjectGDXGame
*
* Notice: If you are using this class or file, check it and do some modification.
*/
class MainMenuScreen: AbstractScreen()
{
override fun buildStage()
{
val atlas = TextureAtlas(Gdx.files.internal("data/uiskin.atlas"), Gdx.files.internal("data"), false)
val skin = Skin(Gdx.files.internal("data/uiskin.json"), atlas)
val buttonStart = TextButton("Start", skin, "default").apply {
this.label.setFontScale(2.0f)
this.pad(10.0f, 50.0f, 10.0f, 50.0f)
}
val buttonScores = TextButton("Scores", skin, "default").apply {
this.label.setFontScale(2.0f)
this.pad(10.0f, 50.0f, 10.0f, 50.0f)
}
val buttonQuit = TextButton("Quit", skin, "default").apply {
this.label.setFontScale(2.0f)
this.pad(10.0f, 50.0f, 10.0f, 50.0f)
}
buttonStart.addListener(object: ClickListener(){
override fun clicked(event: InputEvent?, x: Float, y: Float) = ScreenManager.showScreen(ScreenType.ScreenGame)
})
buttonScores.addListener(object: ClickListener(){
override fun clicked(event: InputEvent?, x: Float, y: Float) = ScreenManager.showScreen(ScreenType.ScreenScoresList)
})
buttonQuit.addListener(object: ClickListener(){
override fun clicked(event: InputEvent?, x: Float, y: Float) = Gdx.app.exit()
})
val group = VerticalGroup().space(20.0f).pad(50.0f).fill().apply {
this.setBounds(0.0f, 0.0f, [email protected], [email protected])
}
group.add(buttonStart).add(buttonScores).add(buttonQuit)
this.addActor(group)
}
}
fun VerticalGroup.add(actor: Actor) = this.addActor(actor).let { this }
| mit | 93c824b1c11f7c5ed0a3ddb40805c92a | 38.84127 | 128 | 0.675299 | 3.575499 | false | false | false | false |
haozileung/test | src/main/kotlin/com/haozileung/web/domain/permission/Element.kt | 1 | 551 | /*
* Powered By [rapid-framework]
* Web Site: http://www.rapid-framework.org.cn
* Google Code: http://code.google.com/p/rapid-framework/
* Since 2008 - 2016
*/
package com.haozileung.web.domain.permission
import java.io.Serializable
/**
* @author Haozi
* *
* @version 1.0
* *
* @since 1.0
*/
data class Element(var elementId: Long? = null,
var code: String? = null,
var name: String? = null,
var remarks: String? = null,
var status: Int? = null) : Serializable
| mit | 2b2cb6e6f15712448a598a0668595f37 | 22.956522 | 58 | 0.578947 | 3.401235 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt | 1 | 1191 | package eu.kanade.tachiyomi.source.model
import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import rx.subjects.Subject
open class Page(
val index: Int,
var url: String = "",
var imageUrl: String? = null,
@Transient var uri: Uri? = null // Deprecated but can't be deleted due to extensions
) : ProgressListener {
val number: Int
get() = index + 1
@Transient @Volatile var status: Int = 0
set(value) {
field = value
statusSubject?.onNext(value)
}
@Transient @Volatile var progress: Int = 0
@Transient private var statusSubject: Subject<Int, Int>? = null
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
progress = if (contentLength > 0) {
(100 * bytesRead / contentLength).toInt()
} else {
-1
}
}
fun setStatusSubject(subject: Subject<Int, Int>?) {
this.statusSubject = subject
}
companion object {
const val QUEUE = 0
const val LOAD_PAGE = 1
const val DOWNLOAD_IMAGE = 2
const val READY = 3
const val ERROR = 4
}
}
| apache-2.0 | f7953f9996fd0f3b7ce58ab8b770fc5c | 23.8125 | 92 | 0.595298 | 4.362637 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/EnderBow.kt | 1 | 1207 | package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.copyOf
import nl.sugcube.dirtyarrows.util.showEnderParticle
import org.bukkit.Material
import org.bukkit.Sound
import org.bukkit.entity.Arrow
import org.bukkit.entity.Player
import org.bukkit.event.entity.ProjectileHitEvent
import org.bukkit.inventory.ItemStack
/**
* Shoots arrows that teleports the player to the arrow location.
*
* @author SugarCaney
*/
open class EnderBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.ENDER,
canShootInProtectedRegions = true,
costRequirements = listOf(ItemStack(Material.ENDER_PEARL, 1)),
description = "Teleport to location of impact."
) {
override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) {
player.showEnderParticle()
player.teleport(arrow.location.copyOf(yaw = player.location.yaw, pitch = player.location.pitch))
player.showEnderParticle()
player.playSound(player.location, Sound.ENTITY_ENDERMAN_TELEPORT, 10f, 1f)
}
} | gpl-3.0 | 5f338720343b4387aa90abc72011ea77 | 34.529412 | 104 | 0.755592 | 4.105442 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetValueTest.kt | 1 | 4586 | package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.interfaces.GlucoseUnit
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import io.reactivex.rxjava3.core.Single
import org.json.JSONObject
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.`when`
class TriggerTempTargetValueTest : TriggerTestBase() {
var now = 1514766900000L
@Before
fun prepare() {
`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL)
`when`(dateUtil.now()).thenReturn(now)
}
@Test
fun shouldRunTest() {
`when`(repository.getTemporaryTargetActiveAt(dateUtil.now())).thenReturn(Single.just(ValueWrapper.Existing(TemporaryTarget(duration = 60000, highTarget = 140.0, lowTarget = 140.0, reason = TemporaryTarget.Reason.CUSTOM, timestamp = now - 1))))
var t: TriggerTempTargetValue = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MMOL).setValue(7.7).comparator(Comparator.Compare.IS_EQUAL)
Assert.assertFalse(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(140.0).comparator(Comparator.Compare.IS_EQUAL)
Assert.assertTrue(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(140.0).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER)
Assert.assertTrue(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(140.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER)
Assert.assertTrue(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(139.0).comparator(Comparator.Compare.IS_EQUAL)
Assert.assertFalse(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(141.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER)
Assert.assertTrue(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(141.0).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER)
Assert.assertFalse(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(139.0).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER)
Assert.assertTrue(t.shouldRun())
t = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(139.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER)
Assert.assertFalse(t.shouldRun())
Assert.assertFalse(t.shouldRun())
t = TriggerTempTargetValue(injector).comparator(Comparator.Compare.IS_NOT_AVAILABLE)
Assert.assertFalse(t.shouldRun())
`when`(repository.getTemporaryTargetActiveAt(dateUtil.now())).thenReturn(Single.just(ValueWrapper.Absent()))
Assert.assertTrue(t.shouldRun())
}
@Test
fun copyConstructorTest() {
val t: TriggerTempTargetValue = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MGDL).setValue(140.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER)
val t1 = t.duplicate() as TriggerTempTargetValue
Assert.assertEquals(140.0, t1.ttValue.value, 0.01)
Assert.assertEquals(GlucoseUnit.MGDL, t1.ttValue.units)
Assert.assertEquals(Comparator.Compare.IS_EQUAL_OR_LESSER, t.comparator.value)
}
private var ttJson = "{\"data\":{\"tt\":7.7,\"comparator\":\"IS_EQUAL\",\"units\":\"mmol\"},\"type\":\"TriggerTempTargetValue\"}"
@Test
fun toJSONTest() {
val t: TriggerTempTargetValue = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MMOL).setValue(7.7).comparator(Comparator.Compare.IS_EQUAL)
Assert.assertEquals(ttJson, t.toJSON())
}
@Test
fun fromJSONTest() {
val t: TriggerTempTargetValue = TriggerTempTargetValue(injector).setUnits(GlucoseUnit.MMOL).setValue(7.7).comparator(Comparator.Compare.IS_EQUAL)
val t2 = TriggerDummy(injector).instantiate(JSONObject(t.toJSON())) as TriggerTempTargetValue
Assert.assertEquals(Comparator.Compare.IS_EQUAL, t2.comparator.value)
Assert.assertEquals(7.7, t2.ttValue.value, 0.01)
Assert.assertEquals(GlucoseUnit.MMOL, t2.ttValue.units)
}
@Test
fun iconTest() {
Assert.assertEquals(Optional.of(R.drawable.ic_keyboard_tab), TriggerTempTargetValue(injector).icon())
}
}
| agpl-3.0 | a090ffdc49d58470e0482f1189a4c379 | 52.952941 | 251 | 0.740951 | 3.980903 | false | true | false | false |
Heiner1/AndroidAPS | danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgSettingBasalProfileAll_k.kt | 1 | 2452 | package info.nightscout.androidaps.danaRKorean.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danar.comm.MessageBase
import info.nightscout.shared.logging.LTag
import java.util.*
/**
* Created by mike on 05.07.2016.
*
*
*
*
* THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE
*/
class MsgSettingBasalProfileAll_k(
injector: HasAndroidInjector
) : MessageBase(injector) {
init {
setCommand(0x3206)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
danaPump.pumpProfiles = Array(4) { Array(48) { 0.0 } }
if (danaPump.basal48Enable) {
for (profile in 0..3) {
val position = intFromBuff(bytes, 107 * profile, 1)
for (index in 0..47) {
var basal = intFromBuff(bytes, 107 * profile + 2 * index + 1, 2)
if (basal < 10) basal = 0
danaPump.pumpProfiles!![position][index] = basal / 100 / 24.0 // in units/day
}
}
} else {
for (profile in 0..3) {
val position = intFromBuff(bytes, 49 * profile, 1)
aapsLogger.debug(LTag.PUMPCOMM, "position $position")
for (index in 0..23) {
var basal = intFromBuff(bytes, 59 * profile + 2 * index + 1, 2)
if (basal < 10) basal = 0
aapsLogger.debug(LTag.PUMPCOMM, "position $position index $index")
danaPump.pumpProfiles!![position][index] = basal / 100 / 24.0 // in units/day
}
}
}
if (danaPump.basal48Enable) {
for (profile in 0..3) {
for (index in 0..23) {
aapsLogger.debug(LTag.PUMPCOMM, "Basal profile " + profile + ": " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaPump.pumpProfiles!![profile][index])
}
}
} else {
for (profile in 0..3) {
for (index in 0..47) {
aapsLogger.debug(
LTag.PUMPCOMM, "Basal profile " + profile + ": " + String.format(Locale.ENGLISH, "%02d", index / 2) +
":" + String.format(Locale.ENGLISH, "%02d", index % 2 * 30) + " : " +
danaPump.pumpProfiles!![profile][index])
}
}
}
}
} | agpl-3.0 | 54cd7e3d006c685a362209b757d479fc | 36.738462 | 183 | 0.515498 | 4.177172 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/media/provider/ProviderCache.kt | 1 | 2748 | package com.sjn.stamp.media.provider
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import android.support.v4.media.MediaMetadataCompat
import com.sjn.stamp.utils.ParcelDiskCache
import java.io.IOException
import java.util.*
internal object ProviderCache {
private const val SUB_DIR = "/media_provider"
private const val CACHE_KEY = "media_map_cache"
fun readCache(context: Context): HashMap<String, MediaMetadataCompat> {
var mediaMapCache: MediaMapCache? = null
try {
val cache = ParcelDiskCache.open(context, MediaMapCache::class.java.classLoader, SUB_DIR, (1024 * 1024 * 10).toLong())
mediaMapCache = cache[CACHE_KEY] as MediaMapCache?
cache.close()
} catch (e: IOException) {
e.printStackTrace()
}
return if (mediaMapCache == null) {
HashMap()
} else mediaMapCache.map
}
private data class MediaMapCache internal constructor(internal val map: HashMap<String, MediaMetadataCompat>) : Parcelable {
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.run {
writeInt(map.size)
for ((key, value) in map) {
writeString(key)
writeParcelable(value, Parcelable.PARCELABLE_WRITE_RETURN_VALUE)
}
}
}
companion object {
@JvmField
@Suppress("unused")
val CREATOR: Parcelable.Creator<MediaMapCache> = object : Parcelable.Creator<MediaMapCache> {
override fun createFromParcel(source: Parcel): MediaMapCache {
val map = HashMap<String, MediaMetadataCompat>()
val size = source.readInt()
for (i in 0 until size) {
val key = source.readString()
val value = source.readParcelable<MediaMetadataCompat>(MediaMetadataCompat::class.java.classLoader)
map[key] = value
}
return MediaMapCache(map)
}
override fun newArray(size: Int): Array<MediaMapCache?> = arrayOfNulls(size)
}
}
}
fun saveCache(context: Context, map: HashMap<String, MediaMetadataCompat>) {
val mediaMapCache = MediaMapCache(map)
try {
val cache = ParcelDiskCache.open(context, MediaMapCache::class.java.classLoader, SUB_DIR, (1024 * 1024 * 10).toLong())
cache[CACHE_KEY] = mediaMapCache
cache.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
| apache-2.0 | 5139a9bb9b509ba5419f843296c88776 | 32.925926 | 130 | 0.589156 | 4.754325 | false | false | false | false |
sirixdb/sirix | bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/json/JsonSerializeHelper.kt | 1 | 1642 | package org.sirix.rest.crud.json
import io.vertx.core.http.HttpHeaders
import io.vertx.ext.web.RoutingContext
import org.sirix.access.trx.node.HashType
import org.sirix.api.json.JsonResourceSession
import java.io.StringWriter
import java.util.concurrent.Callable
class JsonSerializeHelper {
fun serialize(
serializer: Callable<*>,
out: StringWriter,
ctx: RoutingContext,
manager: JsonResourceSession,
revisions: IntArray,
nodeId: Long?,
): String {
serializer.call()
val body = out.toString()
if (manager.resourceConfig.hashType == HashType.NONE) {
writeResponseWithoutHashValue(ctx)
} else {
writeResponseWithHashValue(manager, revisions[0], ctx, nodeId)
}
return body
}
private fun writeResponseWithoutHashValue(ctx: RoutingContext) {
ctx.response().setStatusCode(200)
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
}
private fun writeResponseWithHashValue(
manager: JsonResourceSession,
revision: Int,
ctx: RoutingContext,
nodeId: Long?
) {
val rtx = manager.beginNodeReadOnlyTrx(revision)
rtx.use {
val hash = if (nodeId == null) {
rtx.moveToFirstChild();
rtx.hash
} else {
rtx.moveTo(nodeId);
rtx.hash
}
ctx.response().setStatusCode(200)
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.ETAG, hash.toString())
}
}
} | bsd-3-clause | afe233930604835c52f19cb067ba4a26 | 26.847458 | 74 | 0.607186 | 4.678063 | false | false | false | false |
orbite-mobile/monastic-jerusalem-community | app/src/main/java/pl/orbitemobile/wspolnoty/data/remote/mapper/NewsMapper.kt | 1 | 1610 | package pl.orbitemobile.wspolnoty.data.remote.mapper
import org.jsoup.Connection
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO
class NewsMapper private constructor() {
companion object {
val instance = NewsMapper()
}
fun mapNews(response: Connection.Response): Array<ArticleDTO> {
val news = getNews(response)
return news.map { getSingleNews(it) }.toTypedArray()
}
private fun getNews(response: Connection.Response): Elements =
response.parse().getElementsByTag("article")
private fun getSingleNews(element: Element): ArticleDTO {
val title = getNewsTitle(element)
val imgUrl = getNewsImgUrl(element)
val articleUrl = getNewsUrl(element)
val article = ArticleDTO(title, imgUrl, articleUrl)
article.dataCreated = getNewsDataCreated(element)
return article
}
private fun getNewsTitle(article: Element): String =
article.getElementsByAttributeValue("class", "entry-title").text()
private fun getNewsImgUrl(article: Element): String =
article.getElementsByAttributeValue("class", "meta-image")[0].getElementsByTag("img")[0].absUrl("src")
private fun getNewsDataCreated(article: Element): String =
article.getElementsByAttributeValue("class", "updated").text()
private fun getNewsUrl(article: Element): String {
val elements = article.getElementsByAttributeValue("class", "entry-title")[0].getElementsByTag("a")
return elements[0].absUrl("href")
}
}
| agpl-3.0 | c6d50c0ed06eaa25ea64bbb36767f37a | 35.590909 | 114 | 0.699379 | 4.573864 | false | false | false | false |
SourceUtils/hl2-toolkit | src/main/kotlin/com/timepath/hl2/io/bsp/BSP.kt | 1 | 3061 | package com.timepath.hl2.io.bsp
import com.timepath.Logger
import com.timepath.hl2.io.bsp.lump.LumpType
import com.timepath.io.OrderedInputStream
import com.timepath.io.struct.StructField
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.IntBuffer
/**
* @see <a>https://developer.valvesoftware.com/wiki/Source_BSP_File_Format</a>
* @see <a>https://github.com/TimePath/webgl-source/blob/master/js/source-bsp.js</a>
* @see <a>https://github.com/TimePath/webgl-source/blob/master/js/source-bsp-struct.js</a>
* @see <a>https://github.com/TimePath/webgl-source/blob/master/js/source-bsp-tree.js</a>
*/
public abstract class BSP(
val header: BSP.Header,
val input: OrderedInputStream
) {
public var indices: IntBuffer? = null
public var vertices: FloatBuffer? = null
/**
* Examples:
* <br/>
* {@code String ents = b.<String>getLump(LumpType.LUMP_ENTITIES);}
* <br/>
* {@code String ents = (String) b.getLump(LumpType.LUMP_ENTITIES);}
* <br/>
* {@code String ents = b.getLump(LumpType.LUMP_ENTITIES);}
*
* @param <T> Expected return type. TODO: Wouldn't it be nice if we just knew at compile time?
*/
public fun <T : Any> getLump(type: LumpType): T? {
return getLump(type, type.handler as LumpHandler<T>)
}
/**
* Intended for overriding to change handler functionality
*/
protected fun <T : Any> getLump(type: LumpType, handler: LumpHandler<T>?): T? {
if (handler == null) return null
val lump = header.lumps[type.ID]!!
if (lump.isEmpty()) return null
input.reset()
input.skipBytes(lump.offset)
return handler.invoke(lump, input)
}
val revision: Int get() = header.mapRevision
abstract fun process()
class Header(
/** BSP file identifier: VBSP */
@StructField(index = 0) var ident: Int = 0,
/** BSP file version */
@StructField(index = 1) var version: Int = 0,
/** BSP file identifier: VBSP */
@StructField(index = 2) var lumps: Array<Lump?> = arrayOfNulls<Lump>(64),
/** The map's revision (iteration, version) number */
@StructField(index = 3) var mapRevision: Int = 0
)
companion object {
private val LOG = Logger()
public fun load(`is`: InputStream): BSP? {
val input = OrderedInputStream(BufferedInputStream(`is`))
input.order(ByteOrder.LITTLE_ENDIAN)
input.mark(input.available())
val header = input.readStruct<Header>(Header())
// TODO: Other BSP types
val bsp = VBSP(header, input)
// TODO: Struct parser callbacks
for (i in 0..header.lumps.size() - 1) {
header.lumps[i]!!.type = LumpType.values()[i]
}
LOG.info { "Processing map..." }
bsp.process()
return bsp
}
}
}
| artistic-2.0 | a5f73d63557d312da929b9abf9e44e14 | 33.393258 | 99 | 0.611565 | 3.559302 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ContentRootEntityImpl.kt | 1 | 16642 | package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ContentRootEntityImpl: ContentRootEntity, WorkspaceEntityBase() {
companion object {
internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ContentRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val SOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val SOURCEROOTORDER_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootOrderEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
MODULE_CONNECTION_ID,
SOURCEROOTS_CONNECTION_ID,
SOURCEROOTORDER_CONNECTION_ID,
)
}
override val module: ModuleEntity
get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!!
@JvmField var _url: VirtualFileUrl? = null
override val url: VirtualFileUrl
get() = _url!!
@JvmField var _excludedUrls: List<VirtualFileUrl>? = null
override val excludedUrls: List<VirtualFileUrl>
get() = _excludedUrls!!
@JvmField var _excludedPatterns: List<String>? = null
override val excludedPatterns: List<String>
get() = _excludedPatterns!!
override val sourceRoots: List<SourceRootEntity>
get() = snapshot.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList()
override val sourceRootOrder: SourceRootOrderEntity?
get() = snapshot.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ContentRootEntityData?): ModifiableWorkspaceEntityBase<ContentRootEntity>(), ContentRootEntity.Builder {
constructor(): this(ContentRootEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ContentRootEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "url", this.url)
index(this, "excludedUrls", this.excludedUrls.toHashSet())
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) {
error("Field ContentRootEntity#module should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) {
error("Field ContentRootEntity#module should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ContentRootEntity#entitySource should be initialized")
}
if (!getEntityData().isUrlInitialized()) {
error("Field ContentRootEntity#url should be initialized")
}
if (!getEntityData().isExcludedUrlsInitialized()) {
error("Field ContentRootEntity#excludedUrls should be initialized")
}
if (!getEntityData().isExcludedPatternsInitialized()) {
error("Field ContentRootEntity#excludedPatterns should be initialized")
}
// Check initialization for collection with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(SOURCEROOTS_CONNECTION_ID, this) == null) {
error("Field ContentRootEntity#sourceRoots should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] == null) {
error("Field ContentRootEntity#sourceRoots should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var module: ModuleEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
} else {
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value
}
changedProperty.add("module")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var url: VirtualFileUrl
get() = getEntityData().url
set(value) {
checkModificationAllowed()
getEntityData().url = value
changedProperty.add("url")
val _diff = diff
if (_diff != null) index(this, "url", value)
}
override var excludedUrls: List<VirtualFileUrl>
get() = getEntityData().excludedUrls
set(value) {
checkModificationAllowed()
getEntityData().excludedUrls = value
val _diff = diff
if (_diff != null) index(this, "excludedUrls", value.toHashSet())
changedProperty.add("excludedUrls")
}
override var excludedPatterns: List<String>
get() = getEntityData().excludedPatterns
set(value) {
checkModificationAllowed()
getEntityData().excludedPatterns = value
changedProperty.add("excludedPatterns")
}
// List of non-abstract referenced types
var _sourceRoots: List<SourceRootEntity>? = emptyList()
override var sourceRoots: List<SourceRootEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(SOURCEROOTS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] = value
}
changedProperty.add("sourceRoots")
}
override var sourceRootOrder: SourceRootOrderEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity
} else {
this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(SOURCEROOTORDER_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] = value
}
changedProperty.add("sourceRootOrder")
}
override fun getEntityData(): ContentRootEntityData = result ?: super.getEntityData() as ContentRootEntityData
override fun getEntityClass(): Class<ContentRootEntity> = ContentRootEntity::class.java
}
}
class ContentRootEntityData : WorkspaceEntityData<ContentRootEntity>() {
lateinit var url: VirtualFileUrl
lateinit var excludedUrls: List<VirtualFileUrl>
lateinit var excludedPatterns: List<String>
fun isUrlInitialized(): Boolean = ::url.isInitialized
fun isExcludedUrlsInitialized(): Boolean = ::excludedUrls.isInitialized
fun isExcludedPatternsInitialized(): Boolean = ::excludedPatterns.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ContentRootEntity> {
val modifiable = ContentRootEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ContentRootEntity {
val entity = ContentRootEntityImpl()
entity._url = url
entity._excludedUrls = excludedUrls
entity._excludedPatterns = excludedPatterns
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ContentRootEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ContentRootEntityData
if (this.entitySource != other.entitySource) return false
if (this.url != other.url) return false
if (this.excludedUrls != other.excludedUrls) return false
if (this.excludedPatterns != other.excludedPatterns) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ContentRootEntityData
if (this.url != other.url) return false
if (this.excludedUrls != other.excludedUrls) return false
if (this.excludedPatterns != other.excludedPatterns) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + url.hashCode()
result = 31 * result + excludedUrls.hashCode()
result = 31 * result + excludedPatterns.hashCode()
return result
}
} | apache-2.0 | 5fff00797876f3bfb08a80f8a5e005b7 | 45.102493 | 220 | 0.604735 | 5.994957 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/tweets/view/TwitterFooterFormatter.kt | 1 | 2305 | package net.squanchy.tweets.view
import android.content.Context
import androidx.annotation.StringRes
import net.squanchy.R
import net.squanchy.support.time.createShortDateFormatter
import net.squanchy.support.time.createShortTimeFormatter
import net.squanchy.support.time.toZonedDateTime
import net.squanchy.tweets.domain.view.TweetViewModel
import org.threeten.bp.LocalDate
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
internal class TwitterFooterFormatter(private val context: Context) {
private val timeFormatter = createShortTimeFormatter()
private val dateFormatter = createShortDateFormatter()
fun footerTextFor(tweet: TweetViewModel): String {
val username = tweet.user.screenName
val timestamp = timestampFrom(tweet)
return context.getString(R.string.tweet_footer_format, username, timestamp)
}
private fun timestampFrom(tweet: TweetViewModel): String {
val createdAt = tweet.createdAt.toZonedDateTime(ZoneId.systemDefault())
val formattedTime = timeFormatter.format(createdAt)
return when {
isToday(createdAt) -> formatRecentDay(context, R.string.tweet_date_today, formattedTime)
isYesterday(createdAt) -> formatRecentDay(context, R.string.tweet_date_yesterday, formattedTime)
else -> formatDateAndTime(createdAt, formattedTime)
}
}
private fun isToday(instant: ZonedDateTime): Boolean {
return instant.toLocalDate() == LocalDate.now(instant.zone)
}
private fun isYesterday(instant: ZonedDateTime): Boolean {
return instant.toLocalDate() == LocalDate.now(instant.zone).minusDays(1)
}
private fun formatRecentDay(context: Context, @StringRes dayRes: Int, formattedTime: String): String {
val day = context.getString(dayRes)
return context.getString(R.string.tweet_date_format, day, formattedTime)
}
private fun formatDateAndTime(date: ZonedDateTime, formattedTimestamp: String): String {
val formattedDate = dateFormatter.format(date)
return formatNormalDay(context, formattedDate, formattedTimestamp)
}
private fun formatNormalDay(context: Context, day: String, formattedTime: String) =
context.getString(R.string.tweet_date_format, day, formattedTime)
}
| apache-2.0 | 3a3219e58907ecf1fec755b1ca87b73c | 40.160714 | 108 | 0.745336 | 4.564356 | false | false | false | false |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/plugin/FlexModule.kt | 1 | 9768 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* 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 me.st28.flexseries.flexlib.plugin
import me.st28.flexseries.flexlib.logging.LogHelper
import me.st28.flexseries.flexlib.plugin.storage.flatfile.YamlFileManager
import org.apache.commons.lang.Validate
import org.bukkit.configuration.ConfigurationSection
import org.bukkit.configuration.file.FileConfiguration
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.util.regex.Pattern
/**
* Represents a module of a FlexPlugin.
*
* Module lifestyle:
* 1) Module is registered under a FlexPlugin
* 2) Assuming the module is disabled due to the configuration, the module is enabled.
* 3) handleEnable is called, followed by handleReload
* - Each module is reloaded immediately after being enabled.
*
* Other notes:
* - If an implementation implements Bukkit's Listener interface, the module will automatically be
* registered as a Listener.
* - Modules will not enable if an exception is encountered during handleEnable, but they will still
* enable (with [hasError] = true) if an exception is encountered during handleReload.
* - Modules will also fail to enable if the configuration has invalid YAML syntax.
* - Modules (and any related commands, etc.) should be able to function at least partially if a
* reload fails, and they should be able to recover if valid configuration is given on next reload.
* - FlexPlugins can enable or disable plugins while the server is running. Because of this, implementations
* should take care to **cleanup fully** on disable to help prevent memory leaks.
*/
abstract class FlexModule<out T : FlexPlugin>(
val plugin: T,
val name: String,
val description: String)
{
companion object {
val NAME_PATTERN: Pattern = Pattern.compile("[a-zA-Z0-9-_]+")
}
/**
* The status of the module.
*/
var status: ModuleStatus = ModuleStatus.DISABLED
internal set
/**
* True if the module encountered errors while enabling, reloading, or disabling.
*/
var hasError: Boolean = false
internal set
/**
* The data folder for the module.
* Located at plugins/(Plugin name)/(Module name)
*/
var dataFolder: File
get() {
if (!field.exists()) {
field.mkdirs()
}
return field
}
private set
/**
* The configuration file for the module.
*/
private var hasConfig: Boolean = false
private val configFile: YamlFileManager? = null
get() {
if (field == null) {
field = YamlFileManager(plugin.dataFolder.path + File.separator + "config-$name.yml")
hasConfig = true
}
return field
}
/**
* The primary configuration section for this module.
*/
protected val config: FileConfiguration
get() = configFile!!.config
init {
Validate.isTrue(NAME_PATTERN.matcher(name).matches(), "Name must be alphanumeric with only dashes and underscores")
dataFolder = File(plugin.dataFolder.path + File.separator + name)
}
/**
* Enables the module.
*
* @return True if the module was successfully enabled.
* False if the module encountered errors while loading.
*
* @throws IllegalStateException Thrown if the module is already enabled.
*/
internal fun enable(): Boolean {
if (status == ModuleStatus.DISABLED_CONFIG) {
throw IllegalStateException("Module '$name' is disabled via configuration and cannot be enabled.")
} else if (status.isEnabled) {
throw IllegalStateException("Module '$name' is already enabled")
}
hasError = false
val startTime = System.currentTimeMillis()
// Setup default config
plugin.getResource("modules/$name/config.yml")?.use {
InputStreamReader(it).use {
configFile!!.copyDefaults(YamlConfiguration.loadConfiguration(it))
}
}
try {
// Reload configuration file
reloadConfig()
handleEnable()
} catch (ex: Exception) {
status = ModuleStatus.DISABLED
hasError = true
LogHelper.severe(this, "An exception occurred while enabling module '$name'", ex)
return false
}
status = ModuleStatus.ENABLED
handleReload()
// Register as listener where applicable
if (this is Listener) {
plugin.server.pluginManager.registerEvents(this, plugin)
LogHelper.debug(this, "Registered listener")
}
LogHelper.info(this, "Module enabled (%dms)".format(System.currentTimeMillis() - startTime))
return hasError
}
internal fun reload() {
try {
reloadConfig()
handleReload()
} catch (ex: Exception) {
hasError = true
LogHelper.severe(this, "An exception occurred while reloading module '$name'", ex)
return
}
hasError = false
status = ModuleStatus.ENABLED
}
/**
* Reloads the configuration file.
*/
internal fun reloadConfig() {
if (hasConfig) {
// Create data folder if it doesn't exist.
dataFolder
configFile!!.reload()
}
}
/**
* Saves the module.
*/
internal fun save(async: Boolean) {
try {
handleSave(async)
} catch (ex: Exception) {
hasError = true
LogHelper.severe(this, "An exception occurred while saving module '$name'", ex)
}
}
/**
* Disables the module.
*/
internal fun disable() {
// Unregister self as listener where applicable
if (this is Listener) {
HandlerList.unregisterAll(this)
LogHelper.debug(this, "Unregistered listener")
}
// Final save
save(false)
// Disable
try {
handleDisable()
} catch (ex: Exception) {
status = ModuleStatus.DISABLED
hasError = true
LogHelper.severe(this, "An exception occurred while disabling module '$name'", ex)
return
}
status = ModuleStatus.DISABLED
hasError = false
LogHelper.debug(this, "Module disabled")
}
// ========================================================================================== //
// API Methods //
// ========================================================================================== //
/**
* @return A resource with the given name located under this module's folder in the plugin jar.
*/
fun getResource(name: String): InputStream {
return plugin.getResource("modules/${this.name}/$name")
}
// ========================================================================================== //
// Implementation-specific Methods //
// ========================================================================================== //
/**
* Handles module-specific enable tasks.
*
* Should consist of tasks that should only occur once throughout the lifespan of a module, such as:
* - Initializing a database connection pool
* - Initializing variables
*/
protected open fun handleEnable() { }
/**
* Handles module-specific reload tasks.
*
* Should consist of tasks that are affected by configuration (in general). The configuration is
* always reloaded immediately prior to this method being called, so new configuration values
* will be present when this method is executed.
*/
protected open fun handleReload() { }
/**
* Handles module-specific save tasks.
*
* In an effort to allow plugins and modules to have autosaving functionality, this method should
* save asynchronously where possible (assuming [async] is true).
*
* @param async True if the module should save data asynchronously (where applicable).
* Will be true in many cases, except when the plugin is disabling all modules.
*/
protected open fun handleSave(async: Boolean) { }
/**
* Handles module-specific disable tasks.
*
* handleSave is always called prior to this, so this method shouldn't need to handle saving any
* data.
*
* This method may be called when [hasError] = true, so care should be taken to avoid using any
* uninitialized variables, among other things.
*
* Should consist of cleanup tasks that should only occur at the end of a module's lifespan, such as:
* - Closing database connections
*/
protected open fun handleDisable() { }
}
| apache-2.0 | 7742ca8b43cf4395d891cfc10fd590f1 | 32.56701 | 123 | 0.601761 | 5.019527 | false | true | false | false |
hzsweers/CatchUp | app/src/debug/kotlin/io/sweers/catchup/data/MockDataInterceptor.kt | 1 | 3242 | /*
* 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.data
import android.content.Context
import io.sweers.catchup.data.model.ServiceData
import io.sweers.catchup.util.injection.qualifiers.ApplicationContext
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.buffer
import okio.source
/**
* An interceptor that rewrites the response with mocked data instead.
*
* Note: This is pretty unmaintained right now.
*/
class MockDataInterceptor(
@ApplicationContext private val context: Context,
private val debugPreferences: DebugPreferences
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url
val host = url.host
val path = url.encodedPath
val serviceData = SUPPORTED_ENDPOINTS[host]
return if (debugPreferences.mockModeEnabled && serviceData != null && serviceData.supports(path)) {
Response.Builder().request(request)
.body(
context.assets
.open(formatUrl(serviceData, url)).source().buffer()
.readUtf8().toResponseBody("application/json".toMediaTypeOrNull())
)
.code(200)
.protocol(Protocol.HTTP_1_1)
.build()
} else {
chain.proceed(request)
}
}
companion object {
// TODO Generate this?
// Can also use arrayMapOf()
private val SUPPORTED_ENDPOINTS = mapOf<String, ServiceData>(
// put(RedditApi.HOST,
// ServiceData.Builder("r").addEndpoint("/")
// .build())
// put(MediumApi.HOST,
// ServiceData.Builder("m").addEndpoint("/browse/top")
// .build())
// put(ProductHuntApi.HOST,
// ServiceData.Builder("ph").addEndpoint("/v1/posts")
// .build())
// put(SlashdotApi.HOST,
// ServiceData.Builder("sd").addEndpoint("/Slashdot/slashdotMainatom")
// .fileType("xml")
// .build())
// put(DesignerNewsApi.HOST,
// ServiceData.Builder("dn").addEndpoint("/api/v1/stories")
// .build())
// put(DribbbleApi.HOST,
// ServiceData.Builder("dr").addEndpoint("/v1/shots")
// .build())
)
private fun formatUrl(service: ServiceData, url: HttpUrl): String {
var lastSegment = url.pathSegments[url.pathSize - 1]
if ("" == lastSegment) {
lastSegment = "nopath"
}
return service.assetsPrefix + "/" + lastSegment + "." + service.fileType
}
}
}
| apache-2.0 | 8c3744b63aafab802e384d311a57fee2 | 33.126316 | 103 | 0.654843 | 4.183226 | false | false | false | false |
iPoli/iPoli-android | app/src/test/java/io/ipoli/android/habit/usecase/CreateHabitHistoryItemsUseCaseSpek.kt | 1 | 8405 | package io.ipoli.android.habit.usecase
import io.ipoli.android.TestUtil
import io.ipoli.android.common.datetime.Time
import io.ipoli.android.common.datetime.instant
import io.ipoli.android.common.datetime.toStartOfDayUTC
import io.ipoli.android.habit.data.CompletedEntry
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.habit.usecase.CreateHabitHistoryItemsUseCase.HabitHistoryItem.State.*
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should be`
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
import org.threeten.bp.temporal.TemporalAdjusters
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 10/12/18.
*/
class CreateHabitHistoryItemsUseCaseSpek : Spek({
describe("CreateHabitHistoryItemsUseCase") {
val habit = TestUtil.habit.copy(
createdAt = LocalDate.now().minusDays(7).toStartOfDayUTC().time.instant
)
fun executeUseCase(
habit: Habit,
today: LocalDate = LocalDate.now(),
startDate: LocalDate = today,
endDate: LocalDate = today
) =
CreateHabitHistoryItemsUseCase().execute(
CreateHabitHistoryItemsUseCase.Params(
habit = habit,
startDate = startDate,
endDate = endDate,
today = today
)
)
describe("Good") {
it("should return not completed for today") {
val today = LocalDate.now()
val res = executeUseCase(habit, today)
res.size.`should be equal to`(1)
res.first().state.`should be`(NOT_COMPLETED_TODAY)
}
it("should return completed for today") {
val today = LocalDate.now()
val h = habit.copy(
history = mapOf(
today to CompletedEntry(listOf(Time.now()), TestUtil.reward)
)
)
val res = executeUseCase(h, today)
res.size.`should be equal to`(1)
res.first().state.`should be`(COMPLETED)
}
it("should return failed for yesterday") {
val today = LocalDate.now()
val h = habit.copy(
history = mapOf(
today to CompletedEntry(listOf(Time.now()), TestUtil.reward)
)
)
val res = executeUseCase(h, today, today.minusDays(1), today)
res.size.`should be equal to`(2)
res.first().state.`should be`(FAILED)
}
it("should return empty") {
val today = LocalDate.now().with(DayOfWeek.MONDAY)
val h = habit.copy(
days = setOf(DayOfWeek.TUESDAY)
)
val res = executeUseCase(h, today)
res.size.`should be equal to`(1)
res.first().state.`should be`(EMPTY)
}
it("should return empty for future") {
val today = LocalDate.now()
val h = habit.copy(
history = mapOf(
today to CompletedEntry(listOf(Time.now()), TestUtil.reward)
)
)
val res = executeUseCase(h, today, today, today.plusDays(1))
res.size.`should be equal to`(2)
res[1].state.`should be`(EMPTY)
}
it("should return not completed with times a day 2") {
val today = LocalDate.now()
val h = habit.copy(
timesADay = 2,
history = mapOf(
today to CompletedEntry(listOf(Time.now()))
)
)
val res = executeUseCase(h, today)
res.first().state.`should be`(NOT_COMPLETED_TODAY)
res.first().completedCount.`should be equal to`(1)
}
it("should return completed with times a day 2") {
val today = LocalDate.now()
val h = habit.copy(
timesADay = 2,
history = mapOf(
today to CompletedEntry(listOf(Time.now(), Time.now()), TestUtil.reward)
)
)
val res = executeUseCase(h, today)
res.first().state.`should be`(COMPLETED)
}
it("should return failed with times a day 2") {
val today = LocalDate.now()
val h = habit.copy(
timesADay = 2,
history = mapOf(
today.minusDays(1) to CompletedEntry(listOf(Time.now()))
)
)
val res = executeUseCase(h, today, today.minusDays(1), today)
res.first().state.`should be`(FAILED)
res.first().completedCount.`should be equal to`(1)
}
it("should return empty for day before creation") {
val today = LocalDate.now()
val h = habit.copy(
history = mapOf(today.minusDays(1) to CompletedEntry(listOf(Time.now()))),
createdAt = today.toStartOfDayUTC().time.instant
)
val res = executeUseCase(h, today, today.minusDays(1), today)
res.first().state.`should be`(COMPLETED)
res[1].state.`should be`(NOT_COMPLETED_TODAY)
}
it("should return completed on empty day") {
val today = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
val h = habit.copy(
days = setOf(DayOfWeek.SATURDAY),
history = mapOf(today to CompletedEntry(completedAtTimes = listOf(Time.now())))
)
val res = executeUseCase(h, today)
res.first().state.`should be`(COMPLETED)
}
}
describe("Bad") {
it("should return completed for yesterday") {
val today = LocalDate.now()
val h = habit.copy(
isGood = false
)
val res = executeUseCase(h, today, today.minusDays(1), today)
res.first().state.`should be`(COMPLETED)
}
it("should return completed for today") {
val today = LocalDate.now()
val h = habit.copy(
isGood = false
)
val res = executeUseCase(h, today)
res.first().state.`should be`(COMPLETED)
}
it("should return failed for yesterday") {
val today = LocalDate.now()
val h = habit.copy(
isGood = false,
history = mapOf(
today.minusDays(1) to CompletedEntry(listOf(Time.now()), TestUtil.reward)
)
)
val res = executeUseCase(h, today, today.minusDays(1), today)
res.first().state.`should be`(FAILED)
}
it("should return failed for today") {
val today = LocalDate.now()
val h = habit.copy(
isGood = false,
history = mapOf(
today to CompletedEntry(listOf(Time.now()), TestUtil.reward)
)
)
val res = executeUseCase(h, today)
res.first().state.`should be`(FAILED)
}
it("should return failed on empty day") {
val today = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
val h = habit.copy(
isGood = false,
days = setOf(DayOfWeek.SATURDAY),
history = mapOf(today to CompletedEntry(completedAtTimes = listOf(Time.now())))
)
val res = executeUseCase(h, today)
res.first().state.`should be`(FAILED)
}
}
}
})
| gpl-3.0 | dc28dd84d2f57e32cc05aa1c9bc2711d | 37.031674 | 99 | 0.497561 | 5.020908 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorBracketsFix.kt | 4 | 1951 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.psiUtil.endOffset
class MissingConstructorBracketsFix(element: KtPrimaryConstructor) : KotlinQuickFixAction<KtPrimaryConstructor>(element), CleanupFix {
override fun getFamilyName(): String = text
override fun getText(): String = KotlinBundle.message("add.empty.brackets.after.primary.constructor")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val constructor = element ?: return
val constructorKeyword = constructor.getConstructorKeyword() ?: return
if (constructor.valueParameterList != null) return
editor?.run {
val endOffset = constructorKeyword.endOffset
document.insertString(endOffset, "()")
caretModel.moveToOffset(endOffset + 1)
PsiDocumentManager.getInstance(project).commitDocument(document)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? =
diagnostic.createIntentionForFirstParentOfType(::MissingConstructorBracketsFix)
}
}
| apache-2.0 | 67a79e8d5e308bd7902a0cdff6329d50 | 49.025641 | 158 | 0.780113 | 5.041344 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWithNullsOppositeMultipleImpl.kt | 2 | 9927 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildWithNullsOppositeMultipleImpl(val dataSource: ChildWithNullsOppositeMultipleData) : ChildWithNullsOppositeMultiple, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNullsOppositeMultiple::class.java,
ChildWithNullsOppositeMultiple::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val childData: String
get() = dataSource.childData
override val parentEntity: ParentWithNullsOppositeMultiple?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ChildWithNullsOppositeMultipleData?) : ModifiableWorkspaceEntityBase<ChildWithNullsOppositeMultiple, ChildWithNullsOppositeMultipleData>(
result), ChildWithNullsOppositeMultiple.Builder {
constructor() : this(ChildWithNullsOppositeMultipleData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildWithNullsOppositeMultiple 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().isChildDataInitialized()) {
error("Field ChildWithNullsOppositeMultiple#childData should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildWithNullsOppositeMultiple
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.childData != dataSource.childData) this.childData = dataSource.childData
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<ParentWithNullsOppositeMultiple?>().singleOrNull()
if ((parentEntityNew == null && this.parentEntity != null) || (parentEntityNew != null && this.parentEntity == null) || (parentEntityNew != null && this.parentEntity != null && (this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id)) {
this.parentEntity = parentEntityNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData(true).childData = value
changedProperty.add("childData")
}
override var parentEntity: ParentWithNullsOppositeMultiple?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? ParentWithNullsOppositeMultiple
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentWithNullsOppositeMultiple
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityClass(): Class<ChildWithNullsOppositeMultiple> = ChildWithNullsOppositeMultiple::class.java
}
}
class ChildWithNullsOppositeMultipleData : WorkspaceEntityData<ChildWithNullsOppositeMultiple>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildWithNullsOppositeMultiple> {
val modifiable = ChildWithNullsOppositeMultipleImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildWithNullsOppositeMultiple {
return getCached(snapshot) {
val entity = ChildWithNullsOppositeMultipleImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildWithNullsOppositeMultiple::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildWithNullsOppositeMultiple(childData, entitySource) {
this.parentEntity = parents.filterIsInstance<ParentWithNullsOppositeMultiple>().singleOrNull()
}
}
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 ChildWithNullsOppositeMultipleData
if (this.entitySource != other.entitySource) return false
if (this.childData != other.childData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildWithNullsOppositeMultipleData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | e42136779942a1fe398aa43634678d37 | 39.353659 | 281 | 0.70958 | 5.48453 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-sessions/jvmAndNix/src/io/ktor/server/sessions/SessionData.kt | 1 | 6169 | /*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.sessions
import io.ktor.server.application.*
import io.ktor.util.*
import kotlin.reflect.*
/**
* Gets a current session or fails if the [Sessions] plugin is not installed.
* @throws MissingApplicationPluginException
*/
public val ApplicationCall.sessions: CurrentSession
get() = attributes.getOrNull(SessionDataKey) ?: reportMissingSession()
/**
* A container for all session instances.
*/
public interface CurrentSession {
/**
* Sets a new session instance with [name].
* @throws IllegalStateException if no session provider is registered with for [name]
*/
public fun set(name: String, value: Any?)
/**
* Gets a session instance for [name]
* @throws IllegalStateException if no session provider is registered with for [name]
*/
public fun get(name: String): Any?
/**
* Clears a session instance for [name].
* @throws IllegalStateException if no session provider is registered with for [name]
*/
public fun clear(name: String)
/**
* Finds a session name for the specified [type] or fails if it's not found.
* @throws IllegalStateException if no session provider registered for [type]
*/
public fun findName(type: KClass<*>): String
}
/**
* Sets a session instance with the type [T].
* @throws IllegalStateException if no session provider is registered for the type [T]
*/
public inline fun <reified T : Any> CurrentSession.set(value: T?): Unit = set(findName(T::class), value)
/**
* Gets a session instance with the type [T].
* @throws IllegalStateException if no session provider is registered for the type [T]
*/
public inline fun <reified T : Any> CurrentSession.get(): T? = get(T::class)
/**
* Gets a session instance with the type [T].
* @throws IllegalStateException if no session provider is registered for the type [T]
*/
@Suppress("UNCHECKED_CAST")
public fun <T : Any> CurrentSession.get(klass: KClass<T>): T? = get(findName(klass)) as T?
/**
* Clears a session instance with the type [T].
* @throws IllegalStateException if no session provider is registered for the type [T]
*/
public inline fun <reified T : Any> CurrentSession.clear(): Unit = clear(findName(T::class))
/**
* Gets or generates a new session instance using [generator] with the type [T] (or [name] if specified)
* @throws IllegalStateException if no session provider is registered for the type [T] (or [name] if specified)
*/
public inline fun <reified T : Any> CurrentSession.getOrSet(name: String = findName(T::class), generator: () -> T): T {
val result = get<T>()
if (result != null) {
return result
}
return generator().apply {
set(name, this)
}
}
internal data class SessionData(
val providerData: Map<String, SessionProviderData<*>>
) : CurrentSession {
private var committed = false
internal fun commit() {
committed = true
}
override fun findName(type: KClass<*>): String {
val entry = providerData.entries.firstOrNull { it.value.provider.type == type }
?: throw IllegalArgumentException("Session data for type `$type` was not registered")
return entry.value.provider.name
}
override fun set(name: String, value: Any?) {
if (committed) {
throw TooLateSessionSetException()
}
val providerData =
providerData[name] ?: throw IllegalStateException("Session data for `$name` was not registered")
setTyped(providerData, value)
}
@Suppress("UNCHECKED_CAST")
private fun <S : Any> setTyped(data: SessionProviderData<S>, value: Any?) {
if (value != null) {
data.provider.tracker.validate(value as S)
}
data.value = value as S
}
override fun get(name: String): Any? {
val providerData =
providerData[name] ?: throw IllegalStateException("Session data for `$name` was not registered")
return providerData.value
}
override fun clear(name: String) {
val providerData =
providerData[name] ?: throw IllegalStateException("Session data for `$name` was not registered")
providerData.value = null
}
}
internal suspend fun <S : Any> SessionProvider<S>.receiveSessionData(call: ApplicationCall): SessionProviderData<S> {
val receivedValue = transport.receive(call)
val unwrapped = tracker.load(call, receivedValue)
val incoming = receivedValue != null || unwrapped != null
return SessionProviderData(unwrapped, incoming, this)
}
internal suspend fun <S : Any> SessionProviderData<S>.sendSessionData(call: ApplicationCall) {
val value = value
when {
value != null -> {
val wrapped = provider.tracker.store(call, value)
provider.transport.send(call, wrapped)
}
incoming -> {
/* Deleted session should be cleared off */
provider.transport.clear(call)
provider.tracker.clear(call)
}
}
}
internal data class SessionProviderData<S : Any>(var value: S?, val incoming: Boolean, val provider: SessionProvider<S>)
internal val SessionDataKey = AttributeKey<SessionData>("SessionKey")
private fun ApplicationCall.reportMissingSession(): Nothing {
application.plugin(Sessions) // ensure the plugin is installed
throw SessionNotYetConfiguredException()
}
/**
* Thrown when an HTTP response has already been sent but an attempt to modify the session is made.
*/
public class TooLateSessionSetException :
IllegalStateException("It's too late to set session: response most likely already has been sent")
/**
* Thrown when a session is asked too early before the [Sessions] plugin had chance to configure it.
* For example, in a phase before [ApplicationCallPipeline.Plugins] or in a plugin installed before [Sessions] into
* the same phase.
*/
public class SessionNotYetConfiguredException :
IllegalStateException("Sessions are not yet ready: you are asking it to early before the Sessions plugin.")
| apache-2.0 | 6dd3873e4dbfb02d144726161ab3b759 | 33.853107 | 120 | 0.684876 | 4.344366 | false | false | false | false |
ktorio/ktor | ktor-shared/ktor-websockets/common/src/io/ktor/websocket/WebSocketExtensionHeader.kt | 1 | 1446 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.websocket
/**
* Parsed `Sec-WebSocket-Accept` header item representation.
*
* @param name is extension name.
* @param parameters is list of extension parameters.
*/
public class WebSocketExtensionHeader(public val name: String, public val parameters: List<String>) {
/**
* Parse parameters keys and values
*/
public fun parseParameters(): Sequence<Pair<String, String>> = parameters.asSequence().map {
val equalsIndex = it.indexOf('=')
if (equalsIndex < 0) return@map it to ""
val key = it.substring(0 until equalsIndex)
val value = if (equalsIndex + 1 < it.length) it.substring(equalsIndex + 1) else ""
key to value
}
@Suppress("KDocMissingDocumentation")
override fun toString(): String = "$name ${parametersToString()}"
private fun parametersToString(): String =
if (parameters.isEmpty()) "" else ", ${parameters.joinToString(",")}"
}
/**
* Parse `Sec-WebSocket-Accept` header.
*/
public fun parseWebSocketExtensions(value: String): List<WebSocketExtensionHeader> = value
.split(",")
.map { it ->
val extension = it.split(";")
val name = extension.first().trim()
val parameters = extension.drop(1).map { it.trim() }
WebSocketExtensionHeader(name, parameters)
}
| apache-2.0 | 08fe5bd6cf1f5b06697b06e2ae967664 | 31.133333 | 118 | 0.659751 | 4.22807 | false | false | false | false |
JordanCarr/KotlinForAndroidDevelopers | app/src/main/java/com/jordan_carr/KWeather/ui/utils/DelegatesExt.kt | 1 | 1748 | /*
* MIT License
*
* Copyright (c) 2017 Jordan Carr
*
* 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.jordan_carr.KWeather.ui.utils
import kotlin.reflect.KProperty
object DelegatesExt {
fun <T> notNullSingleValue() = NotNullSingleValueVar<T>()
}
class NotNullSingleValueVar<T> {
private var value: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} not initialized")
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = if (this.value == null) value
else throw IllegalStateException("${property.name} already initialized")
}
}
| mit | cd9b8289a6c6dc08f717708bb0c494a8 | 37.844444 | 87 | 0.733982 | 4.403023 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/widget/CircleLinedImageView.kt | 1 | 1275 | package io.armcha.ribble.presentation.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
import io.armcha.ribble.presentation.utils.extensions.toPx
/**
* Created by Chatikyan on 27.08.2017.
*/
class CircleLinedImageView(context: Context, attrs: AttributeSet? = null)
: AppCompatImageView(context, attrs) {
private val LINE_WIDTH = 3F
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var padding = 17
init {
with(paint) {
color = Color.LTGRAY
strokeWidth = LINE_WIDTH
style = Paint.Style.STROKE
}
setImageResource(io.armcha.ribble.R.drawable.ic_menu_gallery) //TODO remove
padding = padding.toPx(context)
setPadding(padding, padding, padding, padding)
}
override fun onDraw(canvas: Canvas) {
val actualWidth = (width - LINE_WIDTH) / 2F
canvas.drawCircle(width / 2F, width / 2F, actualWidth, paint)
super.onDraw(canvas)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec)
}
} | apache-2.0 | cec6db290e14c006c05d8d5dce2c6fd8 | 29.380952 | 83 | 0.697255 | 4.23588 | false | false | false | false |
isapp/chips | chips/src/main/java/com/isapp/chips/ChipsView.kt | 1 | 7078 | package com.isapp.chips
import android.content.Context
import android.graphics.Rect
import android.support.v4.widget.TextViewCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.isapp.chips.library.R
import java.util.*
interface ChipsListener {
fun onLoadIcon(chip: Chip, imageView: ImageView) {}
fun onChipClicked(chip: Chip) {}
fun onChipDeleted(chip: Chip) {}
}
class ChipsView : RecyclerView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
companion object {
const val HORIZONTAL = RecyclerView.HORIZONTAL
const val VERTICAL = RecyclerView.VERTICAL
private val gridPaddingDecoration = GridSpacingItemDecoration(10)
}
private var adapter = ChipsAdapter()
init {
orientation = HORIZONTAL
setAdapter(adapter)
}
/**
* Can be either [ChipsView.VERTICAL] or [ChipsView.HORIZONTAL]
*/
var orientation: Int
get() = field
set(value) {
field = value
if(value == VERTICAL) {
useFreeFormScrollingLayout(4)
}
else if(value == HORIZONTAL) {
useHorizontalScrollingLayout()
}
}
var chipsListener: ChipsListener?
get() = adapter.listener
set(value) { adapter.listener = value }
var chipTextAppearance: Int
get() = adapter.chipTextAppearance
set(value) {
adapter.chipTextAppearance = value
recycledViewPool.clear()
}
fun getChips(): List<Chip> = synchronized(this) { ArrayList(adapter.chips) }
fun addChip(chip: Chip) { synchronized(this) {
adapter.apply{
chips.add(chip)
val index = chips.lastIndex
notifyItemInserted(index)
scrollToPosition(index)
}
}}
fun removeChip(chip: Chip) { synchronized(this) {
adapter.apply {
val index = chips.indexOf(chip)
if(index >= 0) {
chips.remove(chip)
notifyItemRemoved(index)
}
}
}}
fun clearChips() { synchronized(this) {
adapter.apply {
val chipCount = chips.size
chips.clear()
notifyItemRangeRemoved(0, chipCount)
}
}}
private fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()
private fun useFreeFormScrollingLayout(maxColumns: Int) = synchronized(this) {
addItemDecoration(gridPaddingDecoration)
layoutManager = GridLayoutManager(context, maxColumns).apply {
spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val parentWidth = width
val holder = getChildAt(position)?.let {
getChildViewHolder(it) as? ChipsViewHolder
}
val textPaint = if(holder == null) {
TextView(context).let {
TextViewCompat.setTextAppearance(it, adapter.chipTextAppearance)
it.paint
}
}
else {
holder.text.paint
}
val chip = adapter.chips[position]
val text = chip.text
val rect = Rect()
textPaint.getTextBounds(text, 0, text.length, rect)
// add padding and margins + icon widths
val childWidth = if(chip.deletable && chip.icon) {
(rect.width() + context.dip(80)).toFloat()
}
else if(chip.deletable && !chip.icon) {
(rect.width() + context.dip(55)).toFloat()
}
else if(!chip.deletable && chip.icon) {
(rect.width() + context.dip(60)).toFloat()
}
else {
(rect.width() + context.dip(35)).toFloat()
}
val widthPerSpan = parentWidth.toFloat() / spanCount.toFloat()
return Math.ceil(childWidth / widthPerSpan.toDouble()).toInt()
}
}
spanSizeLookup.isSpanIndexCacheEnabled = true
}
}
private fun useHorizontalScrollingLayout() = synchronized(this) {
removeItemDecoration(gridPaddingDecoration)
layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
}
}
data class Chip(val data: Any, val text: String = data.toString(), val deletable: Boolean = false, val icon: Boolean = false)
private class ChipsAdapter : RecyclerView.Adapter<ChipsViewHolder>() {
companion object {
const val JUST_TEXT = 0
const val DELETABLE = 1
const val ICON = 2
const val DELETABLE_ICON = 3
}
internal val chips: MutableList<Chip> = ArrayList()
internal var chipTextAppearance: Int = R.style.DefaultTextAppearance
internal var listener: ChipsListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChipsViewHolder {
return ChipsViewHolder(
when(viewType) {
JUST_TEXT -> LayoutInflater.from(parent.context).inflate(R.layout.chip, parent, false)
DELETABLE -> LayoutInflater.from(parent.context).inflate(R.layout.deletable_chip, parent, false)
ICON -> LayoutInflater.from(parent.context).inflate(R.layout.icon_chip, parent, false)
DELETABLE_ICON -> LayoutInflater.from(parent.context).inflate(R.layout.deletable_icon_chip, parent, false)
else -> throw UnsupportedOperationException("Trying to create an unsupported view type")
}
).apply {
if(chipTextAppearance > 0) {
TextViewCompat.setTextAppearance(text, chipTextAppearance)
}
}
}
override fun onBindViewHolder(holder: ChipsViewHolder, position: Int) {
val chip = chips[position]
holder.itemView.setOnClickListener {
listener?.onChipClicked(chips[holder.adapterPosition])
}
holder.text.text = chip.text
holder.icon?.let {
listener?.onLoadIcon(chip, it)
}
holder.delete?.setOnClickListener {
listener?.onChipDeleted(chips[holder.adapterPosition])
}
}
override fun getItemCount() = chips.size
override fun getItemViewType(position: Int): Int {
val chip = chips[position]
return if(!chip.deletable and chip.icon) {
ICON
}
else if(chip.deletable and !chip.icon) {
DELETABLE
}
else if(chip.deletable and chip.icon) {
DELETABLE_ICON
}
else {
JUST_TEXT
}
}
}
private class ChipsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val icon = view.findViewById(android.R.id.icon1) as? ImageView
val text = view.findViewById(android.R.id.text1) as TextView
val delete = view.findViewById(android.R.id.icon2) as? ImageView
}
class GridSpacingItemDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
outRect.bottom = spacing // item top
}
} | mit | 3bb7540721b1f61da676bb47603bbf26 | 29.778261 | 125 | 0.67067 | 4.258724 | false | false | false | false |
ayatk/biblio | app/src/main/kotlin/com/ayatk/biblio/data/remote/util/QueryTime.kt | 1 | 1741 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.data.remote.util
import java.text.SimpleDateFormat
import java.util.*
/**
* ランキング用の日付を生成するクラス
*
* @since 0.1.0
*/
object QueryTime {
private val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
private var cal: Calendar = Calendar.getInstance()
fun day2String(date: Date): String = dateFormat.format(cal.apply { cal.time = date }.time)
/**
* 指定された日付の月初めの日付を計算します
*
* @sample 2017/2/13 -> 2017/2/1
* @param date
* @return String 2017/2/1 -> 20170201
*/
fun day2MonthOne(date: Date): String = dateFormat.format(
cal.apply {
time = date
set(Calendar.DAY_OF_MONTH, 1)
}.time
)
/**
*
*/
fun day2Tuesday(date: Date): String =
dateFormat.format(
cal.apply {
time = date
var week = get(Calendar.DAY_OF_WEEK)
if (week == Calendar.MONDAY || week == Calendar.SUNDAY) {
week += Calendar.DAY_OF_WEEK
}
add(Calendar.DAY_OF_MONTH, -week)
add(Calendar.DAY_OF_MONTH, Calendar.TUESDAY)
}.time
)
}
| apache-2.0 | 8c4fefe931592744bff5e7f9e161e0e5 | 25.046875 | 92 | 0.657469 | 3.480167 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/package-search/gradle/src/com/jetbrains/packagesearch/intellij/plugin/gradle/ExternalProjectSignalProvider.kt | 2 | 4799 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.packagesearch.intellij.plugin.gradle
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataImportListener
import com.intellij.openapi.project.Project
import com.intellij.util.messages.SimpleMessageBusConnection
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DumbAwareMessageBusModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.FileWatcherSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.FlowModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.invoke
import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.map
import org.jetbrains.plugins.gradle.settings.DistributionType
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettingsListener
import org.jetbrains.plugins.gradle.settings.TestRunner
import java.nio.file.Paths
internal class ExternalProjectSignalProvider : DumbAwareMessageBusModuleChangesSignalProvider() {
override fun registerDumbAwareModuleChangesListener(project: Project, bus: SimpleMessageBusConnection, listener: Runnable) {
bus.subscribe(
ProjectDataImportListener.TOPIC,
ProjectDataImportListener {
logDebug("ExternalProjectSignalProvider#registerModuleChangesListener#ProjectDataImportListener") { "value=$it" }
listener()
}
)
}
}
internal class SmartModeSignalProvider : DumbAwareMessageBusModuleChangesSignalProvider() {
override fun registerDumbAwareModuleChangesListener(project: Project, bus: SimpleMessageBusConnection, listener: Runnable) =
listener()
}
internal class GradleModuleLinkSignalProvider : DumbAwareMessageBusModuleChangesSignalProvider() {
override fun registerDumbAwareModuleChangesListener(project: Project, bus: SimpleMessageBusConnection, listener: Runnable) {
bus.subscribe(
GradleSettingsListener.TOPIC,
object : GradleSettingsListener {
override fun onProjectRenamed(oldName: String, newName: String) = listener()
override fun onProjectsLinked(settings: MutableCollection<GradleProjectSettings>) = listener()
override fun onProjectsUnlinked(linkedProjectPaths: MutableSet<String>) = listener()
override fun onBulkChangeStart() {}
override fun onBulkChangeEnd() {}
override fun onGradleHomeChange(oldPath: String?, newPath: String?, linkedProjectPath: String) {}
override fun onGradleDistributionTypeChange(currentValue: DistributionType?, linkedProjectPath: String) {}
override fun onServiceDirectoryPathChange(oldPath: String?, newPath: String?) {}
override fun onGradleVmOptionsChange(oldOptions: String?, newOptions: String?) {}
override fun onBuildDelegationChange(delegatedBuild: Boolean, linkedProjectPath: String) {}
override fun onTestRunnerChange(currentTestRunner: TestRunner, linkedProjectPath: String) {}
}
)
}
}
internal class GradlePropertiesChangedSignalProvider : FlowModuleChangesSignalProvider {
override fun registerModuleChangesListener(project: Project) =
project.filesChangedEventFlow.flatMapMerge { it.asFlow() }
.filter { it.file?.name == "gradle.properties" || it.file?.name == "local.properties" }
.map { }
}
internal class GlobalGradlePropertiesChangedSignalProvider : FileWatcherSignalProvider(
System.getenv("GRADLE_USER_HOME")?.let { Paths.get(it, "gradle.properties") }
?: Paths.get(System.getProperty("user.home"), ".gradle", "gradle.properties")
)
| apache-2.0 | f556b900e10a0fb4ff4c1282facf18a2 | 46.99 | 129 | 0.735153 | 5.344098 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SourceEntityImpl.kt | 2 | 8754 | package com.intellij.workspaceModel.storage.entities.test.api
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.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SourceEntityImpl: SourceEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceEntity::class.java, ChildSourceEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField var _data: String? = null
override val data: String
get() = _data!!
override val children: List<ChildSourceEntity>
get() = snapshot.extractOneToManyChildren<ChildSourceEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SourceEntityData?): ModifiableWorkspaceEntityBase<SourceEntity>(), SourceEntity.Builder {
constructor(): this(SourceEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SourceEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// 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().isDataInitialized()) {
error("Field SourceEntity#data should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field SourceEntity#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field SourceEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field SourceEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
// List of non-abstract referenced types
var _children: List<ChildSourceEntity>? = emptyList()
override var children: List<ChildSourceEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildSourceEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildSourceEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildSourceEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): SourceEntityData = result ?: super.getEntityData() as SourceEntityData
override fun getEntityClass(): Class<SourceEntity> = SourceEntity::class.java
}
}
class SourceEntityData : WorkspaceEntityData<SourceEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SourceEntity> {
val modifiable = SourceEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SourceEntity {
val entity = SourceEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SourceEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SourceEntityData
if (this.data != other.data) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SourceEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
} | apache-2.0 | 23bd2af5255ec00d4b42380f9091f770 | 38.977169 | 216 | 0.615376 | 5.906883 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/imports/importer/ActivityFileResultImporter.kt | 2 | 2592 | package co.smartreceipts.android.imports.importer
import android.net.Uri
import androidx.annotation.VisibleForTesting
import co.smartreceipts.analytics.Analytics
import co.smartreceipts.analytics.events.ErrorEvent
import co.smartreceipts.analytics.log.Logger
import co.smartreceipts.android.imports.FileImportProcessorFactory
import co.smartreceipts.android.model.Trip
import co.smartreceipts.core.di.scopes.ApplicationScope
import com.hadisatrio.optional.Optional
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
import javax.inject.Inject
@ApplicationScope
class ActivityFileResultImporter @VisibleForTesting constructor(
private val analytics: Analytics,
private val factory: FileImportProcessorFactory,
private val subscribeOnScheduler: Scheduler,
private val observeOnScheduler: Scheduler
) {
@Inject
constructor(analytics: Analytics, factory: FileImportProcessorFactory)
: this(analytics, factory, Schedulers.io(), AndroidSchedulers.mainThread())
private val importSubject = BehaviorSubject.create<Optional<ActivityFileResultImporterResponse>>()
private var localDisposable: Disposable? = null
val resultStream: Observable<ActivityFileResultImporterResponse>
get() = importSubject
.filter { it.isPresent }
.map { it.get() }
fun importFile(requestCode: Int, resultCode: Int, uri: Uri, trip: Trip) {
localDisposable?.let {
Logger.warn(this, "Clearing cached local subscription, a previous request was never fully completed")
it.dispose()
}
localDisposable =
factory.get(requestCode, trip).process(uri)
.subscribeOn(subscribeOnScheduler)
.map { file -> ActivityFileResultImporterResponse.importerResponse(file, requestCode, resultCode)}
.observeOn(observeOnScheduler)
.doOnError { throwable ->
Logger.error(this, "Failed to save import result", throwable)
analytics.record(ErrorEvent(this, throwable))
}
.subscribe({ response -> importSubject.onNext(Optional.of(response)) },
{ throwable -> importSubject.onNext(Optional.of(ActivityFileResultImporterResponse.importerError(throwable))) })
}
fun markThatResultsWereConsumed() = importSubject.onNext(Optional.absent())
}
| agpl-3.0 | db70433226a3199f108f5a4d95422bbd | 38.876923 | 132 | 0.731096 | 5.0625 | false | false | false | false |
gmariotti/kotlin-koans | lesson2/task6/src/Task.kt | 2 | 247 | data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
fun isLeapDay(date: MyDate): Boolean {
val (year, month, dayOfMonth) = date
// 29 February of a leap year
return year % 4 == 0 && month == 2 && dayOfMonth == 29
} | mit | a6352878b0412105d3b1ff84c2ee2678 | 26.555556 | 69 | 0.639676 | 3.57971 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/cli/RemovePropertyCommand.kt | 1 | 2507 | package io.georocket.cli
import de.undercouch.underline.InputReader
import de.undercouch.underline.Option
import de.undercouch.underline.OptionDesc
import de.undercouch.underline.UnknownAttributes
import io.georocket.index.Index
import io.georocket.index.TagsParser
import io.georocket.storage.Store
import io.vertx.core.buffer.Buffer
import io.vertx.core.impl.NoStackTraceThrowable
import io.vertx.core.streams.WriteStream
import org.antlr.v4.runtime.misc.ParseCancellationException
import org.slf4j.LoggerFactory
/**
* Remove properties from existing chunks in the GeoRocket data store
*/
class RemovePropertyCommand : DataCommand() {
companion object {
private val log = LoggerFactory.getLogger(RemovePropertyCommand::class.java)
}
override val usageName = "property rm"
override val usageDescription =
"Remove properties from existing chunks in the GeoRocket data store"
@set:OptionDesc(longName = "layer", shortName = "l",
description = "absolute path to the layer containing the chunks from " +
"which the properties should be removed",
argumentName = "PATH", argumentType = Option.ArgumentType.STRING)
var layer: String? = null
private var query: String? = null
@set:OptionDesc(longName = "properties", shortName = "props",
description = "comma-separated list of property keys to remove from the chunks",
argumentName = "PROPERTIES", argumentType = Option.ArgumentType.STRING)
var properties: String? = null
/**
* Set the query parts
*/
@UnknownAttributes("QUERY")
@Suppress("UNUSED")
fun setQueryParts(queryParts: List<String>) {
this.query = queryParts.joinToString(" ")
}
override fun checkArguments(): Boolean {
if (properties.isNullOrEmpty()) {
error("no properties given")
return false
}
try {
TagsParser.parse(properties)
} catch (e: ParseCancellationException) {
error("Invalid property syntax: ${e.message}")
return false
}
return super.checkArguments()
}
override suspend fun doRun(remainingArgs: Array<String>, reader: InputReader,
out: WriteStream<Buffer>, store: Store, index: Index): Int {
return try {
val query = compileQuery(query, layer)
val propNames = TagsParser.parse(properties)
index.removeProperties(query, propNames)
0
} catch (t: Throwable) {
error(t.message)
if (t !is NoStackTraceThrowable) {
log.error("Could not remove properties", t)
}
1
}
}
}
| apache-2.0 | 660f81179c2479a9b4e84fb9bed6d970 | 30.734177 | 84 | 0.7144 | 4.344887 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/TypesBuilder.kt | 1 | 3769 | package com.apollographql.apollo3.compiler.codegen.kotlin.file
import com.apollographql.apollo3.compiler.codegen.Identifier
import com.apollographql.apollo3.compiler.codegen.Identifier.type
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinSymbols
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinResolver
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDeprecation
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDescription
import com.apollographql.apollo3.compiler.ir.IrCustomScalar
import com.apollographql.apollo3.compiler.ir.IrEnum
import com.apollographql.apollo3.compiler.ir.IrInterface
import com.apollographql.apollo3.compiler.ir.IrObject
import com.apollographql.apollo3.compiler.ir.IrUnion
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.joinToCode
internal fun IrCustomScalar.typePropertySpec(): PropertySpec {
/**
* Custom Scalars without a mapping will generate code using [AnyResponseAdapter] directly
* so the fallback isn't really required here. We still write it as a way to hint the user
* to what's happening behind the scenes
*/
val kotlinName = kotlinName ?: "kotlin.Any"
return PropertySpec
.builder(Identifier.type, KotlinSymbols.CustomScalarType)
.initializer("%T(%S, %S)", KotlinSymbols.CustomScalarType, name, kotlinName)
.build()
}
internal fun IrEnum.typePropertySpec(): PropertySpec {
return PropertySpec
.builder(Identifier.type, KotlinSymbols.EnumType)
.initializer("%T(%S)", KotlinSymbols.EnumType, name)
.build()
}
private fun Set<String>.toCode(): CodeBlock {
val builder = CodeBlock.builder()
builder.add("listOf(")
builder.add("%L", sorted().map { CodeBlock.of("%S", it) }.joinToCode(", "))
builder.add(")")
return builder.build()
}
private fun List<String>.implementsToCode(resolver: KotlinResolver): CodeBlock {
val builder = CodeBlock.builder()
builder.add("listOf(")
builder.add("%L", sorted().map {
resolver.resolveCompiledType(it)
}.joinToCode(", "))
builder.add(")")
return builder.build()
}
internal fun IrObject.typePropertySpec(resolver: KotlinResolver): PropertySpec {
val builder = CodeBlock.builder()
builder.add("%T(name = %S", KotlinSymbols.ObjectType, name)
if (keyFields.isNotEmpty()) {
builder.add(", ")
builder.add("keyFields = %L", keyFields.toCode())
}
if (implements.isNotEmpty()) {
builder.add(", ")
builder.add("implements = %L", implements.implementsToCode(resolver))
}
builder.add(")")
return PropertySpec
.builder(type, KotlinSymbols.ObjectType)
.initializer(builder.build())
.build()
}
internal fun IrInterface.typePropertySpec(resolver: KotlinResolver): PropertySpec {
val builder = CodeBlock.builder()
builder.add("%T(name = %S", KotlinSymbols.InterfaceType, name)
if (keyFields.isNotEmpty()) {
builder.add(", ")
builder.add("keyFields = %L", keyFields.toCode())
}
if (implements.isNotEmpty()) {
builder.add(", ")
builder.add("implements = %L", implements.implementsToCode(resolver))
}
builder.add(")")
return PropertySpec
.builder(type, KotlinSymbols.InterfaceType)
.initializer(builder.build())
.build()
}
internal fun IrUnion.typePropertySpec(resolver: KotlinResolver): PropertySpec {
val builder = CodeBlock.builder()
builder.add(members.map {
resolver.resolveCompiledType(it)
}.joinToCode(", "))
return PropertySpec
.builder(type, KotlinSymbols.UnionType)
.maybeAddDescription(description)
.maybeAddDeprecation(deprecationReason)
.initializer("%T(%S, %L)", KotlinSymbols.UnionType, name, builder.build())
.build()
} | mit | 96379bbc6368b703092f943cd7f90025 | 34.233645 | 92 | 0.737066 | 4.114629 | false | false | false | false |
oryanm/TrelloWidget | app/src/main/kotlin/com/github/oryanmat/trellowidget/util/color/LabelColors.kt | 1 | 851 | package com.github.oryanmat.trellowidget.util.color
import android.graphics.Color
const val PINK = "#FF80CE"
const val ORANGE = "#FFAB4A"
const val LIME = "#51E898"
const val SKY = "#00C2E0"
const val BLUE = "#0079BF"
const val GREEN = "#61BD4F"
const val YELLOW = "#F2D600"
const val RED = "#EB5A46"
const val PURPLE = "#C377E0"
const val LIGHT_GREY = "#C4C9CC"
val colors = mapOf(
"black" to Color.BLACK,
"purple" to Color.parseColor(PURPLE),
"pink" to Color.parseColor(PINK),
"red" to Color.parseColor(RED),
"orange" to Color.parseColor(ORANGE),
"yellow" to Color.parseColor(YELLOW),
"green" to Color.parseColor(GREEN),
"lime" to Color.parseColor(LIME),
"sky" to Color.parseColor(SKY),
"blue" to Color.parseColor(BLUE),
null to Color.parseColor(LIGHT_GREY)) | mit | 3cd78aa55e7654711ec1a703e50ef864 | 30.555556 | 51 | 0.654524 | 3.211321 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GHPRStateServiceImpl.kt | 2 | 7491 | // 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.pullrequest.data.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import org.jetbrains.plugins.github.api.*
import org.jetbrains.plugins.github.api.data.GHBranchProtectionRules
import org.jetbrains.plugins.github.api.data.GHRepositoryPermissionLevel
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.api.data.GithubPullRequestMergeMethod
import org.jetbrains.plugins.github.pullrequest.GHPRStatisticsCollector
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityStateBuilder
import org.jetbrains.plugins.github.pullrequest.data.service.GHServiceUtil.logError
import org.jetbrains.plugins.github.util.submitIOTask
import java.util.concurrent.CompletableFuture
class GHPRStateServiceImpl internal constructor(private val progressManager: ProgressManager,
private val securityService: GHPRSecurityService,
private val requestExecutor: GithubApiRequestExecutor,
private val serverPath: GithubServerPath,
private val repoPath: GHRepositoryPath)
: GHPRStateService {
private val repository = GHRepositoryCoordinates(serverPath, repoPath)
override fun loadBranchProtectionRules(progressIndicator: ProgressIndicator,
pullRequestId: GHPRIdentifier,
baseBranch: String): CompletableFuture<GHBranchProtectionRules?> {
if (!securityService.currentUserHasPermissionLevel(GHRepositoryPermissionLevel.WRITE)) return CompletableFuture.completedFuture(null)
return progressManager.submitIOTask(progressIndicator) {
try {
requestExecutor.execute(GithubApiRequests.Repos.Branches.getProtection(repository, baseBranch))
}
catch (e: Exception) {
// assume there are no restrictions
if (e !is ProcessCanceledException) LOG.info("Error occurred while loading branch protection rules for $baseBranch", e)
null
}
}
}
override fun loadMergeabilityState(progressIndicator: ProgressIndicator,
pullRequestId: GHPRIdentifier,
headRefOid: String,
prHtmlUrl: String,
baseBranchProtectionRules: GHBranchProtectionRules?) =
progressManager.submitIOTask(progressIndicator) {
val mergeabilityData = requestExecutor.execute(GHGQLRequests.PullRequest.mergeabilityData(repository, pullRequestId.number))
?: error("Could not find pull request $pullRequestId.number")
val builder = GHPRMergeabilityStateBuilder(headRefOid, prHtmlUrl,
mergeabilityData)
if (baseBranchProtectionRules != null) {
builder.withRestrictions(securityService, baseBranchProtectionRules)
}
builder.build()
}.logError(LOG, "Error occurred while loading mergeability state data for PR ${pullRequestId.number}")
override fun close(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(it,
GithubApiRequests.Repos.PullRequests.update(serverPath, repoPath.owner, repoPath.repository,
pullRequestId.number,
state = GithubIssueState.closed))
return@submitIOTask
}.logError(LOG, "Error occurred while closing PR ${pullRequestId.number}")
override fun reopen(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(it,
GithubApiRequests.Repos.PullRequests.update(serverPath, repoPath.owner, repoPath.repository,
pullRequestId.number,
state = GithubIssueState.open))
return@submitIOTask
}.logError(LOG, "Error occurred while reopening PR ${pullRequestId.number}")
override fun markReadyForReview(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(it,
GHGQLRequests.PullRequest.markReadyForReview(repository, pullRequestId.id))
return@submitIOTask
}.logError(LOG, "Error occurred while marking PR ${pullRequestId.number} ready fro review")
override fun merge(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier,
commitMessage: Pair<String, String>, currentHeadRef: String) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.merge(serverPath, repoPath, pullRequestId.number,
commitMessage.first, commitMessage.second,
currentHeadRef))
GHPRStatisticsCollector.logMergedEvent(GithubPullRequestMergeMethod.merge)
return@submitIOTask
}.logError(LOG, "Error occurred while merging PR ${pullRequestId.number}")
override fun rebaseMerge(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier,
currentHeadRef: String) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(it,
GithubApiRequests.Repos.PullRequests.rebaseMerge(serverPath, repoPath, pullRequestId.number,
currentHeadRef))
GHPRStatisticsCollector.logMergedEvent(GithubPullRequestMergeMethod.rebase)
return@submitIOTask
}.logError(LOG, "Error occurred while rebasing PR ${pullRequestId.number}")
override fun squashMerge(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier,
commitMessage: Pair<String, String>, currentHeadRef: String) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(it,
GithubApiRequests.Repos.PullRequests.squashMerge(serverPath, repoPath, pullRequestId.number,
commitMessage.first, commitMessage.second,
currentHeadRef))
GHPRStatisticsCollector.logMergedEvent(GithubPullRequestMergeMethod.squash)
return@submitIOTask
}.logError(LOG, "Error occurred while squash-merging PR ${pullRequestId.number}")
companion object {
private val LOG = logger<GHPRStateService>()
}
}
| apache-2.0 | 8a5bce12a164a64cd8c50ab9460b05a2 | 59.902439 | 140 | 0.658123 | 6.502604 | false | false | false | false |
leafclick/intellij-community | platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/LibraryLicensesTester.kt | 1 | 2154 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build
import gnu.trove.THashSet
import junit.framework.AssertionFailedError
import org.jetbrains.intellij.build.impl.LibraryLicensesListGenerator
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JpsJavaClasspathKind
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.library.JpsLibrary
import org.jetbrains.jps.model.module.JpsModule
import org.junit.rules.ErrorCollector
class LibraryLicensesTester(private val project: JpsProject, private val licenses: List<LibraryLicense>) {
fun reportMissingLicenses(collector: ErrorCollector) {
val nonPublicModules = setOf("intellij.idea.ultimate.build", "intellij.idea.community.build", "buildSrc", "intellij.platform.testGuiFramework")
val libraries = HashMap<JpsLibrary, JpsModule>()
project.modules.filter { it.name !in nonPublicModules && !it.name.contains("guiTests") && !it.name.contains("integrationTests", ignoreCase = true)}.forEach { module ->
JpsJavaExtensionService.dependencies(module).includedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME).libraries.forEach {
libraries[it] = module
}
}
val librariesWithLicenses = licenses.flatMapTo(THashSet()) { it.libraryNames }
for ((jpsLibrary, jpsModule) in libraries) {
val libraryName = LibraryLicensesListGenerator.getLibraryName(jpsLibrary)
if (libraryName !in librariesWithLicenses) {
collector.addError(AssertionFailedError("""
|License isn't specified for '$libraryName' library (used in module '${jpsModule.name}' in ${jpsModule.contentRootsList.urls})
|If a library is packaged into IDEA installation information about its license must be added into one of *LibraryLicenses.groovy files
|If a library is used in tests only change its scope to 'Test'
|If a library is used for compilation only change its scope to 'Provided'
""".trimMargin()))
}
}
}
} | apache-2.0 | a181db167b21ea32e0acfde343bfc4de | 55.710526 | 171 | 0.748839 | 4.602564 | false | true | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/find/actions/SearchTargetVariantsDataRule.kt | 2 | 1917 | // 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.find.actions
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter
import com.intellij.ide.impl.dataRules.GetDataRule
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageView
import com.intellij.util.SmartList
/**
* @see com.intellij.codeInsight.navigation.actions.GotoDeclarationAction.doChooseAmbiguousTarget
*/
class SearchTargetVariantsDataRule : GetDataRule {
override fun getData(dataProvider: DataProvider): Any? {
val allTargets = SmartList<TargetVariant>()
FindUsagesAction.SEARCH_TARGETS.getData(dataProvider)?.mapTo(allTargets, ::SearchTargetVariant)
val usageTargets: Array<out UsageTarget>? = UsageView.USAGE_TARGETS_KEY.getData(dataProvider)
if (usageTargets == null) {
val editor = CommonDataKeys.EDITOR.getData(dataProvider)
if (editor != null) {
val offset = editor.caretModel.offset
try {
val reference = TargetElementUtil.findReference(editor, offset)
if (reference != null) {
TargetElementUtil.getInstance().getTargetCandidates(reference).mapTo(allTargets, ::PsiTargetVariant)
}
}
catch (ignore: IndexNotReadyException) { }
}
}
else if (usageTargets.isNotEmpty()) {
val target: UsageTarget = usageTargets[0]
allTargets += if (target is PsiElement2UsageTargetAdapter) {
PsiTargetVariant(target.element)
}
else {
CustomTargetVariant(target)
}
}
return allTargets.takeUnless {
it.isEmpty()
}
}
}
| apache-2.0 | 98024ae5e59289b505b9fbb095adf4f2 | 35.865385 | 140 | 0.733438 | 4.586124 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/scanner/Cache.kt | 1 | 3779 | /*
* 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 android.net.wifi.ScanResult
import android.net.wifi.WifiInfo
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.MainContext
internal class CacheResult(val scanResult: ScanResult, val average: Int)
internal data class CacheKey(val bssid: String, val ssid: String)
@OpenClass
internal class Cache {
private val scanResults: ArrayDeque<List<ScanResult>> = ArrayDeque(MAXIMUM)
private var wifiInfo: WifiInfo? = null
private var count: Int = COUNT_MIN
fun scanResults(): List<CacheResult> =
combineCache()
.groupingBy { CacheKey(it.BSSID, it.SSID) }
.aggregate { _, accumulator: CacheResult?, element, first ->
CacheResult(element, calculate(first, element, accumulator))
}
.values
.toList()
fun add(scanResults: List<ScanResult>, wifiInfo: WifiInfo?) {
count = if (count >= MAXIMUM * FACTOR) COUNT_MIN else count + 1
val size = size()
while (this.scanResults.size >= size) {
this.scanResults.removeLastOrNull()
}
this.scanResults.addFirst(scanResults)
this.wifiInfo = wifiInfo
}
fun first(): List<ScanResult> = scanResults.first()
fun last(): List<ScanResult> = scanResults.last()
fun size(): Int =
if (sizeAvailable) {
val settings = MainContext.INSTANCE.settings
if (settings.cacheOff())
MINIMUM
else {
with(settings.scanSpeed()) {
when {
this < 2 -> MAXIMUM
this < 5 -> MAXIMUM - 1
this < 10 -> MAXIMUM - 2
else -> MINIMUM
}
}
}
} else MINIMUM
fun wifiInfo(): WifiInfo? = wifiInfo
private fun calculate(first: Boolean, element: ScanResult, accumulator: CacheResult?): Int {
val average: Int = if (first) element.level else (accumulator!!.average + element.level) / DENOMINATOR
return (if (sizeAvailable) average else average - SIZE * (count + count % FACTOR) / DENOMINATOR)
.coerceIn(LEVEL_MINIMUM, LEVEL_MAXIMUM)
}
private fun combineCache(): List<ScanResult> =
scanResults.flatten().sortedWith(comparator())
private fun comparator(): Comparator<ScanResult> =
compareBy<ScanResult> { it.BSSID }.thenBy { it.SSID }.thenBy { it.level }
private val sizeAvailable: Boolean
get() = MainContext.INSTANCE.configuration.sizeAvailable
companion object {
private const val MINIMUM: Int = 1
private const val MAXIMUM: Int = 4
private const val SIZE: Int = MINIMUM + MAXIMUM
private const val LEVEL_MINIMUM: Int = -100
private const val LEVEL_MAXIMUM: Int = 0
private const val FACTOR: Int = 3
private const val DENOMINATOR: Int = 2
private const val COUNT_MIN: Int = 2
}
} | gpl-3.0 | 8934dd6552c6cf791394a0553d29096f | 36.058824 | 110 | 0.636147 | 4.569528 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/repository/PlusRepo.kt | 1 | 8694 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2022 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package repository
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asFlow
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import model.AccountType
import model.AppState
import model.BlockaConfig
import model.toAccountType
import service.*
import ui.MainApplication
import ui.TunnelViewModel
import utils.Logger
class PlusRepo {
private val api by lazy { Services.apiForCurrentUser }
private val persistence by lazy { PersistenceService }
private val dialog by lazy { DialogService }
private val env by lazy { EnvironmentService }
private val context by lazy { ContextService }
private val tunnelVM by lazy {
val app = context.requireApp() as MainApplication
ViewModelProvider(app).get(TunnelViewModel::class.java)
}
private val accountHot by lazy { Repos.account.accountHot }
private val appRepo by lazy { Repos.app }
private val processingRepo by lazy { Repos.processing }
// private lazy var leaseRepo = Repos.leaseRepo
// private lazy var gatewayRepo = Repos.gatewayRepo
// private lazy var netxRepo = Repos.netxRepo
private val writeBlockaConfig = MutableSharedFlow<BlockaConfig>(replay = 0)
private val writePlusEnabled = MutableStateFlow<Boolean?>(null)
val blockaConfig = writeBlockaConfig.filterNotNull()
val plusEnabled = writePlusEnabled.filterNotNull()
// private val newPlusT = Tasker<Gateway, Ignored>("newPlus")
fun start() {
onBlockaConfig_ExposeState()
onTunnelStatus_UpdateProcessing()
onAppPausedIndefinitely_StopPlusIfNecessary()
onAppUnpaused_StartPlusIfNecessary()
onAccountInactive_StopPlusIfNecessary()
}
// User engaged actions of turning Plus on and off are managed by
// TunnelViewModel, here we only listen to those changes and
// propagate the status to expose similar api like on ios.
fun onBlockaConfig_ExposeState() {
tunnelVM.config.observeForever {
GlobalScope.launch {
writeBlockaConfig.emit(it)
writePlusEnabled.emit(it.vpnEnabled)
}
}
}
fun onTunnelStatus_UpdateProcessing() {
tunnelVM.tunnelStatus.observeForever {
GlobalScope.launch {
processingRepo.notify("plusWorking", ongoing = it.inProgress)
}
}
}
// private func onChangePlusPause() {
// changePlusPauseT.setTask { until in Just(until)
// .flatMap { _ in self.netxRepo.changePause(until: until) }
// .map { _ in true }
// .eraseToAnyPublisher()
// }
// }
//
// private func onCurrentLeaseGone_StopPlus() {
// leaseRepo.currentHot
// .filter { it in it.lease == nil }
// .flatMap { _ in self.plusEnabledHot.first() }
// .filter { plusEnabled in plusEnabled == true }
// .flatMap { _ in self.accountHot.first() }
// .sink(onValue: { it in
// self.switchPlusOff()
// let msg = (it.account.isActive()) ?
// L10n.errorVpnNoCurrentLeaseNew : L10n.errorVpnExpired
//
// self.dialog.showAlert(
// message: msg,
// header: L10n.notificationVpnExpiredSubtitle
// )
// .sink()
// .store(in: &self.cancellables)
// })
// .store(in: &cancellables)
// }
// Untimed pause (appState Paused, but no pausedUntilHot value)
private fun onAppPausedIndefinitely_StopPlusIfNecessary() {
GlobalScope.launch {
appRepo.appStateHot
.filter { it == AppState.Paused }
.collect {
delay(500)
// val paused = appRepo.pausedUntilHot.first()
// if (paused == null) {
// Do only if NETX is active
val s = tunnelVM.tunnelStatus.asFlow().first { !it.inProgress }
if (s.active /* || s.pauseSeconds > 0 */) {
// Just switch off Plus
tunnelVM.turnOff()
}
// }
}
}
}
// Simple restore Plus when app activated again and Plus was active before
private fun onAppUnpaused_StartPlusIfNecessary() {
GlobalScope.launch {
appRepo.appStateHot
.filter { it == AppState.Activated }
.collect {
delay(500)
// Do only if NETX is inactive but was on
val s = tunnelVM.tunnelStatus.asFlow().first { !it.inProgress }
val vpnEnabled = tunnelVM.config.value?.vpnEnabled ?: false
if (!s.active && vpnEnabled) {
// Just switch on Plus
tunnelVM.turnOn()
}
}
}
}
private fun onAccountInactive_StopPlusIfNecessary() {
GlobalScope.launch {
accountHot
.filter { it.type.toAccountType() != AccountType.Plus }
.collect {
val vpnEnabled = tunnelVM.config.value?.vpnEnabled ?: false
if (vpnEnabled) {
Logger.w("Plus", "Turning off VPN because was active and account is not Plus anymore")
tunnelVM.turnOff(vpnEnabled = false)
}
}
}
}
// // Timed pause
// private func onAppPausedWithTimer_PausePlusIfNecessary() {
// appRepo.pausedUntilHot
// .compactMap { $0 }
// .flatMap { until in Publishers.CombineLatest(
// Just(until),
// // Get NETX state once it settles
// // TODO: this may introduce delay, not sure if it's safe
// self.netxRepo.netxStateHot.filter { !$0.inProgress }.first()
// ) }
// // Do only if NETX is active
// .filter { it in it.1.active || it.1.pauseSeconds > 0 }
// // Make NETX pause (also will update "until" if changed)
// .sink(onValue: { it in
// Logger.v("PlusRepo", "Pausing VPN as app is paused with timer")
// self.changePlusPauseT.send(it.0)
// })
// .store(in: &cancellables)
// }
//
// private func onAppUnpaused_UnpausePlusIfNecessary() {
// appRepo.pausedUntilHot
// .filter { it in it == nil }
// .flatMap { until in Publishers.CombineLatest(
// Just(until),
// // Get NETX state once it settles
// // TODO: this may introduce delay, not sure if it's safe
// self.netxRepo.netxStateHot.filter { !$0.inProgress }.first()
// ) }
// // Do only if NETX is paused
// .filter { it in it.1.pauseSeconds > 0 }
// // Make NETX unpause
// .sink(onValue: { it in
// Logger.v("PlusRepo", "Unpausing VPN as app is unpaused")
// self.changePlusPauseT.send(nil)
// })
// .store(in: &cancellables)
// }
// private suspend fun onAppActive_StartPlusIfNecessary() {
// Publishers.CombineLatest(
// appRepo.appStateHot,
// leaseRepo.currentHot.removeDuplicates { a, b in a.lease != b.lease }
// )
// // If app got activated and current lease is there...
// .filter { it in
// let (appState, currentLease) = it
// return appState == .Activated && currentLease.lease != nil
// }
// .flatMap { _ in Publishers.CombineLatest(
// self.plusEnabledHot.first(),
// self.netxRepo.netxStateHot.filter { !$0.inProgress }.first()
// ) }
// // ... and while plus is enabled, but netx is not active...
// .filter { it in
// let (plusEnabled, netxState) = it
// return plusEnabled && !netxState.active
// }
// // ... start Plus
// .sink(onValue: { it in
// Logger.v("PlusRepo", "Switch VPN on because app is active and Plus is enabled")
// self.switchPlusOn()
// })
// .store(in: &cancellables)
// }
//
} | mpl-2.0 | c28a9e47a8397fba1e14e39f20782bd7 | 35.683544 | 106 | 0.567008 | 4.177319 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveDeclarationsDelegate.kt | 5 | 8599 | // 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.move.moveDeclarations
import com.intellij.psi.PsiElement
import com.intellij.refactoring.move.moveInner.MoveInnerClassUsagesHandler
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.shorten.isToBeShortened
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
sealed class MoveDeclarationsDelegate {
abstract fun getContainerChangeInfo(originalDeclaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): ContainerChangeInfo
open fun findInternalUsages(descriptor: MoveDeclarationsDescriptor): List<UsageInfo> = emptyList()
open fun collectConflicts(
descriptor: MoveDeclarationsDescriptor,
internalUsages: MutableSet<UsageInfo>,
conflicts: MultiMap<PsiElement, String>
) {
}
open fun preprocessDeclaration(descriptor: MoveDeclarationsDescriptor, originalDeclaration: KtNamedDeclaration) {
}
open fun preprocessUsages(descriptor: MoveDeclarationsDescriptor, usages: List<UsageInfo>) {
}
object TopLevel : MoveDeclarationsDelegate() {
override fun getContainerChangeInfo(originalDeclaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): ContainerChangeInfo {
val sourcePackage = ContainerInfo.Package(originalDeclaration.containingKtFile.packageFqName)
val targetPackage = moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage
return ContainerChangeInfo(sourcePackage, targetPackage)
}
}
class NestedClass(
val newClassName: String? = null,
val outerInstanceParameterName: String? = null
) : MoveDeclarationsDelegate() {
override fun getContainerChangeInfo(originalDeclaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): ContainerChangeInfo {
val originalInfo = ContainerInfo.Class(originalDeclaration.containingClassOrObject!!.fqName!!)
val movingToClass = (moveTarget as? KotlinMoveTargetForExistingElement)?.targetElement is KtClassOrObject
val targetContainerFqName = moveTarget.targetContainerFqName
val newInfo = when {
targetContainerFqName == null -> ContainerInfo.UnknownPackage
movingToClass -> ContainerInfo.Class(targetContainerFqName)
else -> ContainerInfo.Package(targetContainerFqName)
}
return ContainerChangeInfo(originalInfo, newInfo)
}
override fun findInternalUsages(descriptor: MoveDeclarationsDescriptor): List<UsageInfo> {
val classToMove = descriptor.moveSource.elementsToMove.singleOrNull() as? KtClass ?: return emptyList()
return collectOuterInstanceReferences(classToMove)
}
private fun isValidTargetForImplicitCompanionAsDispatchReceiver(
moveDescriptor: MoveDeclarationsDescriptor,
companionDescriptor: ClassDescriptor
): Boolean {
return when (val moveTarget = moveDescriptor.moveTarget) {
is KotlinMoveTargetForCompanion -> true
is KotlinMoveTargetForExistingElement -> {
val targetClass = moveTarget.targetElement as? KtClassOrObject ?: return false
val targetClassDescriptor = targetClass.unsafeResolveToDescriptor() as ClassDescriptor
val companionClassDescriptor = companionDescriptor.containingDeclaration as? ClassDescriptor ?: return false
targetClassDescriptor.isSubclassOf(companionClassDescriptor)
}
else -> false
}
}
override fun collectConflicts(
descriptor: MoveDeclarationsDescriptor,
internalUsages: MutableSet<UsageInfo>,
conflicts: MultiMap<PsiElement, String>
) {
val usageIterator = internalUsages.iterator()
while (usageIterator.hasNext()) {
val usage = usageIterator.next()
val element = usage.element ?: continue
val isConflict = when (usage) {
is ImplicitCompanionAsDispatchReceiverUsageInfo -> {
if (!isValidTargetForImplicitCompanionAsDispatchReceiver(descriptor, usage.companionDescriptor)) {
conflicts.putValue(
element,
KotlinBundle.message("text.implicit.companion.object.will.be.inaccessible.0", element.text)
)
}
true
}
is OuterInstanceReferenceUsageInfo -> usage.reportConflictIfAny(conflicts)
else -> false
}
if (isConflict) {
usageIterator.remove()
}
}
}
override fun preprocessDeclaration(descriptor: MoveDeclarationsDescriptor, originalDeclaration: KtNamedDeclaration) {
with(originalDeclaration) {
newClassName?.let { setName(it) }
if (this is KtClass) {
if ((descriptor.moveTarget as? KotlinMoveTargetForExistingElement)?.targetElement !is KtClassOrObject) {
if (hasModifier(KtTokens.INNER_KEYWORD)) removeModifier(KtTokens.INNER_KEYWORD)
if (hasModifier(KtTokens.PROTECTED_KEYWORD)) removeModifier(KtTokens.PROTECTED_KEYWORD)
}
if (outerInstanceParameterName != null) {
val type = (containingClassOrObject!!.unsafeResolveToDescriptor() as ClassDescriptor).defaultType
val parameter = KtPsiFactory(project).createParameter(
"private val $outerInstanceParameterName: ${IdeDescriptorRenderers.SOURCE_CODE.renderType(type)}"
)
createPrimaryConstructorParameterListIfAbsent().addParameter(parameter).isToBeShortened = true
}
}
}
}
override fun preprocessUsages(descriptor: MoveDeclarationsDescriptor, usages: List<UsageInfo>) {
if (outerInstanceParameterName == null) return
val psiFactory = KtPsiFactory(descriptor.project)
val newOuterInstanceRef = psiFactory.createExpression(outerInstanceParameterName)
val classToMove = descriptor.moveSource.elementsToMove.singleOrNull() as? KtClass
for (usage in usages) {
if (usage is MoveRenameUsageInfo) {
val referencedNestedClass = usage.referencedElement?.unwrapped as? KtClassOrObject
if (referencedNestedClass == classToMove) {
val outerClass = referencedNestedClass?.containingClassOrObject
val lightOuterClass = outerClass?.toLightClass()
if (lightOuterClass != null) {
MoveInnerClassUsagesHandler.EP_NAME
.forLanguage(usage.element!!.language)
?.correctInnerClassUsage(usage, lightOuterClass, outerInstanceParameterName)
}
}
}
when (usage) {
is OuterInstanceReferenceUsageInfo.ExplicitThis -> {
usage.expression?.replace(newOuterInstanceRef)
}
is OuterInstanceReferenceUsageInfo.ImplicitReceiver -> {
usage.callElement?.let { it.replace(psiFactory.createExpressionByPattern("$0.$1", outerInstanceParameterName, it)) }
}
}
}
}
}
} | apache-2.0 | d660f72227bf92c84d3bb2fcf1c2fb5d | 49 | 158 | 0.652053 | 6.285819 | false | false | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/asm.kt | 9 | 1596 | // 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.intellij.build.tasks
import org.jetbrains.org.objectweb.asm.*
import java.nio.file.Files
import java.nio.file.Path
//fun main() {
// val file = Path.of(System.getProperty("user.home"),
// "Documents/idea/out/classes/production/intellij.platform.core/com/intellij/openapi/application/ApplicationNamesInfo.class")
// val outFile = Path.of(System.getProperty("user.home"), "t/ApplicationNamesInfo.class")
// injectAppInfo(file, outFile, "test")
//}
// see https://stackoverflow.com/a/49454118
fun injectAppInfo(inFile: Path, newFieldValue: String): ByteArray {
val classReader = ClassReader(Files.readAllBytes(inFile))
val classWriter = ClassWriter(classReader, 0)
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION, classWriter) {
override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<String?>?): MethodVisitor? {
val methodVisitor = super.visitMethod(access, name, desc, signature, exceptions)
if (name != "getAppInfoData") {
return methodVisitor
}
return object : MethodVisitor(Opcodes.API_VERSION, methodVisitor) {
override fun visitLdcInsn(value: Any) {
if (value == "") {
super.visitLdcInsn(newFieldValue)
}
else {
super.visitLdcInsn(value)
}
}
}
}
}, 0)
return classWriter.toByteArray()
} | apache-2.0 | fbcf420ca0667846855c28fd979295a7 | 39.948718 | 158 | 0.689223 | 4.081841 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/impl.kt | 11 | 4010 | // 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.
@file:JvmName("GroovyUnresolvedAccessChecker")
package org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.QuickFixFactory
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider
import com.intellij.codeInspection.ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
import com.intellij.openapi.util.TextRange
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.codeInspection.GroovyQuickFixFactory
import org.jetbrains.plugins.groovy.highlighting.HighlightSink
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
fun checkUnresolvedReference(
expression: GrReferenceExpression,
highlightIfGroovyObjectOverridden: Boolean,
highlightIfMissingMethodsDeclared: Boolean,
highlightSink: HighlightSink
) {
val referenceNameElement = expression.referenceNameElement ?: return
val referenceName = expression.referenceName ?: return
val parent = expression.parent
val results: Collection<GroovyResolveResult> = getBestResolveResults(expression)
if (results.isNotEmpty()) {
val staticsOk = results.all(GrUnresolvedAccessChecker::isStaticOk)
if (!staticsOk) {
highlightSink.registerProblem(referenceNameElement, LIKE_UNKNOWN_SYMBOL, message("cannot.reference.non.static", referenceName))
}
return
}
if (ResolveUtil.isKeyOfMap(expression) || ResolveUtil.isClassReference(expression)) {
return
}
if (!highlightIfGroovyObjectOverridden && GrUnresolvedAccessChecker.areGroovyObjectMethodsOverridden(expression)) return
if (!highlightIfMissingMethodsDeclared && GrUnresolvedAccessChecker.areMissingMethodsDeclared(expression)) return
val actions = ArrayList<IntentionAction>()
if (parent is GrMethodCall) {
actions += GroovyQuickFixFactory.getInstance().createGroovyStaticImportMethodFix(parent)
if (PsiUtil.isNewified(expression)) {
actions += generateAddImportActions(expression)
}
}
else {
actions += generateCreateClassActions(expression)
actions += generateAddImportActions(expression)
}
actions += generateReferenceExpressionFixes(expression)
val registrar = object : QuickFixActionRegistrar {
override fun register(action: IntentionAction) {
actions += action
}
override fun register(fixRange: TextRange, action: IntentionAction, key: HighlightDisplayKey?) {
actions += action
}
}
UnresolvedReferenceQuickFixProvider.registerReferenceFixes(expression, registrar)
QuickFixFactory.getInstance().registerOrderEntryFixes(registrar, expression)
highlightSink.registerProblem(referenceNameElement, LIKE_UNKNOWN_SYMBOL, message("cannot.resolve", referenceName), actions)
}
private fun getBestResolveResults(ref: GroovyReference): Collection<GroovyResolveResult> = getBestResolveResults(ref.resolve(false))
private fun getBestResolveResults(results: Collection<GroovyResolveResult>): Collection<GroovyResolveResult> {
val staticsOk: Collection<GroovyResolveResult> = results.filter(GroovyResolveResult::isStaticsOK)
if (staticsOk.isEmpty()) {
return results
}
val accessibleStaticsOk: Collection<GroovyResolveResult> = staticsOk.filter(GroovyResolveResult::isAccessible)
if (accessibleStaticsOk.isEmpty()) {
return staticsOk
}
return accessibleStaticsOk
}
| apache-2.0 | dcc0cc70146750d25cc70e02fda7272e | 45.091954 | 140 | 0.815461 | 4.920245 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/fromJavaToKotlin/delegateStaticToStaticFieldWithNameConflict.kt | 24 | 716 | val staticField = 42 //KT-40835
fun a() {
JavaClass.field
val d = JavaClass()
JavaClass.field
d.let {
JavaClass.field
}
d.also {
JavaClass.field
}
with(d) {
JavaClass.field
}
with(d) out@{
with(4) {
JavaClass.field
}
}
}
fun a2() {
val d: JavaClass? = null
d?.field
d?.let {
JavaClass.field
}
d?.also {
JavaClass.field
}
with(d) {
JavaClass.field
}
with(d) out@{
with(4) {
JavaClass.field
}
}
}
fun JavaClass.b(): Int? = JavaClass.field
fun JavaClass.c(): Int = JavaClass.field
fun d(d: JavaClass) = JavaClass.field
| apache-2.0 | 9f237dea17a6855400c2e5d6624e98be | 12.509434 | 41 | 0.488827 | 3.59799 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/canvas/tool/DragListener3D.kt | 1 | 2557 | package com.cout970.modeler.gui.canvas.tool
import com.cout970.modeler.controller.Dispatch
import com.cout970.modeler.controller.tasks.TaskUpdateModel
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.gui.canvas.SceneSpaceContext
import com.cout970.modeler.gui.canvas.helpers.CanvasHelper
import com.cout970.modeler.util.getClosest
import com.cout970.modeler.util.toIVector
import com.cout970.raytrace.IRayObstacle
import com.cout970.raytrace.RayTraceResult
import com.cout970.vector.api.IVector2
class DragListener3D(val gui: Gui) : IDragListener {
private val helper = Cursor3DTransformHelper()
override fun onNoDrag() {
val mousePos = gui.input.mouse.getMousePos()
val canvas = gui.canvasContainer.selectedCanvas ?: return
val context = CanvasHelper.getMouseSpaceContext(canvas, mousePos)
val cursor = gui.state.cursor
val camera = canvas.cameraHandler.camera
val viewport = canvas.size.toIVector()
cursor.getParts().forEach { it.hovered = false }
val targets = cursor.getParts().map { part ->
part to part.calculateHitbox2(cursor, camera, viewport)
}
val part = getHoveredObject3D(context, targets) ?: return
part.hovered = true
}
override fun onTick(startMousePos: IVector2, endMousePos: IVector2) {
val selection = gui.programState.modelSelection.getOrNull() ?: return
val cursor = gui.state.cursor
val canvas = gui.canvasContainer.selectedCanvas ?: return
val part = cursor.getParts().find { it.hovered } ?: return
val mouse = startMousePos to endMousePos
gui.state.tmpModel = helper.applyTransformation(gui, selection, cursor, part, mouse, canvas)
if (cursor.mode != CursorMode.ROTATION) {
cursor.update(gui)
}
}
override fun onEnd(startMousePos: IVector2, endMousePos: IVector2) {
helper.cache?.let { cache ->
val task = TaskUpdateModel(oldModel = gui.programState.model, newModel = cache)
Dispatch.run("run") { this["task"] = task }
}
helper.cache = null
gui.state.cursor.update(gui)
}
fun <T> getHoveredObject3D(ctx: SceneSpaceContext, objs: List<Pair<T, IRayObstacle>>): T? {
val ray = ctx.mouseRay
val list = mutableListOf<Pair<RayTraceResult, T>>()
objs.forEach { obj ->
val res = obj.second.rayTrace(ray)
res?.let { list += it to obj.first }
}
return list.getClosest(ray)?.second
}
} | gpl-3.0 | 4eeee9c35bbd636fc44bd2bf7bf6aef4 | 35.028169 | 100 | 0.676183 | 4.052298 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/deferred/BloomBlurPass.kt | 1 | 2828 | package de.fabmax.kool.pipeline.deferred
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.Vec2f
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.shading.BlurShader
import de.fabmax.kool.pipeline.shading.BlurShaderConfig
import de.fabmax.kool.scene.Group
import de.fabmax.kool.scene.mesh
import de.fabmax.kool.util.Color
import kotlin.math.sqrt
class BloomBlurPass(kernelSize: Int, thresholdPass: BloomThresholdPass) :
OffscreenRenderPass2dPingPong(renderPassConfig {
name = "BloomBlurPass"
setSize(0, 0)
addColorTexture(TexFormat.RGBA_F16)
clearDepthTexture()
}) {
private val pingShader: BlurShader
private val pongShader: BlurShader
private var blurDirDirty = true
val bloomMap: Texture2d
get() = pong.colorTexture!!
var bloomScale = 1f
set(value) {
field = value
blurDirDirty = true
}
var bloomStrength: Float
get() = pongShader.strength.value
set(value) {
pongShader.strength.value = value
}
init {
pingPongPasses = 1
val pingCfg = BlurShaderConfig().apply {
kernelRadius = kernelSize
}
pingShader = BlurShader(pingCfg)
pingShader.blurInput(thresholdPass.colorTexture)
val pongCfg = BlurShaderConfig().apply {
kernelRadius = kernelSize
}
pongShader = BlurShader(pongCfg)
pongShader.blurInput(ping.colorTexture)
pingContent.fullScreenQuad(pingShader)
pongContent.fullScreenQuad(pongShader)
ping.clearColor = Color(0f, 0f, 0f, 0f)
pong.clearColor = Color(0f, 0f, 0f, 0f)
bloomStrength = 1f
dependsOn(thresholdPass)
}
override fun update(ctx: KoolContext) {
super.update(ctx)
// pingShader.setXDirectionByTexWidth(width, bloomScale)
// pongShader.setYDirectionByTexHeight(height, bloomScale)
if (blurDirDirty) {
val sqrt2 = sqrt(2f)
val dx = 1f / width * bloomScale * sqrt2
val dy = 1f / height * bloomScale * sqrt2
pingShader.direction.value = Vec2f(dx, dy)
pongShader.direction.value = Vec2f(dx, -dy)
}
}
override fun resize(width: Int, height: Int, ctx: KoolContext) {
super.resize(width, height, ctx)
blurDirDirty = true
}
private fun Group.fullScreenQuad(quadShader: Shader) {
isFrustumChecked = false
+mesh(listOf(Attribute.POSITIONS, Attribute.TEXTURE_COORDS)) {
isFrustumChecked = false
generate {
rect {
size.set(1f, 1f)
mirrorTexCoordsY()
}
}
shader = quadShader
}
}
} | apache-2.0 | c75771e4a5dda0d93d354388345c3c0c | 28.164948 | 73 | 0.615629 | 4.074928 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/reactive/internal/scrollablepanel/ScrollablePanel.kt | 1 | 2635 | package com.cout970.reactive.internal.scrollablepanel
import com.cout970.reactive.core.*
import com.cout970.reactive.dsl.*
import com.cout970.reactive.internal.demoWindow
import com.cout970.reactive.nodes.child
import com.cout970.reactive.nodes.div
import com.cout970.reactive.nodes.scrollablePanel
import com.cout970.reactive.nodes.style
import org.joml.Vector4f
import org.liquidengine.legui.style.color.ColorConstants.black
import org.liquidengine.legui.style.color.ColorConstants.white
import java.awt.Color.getHSBColor
fun main(args: Array<String>) {
demoWindow { env ->
env.frame.container.backgroundColor { black() }
env.context.isDebugEnabled = true
Renderer.render(env.frame.container) {
child(Scroll::class)
}
}
}
data class ScrollState(val seconds: Int) : RState
class Scroll : RComponent<EmptyProps, ScrollState>() {
override fun getInitialState() = ScrollState(0)
override fun RBuilder.render() = scrollablePanel("test") {
postMount {
fill()
}
verticalScroll {
style {
arrowColor = Vector4f(0xF1.toFloat(), 0xF1.toFloat(), 0xF1.toFloat(), 255f).div(255f)
scrollColor = Vector4f(0xC1.toFloat(), 0xC1.toFloat(), 0xC1.toFloat(), 255f).div(255f)
arrowSize = 17f
style.setMinimumSize(17f, 17f)
backgroundColor { arrowColor }
rectCorners()
borderless()
}
}
horizontalScroll {
style { hide() }
}
viewport {
postMount {
sizeX = parent.sizeX - 10f
}
}
container {
style {
backgroundColor { white() }
sizeY = 8f * 255f
}
postMount {
sizeX = parent.sizeX - 10f
// Place colors in column, starting at the top and going down
floatTop(0f)
}
for (i in 1..255) {
div(i.toString()) {
style {
borderless()
rectCorners()
backgroundColor {
val color = getHSBColor(i / 255f, 1.0f, 1.0f)
Vector4f(color.red / 255f, color.green / 255f, color.blue / 255f, 1f)
}
sizeY = 8f
}
postMount {
sizeX = parent.sizeX
}
}
}
}
}
} | gpl-3.0 | d0f4a4b410594e85392e964c012e70db | 26.747368 | 102 | 0.517647 | 4.473684 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/models/ProjectNotification.kt | 1 | 3624 | package com.kickstarter.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class ProjectNotification private constructor(
private val project: Project,
private val id: Long,
private val email: Boolean,
private val mobile: Boolean,
private val urls: Urls
) : Parcelable {
fun project() = this.project
fun id() = this.id
fun email() = this.email
fun mobile() = this.mobile
fun urls() = this.urls
@Parcelize
data class Builder(
private var project: Project = Project.builder().build(),
private var id: Long = 0L,
private var email: Boolean = false,
private var mobile: Boolean = false,
private var urls: Urls = Urls.builder().build()
) : Parcelable {
fun project(project: Project?) = apply { this.project = project ?: Project.builder().build() }
fun id(id: Long?) = apply { id?.let { this.id = it } }
fun email(email: Boolean?) = apply { email?.let { this.email = it } }
fun mobile(mobile: Boolean?) = apply { mobile?.let { this.mobile = it } }
fun urls(urls: Urls?) = apply { this.urls = urls ?: Urls.builder().build() }
fun build() = ProjectNotification(
project = project,
id = id,
email = email,
mobile = mobile,
urls = urls
)
}
fun toBuilder() = Builder(
project = project,
id = id,
email = email,
mobile = mobile,
urls = urls
)
@Parcelize
class Project private constructor(
private val name: String,
private val id: Long
) : Parcelable {
fun name() = this.name
fun id() = this.id
@Parcelize
data class Builder(
private var name: String = "",
private var id: Long = 0L
) : Parcelable {
fun name(name: String?) = apply { this.name = name ?: "" }
fun id(id: Long?) = apply { this.id = id ?: 0L }
fun build() = Project(
name = name,
id = id
)
}
companion object {
@JvmStatic
fun builder(): Builder {
return Builder()
}
}
}
@Parcelize
class Urls private constructor(
private val api: Api
) : Parcelable {
fun api() = this.api
@Parcelize
data class Builder(
private var api: Api = Api.builder().build()
) : Parcelable {
fun api(api: Api?) = apply { this.api = api ?: Api.builder().build() }
fun build() = Urls(api = api)
}
@Parcelize
class Api private constructor(
private val notification: String
) : Parcelable {
fun notification() = this.notification
@Parcelize
data class Builder(
private var notification: String = ""
) : Parcelable {
fun notification(notification: String?) = apply { this.notification = notification ?: "" }
fun build() = Api(notification = notification)
}
companion object {
@JvmStatic
fun builder(): Builder {
return Builder()
}
}
}
companion object {
@JvmStatic
fun builder(): Builder {
return Builder()
}
}
}
companion object {
@JvmStatic
fun builder(): Builder {
return Builder()
}
}
}
| apache-2.0 | 68d08e4aa50d93defd3290a166611090 | 27.093023 | 106 | 0.509934 | 4.793651 | false | false | false | false |
siosio/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/actions/IgnoreFileActionGroup.kt | 2 | 6230 | // 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.openapi.vcs.changes.ignore.actions
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsRoot
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionAction
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.vcsUtil.VcsImplUtil
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.Nls
import kotlin.streams.toList
open class IgnoreFileActionGroup(private val ignoreFileType: IgnoreFileType) :
ActionGroup(
message("vcs.add.to.ignore.file.action.group.text", ignoreFileType.ignoreLanguage.filename),
message("vcs.add.to.ignore.file.action.group.description", ignoreFileType.ignoreLanguage.filename),
ignoreFileType.icon
), DumbAware, UpdateInBackground {
private var actions: Collection<AnAction> = emptyList()
override fun update(e: AnActionEvent) {
val selectedFiles = getSelectedFiles(e)
val presentation = e.presentation
val project = e.getData(CommonDataKeys.PROJECT)
if (project == null) {
presentation.isVisible = false
return
}
val unversionedFiles = ScheduleForAdditionAction.getUnversionedFiles(e, project).toList()
if (unversionedFiles.isEmpty()) {
presentation.isVisible = false
return
}
val ignoreFiles =
filterSelectedFiles(project, selectedFiles).map { findSuitableIgnoreFiles(project, it) }.filterNot(Collection<*>::isEmpty)
val resultedIgnoreFiles = ignoreFiles.flatten().toHashSet()
for (files in ignoreFiles) {
resultedIgnoreFiles.retainAll(files) //only take ignore files which is suitable for all selected files
}
val additionalActions = createAdditionalActions(project, selectedFiles, unversionedFiles)
if (resultedIgnoreFiles.isNotEmpty()) {
actions = resultedIgnoreFiles.toActions(project, additionalActions.size)
}
else {
actions = listOfNotNull(createNewIgnoreFileAction(project, selectedFiles))
}
if (additionalActions.isNotEmpty()) {
actions += additionalActions
}
isPopup = actions.size > 1
presentation.isVisible = actions.isNotEmpty()
}
protected open fun createAdditionalActions(project: Project,
selectedFiles: List<VirtualFile>,
unversionedFiles: List<VirtualFile>): List<AnAction> = emptyList()
override fun canBePerformed(context: DataContext) = actions.size == 1
override fun actionPerformed(e: AnActionEvent) {
actions.firstOrNull()?.actionPerformed(e)
}
override fun getChildren(e: AnActionEvent?) = actions.toTypedArray()
private fun filterSelectedFiles(project: Project, files: List<VirtualFile>) =
files.filter { file ->
VcsUtil.isFileUnderVcs(project, VcsUtil.getFilePath(file)) && !ChangeListManager.getInstance(project).isIgnoredFile(file)
}
private fun findSuitableIgnoreFiles(project: Project, file: VirtualFile): Collection<VirtualFile> {
val fileParent = file.parent
return FileTypeIndex.getFiles(ignoreFileType, ProjectScope.getProjectScope(project))
.filter {
fileParent == it.parent || fileParent != null && it.parent != null && VfsUtil.isAncestor(it.parent, fileParent, false)
}
}
private fun Collection<VirtualFile>.toActions(project: Project, additionalActionsSize: Int): Collection<AnAction> {
val projectDir = project.guessProjectDir()
return map { file ->
IgnoreFileAction(file).apply {
templatePresentation.apply {
icon = ignoreFileType.icon
text = file.toTextRepresentation(project, projectDir, [email protected] + additionalActionsSize)
}
}
}
}
private fun createNewIgnoreFileAction(project: Project, selectedFiles: List<VirtualFile>): AnAction? {
val filename = ignoreFileType.ignoreLanguage.filename
val (rootVcs, commonIgnoreFileRoot) = getCommonIgnoreFileRoot(selectedFiles, project) ?: return null
if (rootVcs == null) return null
if (commonIgnoreFileRoot.findChild(filename) != null) return null
val ignoredFileContentProvider = VcsImplUtil.findIgnoredFileContentProvider(rootVcs) ?: return null
if (ignoredFileContentProvider.fileName != filename) return null
return CreateNewIgnoreFileAction(filename, commonIgnoreFileRoot).apply {
templatePresentation.apply {
icon = ignoreFileType.icon
text = message("vcs.add.to.ignore.file.action.group.text", filename)
}
}
}
private fun VirtualFile.toTextRepresentation(project: Project, projectDir: VirtualFile?, size: Int): @Nls String {
if (size == 1) {
return message("vcs.add.to.ignore.file.action.group.text", ignoreFileType.ignoreLanguage.filename)
}
val projectRootOrVcsRoot = projectDir ?: VcsUtil.getVcsRootFor(project, this) ?: return name
return VfsUtil.getRelativePath(this, projectRootOrVcsRoot) ?: name
}
private operator fun VcsRoot.component1() = vcs
private operator fun VcsRoot.component2() = path
}
private fun getCommonIgnoreFileRoot(files: Collection<VirtualFile>, project: Project): VcsRoot? {
val first = files.firstOrNull() ?: return null
val vcsManager = ProjectLevelVcsManager.getInstance(project)
val commonVcsRoot = vcsManager.getVcsRootObjectFor(first) ?: return null
if (first == commonVcsRoot.path) {
// trying to ignore vcs root itself
return null
}
val haveCommonRoot = files.asSequence().drop(1).all {
it != commonVcsRoot.path && vcsManager.getVcsRootObjectFor(it) == commonVcsRoot
}
return if (haveCommonRoot) commonVcsRoot else null
}
| apache-2.0 | a03a474c082245c5f223f7a45c989288 | 40.258278 | 140 | 0.743499 | 4.730448 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KtFileClassProviderImpl.kt | 2 | 3332 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.caches.project.getModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.util.isInDumbMode
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFileClassProvider
import org.jetbrains.kotlin.psi.analysisContext
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.scripting.definitions.runReadAction
class KtFileClassProviderImpl(val project: Project) : KtFileClassProvider {
override fun getFileClasses(file: KtFile): Array<PsiClass> {
if (file.project.isInDumbMode()) {
return PsiClass.EMPTY_ARRAY
}
// TODO We don't currently support finding light classes for scripts
if (file.isCompiled || runReadAction { file.isScript() }) {
return PsiClass.EMPTY_ARRAY
}
val result = arrayListOf<PsiClass>()
file.declarations.filterIsInstance<KtClassOrObject>().map { it.toLightClass() }.filterNotNullTo(result)
val moduleInfo = file.getModuleInfo()
// prohibit obtaining light classes for non-jvm modules trough KtFiles
// common files might be in fact compiled to jvm and thus correspond to a PsiClass
// this API does not provide context (like GSS) to be able to determine if this file is in fact seen through a jvm module
// this also fixes a problem where a Java JUnit run configuration producer would produce run configurations for a common file
if (!moduleInfo.platform.isJvm()) return emptyArray()
val jvmClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(file)
val fileClassFqName = file.javaFileFacadeFqName
val kotlinAsJavaSupport = KotlinAsJavaSupport.getInstance(project)
val facadeClasses = when {
file.analysisContext != null && file.hasTopLevelCallables() ->
listOf(
KtLightClassForFacade.createForSyntheticFile(
PsiManager.getInstance(
file.project
), fileClassFqName, file
)
)
jvmClassInfo.withJvmMultifileClass ->
kotlinAsJavaSupport.getFacadeClasses(fileClassFqName, moduleInfo.contentScope())
file.hasTopLevelCallables() ->
(kotlinAsJavaSupport as IDEKotlinAsJavaSupport).createLightClassForFileFacade(
fileClassFqName, listOf(file), moduleInfo
)
else -> emptyList<PsiClass>()
}
facadeClasses.filterTo(result) {
it is KtLightClassForFacade && file in it.files
}
return result.toTypedArray()
}
} | apache-2.0 | 7e2172892e2c97d5cd083602c82d4491 | 42.855263 | 158 | 0.703782 | 5.198128 | false | false | false | false |
siosio/intellij-community | plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesTree.kt | 1 | 19248 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch.dashboard
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.dvcs.branch.isGroupingEnabled
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode.Companion.getColorManager
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode.Companion.getRepositoryIcon
import com.intellij.icons.AllIcons
import com.intellij.ide.dnd.TransferableList
import com.intellij.ide.dnd.aware.DnDAwareTree
import com.intellij.ide.util.treeView.TreeState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.codeStyle.FixingLayoutMatcher
import com.intellij.psi.codeStyle.MinusculeMatcher
import com.intellij.psi.codeStyle.NameUtil
import com.intellij.ui.*
import com.intellij.ui.hover.TreeHoverListener
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.speedSearch.SpeedSearch
import com.intellij.ui.speedSearch.SpeedSearchSupply
import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent
import com.intellij.util.PlatformIcons
import com.intellij.util.ThreeState
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.branch.BranchData
import com.intellij.vcs.branch.BranchPresentation
import com.intellij.vcs.branch.LinkedBranchDataImpl
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcsUtil.VcsImplUtil
import git4idea.config.GitVcsSettings
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.ui.branch.GitBranchPopupActions.LocalBranchActions.constructIncomingOutgoingTooltip
import git4idea.ui.branch.dashboard.BranchesDashboardActions.BranchesTreeActionGroup
import icons.DvcsImplIcons
import java.awt.Graphics
import java.awt.GraphicsEnvironment
import java.awt.datatransfer.Transferable
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JTree
import javax.swing.TransferHandler
import javax.swing.event.TreeExpansionEvent
import javax.swing.event.TreeExpansionListener
import javax.swing.tree.TreePath
internal class BranchesTreeComponent(project: Project) : DnDAwareTree() {
var doubleClickHandler: (BranchTreeNode) -> Unit = {}
var searchField: SearchTextField? = null
init {
putClientProperty(AUTO_SELECT_ON_MOUSE_PRESSED, false)
setCellRenderer(BranchTreeCellRenderer(project))
isRootVisible = false
setShowsRootHandles(true)
isOpaque = false
isHorizontalAutoScrollingEnabled = false
installDoubleClickHandler()
SmartExpander.installOn(this)
TreeHoverListener.DEFAULT.addTo(this)
initDnD()
}
private inner class BranchTreeCellRenderer(project: Project) : ColoredTreeCellRenderer() {
private val repositoryManager = GitRepositoryManager.getInstance(project)
private val colorManager = getColorManager(project)
private val branchSettings = GitVcsSettings.getInstance(project).branchSettings
private var incomingOutgoingIcon: NodeIcon? = null
override fun customizeCellRenderer(tree: JTree,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean) {
if (value !is BranchTreeNode) return
val descriptor = value.getNodeDescriptor()
val branchInfo = descriptor.branchInfo
val isBranchNode = descriptor.type == NodeType.BRANCH
val isGroupNode = descriptor.type == NodeType.GROUP_NODE
val isRepositoryNode = descriptor.type == NodeType.GROUP_REPOSITORY_NODE
icon = when {
isBranchNode && branchInfo != null && branchInfo.isCurrent && branchInfo.isFavorite -> DvcsImplIcons.CurrentBranchFavoriteLabel
isBranchNode && branchInfo != null && branchInfo.isCurrent -> DvcsImplIcons.CurrentBranchLabel
isBranchNode && branchInfo != null && branchInfo.isFavorite -> AllIcons.Nodes.Favorite
isBranchNode -> AllIcons.Vcs.BranchNode
isGroupNode -> PlatformIcons.FOLDER_ICON
isRepositoryNode -> getRepositoryIcon(descriptor.repository!!, colorManager)
else -> null
}
toolTipText =
if (branchInfo != null && branchInfo.isLocal)
BranchPresentation.getTooltip(getBranchesTooltipData(branchInfo.branchName, getSelectedRepositories(descriptor)))
else null
append(value.getTextRepresentation(), SimpleTextAttributes.REGULAR_ATTRIBUTES, true)
val repositoryGrouping = branchSettings.isGroupingEnabled(GroupingKey.GROUPING_BY_REPOSITORY)
if (!repositoryGrouping && branchInfo != null && branchInfo.repositories.size < repositoryManager.repositories.size) {
append(" (${DvcsUtil.getShortNames(branchInfo.repositories)})", SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
val incomingOutgoingState = branchInfo?.incomingOutgoingState
incomingOutgoingIcon = incomingOutgoingState?.icon?.let { NodeIcon(it, preferredSize.width + tree.insets.left) }
tree.toolTipText = incomingOutgoingState?.run { constructIncomingOutgoingTooltip(hasIncoming(), hasOutgoing()) }
}
override fun calcFocusedState() = super.calcFocusedState() || searchField?.textEditor?.hasFocus() ?: false
private fun getBranchesTooltipData(branchName: String, repositories: Collection<GitRepository>): List<BranchData> {
return repositories.map { repo ->
val trackedBranchName = repo.branches.findLocalBranch(branchName)?.findTrackedBranch(repo)?.name
val presentableRootName = VcsImplUtil.getShortVcsRootName(repo.project, repo.root)
LinkedBranchDataImpl(presentableRootName, branchName, trackedBranchName)
}
}
override fun paint(g: Graphics) {
super.paint(g)
incomingOutgoingIcon?.let { (icon, locationX) ->
icon.paintIcon(this@BranchTreeCellRenderer, g, locationX, JBUIScale.scale(2))
}
}
}
private data class NodeIcon(val icon: Icon, val locationX: Int)
override fun hasFocus() = super.hasFocus() || searchField?.textEditor?.hasFocus() ?: false
private fun installDoubleClickHandler() {
object : DoubleClickListener() {
override fun onDoubleClick(e: MouseEvent): Boolean {
val clickPath = getClosestPathForLocation(e.x, e.y) ?: return false
val selectionPath = selectionPath
if (selectionPath == null || clickPath != selectionPath) return false
val node = (selectionPath.lastPathComponent as? BranchTreeNode) ?: return false
if (isToggleEvent(this@BranchesTreeComponent, e)) return false
doubleClickHandler(node)
return true
}
}.installOn(this)
}
private fun initDnD() {
if (!GraphicsEnvironment.isHeadless()) {
transferHandler = BRANCH_TREE_TRANSFER_HANDLER
}
}
fun getSelectedBranches(): List<BranchInfo> {
return getSelectedNodes()
.mapNotNull { it.getNodeDescriptor().branchInfo }
.toList()
}
fun getSelectedNodes(): Sequence<BranchTreeNode> {
val paths = selectionPaths ?: return emptySequence()
return paths.asSequence()
.map(TreePath::getLastPathComponent)
.mapNotNull { it as? BranchTreeNode }
}
fun getSelectedRemotes(): Set<RemoteInfo> {
val paths = selectionPaths ?: return emptySet()
return paths.asSequence()
.map(TreePath::getLastPathComponent)
.mapNotNull { it as? BranchTreeNode }
.filter {
it.getNodeDescriptor().displayName != null &&
it.getNodeDescriptor().type == NodeType.GROUP_NODE &&
(it.getNodeDescriptor().parent?.type == NodeType.REMOTE_ROOT || it.getNodeDescriptor().parent?.repository != null)
}
.mapNotNull { with(it.getNodeDescriptor()) { RemoteInfo(displayName!!, parent?.repository) } }
.toSet()
}
fun getSelectedRepositories(descriptor: BranchNodeDescriptor): List<GitRepository> {
var parent = descriptor.parent
while (parent != null) {
val repository = parent.repository
if (repository != null) return listOf(repository)
parent = parent.parent
}
return descriptor.branchInfo?.repositories ?: emptyList()
}
fun getSelectedRepositories(branchInfo: BranchInfo): Set<GitRepository> {
val paths = selectionPaths ?: return emptySet()
return paths.asSequence()
.filter {
val lastPathComponent = it.lastPathComponent
lastPathComponent is BranchTreeNode && lastPathComponent.getNodeDescriptor().branchInfo == branchInfo
}
.mapNotNull { findNodeDescriptorInPath(it) { descriptor -> Objects.nonNull(descriptor.repository) } }
.mapNotNull(BranchNodeDescriptor::repository)
.toSet()
}
private fun findNodeDescriptorInPath(path: TreePath, condition: (BranchNodeDescriptor) -> Boolean): BranchNodeDescriptor? {
var curPath: TreePath? = path
while (curPath != null) {
val node = curPath.lastPathComponent as? BranchTreeNode
if (node != null && condition(node.getNodeDescriptor())) return node.getNodeDescriptor()
curPath = curPath.parentPath
}
return null
}
}
internal class FilteringBranchesTree(project: Project,
val component: BranchesTreeComponent,
private val uiController: BranchesDashboardController,
rootNode: BranchTreeNode = BranchTreeNode(BranchNodeDescriptor(NodeType.ROOT)))
: FilteringTree<BranchTreeNode, BranchNodeDescriptor>(project, component, rootNode) {
private val expandedPaths = HashSet<TreePath>()
private val localBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.LOCAL_ROOT))
private val remoteBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.REMOTE_ROOT))
private val headBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.HEAD_NODE))
private val branchFilter: (BranchInfo) -> Boolean =
{ branch -> !uiController.showOnlyMy || branch.isMy == ThreeState.YES }
private val nodeDescriptorsModel = NodeDescriptorsModel(localBranchesNode.getNodeDescriptor(),
remoteBranchesNode.getNodeDescriptor())
private var localNodeExist = false
private var remoteNodeExist = false
private val treeStateHolder: BranchesTreeStateHolder get() = project.service()
private val groupingConfig: MutableMap<GroupingKey, Boolean> =
with(GitVcsSettings.getInstance(project).branchSettings) {
hashMapOf(
GroupingKey.GROUPING_BY_DIRECTORY to isGroupingEnabled(GroupingKey.GROUPING_BY_DIRECTORY),
GroupingKey.GROUPING_BY_REPOSITORY to isGroupingEnabled(GroupingKey.GROUPING_BY_REPOSITORY)
)
}
fun toggleGrouping(key: GroupingKey, state: Boolean) {
groupingConfig[key] = state
refreshTree()
}
fun isGroupingEnabled(key: GroupingKey) = groupingConfig[key] == true
init {
runInEdt {
PopupHandler.installPopupMenu(component, BranchesTreeActionGroup(project, this), "BranchesTreePopup")
setupTreeListeners()
}
}
override fun createSpeedSearch(searchTextField: SearchTextField): SpeedSearchSupply =
object : FilteringSpeedSearch(searchTextField) {
private val customWordMatchers = hashSetOf<MinusculeMatcher>()
override fun matchingFragments(text: String): Iterable<TextRange?>? {
val allTextRanges = super.matchingFragments(text)
if (customWordMatchers.isEmpty()) return allTextRanges
val wordRanges = arrayListOf<TextRange>()
for (wordMatcher in customWordMatchers) {
wordMatcher.matchingFragments(text)?.let(wordRanges::addAll)
}
return when {
allTextRanges != null -> allTextRanges + wordRanges
wordRanges.isNotEmpty() -> wordRanges
else -> null
}
}
override fun updatePattern(string: String?) {
super.updatePattern(string)
onUpdatePattern(string)
}
override fun onUpdatePattern(text: String?) {
customWordMatchers.clear()
customWordMatchers.addAll(buildCustomWordMatchers(text))
}
private fun buildCustomWordMatchers(text: String?): Set<MinusculeMatcher> {
if (text == null) return emptySet()
val wordMatchers = hashSetOf<MinusculeMatcher>()
for (word in StringUtil.split(text, " ")) {
wordMatchers.add(
FixingLayoutMatcher("*$word", NameUtil.MatchingCaseSensitivity.NONE, ""))
}
return wordMatchers
}
}
override fun installSearchField(): SearchTextField {
val searchField = super.installSearchField()
component.searchField = searchField
return searchField
}
private fun setupTreeListeners() {
component.addTreeExpansionListener(object : TreeExpansionListener {
override fun treeExpanded(event: TreeExpansionEvent) {
expandedPaths.add(event.path)
treeStateHolder.storeState(this@FilteringBranchesTree)
}
override fun treeCollapsed(event: TreeExpansionEvent) {
expandedPaths.remove(event.path)
treeStateHolder.storeState(this@FilteringBranchesTree)
}
})
component.addTreeSelectionListener { treeStateHolder.storeState(this@FilteringBranchesTree) }
}
fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> {
val selectedRepositories = component.getSelectedRepositories(branchInfo)
return if (selectedRepositories.isNotEmpty()) selectedRepositories.toList() else branchInfo.repositories
}
fun getSelectedBranches() = component.getSelectedBranches()
fun getSelectedBranchFilters(): List<String> {
return component.getSelectedNodes()
.mapNotNull { with(it.getNodeDescriptor()) { if (type == NodeType.HEAD_NODE) VcsLogUtil.HEAD else branchInfo?.branchName } }
.toList()
}
fun getSelectedRemotes() = component.getSelectedRemotes()
fun getSelectedBranchNodes() = component.getSelectedNodes().map(BranchTreeNode::getNodeDescriptor).toSet()
private fun restorePreviouslyExpandedPaths() {
TreeUtil.restoreExpandedPaths(component, expandedPaths.toList())
}
override fun expandTreeOnSearchUpdateComplete(pattern: String?) {
restorePreviouslyExpandedPaths()
}
override fun onSpeedSearchUpdateComplete(pattern: String?) {
updateSpeedSearchBackground()
}
override fun useIdentityHashing(): Boolean = false
private fun updateSpeedSearchBackground() {
val speedSearch = searchModel.speedSearch as? SpeedSearch ?: return
val textEditor = component.searchField?.textEditor ?: return
if (isEmptyModel()) {
textEditor.isOpaque = true
speedSearch.noHits()
}
else {
textEditor.isOpaque = false
textEditor.background = UIUtil.getTextFieldBackground()
}
}
private fun isEmptyModel() = searchModel.isLeaf(localBranchesNode) && searchModel.isLeaf(remoteBranchesNode)
override fun getNodeClass() = BranchTreeNode::class.java
override fun createNode(nodeDescriptor: BranchNodeDescriptor) =
when (nodeDescriptor.type) {
NodeType.LOCAL_ROOT -> localBranchesNode
NodeType.REMOTE_ROOT -> remoteBranchesNode
NodeType.HEAD_NODE -> headBranchesNode
else -> BranchTreeNode(nodeDescriptor)
}
override fun getChildren(nodeDescriptor: BranchNodeDescriptor) =
when (nodeDescriptor.type) {
NodeType.ROOT -> getRootNodeDescriptors()
NodeType.LOCAL_ROOT -> localBranchesNode.getNodeDescriptor().getDirectChildren()
NodeType.REMOTE_ROOT -> remoteBranchesNode.getNodeDescriptor().getDirectChildren()
NodeType.GROUP_NODE -> nodeDescriptor.getDirectChildren()
NodeType.GROUP_REPOSITORY_NODE -> nodeDescriptor.getDirectChildren()
else -> emptyList() //leaf branch node
}
private fun BranchNodeDescriptor.getDirectChildren() = nodeDescriptorsModel.getChildrenForParent(this)
fun update(initial: Boolean) {
val branchesReloaded = uiController.reloadBranches()
runPreservingTreeState(initial) {
searchModel.updateStructure()
}
if (branchesReloaded) {
tree.revalidate()
tree.repaint()
}
}
private fun runPreservingTreeState(loadSaved: Boolean, runnable: () -> Unit) {
val treeState = if (loadSaved) treeStateHolder.treeState else TreeState.createOn(tree, root)
runnable()
if (treeState != null) {
treeState.applyTo(tree)
}
else {
// expanding lots of nodes is a slow operation (and result is not very useful)
if (TreeUtil.hasManyNodes(tree, 30000)) {
TreeUtil.collapseAll(tree, 1)
}
else {
TreeUtil.expandAll(tree)
}
}
}
fun refreshTree() {
runPreservingTreeState(false) {
tree.selectionModel.clearSelection()
refreshNodeDescriptorsModel()
searchModel.updateStructure()
}
}
fun refreshNodeDescriptorsModel() {
with(uiController) {
nodeDescriptorsModel.clear()
localNodeExist = localBranches.isNotEmpty()
remoteNodeExist = remoteBranches.isNotEmpty()
nodeDescriptorsModel.populateFrom((localBranches.asSequence() + remoteBranches.asSequence()).filter(branchFilter), groupingConfig)
}
}
override fun getText(nodeDescriptor: BranchNodeDescriptor?) = nodeDescriptor?.branchInfo?.branchName ?: nodeDescriptor?.displayName
private fun getRootNodeDescriptors() =
mutableListOf<BranchNodeDescriptor>().apply {
if (localNodeExist || remoteNodeExist) add(headBranchesNode.getNodeDescriptor())
if (localNodeExist) add(localBranchesNode.getNodeDescriptor())
if (remoteNodeExist) add(remoteBranchesNode.getNodeDescriptor())
}
}
private val BRANCH_TREE_TRANSFER_HANDLER = object : TransferHandler() {
override fun createTransferable(tree: JComponent): Transferable? {
if (tree is BranchesTreeComponent) {
val branches = tree.getSelectedBranches()
if (branches.isEmpty()) return null
return object : TransferableList<BranchInfo>(branches.toList()) {
override fun toString(branch: BranchInfo) = branch.toString()
}
}
return null
}
override fun getSourceActions(c: JComponent) = COPY_OR_MOVE
}
@State(name = "BranchesTreeState", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)], reportStatistic = false)
@Service(Service.Level.PROJECT)
internal class BranchesTreeStateHolder : PersistentStateComponent<TreeState> {
private lateinit var _treeState: TreeState
val treeState get() = if (::_treeState.isInitialized) _treeState else null
override fun getState(): TreeState? {
if (::_treeState.isInitialized) {
return _treeState
}
return null
}
override fun loadState(state: TreeState) {
_treeState = state
}
fun storeState(branchesTree: FilteringBranchesTree) {
_treeState = TreeState.createOn(branchesTree.tree, branchesTree.root)
}
}
| apache-2.0 | 82f7111add566640b940a1da89b5eeb2 | 37.72837 | 140 | 0.724958 | 5.251842 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/ScriptingSupportChecker.kt | 2 | 3906 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.script.configuration
import com.intellij.ide.BrowserUtil
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.KOTLIN_AWARE_SOURCE_ROOT_TYPES
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.kotlin.scripting.definitions.isNonScript
import java.util.function.Function
import javax.swing.JComponent
class ScriptingSupportChecker: EditorNotificationProvider {
override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> {
if (!Registry.`is`("kotlin.scripting.support.warning") || file.isNonScript() || ScratchUtil.isScratch(file)) {
return EditorNotificationProvider.CONST_NULL
}
// warning panel is hidden
if (file.scriptingSupportLimitationWarning == true) {
return EditorNotificationProvider.CONST_NULL
}
// if script file is under source root
val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex
if (projectFileIndex.isUnderSourceRootOfType(file, KOTLIN_AWARE_SOURCE_ROOT_TYPES)) {
return Function {
EditorNotificationPanel(it).apply {
text = KotlinBundle.message("kotlin.script.in.project.sources")
createActionLabel(
KotlinBundle.message("kotlin.script.warning.more.info"),
Runnable {
BrowserUtil.browse(KotlinBundle.message("kotlin.script.in.project.sources.link"))
},
false
)
addHideAction(file, project)
}
}
}
if (!file.supportedScriptExtensions()) {
return Function {
EditorNotificationPanel(it).apply {
text = KotlinBundle.message("kotlin.script.in.beta.stage")
createActionLabel(
KotlinBundle.message("kotlin.script.warning.more.info"),
Runnable {
BrowserUtil.browse(KotlinBundle.message("kotlin.script.in.beta.stage.link"))
},
false
)
addHideAction(file, project)
}
}
}
return EditorNotificationProvider.CONST_NULL
}
}
private fun EditorNotificationPanel.addHideAction(
file: VirtualFile,
project: Project
) {
createActionLabel(
KotlinBundle.message("kotlin.script.in.project.sources.hide"),
Runnable {
file.scriptingSupportLimitationWarning = true
val fileEditorManager = FileEditorManager.getInstance(project)
fileEditorManager.getSelectedEditor(file)?.let { editor ->
fileEditorManager.removeTopComponent(editor, this)
}
},
false
)
}
private fun VirtualFile.supportedScriptExtensions() =
name.endsWith(".main.kts") || name.endsWith(".space.kts") || name.endsWith(".gradle.kts")
private var VirtualFile.scriptingSupportLimitationWarning: Boolean? by UserDataProperty(Key.create("SCRIPTING_SUPPORT_LIMITATION")) | apache-2.0 | 184b8cbb0fb88a2881846c1093524f4e | 41.010753 | 131 | 0.66001 | 5.187251 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/completion/tests/testData/smart/propertyDelegate/ExtensionVar.kt | 13 | 1146 | import kotlin.reflect.KProperty
class X1 {
operator fun getValue(thisRef: C, property: KProperty<*>): String = ""
operator fun setValue(thisRef: C, property: KProperty<*>, value: String) {}
}
class X2 {
operator fun getValue(thisRef: C, property: KProperty<*>): String = ""
}
class X3 {
operator fun getValue(thisRef: C, property: KProperty<*>): String = ""
operator fun setValue(thisRef: String, property: KProperty<*>, value: String) {}
}
class X4 {
operator fun getValue(thisRef: C, property: KProperty<*>): String = ""
operator fun setValue(thisRef: C, property: KProperty<*>, value: CharSequence) {}
}
class X5 {
operator fun getValue(thisRef: C, property: KProperty<*>): CharSequence = ""
operator fun setValue(thisRef: C, property: KProperty<*>, value: String) {}
}
fun createX1() = X1()
fun createX2() = X2()
fun createX3() = X3()
fun createX4() = X4()
fun createX5() = X5()
class C
var C.property by <caret>
// ABSENT: lazy
// EXIST: createX1
// ABSENT: createX2
// ABSENT: createX3
// EXIST: createX4
// ABSENT: createX5
// EXIST: X1
// ABSENT: X2
// ABSENT: X3
// EXIST: X4
// ABSENT: X5
| apache-2.0 | d8552e89b7a817fc3b140ac70725a32e | 22.387755 | 85 | 0.659686 | 3.400593 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/androidTest/java/androidx/graphics/lowlatency/Rectangle.kt | 3 | 5572 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.graphics.lowlatency
import android.graphics.Color
import android.opengl.GLES20
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.ShortBuffer
class Rectangle {
private val mVertexBuffer: FloatBuffer
private val mDrawListBuffer: ShortBuffer
private val mProgram: Int
private var mPositionHandle = 0
private var mColorHandle = 0
private var mMVPMatrixHandle = 0
private var mColor = floatArrayOf(1f, 0f, 0f, 1f)
private var mSquareCoords = FloatArray(12)
/**
* Sets up the drawing object data for use in an OpenGL ES context.
*/
init {
// initialize vertex byte buffer for shape coordinates
val bb = ByteBuffer.allocateDirect( // (# of coordinate values * 4 bytes per float)
mSquareCoords.size * 4
)
bb.order(ByteOrder.nativeOrder())
mVertexBuffer = bb.asFloatBuffer()
mVertexBuffer.put(mSquareCoords)
mVertexBuffer.position(0)
// initialize byte buffer for the draw list
val dlb = ByteBuffer.allocateDirect( // (# of coordinate values * 2 bytes per short)
DRAW_ORDER.size * 2
)
dlb.order(ByteOrder.nativeOrder())
mDrawListBuffer = dlb.asShortBuffer()
mDrawListBuffer.put(DRAW_ORDER)
mDrawListBuffer.position(0)
// prepare shaders and OpenGL program
val vertexShader = loadShader(
GLES20.GL_VERTEX_SHADER,
vertexShaderCode
)
val fragmentShader = loadShader(
GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode
)
mProgram = GLES20.glCreateProgram() // create empty OpenGL Program
GLES20.glAttachShader(mProgram, vertexShader) // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader) // add the fragment shader to program
GLES20.glLinkProgram(mProgram) // create OpenGL program executables
}
fun draw(
mvpMatrix: FloatArray?,
color: Int,
left: Float,
top: Float,
right: Float,
bottom: Float
) {
mColor[0] = Color.red(color) / 255f
mColor[1] = Color.green(color) / 255f
mColor[2] = Color.blue(color) / 255f
mColor[3] = Color.alpha(color) / 255f
// top left
mSquareCoords[0] = left
mSquareCoords[1] = top
mSquareCoords[2] = 0f
// bottom left
mSquareCoords[3] = left
mSquareCoords[4] = bottom
mSquareCoords[5] = 0f
// bottom right
mSquareCoords[6] = right
mSquareCoords[7] = bottom
mSquareCoords[8] = 0f
// top right
mSquareCoords[9] = right
mSquareCoords[10] = top
mSquareCoords[11] = 0f
mVertexBuffer.clear()
mVertexBuffer.put(mSquareCoords)
mVertexBuffer.position(0)
GLES20.glUseProgram(mProgram)
// get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition")
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle)
// Prepare the triangle coordinate data
// 4 bytes per vertex
val vertexStride = COORDS_PER_VERTEX * 4
GLES20.glVertexAttribPointer(
mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, mVertexBuffer
)
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor")
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, mColor, 0)
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix")
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0)
// Draw the square
GLES20.glDrawElements(
GLES20.GL_TRIANGLES, DRAW_ORDER.size,
GLES20.GL_UNSIGNED_SHORT, mDrawListBuffer
)
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle)
}
companion object {
private val vertexShaderCode =
"""
uniform mat4 uMVPMatrix;
attribute vec4 vPosition;
void main() {
gl_Position = uMVPMatrix * vPosition;
}
"""
private val fragmentShaderCode =
"""
precision mediump float;
uniform vec4 vColor;
void main() {
gl_FragColor = vColor;
}
"""
// number of coordinates per vertex in this array
val COORDS_PER_VERTEX = 3
val DRAW_ORDER = shortArrayOf(0, 1, 2, 0, 2, 3) // order to draw vertices
}
} | apache-2.0 | aa365daf8ba05cadd2b414651ed17074 | 34.272152 | 93 | 0.628141 | 4.544861 | false | false | false | false |
androidx/androidx | compose/ui/ui-unit/src/commonMain/kotlin/androidx/compose/ui/unit/Density.kt | 3 | 4289 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.unit
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import kotlin.math.roundToInt
import androidx.compose.ui.unit.internal.JvmDefaultWithCompatibility
/**
* A density of the screen. Used for convert [Dp] to pixels.
*
* @param density The logical density of the display. This is a scaling factor for the [Dp] unit.
* @param fontScale Current user preference for the scaling factor for fonts.
*/
@Stable
fun Density(density: Float, fontScale: Float = 1f): Density =
DensityImpl(density, fontScale)
private data class DensityImpl(
override val density: Float,
override val fontScale: Float
) : Density
/**
* A density of the screen. Used for the conversions between pixels, [Dp], [Int] and [TextUnit].
*
* @sample androidx.compose.ui.unit.samples.WithDensitySample
*/
@Immutable
@JvmDefaultWithCompatibility
interface Density {
/**
* The logical density of the display. This is a scaling factor for the [Dp] unit.
*/
@Stable
val density: Float
/**
* Current user preference for the scaling factor for fonts.
*/
@Stable
val fontScale: Float
/**
* Convert [Dp] to pixels. Pixels are used to paint to Canvas.
*/
@Stable
fun Dp.toPx(): Float = value * density
/**
* Convert [Dp] to [Int] by rounding
*/
@Stable
fun Dp.roundToPx(): Int {
val px = toPx()
return if (px.isInfinite()) Constraints.Infinity else px.roundToInt()
}
/**
* Convert [Dp] to Sp. Sp is used for font size, etc.
*/
@Stable
fun Dp.toSp(): TextUnit = (value / fontScale).sp
/**
* Convert Sp to pixels. Pixels are used to paint to Canvas.
* @throws IllegalStateException if TextUnit other than SP unit is specified.
*/
@Stable
fun TextUnit.toPx(): Float {
check(type == TextUnitType.Sp) { "Only Sp can convert to Px" }
return value * fontScale * density
}
/**
* Convert Sp to [Int] by rounding
*/
@Stable
fun TextUnit.roundToPx(): Int = toPx().roundToInt()
/**
* Convert Sp to [Dp].
* @throws IllegalStateException if TextUnit other than SP unit is specified.
*/
@Stable
fun TextUnit.toDp(): Dp {
check(type == TextUnitType.Sp) { "Only Sp can convert to Px" }
return Dp(value * fontScale)
}
/**
* Convert an [Int] pixel value to [Dp].
*/
@Stable
fun Int.toDp(): Dp = (this / density).dp
/**
* Convert an [Int] pixel value to Sp.
*/
@Stable
fun Int.toSp(): TextUnit = (this / (fontScale * density)).sp
/** Convert a [Float] pixel value to a Dp */
@Stable
fun Float.toDp(): Dp = (this / density).dp
/** Convert a [Float] pixel value to a Sp */
@Stable
fun Float.toSp(): TextUnit = (this / (fontScale * density)).sp
/**
* Convert a [DpRect] to a [Rect].
*/
@Stable
fun DpRect.toRect(): Rect {
return Rect(
left.toPx(),
top.toPx(),
right.toPx(),
bottom.toPx()
)
}
/**
* Convert a [DpSize] to a [Size].
*/
@Stable
fun DpSize.toSize(): Size = if (isSpecified) {
Size(width.toPx(), height.toPx())
} else {
Size.Unspecified
}
/**
* Convert a [Size] to a [DpSize].
*/
@Stable
fun Size.toDpSize(): DpSize = if (isSpecified) {
DpSize(width.toDp(), height.toDp())
} else {
DpSize.Unspecified
}
}
| apache-2.0 | bc27803c7d6209ee4501eaefd68b9729 | 25.475309 | 97 | 0.624621 | 4.065403 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/LoginSessionInfoModelMapper.kt | 1 | 866 | package com.sedsoftware.yaptalker.presentation.mapper
import com.sedsoftware.yaptalker.data.extensions.getLastDigits
import com.sedsoftware.yaptalker.domain.entity.base.LoginSessionInfo
import com.sedsoftware.yaptalker.presentation.model.base.LoginSessionInfoModel
import io.reactivex.functions.Function
import javax.inject.Inject
class LoginSessionInfoModelMapper @Inject constructor() : Function<LoginSessionInfo, LoginSessionInfoModel> {
override fun apply(info: LoginSessionInfo): LoginSessionInfoModel =
LoginSessionInfoModel(
nickname = info.nickname,
userId = if (info.profileLink.isEmpty()) 0 else info.profileLink.getLastDigits(),
title = info.title,
uq = info.uq,
avatar = info.avatar,
mailCounter = info.mailCounter,
sessionId = info.sessionId
)
}
| apache-2.0 | 38db60065a3b4fbedd8d6085422b6897 | 40.238095 | 109 | 0.732102 | 4.655914 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt | 3 | 9420 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import java.util.*
open class ChangeVariableTypeFix(element: KtCallableDeclaration, type: KotlinType) : KotlinQuickFixAction<KtCallableDeclaration>(element) {
private val typeContainsError = ErrorUtils.containsErrorType(type)
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type)
private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type)
open fun variablePresentation(): String? {
val element = element!!
val name = element.name
return if (name != null) {
val container = element.unsafeResolveToDescriptor().containingDeclaration as? ClassDescriptor
val containerName = container?.name?.takeUnless { it.isSpecial }?.asString()
if (containerName != null) "'$containerName.$name'" else "'$name'"
} else {
null
}
}
override fun getText(): String {
if (element == null) return ""
val variablePresentation = variablePresentation()
return if (variablePresentation != null) {
KotlinBundle.message("change.type.of.0.to.1", variablePresentation, typePresentation)
} else {
KotlinBundle.message("change.type.to.0", typePresentation)
}
}
class OnType(element: KtCallableDeclaration, type: KotlinType) : ChangeVariableTypeFix(element, type), HighPriorityAction {
override fun variablePresentation() = null
}
class ForOverridden(element: KtVariableDeclaration, type: KotlinType) : ChangeVariableTypeFix(element, type) {
override fun variablePresentation(): String? {
val presentation = super.variablePresentation() ?: return null
return KotlinBundle.message("base.property.0", presentation)
}
}
override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = !typeContainsError
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(file)
assert(element.nameIdentifier != null) { "ChangeVariableTypeFix applied to variable without name" }
val replacingTypeReference = psiFactory.createType(typeSourceCode)
val toShorten = ArrayList<KtTypeReference>()
toShorten.add(element.setTypeReference(replacingTypeReference)!!)
if (element is KtProperty) {
val getterReturnTypeRef = element.getter?.returnTypeReference
if (getterReturnTypeRef != null) {
toShorten.add(getterReturnTypeRef.replace(replacingTypeReference) as KtTypeReference)
}
val setterParameterTypeRef = element.setter?.parameter?.typeReference
if (setterParameterTypeRef != null) {
toShorten.add(setterParameterTypeRef.replace(replacingTypeReference) as KtTypeReference)
}
}
ShortenReferences.DEFAULT.process(toShorten)
}
object ComponentFunctionReturnTypeMismatchFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val entry = ChangeCallableReturnTypeFix.getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic)
val context = entry.analyze()
val resolvedCall = context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry) ?: return null
if (DescriptorToSourceUtils.descriptorToDeclaration(resolvedCall.candidateDescriptor) == null) return null
val expectedType = resolvedCall.candidateDescriptor.returnType ?: return null
return ChangeVariableTypeFix(entry, expectedType)
}
}
object PropertyOrReturnTypeMismatchOnOverrideFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val actions = LinkedList<IntentionAction>()
val element = diagnostic.psiElement as? KtCallableDeclaration
if (element !is KtProperty && element !is KtParameter) return actions
val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? PropertyDescriptor ?: return actions
var lowerBoundOfOverriddenPropertiesTypes = QuickFixBranchUtil.findLowerBoundOfOverriddenCallablesReturnTypes(descriptor)
val propertyType = descriptor.returnType ?: error("Property type cannot be null if it mismatches something")
val overriddenMismatchingProperties = LinkedList<PropertyDescriptor>()
var canChangeOverriddenPropertyType = true
for (overriddenProperty in descriptor.overriddenDescriptors) {
val overriddenPropertyType = overriddenProperty.returnType
if (overriddenPropertyType != null) {
if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(propertyType, overriddenPropertyType)) {
overriddenMismatchingProperties.add(overriddenProperty)
} else if (overriddenProperty.isVar && !KotlinTypeChecker.DEFAULT.equalTypes(
overriddenPropertyType,
propertyType
)
) {
canChangeOverriddenPropertyType = false
}
if (overriddenProperty.isVar && lowerBoundOfOverriddenPropertiesTypes != null &&
!KotlinTypeChecker.DEFAULT.equalTypes(lowerBoundOfOverriddenPropertiesTypes, overriddenPropertyType)
) {
lowerBoundOfOverriddenPropertiesTypes = null
}
}
}
if (lowerBoundOfOverriddenPropertiesTypes != null) {
actions.add(OnType(element, lowerBoundOfOverriddenPropertiesTypes))
}
if (overriddenMismatchingProperties.size == 1 && canChangeOverriddenPropertyType) {
val overriddenProperty = DescriptorToSourceUtils.descriptorToDeclaration(overriddenMismatchingProperties.single())
if (overriddenProperty is KtProperty) {
actions.add(ForOverridden(overriddenProperty, propertyType))
}
}
return actions
}
}
object VariableInitializedWithNullFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val binaryExpression = diagnostic.psiElement.getStrictParentOfType<KtBinaryExpression>() ?: return null
val left = binaryExpression.left ?: return null
if (binaryExpression.operationToken != KtTokens.EQ) return null
val property = left.mainReference?.resolve() as? KtProperty ?: return null
if (!property.isVar || property.typeReference != null || !property.initializer.isNullExpression()) return null
val actualType = when (diagnostic.factory) {
Errors.TYPE_MISMATCH -> Errors.TYPE_MISMATCH.cast(diagnostic).b
Errors.TYPE_MISMATCH_WARNING -> Errors.TYPE_MISMATCH_WARNING.cast(diagnostic).b
ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS ->
ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS.cast(diagnostic).b
else -> null
} ?: return null
return ChangeVariableTypeFix(property, actualType.makeNullable())
}
}
}
| apache-2.0 | b0b5f19a4453450da523dd6258c7ae4a | 51.333333 | 158 | 0.708705 | 5.789797 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/injection/aliases/CodeFenceLanguageGuesser.kt | 5 | 3174 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.intellij.plugins.markdown.injection.aliases
import com.intellij.lang.Language
import com.intellij.lang.LanguageUtil
import com.intellij.lexer.EmbeddedTokenTypesProvider
import org.intellij.plugins.markdown.injection.CodeFenceLanguageProvider
import org.jetbrains.annotations.ApiStatus
/**
* Service capable of guessing IntelliJ Language from info string.
*
* It would perform search by aliases, by ids and in [EmbeddedTokenTypesProvider]
* case-insensitively
*/
@ApiStatus.Internal
object CodeFenceLanguageGuesser {
val customProviders: List<CodeFenceLanguageProvider>
get() = CodeFenceLanguageProvider.EP_NAME.extensionList
/**
* Guess IntelliJ Language from Markdown info-string.
* It may either be lower-cased id or some of the aliases.
*
* Language is guaranteed to be safely injectable
*
* @return IntelliJ Language if it was found
*/
@JvmStatic
fun guessLanguageForInjection(value: String): Language? {
return guessLanguage(value)?.takeIf { LanguageUtil.isInjectableLanguage(it) }
}
private fun findLanguage(
value: String,
registeredLanguages: Collection<Language>,
embeddedTokenTypesProviders: Sequence<EmbeddedTokenTypesProvider>
): Language? {
val entry = CodeFenceLanguageAliases.findRegisteredEntry(value) ?: value
val registered = registeredLanguages.find { it.id.equals(entry, ignoreCase = true) }
if (registered != null) {
return registered
}
val providers = embeddedTokenTypesProviders.filter { it.name.equals(entry, ignoreCase = true) }
return providers.map { it.elementType.language }.firstOrNull()
}
private fun findLanguage(value: String): Language? {
val registeredLanguages = Language.getRegisteredLanguages()
val embeddedTokenTypesProviders = EmbeddedTokenTypesProvider.getProviders().asSequence()
val exactMatch = findLanguage(value, registeredLanguages, embeddedTokenTypesProviders)
if (exactMatch != null) {
return exactMatch
}
var index = value.lastIndexOf(' ')
while (index != -1) {
val nameWithoutCustomizations = value.substring(0, index)
val language = findLanguage(nameWithoutCustomizations, registeredLanguages, embeddedTokenTypesProviders)
if (language != null) {
return language
}
index = value.lastIndexOf(' ', startIndex = (index - 1).coerceAtLeast(0))
}
return null
}
/**
* Guess IntelliJ Language from Markdown info-string.
* It may either be lower-cased id or some of the aliases.
*
* Note, that returned language can be non-injectable.
* Consider using [guessLanguageForInjection]
*
* @return IntelliJ Language if it was found
*/
@JvmStatic
private fun guessLanguage(value: String): Language? {
// Custom providers should handle customizations by themselves
for (provider in customProviders) {
val lang = provider.getLanguageByInfoString(value)
if (lang != null) {
return lang
}
}
val name = value.lowercase()
return findLanguage(name)
}
}
| apache-2.0 | e47aaeab8f52cf98953d4688819e2e1b | 35.068182 | 120 | 0.730624 | 4.560345 | false | false | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/test/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereStateFeaturesProviderTest.kt | 8 | 2754 | package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereStateFeaturesProvider.Companion.QUERY_CONTAINS_PATH_DATA_KEY
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.testFramework.fixtures.BasePlatformTestCase
class SearchEverywhereStateFeaturesProviderTest : BasePlatformTestCase() {
private val featuresProvider = SearchEverywhereStateFeaturesProvider()
fun `test contains path feature exists in all tab`() {
val features = featuresProvider.getSearchStateFeatures(SearchEverywhereManagerImpl.ALL_CONTRIBUTORS_GROUP_ID, "foo")
assertNotNull(findFeature(QUERY_CONTAINS_PATH_DATA_KEY, features))
}
fun `test contains path feature exists in files tab`() {
val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "foo")
assertNotNull(findFeature(QUERY_CONTAINS_PATH_DATA_KEY, features))
}
fun `test contains path feature is false when no path specified`() {
val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "foo")
val containsPath = findBooleanFeature(QUERY_CONTAINS_PATH_DATA_KEY, features)
assertFalse(containsPath)
}
fun `test contains path feature is false when nothing before slash`() {
val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "/foo")
val containsPath = findBooleanFeature(QUERY_CONTAINS_PATH_DATA_KEY, features)
assertFalse(containsPath)
}
fun `test contains path feature is true with one slash`() {
val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "bar/foo")
val containsPath = findBooleanFeature(QUERY_CONTAINS_PATH_DATA_KEY, features)
assertTrue(containsPath)
}
fun `test contains path feature is true with multiple slashes`() {
val features = featuresProvider.getSearchStateFeatures(FileSearchEverywhereContributor::class.java.simpleName, "/x/bar/foo")
val containsPath = findBooleanFeature(QUERY_CONTAINS_PATH_DATA_KEY, features)
assertTrue(containsPath)
}
private fun findFeature(field: EventField<*>, features: List<EventPair<*>>): EventPair<*>? =
features.find { field.name == it.field.name }
private fun findBooleanFeature(field: EventField<*>, features: List<EventPair<*>>): Boolean=
findFeature(field, features)!!.data as Boolean
} | apache-2.0 | 2d8eba27a1635546f85afe42c043d3aa | 48.196429 | 137 | 0.796296 | 4.683673 | false | true | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowToolbar.kt | 3 | 4881 | // 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.actionSystem.ActionPlaces.TOOLWINDOW_TOOLBAR_BAR
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.wm.ToolWindow
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.ui.ComponentUtil
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Point
import java.awt.Rectangle
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.border.Border
internal abstract class ToolWindowToolbar : JPanel() {
lateinit var defaults: List<String>
abstract val bottomStripe: StripeV2
abstract val topStripe: StripeV2
protected fun init() {
layout = BorderLayout()
isOpaque = true
background = JBUI.CurrentTheme.ToolWindow.background()
val topWrapper = JPanel(BorderLayout())
border = createBorder()
topStripe.background = JBUI.CurrentTheme.ToolWindow.background()
bottomStripe.background = JBUI.CurrentTheme.ToolWindow.background()
topWrapper.background = JBUI.CurrentTheme.ToolWindow.background()
topWrapper.add(topStripe, BorderLayout.NORTH)
add(topWrapper, BorderLayout.NORTH)
add(bottomStripe, BorderLayout.SOUTH)
}
open fun createBorder():Border = JBUI.Borders.empty()
open fun getBorderColor(): Color? = JBUI.CurrentTheme.ToolWindow.borderColor()
abstract fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe
fun getButtonFor(toolWindowId: String): StripeButtonManager? {
return topStripe.getButtons().find { it.id == toolWindowId } ?: bottomStripe.getButtons().find { it.id == toolWindowId }
}
open fun getStripeFor(screenPoint: Point): AbstractDroppableStripe? {
if (!isShowing) {
return null
}
val topRect = Rectangle(locationOnScreen, size).also {
it.width = it.width.coerceAtLeast(SHADOW_WIDTH)
it.height = (it.height / 2).coerceAtLeast(SHADOW_WIDTH)
}
val bottomRect = Rectangle(topRect).also {
it.y += topRect.height
}
return if (topRect.contains(screenPoint)) {
topStripe
}
else if (bottomRect.contains(screenPoint)) {
bottomStripe
}
else {
null
}
}
fun removeStripeButton(toolWindow: ToolWindow, anchor: ToolWindowAnchor) {
remove(getStripeFor(anchor), toolWindow)
}
fun hasButtons() = topStripe.getButtons().isNotEmpty() || bottomStripe.getButtons().isNotEmpty()
fun reset() {
topStripe.reset()
bottomStripe.reset()
}
fun startDrag() {
revalidate()
repaint()
}
fun stopDrag() = startDrag()
fun tryDroppingOnGap(data: LayoutData, gap: Int, dropRectangle: Rectangle, doLayout: () -> Unit) {
val sideDistance = data.eachY + gap - dropRectangle.y + dropRectangle.height
if (sideDistance > 0) {
data.dragInsertPosition = -1
data.dragToSide = false
data.dragTargetChosen = true
doLayout()
}
}
companion object {
val SHADOW_WIDTH = JBUI.scale(40)
fun updateButtons(panel: JComponent) {
ComponentUtil.findComponentsOfType(panel, SquareStripeButton::class.java).forEach { it.update() }
panel.revalidate()
panel.repaint()
}
fun remove(panel: AbstractDroppableStripe, toolWindow: ToolWindow) {
val component = panel.components.firstOrNull { it is SquareStripeButton && it.toolWindow.id == toolWindow.id } ?: return
panel.remove(component)
panel.revalidate()
panel.repaint()
}
}
open class ToolwindowActionToolbar(val panel: JComponent) : ActionToolbarImpl(TOOLWINDOW_TOOLBAR_BAR, DefaultActionGroup(), false) {
override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) = updateButtons(panel)
}
internal class StripeV2(private val toolBar: ToolWindowToolbar,
paneId: String,
override val anchor: ToolWindowAnchor,
override val split: Boolean = false) : AbstractDroppableStripe(paneId, VerticalFlowLayout(0, 0)) {
override val isNewStripes: Boolean
get() = true
override fun getButtonFor(toolWindowId: String) = toolBar.getButtonFor(toolWindowId)
override fun tryDroppingOnGap(data: LayoutData, gap: Int, insertOrder: Int) {
toolBar.tryDroppingOnGap(data, gap, dropRectangle) {
layoutDragButton(data, gap)
}
}
override fun toString() = "StripeNewUi(anchor=$anchor)"
}
} | apache-2.0 | 5ff70819275c2ad2f5e493e81a5a7103 | 32.902778 | 134 | 0.723622 | 4.365832 | false | false | false | false |
hugh114/HPaste | app/src/main/java/com/hugh/paste/app/BaseActivity.kt | 1 | 2325 | package com.hugh.paste.app
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
/**
* Created by hugh on 2017/9/29.
*/
open class BaseActivity: AppCompatActivity() {
/** activity是否已销毁 */
private var isDestroy = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activities.add(this)
}
override fun onStart() {
super.onStart()
foregroundCount++
}
override fun onStop() {
super.onStop()
foregroundCount--
}
override fun onDestroy() {
super.onDestroy()
activities.remove(this)
}
/** activity是否已销毁 */
open fun isDestroy():Boolean {
return isDestroy
}
companion object {
private var msgBase = 100
private val activities = mutableListOf<Activity>()
private var foregroundCount = 0
/** 仅供获取handler msg id */
fun getMsgId(): Int {
return msgBase++
}
fun isForeground(): Boolean {
return foregroundCount > 0
}
/**
* 获取栈顶activity
*
* @return
*/
fun getTopActivity(): Activity? {
return if (!activities.isEmpty()) activities.last() else null
}
/**
* 关闭指定的activity
*
* @param actClass
*/
fun finishActivity(actClass: Class<*>) {
activities.forEach {
if (it.javaClass == actClass) {
it.finish()
}
}
}
/**
* 关闭所有activity
*/
fun finishAllActivity() {
activities.forEach {
it.finish()
}
}
/**
* 关闭某个activity之前的所有activity
*
* @param actClass
*/
fun finishToActivity(actClass: Class<*>) {
for (i in activities.size - 1 downTo 0) {
val activity = activities[i]
if (activity.javaClass != actClass && !activity.isFinishing) {
activity.finish()
} else {
break
}
}
}
}
} | gpl-3.0 | d626d470a82a90475e082c5b4f066b06 | 21.316832 | 78 | 0.495783 | 4.897826 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/editorActions/rotateSelection/RotateSelectionsHandler.kt | 1 | 1649 | // 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.codeInsight.editorActions.rotateSelection
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler
class RotateSelectionsHandler(private val isBackwards: Boolean) : EditorWriteActionHandler() {
override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) {
if (editor.caretModel.caretCount <= 1) return
val carets = editor.caretModel.allCarets
.sortedByDescending { it.selectionRange.endOffset }
val textToReplace = carets
.map { editor.document.getText(it.selectionRange) }
.rotateElements(!isBackwards) // isBackwards is inversed because carets are in the reverse order (sorted by descending offset)
assert(carets.size == textToReplace.size)
for ((i, caret) in carets.withIndex()) {
val selection = caret.selectionRange
val newText = textToReplace[i]
editor.document.replaceString(selection.startOffset, selection.endOffset, newText)
caret.setSelection(selection.startOffset, selection.startOffset + newText.length)
caret.moveToOffset(caret.selectionEnd)
}
}
private fun <T> List<T>.rotateElements(isBackwards: Boolean): List<T> {
if (this.size <= 1) return this.toList()
return if (isBackwards) {
this.subList(1, this.size) + this[0]
} else {
listOf(this[this.size - 1]) + this.subList(0, this.size - 1)
}
}
} | apache-2.0 | 27073c63bd71d3b09910ab9130a58f8a | 42.421053 | 132 | 0.741055 | 4.153652 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitCommitWithStagingAreaAction.kt | 2 | 1454 | // 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 git4idea.index.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.wm.IdeFocusManager
import git4idea.index.GitStageContentProvider
import git4idea.index.isStagingAreaAvailable
import git4idea.index.showStagingArea
class GitCommitWithStagingAreaAction : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isEnabledAndVisible =
isStagingAreaAvailable(project) &&
ChangesViewContentManager.getToolWindowFor(project, GitStageContentProvider.STAGING_AREA_TAB_NAME) != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
showStagingArea(project) { gitStagePanel ->
IdeFocusManager.getInstance(project).requestFocus(gitStagePanel.commitMessage.editorField, false).doWhenDone {
gitStagePanel.commitMessage.editorField.selectAll()
}
}
}
} | apache-2.0 | 439c2dc013ca8e8282e9edf9b78652c9 | 37.289474 | 158 | 0.784044 | 4.736156 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/console/transport/TCumulativeTransport.kt | 17 | 1505 | package com.jetbrains.python.console.transport
import com.intellij.openapi.diagnostic.Logger
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import org.apache.thrift.transport.TTransport
import org.apache.thrift.transport.TTransportException
import java.io.IOException
import java.io.PipedInputStream
import java.io.PipedOutputStream
abstract class TCumulativeTransport : TTransport() {
val outputStream: PipedOutputStream = PipedOutputStream()
private val pipedInputStream: PipedInputStream = PipedInputStream(outputStream)
private val messageBuffer: ByteBuf = Unpooled.buffer()
override fun open() {}
final override fun write(buf: ByteArray, off: Int, len: Int) {
messageBuffer.writeBytes(buf, off, len)
}
final override fun flush() {
val length = messageBuffer.readableBytes()
val content = ByteArray(length)
messageBuffer.readBytes(content)
messageBuffer.clear()
writeMessage(content)
}
abstract fun writeMessage(content: ByteArray)
override fun close() {
LOG.debug("Closing cumulative transport")
outputStream.close()
pipedInputStream.close()
}
@Throws(TTransportException::class)
final override fun read(buf: ByteArray, off: Int, len: Int): Int {
try {
return pipedInputStream.read(buf, off, len)
}
catch (e: IOException) {
throw TTransportException(TTransportException.UNKNOWN, e)
}
}
companion object {
val LOG = Logger.getInstance(TCumulativeTransport::class.java)
}
} | apache-2.0 | cfebd3691b2c4545ca383aa88af05ed9 | 25.892857 | 81 | 0.747508 | 4.239437 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/smart/BooleanOrNullableArgumentExpected.kt | 13 | 492 | fun foo(s: String?, flag: Boolean, x: Int){}
fun foo(xx: Boolean){}
fun bar() {
foo(<caret>)
}
// EXIST: { itemText: "null", attributes: "bold" }
// EXIST: { itemText: "true", attributes: "bold" }
// EXIST: { itemText: "false", attributes: "bold" }
// EXIST: { lookupString: "s = null", itemText: "s = null", attributes: "" }
// EXIST: { lookupString: "xx = true", itemText: "xx = true", attributes: "" }
// EXIST: { lookupString: "xx = false", itemText: "xx = false", attributes: "" }
| apache-2.0 | 2a2de7dedb3ec5e23a38e07b34af3e8b | 36.846154 | 80 | 0.593496 | 3.174194 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/list/TargetPresentationRenderer.kt | 8 | 2644 | // 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.ui.list
import com.intellij.navigation.TargetPresentation
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import java.awt.Component
import java.util.function.Function
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListCellRenderer
import javax.swing.SwingConstants
internal class TargetPresentationRenderer<T>(
private val presentationProvider: Function<in T, out TargetPresentation>,
) : ListCellRenderer<T> {
private val myComponent = JPanel(BorderLayout())
private val myMainRenderer = TargetPresentationMainRenderer(presentationProvider)
private val mySpacerComponent = JPanel().apply {
border = JBUI.Borders.empty(0, 2)
}
private val myLocationComponent = JBLabel().apply {
border = JBUI.Borders.emptyRight(UIUtil.getListCellHPadding())
horizontalTextPosition = SwingConstants.LEFT
horizontalAlignment = SwingConstants.RIGHT // align icon to the right
}
override fun getListCellRendererComponent(list: JList<out T>,
value: T,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
val mainComponent = myMainRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
val presentation = presentationProvider.apply(value)
val locationText = presentation.locationText
if (locationText == null) {
return mainComponent
}
myComponent.removeAll()
val background = mainComponent.background
myComponent.background = background
mySpacerComponent.background = background
myLocationComponent.background = background
myLocationComponent.text = locationText
myLocationComponent.icon = presentation.locationIcon
myLocationComponent.foreground = if (isSelected) UIUtil.getListSelectionForeground(cellHasFocus) else UIUtil.getInactiveTextColor()
myComponent.add(mainComponent, BorderLayout.WEST)
myComponent.add(mySpacerComponent, BorderLayout.CENTER)
myComponent.add(myLocationComponent, BorderLayout.EAST)
myComponent.accessibleContext.accessibleName = listOfNotNull(
mainComponent.accessibleContext?.accessibleName,
myLocationComponent.accessibleContext?.accessibleName
).joinToString(separator = " ")
return myComponent
}
}
| apache-2.0 | 6c30179a5cfd82cb7ba8094f1bc8686c | 39.676923 | 140 | 0.737141 | 5.31992 | false | false | false | false |
s-nagahori/TDD_book | src/main/kotlin/money/Bank.kt | 1 | 807 | package money
import money.Money.Currency
class Bank {
private val rates: MutableMap<Pair<Currency, Currency>, Int> = HashMap()
fun reduce(source: Expression, to: Currency) = when (source) {
is Money -> Money(source.amount / rate(source.currency, to), to)
is Expression.Sum -> Money(sum(source.augend, source.addend, to), to)
}
fun rate(from: Currency, to: Currency) =
if (from == to) 1 else rates[Pair(from, to)]
?: throw IllegalArgumentException("Unregistered rate: $from to $to")
private fun sum(augend: Expression, addend: Expression, to: Currency): Int =
reduce(augend, to).amount + reduce(addend, to).amount
fun addRate(from: Currency, to: Currency, rate: Int) {
rates.put(Pair(from, to), rate)
}
} | mit | d9f6cee219787fd440dd31f98dbb7fc9 | 32.666667 | 88 | 0.633209 | 3.753488 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/breadbox/extensions.kt | 1 | 5746 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 10/30/20.
* Copyright (c) 2020 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.breadbox
import com.breadwallet.crypto.TransferAttribute
import com.breadwallet.crypto.Account
import com.breadwallet.crypto.Address
import com.breadwallet.crypto.Amount
import com.breadwallet.crypto.Currency
import com.breadwallet.crypto.ExportablePaperWallet
import com.breadwallet.crypto.Key
import com.breadwallet.crypto.Network
import com.breadwallet.crypto.NetworkFee
import com.breadwallet.crypto.System
import com.breadwallet.crypto.TransferFeeBasis
import com.breadwallet.crypto.Unit
import com.breadwallet.crypto.Wallet
import com.breadwallet.crypto.WalletManager
import com.breadwallet.crypto.WalletSweeper
import com.breadwallet.crypto.errors.AccountInitializationError
import com.breadwallet.crypto.errors.ExportablePaperWalletError
import com.breadwallet.crypto.errors.FeeEstimationError
import com.breadwallet.crypto.errors.LimitEstimationError
import com.breadwallet.crypto.errors.WalletSweeperError
import com.breadwallet.util.asyncApiCall
import java.math.BigDecimal
import java.math.RoundingMode
/** Returns the [Address] object for [address] from the [Wallet]'s [Network] */
fun Wallet.addressFor(address: String): Address? {
return Address.create(address, walletManager.network).orNull()
}
/**
* By default [WalletManager.getDefaultNetworkFee] is used for the [networkFee].
*/
suspend fun Wallet.estimateFee(
address: Address,
amount: Amount,
networkFee: NetworkFee = walletManager.defaultNetworkFee,
attrs: Set<TransferAttribute> = emptySet()
): TransferFeeBasis = asyncApiCall<TransferFeeBasis, FeeEstimationError> {
estimateFee(address, amount, networkFee, attrs, this)
}
suspend fun WalletManager.createSweeper(wallet: Wallet, key: Key): WalletSweeper =
asyncApiCall<WalletSweeper, WalletSweeperError> { createSweeper(wallet, key, this) }
suspend fun WalletSweeper.estimateFee(networkFee: NetworkFee): TransferFeeBasis =
asyncApiCall<TransferFeeBasis, FeeEstimationError> { estimate(networkFee, this) }
suspend fun System.accountInitialize(
account: Account,
network: Network,
create: Boolean
): ByteArray = asyncApiCall<ByteArray, AccountInitializationError> {
accountInitialize(account, network, create, this)
}
suspend fun Wallet.estimateMaximum(
address: Address,
networkFee: NetworkFee
): Amount = asyncApiCall<Amount, LimitEstimationError> {
estimateLimitMaximum(address, networkFee, this)
}
suspend fun WalletManager.createExportablePaperWallet(): ExportablePaperWallet =
asyncApiCall<ExportablePaperWallet, ExportablePaperWalletError> {
createExportablePaperWallet(this)
}
/** Returns the [Amount] as a [BigDecimal]. */
fun Amount.toBigDecimal(
unit: Unit = this.unit,
roundingMode: RoundingMode = RoundingMode.HALF_EVEN
): BigDecimal {
return BigDecimal(doubleAmount(unit).or(0.0))
.setScale(unit.decimals.toInt(), roundingMode)
}
fun Currency.isNative() = type.equals("native", true)
fun Currency.isErc20() = type.equals("erc20", true)
fun Currency.isEthereum() =
uids.equals("ethereum-mainnet:__native__", true) ||
uids.equals("ethereum-ropsten:__native__", true)
fun Currency.isBitcoin() =
uids.equals("bitcoin-mainnet:__native__", true) ||
uids.equals("bitcoin-testnet:__native__", true)
fun Currency.isBitcoinCash() =
uids.equals("bitcoincash-mainnet:__native__", true) ||
uids.equals("bitcoincash-testnet:__native__", true)
fun Currency.isTezos() = uids.equals("tezos-mainnet:__native__", true)
/** Returns the default [Unit] for the [Wallet]'s [Network]. */
val Wallet.defaultUnit: Unit
get() = walletManager.network.defaultUnitFor(currency).get()
/** Returns the base [Unit] for the [Wallet]'s [Network] */
val Wallet.baseUnit: Unit
get() = walletManager.network.baseUnitFor(currency).get()
fun Wallet.feeForSpeed(speed: TransferSpeed): NetworkFee {
if (currency.isTezos()) {
return checkNotNull(
walletManager.network.fees.minByOrNull {
it.confirmationTimeInMilliseconds.toLong()
}
)
}
val fees = walletManager.network.fees
return when (fees.size) {
1 -> fees.single()
else -> fees
.filter { it.confirmationTimeInMilliseconds.toLong() <= speed.targetTime }
.minByOrNull { fee ->
speed.targetTime - fee.confirmationTimeInMilliseconds.toLong()
}
?: fees.minByOrNull { it.confirmationTimeInMilliseconds }
?: walletManager.defaultNetworkFee
}
}
| mit | 36bb47088af9120eaa85b79483248c80 | 37.824324 | 88 | 0.745562 | 4.160753 | false | false | false | false |
lisawray/groupie | example-viewbinding/src/main/java/com/xwray/groupie/example/viewbinding/item/CarouselItem.kt | 2 | 1647 | package com.xwray.groupie.example.viewbinding.item
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.xwray.groupie.GroupieAdapter
import com.xwray.groupie.Item
import com.xwray.groupie.OnItemClickListener
import com.xwray.groupie.example.viewbinding.R
import com.xwray.groupie.example.viewbinding.databinding.ItemCarouselBinding
import com.xwray.groupie.viewbinding.BindableItem
import com.xwray.groupie.viewbinding.GroupieViewHolder
/**
* A horizontally scrolling RecyclerView, for use in a vertically scrolling RecyclerView.
*/
class CarouselItem(
private val carouselDecoration: ItemDecoration,
private val adapter: GroupieAdapter
) : BindableItem<ItemCarouselBinding>(), OnItemClickListener {
init {
adapter.setOnItemClickListener(this)
}
override fun initializeViewBinding(view: View): ItemCarouselBinding =
ItemCarouselBinding.bind(view)
override fun createViewHolder(itemView: View): GroupieViewHolder<ItemCarouselBinding> =
super.createViewHolder(itemView).also {
it.binding.recyclerView.apply {
addItemDecoration(carouselDecoration)
layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false)
}
}
override fun bind(viewBinding: ItemCarouselBinding, position: Int) {
viewBinding.recyclerView.adapter = adapter
}
override fun getLayout(): Int = R.layout.item_carousel
override fun onItemClick(item: Item<*>, view: View) {
adapter.remove(item)
}
}
| mit | 158805058261245c64990a7490865158 | 34.804348 | 104 | 0.758349 | 4.88724 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/AnnouncementItemFragment.kt | 1 | 5326 | package org.eurofurence.connavigator.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.github.chrisbanes.photoview.PhotoView
import io.reactivex.disposables.Disposables
import org.eurofurence.connavigator.R
import org.eurofurence.connavigator.database.HasDb
import org.eurofurence.connavigator.database.lazyLocateDb
import org.eurofurence.connavigator.services.ImageService
import org.eurofurence.connavigator.util.extensions.fontAwesomeTextView
import org.eurofurence.connavigator.util.extensions.jodatime
import org.eurofurence.connavigator.util.extensions.markdownView
import org.eurofurence.connavigator.util.extensions.photoView
import org.eurofurence.connavigator.util.v2.compatAppearance
import org.eurofurence.connavigator.util.v2.get
import org.eurofurence.connavigator.util.v2.plus
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.toast
import org.joda.time.DateTime
import us.feras.mdv.MarkdownView
import java.util.*
class AnnouncementItemFragment : DisposingFragment(), HasDb, AnkoLogger {
private val args: AnnouncementItemFragmentArgs by navArgs()
private val announcementId by lazy { UUID.fromString(args.announcementId) }
override val db by lazyLocateDb()
val ui = AnnouncementItemUi()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
UI { ui.createView(this) }.view
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
info { "Created announcement view for $announcementId" }
if (announcementId == null) {
toast("No announcement ID was sent!")
findNavController().popBackStack()
}
db.subscribe {
val announcement = it.announcements[announcementId]
if (announcement != null) {
info { "Updating announcement item" }
ui.loadingIndicator.visibility = View.GONE
ui.title.text = announcement.title
ui.text.loadMarkdown(announcement.content)
// Retrieve top image
val image = announcement.let { it[toAnnouncementImage] }
// Set image on top
if (image != null) {
ImageService.load(image, ui.image, true)
} else {
ui.image.visibility = View.GONE
}
ui.warningLayout.visibility = if (DateTime.now().isAfter(announcement.validUntilDateTimeUtc.jodatime()))
View.VISIBLE
else
View.GONE
}
}
.collectOnDestroyView()
}
}
class AnnouncementItemUi : AnkoComponent<Fragment> {
lateinit var title: TextView
lateinit var text: MarkdownView
lateinit var image: PhotoView
lateinit var loadingIndicator: ProgressBar
lateinit var warningLayout: LinearLayout
override fun createView(ui: AnkoContext<Fragment>) = with(ui) {
relativeLayout {
backgroundResource = R.color.backgroundGrey
lparams(matchParent, matchParent)
scrollView {
lparams(matchParent, matchParent)
verticalLayout {
backgroundResource = R.color.lightBackground
isClickable = true
loadingIndicator = progressBar()
linearLayout {
padding = dip(50)
backgroundResource = R.drawable.image_fade
title = textView {
compatAppearance = android.R.style.TextAppearance_DeviceDefault_Large_Inverse
}
}
warningLayout = linearLayout {
padding = dip(20 - 8)
fontAwesomeTextView {
text = "This announcement has expired!"
textAlignment = View.TEXT_ALIGNMENT_CENTER
textAppearance = android.R.style.TextAppearance_DeviceDefault_Medium
}.lparams(matchParent, wrapContent)
}
text = markdownView {
}.lparams(matchParent, wrapContent) {
margin = dip(20 - 8)
}
image = photoView {
backgroundResource = R.color.darkBackground
imageResource = R.drawable.placeholder_event
scaleType = ImageView.ScaleType.FIT_CENTER
adjustViewBounds = true
visibility = View.GONE
}.lparams(matchParent, wrapContent) {
margin = dip(20)
}
}.lparams(matchParent, wrapContent)
}
}
}
} | mit | 60fd7aaabe556fdbbb12267960a75730 | 36.780142 | 120 | 0.619039 | 5.423625 | false | false | false | false |
GoldRenard/JuniperBotJ | modules/jb-module-ranking/src/main/java/ru/juniperbot/module/ranking/commands/LevelCommand.kt | 1 | 4027 | /*
* This file is part of JuniperBot.
*
* JuniperBot 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.
* JuniperBot 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 JuniperBot. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.juniperbot.module.ranking.commands
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import ru.juniperbot.common.model.request.RankingUpdateRequest
import ru.juniperbot.common.service.RankingConfigService
import ru.juniperbot.common.utils.RankingUtils
import ru.juniperbot.common.worker.command.model.BotContext
import ru.juniperbot.common.worker.command.model.DiscordCommand
import ru.juniperbot.common.worker.command.model.MemberReference
import ru.juniperbot.common.worker.command.model.MentionableCommand
import ru.juniperbot.common.worker.modules.moderation.service.ModerationService
import ru.juniperbot.module.ranking.service.RankingService
@DiscordCommand(
key = "discord.command.level.key",
description = "discord.command.level.desc",
group = ["discord.command.group.ranking"],
permissions = [Permission.MESSAGE_WRITE, Permission.MESSAGE_EMBED_LINKS],
priority = 245)
class LevelCommand protected constructor() : MentionableCommand(false, true) {
@Autowired
lateinit var moderationService: ModerationService
@Autowired
lateinit var rankingConfigService: RankingConfigService
@Autowired
lateinit var rankingService: RankingService
override fun doCommand(reference: MemberReference, event: GuildMessageReceivedEvent, context: BotContext, content: String): Boolean {
if (reference.localMember == null) {
showHelp(event, context)
return false
}
if (!StringUtils.isNumeric(content)) {
showHelp(event, context)
return false
}
val level: Int
try {
level = Integer.parseInt(content)
} catch (e: NumberFormatException) {
showHelp(event, context)
return false
}
if (level < 0 || level > RankingUtils.MAX_LEVEL) {
showHelp(event, context)
return false
}
val request = RankingUpdateRequest(reference.localMember).apply { this.level = level }
contextService.queue(event.guild, event.channel.sendTyping()) { _ ->
rankingConfigService.update(request)
if (reference.member != null) {
rankingService.updateRewards(reference.member)
}
messageService.onTempEmbedMessage(event.channel, 10, "discord.command.level.success",
"**${reference.member?.asMention ?: reference.localMember.effectiveName}**", level)
}
return true
}
override fun showHelp(event: GuildMessageReceivedEvent, context: BotContext) {
val command = messageService.getMessageByLocale("discord.command.level.key", context.commandLocale)
messageService.onEmbedMessage(event.channel, "discord.command.level.help",
RankingUtils.MAX_LEVEL, context.config.prefix, command)
}
override fun isAvailable(user: User, member: Member, guild: Guild): Boolean {
return rankingConfigService.isEnabled(guild.idLong) && moderationService.isModerator(member)
}
}
| gpl-3.0 | 3b66bae909138607adb1476e0cf7813a | 40.947917 | 137 | 0.717656 | 4.464523 | false | true | false | false |
chrisdoc/kotlin-koans | src/v_builders/_39_HtmlBuilders.kt | 1 | 1570 | package v_builders
import util.TODO
import util.doc39
import v_builders.data.getProducts
import v_builders.htmlLibrary.*
fun getTitleColor() = "#b9c9fe"
fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"
fun todoTask39(): Nothing = TODO(
"""
Task 39.
1) Fill the table with the proper values from products.
2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
Pass a color as an argument to functions 'tr', 'td'.
You can run the 'Html Demo' configuration in IntelliJ IDEA to see the rendered table.
""",
documentation = doc39()
)
fun renderProductTable(): String {
return html {
table {
tr(getTitleColor()) {
td {
text("Product")
}
td {
text("Price")
}
td {
text("Popularity")
}
}
val products = getProducts()
products.forEachIndexed { index, product ->
tr(getTitleColor()) {
td(getCellColor(index, 0)) {
text(product.description)
}
td(getCellColor(index, 1)) {
text(product.price)
}
td(getCellColor(index, 2)) {
text(product.popularity)
}
}
}
}
}.toString()
}
| mit | d5ab32cf0b3da86da83b7d771e51375b | 29.192308 | 105 | 0.477707 | 4.757576 | false | false | false | false |
thanhtrixx/music-web-spring-boot | src/main/java/tri/le/music/util/TokenUtil.kt | 1 | 350 | @file:JvmName("TokenUtil")
package tri.le.music.util
import org.apache.logging.log4j.LogManager
import java.util.*
/**
* Created by TriLe on 2016-04-22.
*/
private val log = LogManager.getLogger("TokenUtil")
private val TOKEN_SIZE = 36
fun generateToke() = UUID.randomUUID().toString()
fun validate(token: String) = token.length == TOKEN_SIZE
| apache-2.0 | 4599dc8d51bf439a0a17ddc8a19c2a71 | 20.875 | 56 | 0.734286 | 3.301887 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/analysis/impl/ManagementStrategyValidation.kt | 1 | 4444 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.analysis.impl
import com.google.android.libraries.pcc.chronicle.analysis.ManagementStrategyComparator.compare
import com.google.android.libraries.pcc.chronicle.analysis.retentionsAsManagementStrategies
import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider
import com.google.android.libraries.pcc.chronicle.api.DataType
import com.google.android.libraries.pcc.chronicle.api.DeletionTrigger
import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy
import com.google.android.libraries.pcc.chronicle.api.policy.Policy
import com.google.android.libraries.pcc.chronicle.api.policy.PolicyRetention
import com.google.android.libraries.pcc.chronicle.api.policy.PolicyTarget
import com.google.android.libraries.pcc.chronicle.api.policy.builder.PolicyCheck
import com.google.android.libraries.pcc.chronicle.api.policy.builder.deletionTriggers
/**
* Verifies that [ManagementStrategy] values declared by the [ConnectionProviders]
* [ConnectionProvider] are valid given policy-requirements for the receiving [Policy] object.
*
* @return a list of [Checks][PolicyCheck]. If empty, the implication is that policy adherence is
* satisfied. If non-empty, the values will describe how policy is not being met.
*/
internal fun Policy.verifyManagementStrategies(
connectionProviders: Collection<ConnectionProvider>
): List<PolicyCheck> {
val targetsBySchemaName = targets.map(PolicyTarget::schemaName).toSet()
val managedDataTypesBySchemaName =
connectionProviders
.asSequence()
.map { it.dataType }
// Ensure that this managed data type is mentioned by the policy.
.filter { it.descriptor.name in targetsBySchemaName }
.associateBy { it.descriptor.name }
return targets.flatMap { target ->
// If there is no managed data type for the target, it means that the policy contains an extra
// target, which is no problem - skip it.
val dataType = managedDataTypesBySchemaName[target.schemaName] ?: return@flatMap emptyList()
val retentionViolations = target.verifyRetentionSatisfiedBy(dataType)
val deletionViolations = target.verifyDeletionTriggersSatisfiedBy(dataType)
retentionViolations + deletionViolations
}
}
/**
* Verifies that one of the receiving [PolicyTarget]'s [PolicyRetentions][PolicyRetention] and the
* max age are satisfied by the given [strategy]. Returns a list of any failing [Checks]
* [PolicyCheck] (one per unsatisfied [PolicyRetention]) if-and-only-if all retentions fail.
*/
internal fun PolicyTarget.verifyRetentionSatisfiedBy(dataType: DataType): List<PolicyCheck> {
val strategy = dataType.managementStrategy
val failedRetentions = retentionsAsManagementStrategies().filter { compare(strategy, it) > 0 }
if (failedRetentions.size < retentions.size) return emptyList()
return retentions.map {
PolicyCheck("h:${dataType.descriptor.name} is $it with maxAgeMs = $maxAgeMs")
}
}
/**
* Verifies that any deletion triggers required by the receiving [PolicyTarget] are satisfied by the
* given [ManagementStrategy]. Returns any violations as [Checks][PolicyCheck].
*/
internal fun PolicyTarget.verifyDeletionTriggersSatisfiedBy(dataType: DataType): List<PolicyCheck> {
val strategy = dataType.managementStrategy
val missingDeletionTriggers = this.deletionTriggers().filter { !strategy.satisfies(it) }
return missingDeletionTriggers.map { PolicyCheck("h:${dataType.descriptor.name} is $it") }
}
/**
* Returns whether or not the receiving [ManagementStrategy] satisfies the given [DeletionTrigger].
*/
internal fun ManagementStrategy.satisfies(policyDeletionTrigger: DeletionTrigger): Boolean {
return when (this) {
ManagementStrategy.PassThru -> true
is ManagementStrategy.Stored -> this.deletionTriggers.contains(policyDeletionTrigger)
}
}
| apache-2.0 | 01c7646aff1fa55315d2c979c1ac6280 | 45.291667 | 100 | 0.781953 | 4.426295 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/jobs/NetworkJobProcessor.kt | 1 | 8874 | package com.battlelancer.seriesguide.jobs
import android.app.NotificationManager
import android.content.ContentProviderOperation
import android.content.Context
import android.content.OperationApplicationException
import android.text.format.DateUtils
import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.backend.HexagonTools
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.jobs.episodes.JobAction
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Jobs
import com.battlelancer.seriesguide.settings.NotificationSettings
import com.battlelancer.seriesguide.traktapi.TraktCredentials
import com.battlelancer.seriesguide.util.DBUtils
import com.uwetrottmann.androidutils.AndroidUtils
import timber.log.Timber
import java.nio.ByteBuffer
/**
* Gets jobs from the [Jobs] table, executes them one by one starting with the oldest.
* Based on the job result shows an error notification and maybe removes the job.
* If the job isn't removed, will stop processing further jobs. The job will be tried
* again the next time jobs are processed.
*/
class NetworkJobProcessor(private val context: Context) {
private val shouldSendToHexagon = HexagonSettings.isEnabled(context)
private val shouldSendToTrakt = TraktCredentials.get(context).hasCredentials()
fun process() {
// query for jobs
val query = context.contentResolver
.query(Jobs.CONTENT_URI, Jobs.PROJECTION, null, null, Jobs.SORT_OLDEST)
?: return // query failed
// process jobs, starting with oldest
val jobsToRemove: MutableList<Long> = ArrayList()
while (query.moveToNext()) {
val jobId = query.getLong(0)
val typeId = query.getInt(1)
val action = JobAction.fromId(typeId)
if (action != JobAction.UNKNOWN) {
Timber.d("Running job %d %s", jobId, action)
val createdAt = query.getLong(2)
val jobInfoArr = query.getBlob(3)
val jobInfoBuffered = ByteBuffer.wrap(jobInfoArr)
val jobInfo = SgJobInfo.getRootAsSgJobInfo(jobInfoBuffered)
if (!doNetworkJob(jobId, action, createdAt, jobInfo)) {
Timber.e("Job %d failed, will retry.", jobId)
break // abort to avoid ordering issues
}
Timber.d("Job %d completed, will remove.", jobId)
}
jobsToRemove.add(jobId)
}
query.close()
// remove completed jobs
if (jobsToRemove.isNotEmpty()) {
removeJobs(jobsToRemove)
}
}
/**
* Returns true if the job can be removed, false if it should be retried later.
*/
private fun doNetworkJob(
jobId: Long,
action: JobAction,
createdAt: Long,
jobInfo: SgJobInfo
): Boolean {
// upload to hexagon
if (shouldSendToHexagon) {
if (!AndroidUtils.isNetworkConnected(context)) {
return false
}
val hexagonTools = SgApp.getServicesComponent(context).hexagonTools()
val hexagonJob = getHexagonJobForAction(hexagonTools, action, jobInfo)
if (hexagonJob != null) {
val result = hexagonJob.execute(context)
if (!result.successful) {
showNotification(jobId, createdAt, result)
return result.jobRemovable
}
}
}
// upload to trakt
if (shouldSendToTrakt) {
if (!AndroidUtils.isNetworkConnected(context)) {
return false
}
val traktJob = getTraktJobForAction(action, jobInfo, createdAt)
if (traktJob != null) {
val result = traktJob.execute(context)
// may need to show notification if successful (for not found error)
showNotification(jobId, createdAt, result)
if (!result.successful) {
return result.jobRemovable
}
}
}
return true
}
private fun getHexagonJobForAction(
hexagonTools: HexagonTools, action: JobAction,
jobInfo: SgJobInfo
): NetworkJob? {
return when (action) {
JobAction.EPISODE_COLLECTION,
JobAction.EPISODE_WATCHED_FLAG -> {
HexagonEpisodeJob(hexagonTools, action, jobInfo)
}
JobAction.MOVIE_COLLECTION_ADD,
JobAction.MOVIE_COLLECTION_REMOVE,
JobAction.MOVIE_WATCHLIST_ADD,
JobAction.MOVIE_WATCHLIST_REMOVE,
JobAction.MOVIE_WATCHED_SET,
JobAction.MOVIE_WATCHED_REMOVE -> {
HexagonMovieJob(hexagonTools, action, jobInfo)
}
else -> {
null // Action not supported by hexagon.
}
}
}
private fun getTraktJobForAction(
action: JobAction,
jobInfo: SgJobInfo,
createdAt: Long
): NetworkJob? {
return when (action) {
JobAction.EPISODE_COLLECTION,
JobAction.EPISODE_WATCHED_FLAG -> {
TraktEpisodeJob(action, jobInfo, createdAt)
}
JobAction.MOVIE_COLLECTION_ADD,
JobAction.MOVIE_COLLECTION_REMOVE, JobAction.MOVIE_WATCHLIST_ADD, JobAction.MOVIE_WATCHLIST_REMOVE, JobAction.MOVIE_WATCHED_SET, JobAction.MOVIE_WATCHED_REMOVE -> // action not supported by trakt
{
TraktMovieJob(action, jobInfo, createdAt)
}
else -> {
null // Action not supported by Trakt.
}
}
}
private fun showNotification(jobId: Long, jobCreatedAt: Long, result: NetworkJobResult) {
if (result.action == null || result.error == null || result.item == null) {
return // missing required values
}
val nb = NotificationCompat.Builder(context, SgApp.NOTIFICATION_CHANNEL_ERRORS)
NotificationSettings.setDefaultsForChannelErrors(context, nb)
nb.setSmallIcon(R.drawable.ic_notification)
// like: 'Failed: Remove from collection · BoJack Horseman'
nb.setContentTitle(
context.getString(R.string.api_failed, "${result.action} · ${result.item}")
)
nb.setContentText(result.error)
nb.setStyle(
NotificationCompat.BigTextStyle().bigText(
getErrorDetails(result.item, result.error, result.action, jobCreatedAt)
)
)
nb.setContentIntent(result.contentIntent)
nb.setAutoCancel(true)
// notification for each failed job
val nm = context.getSystemService<NotificationManager>()
nm?.notify(jobId.toString(), SgApp.NOTIFICATION_JOB_ID, nb.build())
}
private fun getErrorDetails(
item: String, error: String,
action: String, jobCreatedAt: Long
): String {
val builder = StringBuilder()
// build message like:
// 'Could not talk to server.
// BoJack Horseman · Set watched · 5 sec ago'
builder.append(error).append("\n").append(item).append(" · ").append(action)
// append time if job is executed a while after it was created
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - jobCreatedAt > 3 * DateUtils.SECOND_IN_MILLIS) {
builder.append(" · ")
builder.append(
DateUtils.getRelativeTimeSpanString(
jobCreatedAt,
currentTimeMillis, DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL
)
)
}
return builder.toString()
}
private fun removeJobs(jobsToRemove: List<Long>) {
val batch = ArrayList<ContentProviderOperation>()
for (jobId in jobsToRemove) {
batch.add(
ContentProviderOperation.newDelete(Jobs.buildJobUri(jobId))
.build()
)
}
try {
DBUtils.applyInSmallBatches(context, batch)
} catch (e: OperationApplicationException) {
Timber.e(e, "process: failed to delete completed jobs")
}
}
/**
* If neither Trakt or Cloud are connected, clears all remaining jobs.
*/
fun removeObsoleteJobs(ignoreHexagonState: Boolean) {
if (!ignoreHexagonState && shouldSendToHexagon || shouldSendToTrakt) {
return // Still signed in to either service, do not clear jobs.
}
context.contentResolver.delete(Jobs.CONTENT_URI, null, null)
}
} | apache-2.0 | 97e44919b50d780bff97bfc948dbc0db | 37.064378 | 207 | 0.615697 | 4.956959 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/database/table/RPKMinecraftProfileTable.kt | 1 | 8790 | /*
* Copyright 2022 Ren Binden
*
* 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.rpkit.players.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.database.create
import com.rpkit.players.bukkit.database.jooq.Tables.RPKIT_MINECRAFT_PROFILE
import com.rpkit.players.bukkit.profile.*
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileId
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileImpl
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class RPKMinecraftProfileTable(private val database: Database, private val plugin: RPKPlayersBukkit) : Table {
private val cache = if (plugin.config.getBoolean("caching.rpkit_minecraft_profile.id.enabled")) {
database.cacheManager.createCache(
"rpk-players-bukkit.rpkit_minecraft_profile.id",
Int::class.javaObjectType,
RPKMinecraftProfile::class.java,
plugin.config.getLong("caching.rpkit_minecraft_profile.id.size")
)
} else {
null
}
private val minecraftUUIDCache = if (plugin.config.getBoolean("caching.rpkit_minecraft_profile.minecraft_uuid.enabled")) {
database.cacheManager.createCache(
"rpk-players-bukkit.rpkit_minecraft_profile.minecraft_uuid",
UUID::class.java,
RPKMinecraftProfile::class.java,
plugin.config.getLong("caching.rpkit_minecraft_profile.minecraft_uuid.size")
)
} else {
null
}
fun insert(entity: RPKMinecraftProfile): CompletableFuture<Void> {
val profile = entity.profile
return CompletableFuture.runAsync {
database.create
.insertInto(
RPKIT_MINECRAFT_PROFILE,
RPKIT_MINECRAFT_PROFILE.PROFILE_ID,
RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID
)
.values(
if (profile is RPKProfile) {
profile.id?.value
} else {
null
},
entity.minecraftUUID.toString()
)
.execute()
val id = database.create.lastID().toInt()
entity.id = RPKMinecraftProfileId(id)
cache?.set(id, entity)
minecraftUUIDCache?.set(entity.minecraftUUID, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to insert Minecraft profile", exception)
throw exception
}
}
fun update(entity: RPKMinecraftProfile): CompletableFuture<Void> {
val profile = entity.profile
val id = entity.id ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
database.create
.update(RPKIT_MINECRAFT_PROFILE)
.set(
RPKIT_MINECRAFT_PROFILE.PROFILE_ID,
if (profile is RPKProfile) {
profile.id?.value
} else {
null
}
)
.set(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID, entity.minecraftUUID.toString())
.where(RPKIT_MINECRAFT_PROFILE.ID.eq(id.value))
.execute()
cache?.set(id.value, entity)
minecraftUUIDCache?.set(entity.minecraftUUID, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to update Minecraft profile", exception)
throw exception
}
}
operator fun get(id: RPKMinecraftProfileId): CompletableFuture<out RPKMinecraftProfile?> {
if (cache?.containsKey(id.value) == true) {
return CompletableFuture.completedFuture(cache[id.value])
} else {
return CompletableFuture.supplyAsync {
val result = database.create
.select(
RPKIT_MINECRAFT_PROFILE.PROFILE_ID,
RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID
)
.from(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.ID.eq(id.value))
.fetchOne() ?: return@supplyAsync null
val profileService = Services[RPKProfileService::class.java]
val profileId = result.get(RPKIT_MINECRAFT_PROFILE.PROFILE_ID)
val profile = if (profileId != null && profileService != null) {
profileService.getProfile(RPKProfileId(profileId)).join()
} else {
null
} ?: RPKThinProfileImpl(
RPKProfileName(
plugin.server.getOfflinePlayer(
UUID.fromString(result.get(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID))
).name ?: "Unknown Minecraft user"
)
)
val minecraftProfile = RPKMinecraftProfileImpl(
id,
profile,
UUID.fromString(result.get(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID))
)
cache?.set(id.value, minecraftProfile)
minecraftUUIDCache?.set(minecraftProfile.minecraftUUID, minecraftProfile)
return@supplyAsync minecraftProfile
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get Minecraft profile", exception)
throw exception
}
}
}
fun get(profile: RPKProfile): CompletableFuture<List<RPKMinecraftProfile>> {
val profileId = profile.id ?: return CompletableFuture.completedFuture(emptyList())
return CompletableFuture.supplyAsync {
val results = database.create
.select(RPKIT_MINECRAFT_PROFILE.ID)
.from(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.PROFILE_ID.eq(profileId.value))
.fetch()
val futures = results.map { result -> get(RPKMinecraftProfileId(result[RPKIT_MINECRAFT_PROFILE.ID])) }
CompletableFuture.allOf(*futures.toTypedArray()).join()
return@supplyAsync futures.mapNotNull(CompletableFuture<out RPKMinecraftProfile?>::join)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get Minecraft profiles", exception)
throw exception
}
}
operator fun get(minecraftUUID: UUID): CompletableFuture<RPKMinecraftProfile?> {
if (minecraftUUIDCache?.containsKey(minecraftUUID) == true) {
return CompletableFuture.completedFuture(minecraftUUIDCache[minecraftUUID])
}
return CompletableFuture.supplyAsync {
val result = database.create
.select(RPKIT_MINECRAFT_PROFILE.ID)
.from(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID.eq(minecraftUUID.toString()))
.fetchOne() ?: return@supplyAsync null
return@supplyAsync get(RPKMinecraftProfileId(result.get(RPKIT_MINECRAFT_PROFILE.ID))).join()
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get Minecraft profile", exception)
throw exception
}
}
fun delete(entity: RPKMinecraftProfile): CompletableFuture<Void> {
val id = entity.id ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
database.create
.deleteFrom(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.ID.eq(id.value))
.execute()
cache?.remove(id.value)
minecraftUUIDCache?.remove(entity.minecraftUUID)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to delete Minecraft profile", exception)
throw exception
}
}
} | apache-2.0 | c0f3d51f98bed26da4748641467c5345 | 42.955 | 126 | 0.61058 | 5.143359 | false | false | false | false |
appnexus/mobile-sdk-android | tests/AppNexusSDKTestApp/app/src/androidTest/java/appnexus/com/appnexussdktestapp/functional/banner/BannerScaleTest.kt | 1 | 3920 | /*
* Copyright 2012 APPNEXUS 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 appnexus.com.appnexussdktestapp.functional.banner
import android.content.Intent
import android.content.res.Resources
import androidx.test.espresso.Espresso
import androidx.test.espresso.IdlingPolicies
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.runner.AndroidJUnit4
import appnexus.com.appnexussdktestapp.BannerScaleLoadAndDisplayActivity
import appnexus.com.appnexussdktestapp.R
import com.appnexus.opensdk.XandrAd
import com.appnexus.opensdk.utils.Clog
import com.microsoft.appcenter.espresso.Factory
import kotlinx.android.synthetic.main.activity_mar_load.*
import org.junit.*
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class BannerScaleTest {
val Int.dp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Int.px: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
@get:Rule
var reportHelper = Factory.getReportHelper()
@Rule
@JvmField
var mActivityTestRule = IntentsTestRule(BannerScaleLoadAndDisplayActivity::class.java, false, false)
lateinit var bannerActivity: BannerScaleLoadAndDisplayActivity
@Before
fun setup() {
XandrAd.init(123, null, false, null)
IdlingPolicies.setMasterPolicyTimeout(1, TimeUnit.MINUTES)
IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.MINUTES)
}
@After
fun destroy() {
IdlingRegistry.getInstance().unregister(bannerActivity.idlingResource)
reportHelper.label("Stopping App")
}
/*
* Test for the Invalid Renderer Url for Banner Native Ad (NativeAssemblyRenderer)
* */
@Test
fun bannerScaleForCountNumberOfBanners() {
var intent = Intent()
var count = 64
intent.putExtra(BannerScaleLoadAndDisplayActivity.COUNT, count)
mActivityTestRule.launchActivity(intent)
bannerActivity = mActivityTestRule.activity
IdlingRegistry.getInstance().register(bannerActivity.idlingResource)
Thread.sleep(2000)
Espresso.onView(ViewMatchers.withId(R.id.recyclerListAdView))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Clog.e("COUNT: ", bannerActivity.recyclerListAdView.adapter!!.itemCount.toString())
scrollDown(count)
Thread.sleep(1000)
scrollUp(count)
Thread.sleep(1000)
scrollUp(count)
Espresso.onView(ViewMatchers.withId(R.id.recyclerListAdView))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
}
fun scrollDown(count: Int) {
(0 until count - 1 step 1).forEach { i ->
bannerActivity.recyclerListAdView.smoothScrollToPosition(i)
Thread.sleep(1000)
}
}
fun scrollUp(count: Int) {
(count - 1 until 0 step 1).forEach { i ->
bannerActivity.recyclerListAdView.smoothScrollToPosition(i)
Thread.sleep(1000)
}
}
}
| apache-2.0 | e5a44a3da8b77f48b205365549f27e99 | 31.666667 | 104 | 0.717347 | 4.505747 | false | true | false | false |
sav007/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/InputFieldSpec.kt | 1 | 8901 | package com.apollographql.apollo.compiler
import com.apollographql.apollo.api.InputFieldWriter
import com.apollographql.apollo.compiler.ir.CodeGenerationContext
import com.squareup.javapoet.*
import java.io.IOException
import java.util.*
import javax.lang.model.element.Modifier
class InputFieldSpec(
val type: Type,
val name: String,
val graphQLType: String,
val javaType: TypeName,
val context: CodeGenerationContext
) {
fun writeValueCode(writerParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
return when (type) {
Type.STRING,
Type.INT,
Type.LONG,
Type.DOUBLE,
Type.BOOLEAN -> writeScalarCode(writerParam)
Type.ENUM -> writeEnumCode(writerParam)
Type.CUSTOM -> writeCustomCode(writerParam)
Type.OBJECT -> writeObjectCode(writerParam, marshaller)
Type.SCALAR_LIST -> writeScalarList(writerParam)
Type.CUSTOM_LIST -> writeCustomList(writerParam)
Type.OBJECT_LIST -> writeObjectList(writerParam, marshaller)
}
}
private fun writeScalarCode(writerParam: CodeBlock): CodeBlock {
val valueCode = javaType.unwrapOptionalValue(name)
return CodeBlock.of("\$L.\$L(\$S, \$L);\n", writerParam, WRITE_METHODS[type], name, valueCode)
}
private fun writeEnumCode(writerParam: CodeBlock): CodeBlock {
val valueCode = javaType.unwrapOptionalValue(name) {
CodeBlock.of("\$L.name()", it)
}
return CodeBlock.of("\$L.\$L(\$S, \$L);\n", writerParam, WRITE_METHODS[type], name, valueCode)
}
private fun writeCustomCode(writerParam: CodeBlock): CodeBlock {
val customScalarEnum = CustomEnumTypeSpecBuilder.className(context)
val customScalarEnumConst = normalizeGraphQlType(graphQLType).toUpperCase(Locale.ENGLISH)
val valueCode = javaType.unwrapOptionalValue(name)
return CodeBlock.of("\$L.\$L(\$S, \$L.\$L, \$L);\n", writerParam, WRITE_METHODS[type],
name, customScalarEnum, customScalarEnumConst, valueCode)
}
private fun writeObjectCode(writerParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
val valueCode = javaType.unwrapOptionalValue(name) {
CodeBlock.of("\$L.\$L", it, marshaller)
}
return CodeBlock.of("\$L.\$L(\$S, \$L);\n", writerParam, WRITE_METHODS[type], name, valueCode)
}
private fun writeScalarList(writerParam: CodeBlock): CodeBlock {
val rawFieldType = with(javaType) { if (isList()) listParamType() else this }
val writeMethod = SCALAR_LIST_ITEM_WRITE_METHODS[rawFieldType] ?: "writeString"
val writeStatement = CodeBlock.builder()
.beginControlFlow("for (\$T \$L : \$L)", rawFieldType, "\$item",
javaType.unwrapOptionalValue(name, false))
.add(
if (rawFieldType.isEnum(context)) {
CodeBlock.of("\$L.\$L(\$L.name());\n", LIST_ITEM_WRITER_PARAM.name, writeMethod, "\$item")
} else {
CodeBlock.of("\$L.\$L(\$L);\n", LIST_ITEM_WRITER_PARAM.name, writeMethod, "\$item")
})
.endControlFlow()
.build()
val listWriterType = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(InputFieldWriter.ListWriter::class.java)
.addMethod(MethodSpec.methodBuilder("write")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addException(IOException::class.java)
.addParameter(LIST_ITEM_WRITER_PARAM)
.addCode(writeStatement)
.build()
)
.build()
val valueCode = javaType.unwrapOptionalValue(name) {
CodeBlock.of("\$L", listWriterType)
}
return CodeBlock.of("\$L.\$L(\$S, \$L);\n", writerParam, WRITE_METHODS[type], name, valueCode)
}
private fun writeCustomList(writerParam: CodeBlock): CodeBlock {
val rawFieldType = javaType.let { if (it.isList()) it.listParamType() else it }
val customScalarEnum = CustomEnumTypeSpecBuilder.className(context)
val customScalarEnumConst = normalizeGraphQlType(graphQLType).toUpperCase(Locale.ENGLISH)
val writeStatement = CodeBlock.builder()
.beginControlFlow("for (\$T \$L : \$L)", rawFieldType, "\$item",
javaType.unwrapOptionalValue(name, false))
.addStatement("\$L.writeCustom(\$T.\$L, \$L)", LIST_ITEM_WRITER_PARAM.name, customScalarEnum,
customScalarEnumConst, "\$item")
.endControlFlow()
.build()
val listWriterType = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(InputFieldWriter.ListWriter::class.java)
.addMethod(MethodSpec.methodBuilder("write")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addParameter(LIST_ITEM_WRITER_PARAM)
.addException(IOException::class.java)
.addCode(writeStatement)
.build()
)
.build()
val valueCode = javaType.unwrapOptionalValue(name) {
CodeBlock.of("\$L", listWriterType)
}
return CodeBlock.of("\$L.\$L(\$S, \$L);\n", writerParam, WRITE_METHODS[type], name, valueCode)
}
private fun writeObjectList(writerParam: CodeBlock, marshaller: CodeBlock): CodeBlock {
val rawFieldType = with(javaType) { if (isList()) listParamType() else this }
val writeStatement = CodeBlock.builder()
.beginControlFlow("for (\$T \$L : \$L)", rawFieldType, "\$item",
javaType.unwrapOptionalValue(name, false))
.addStatement("\$L.writeObject(\$L.\$L)", LIST_ITEM_WRITER_PARAM.name, "\$item", marshaller)
.endControlFlow()
.build()
val listWriterType = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(InputFieldWriter.ListWriter::class.java)
.addMethod(MethodSpec.methodBuilder("write")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addParameter(LIST_ITEM_WRITER_PARAM)
.addException(IOException::class.java)
.addCode(writeStatement)
.build()
)
.build()
val valueCode = javaType.unwrapOptionalValue(name) {
CodeBlock.of("\$L", listWriterType)
}
return CodeBlock.of("\$L.\$L(\$S, \$L);\n", writerParam, WRITE_METHODS[type], name, valueCode)
}
companion object {
private val WRITE_METHODS = mapOf(
Type.STRING to "writeString",
Type.INT to "writeInt",
Type.LONG to "writeLong",
Type.DOUBLE to "writeDouble",
Type.BOOLEAN to "writeBoolean",
Type.ENUM to "writeString",
Type.CUSTOM to "writeCustom",
Type.OBJECT to "writeObject",
Type.SCALAR_LIST to "writeList",
Type.CUSTOM_LIST to "writeList",
Type.OBJECT_LIST to "writeList"
)
private val SCALAR_LIST_ITEM_WRITE_METHODS = mapOf(
ClassNames.STRING to "writeString",
TypeName.INT to "writeInt",
TypeName.INT.box() to "writeInt",
TypeName.LONG to "writeLong",
TypeName.LONG.box() to "writeLong",
TypeName.DOUBLE to "writeDouble",
TypeName.DOUBLE.box() to "writeDouble",
TypeName.BOOLEAN to "writeBoolean",
TypeName.BOOLEAN.box() to "writeBoolean"
)
private val LIST_ITEM_WRITER_PARAM =
ParameterSpec.builder(InputFieldWriter.ListItemWriter::class.java, "listItemWriter").build()
fun build(name: String, graphQLType: String, context: CodeGenerationContext): InputFieldSpec {
val javaType = JavaTypeResolver(context = context, packageName = "")
.resolve(typeName = graphQLType, nullableValueType = NullableValueType.ANNOTATED)
val normalizedJavaType = javaType.withoutAnnotations()
val type = when {
normalizedJavaType.isList() -> {
val rawFieldType = normalizedJavaType.let { if (it.isList()) it.listParamType() else it }
if (graphQLType.isCustomScalarType(context)) {
Type.CUSTOM_LIST
} else if (rawFieldType.isScalar(context)) {
Type.SCALAR_LIST
} else {
Type.OBJECT_LIST
}
}
graphQLType.isCustomScalarType(context) -> Type.CUSTOM
normalizedJavaType.isScalar(context) -> {
when (normalizedJavaType) {
TypeName.INT, TypeName.INT.box() -> Type.INT
TypeName.LONG, TypeName.LONG.box() -> Type.LONG
TypeName.DOUBLE, TypeName.DOUBLE.box() -> Type.DOUBLE
TypeName.BOOLEAN, TypeName.BOOLEAN.box() -> Type.BOOLEAN
else -> if (normalizedJavaType.isEnum(context)) Type.ENUM else Type.STRING
}
}
else -> Type.OBJECT
}
return InputFieldSpec(
type = type,
name = name,
graphQLType = graphQLType,
javaType = javaType,
context = context
)
}
}
enum class Type {
STRING,
INT,
LONG,
DOUBLE,
BOOLEAN,
ENUM,
OBJECT,
SCALAR_LIST,
CUSTOM_LIST,
OBJECT_LIST,
CUSTOM,
}
} | mit | 58e984e86d957e56cf7c7c8d5283ee4e | 38.919283 | 104 | 0.644984 | 4.325073 | false | false | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/widget/TimeTextView.kt | 1 | 2016 | package com.angcyo.uiview.widget
import android.content.Context
import android.util.AttributeSet
import com.angcyo.uiview.R
import com.angcyo.uiview.kotlin.nowTime
import com.angcyo.uiview.utils.RUtils
import java.text.SimpleDateFormat
import java.util.*
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:用来显示时间的控件, 支持模板自定义
* 创建人员:Robi
* 创建时间:2018/01/10 14:30
* 修改人员:Robi
* 修改时间:2018/01/10 14:30
* 修改备注:
* Version: 1.0.0
*/
open class TimeTextView(context: Context, attributeSet: AttributeSet? = null) : RTextView(context, attributeSet) {
private val simpleFormat = SimpleDateFormat("yyyy-MM-dd HH:mm" /*ss:SSS*/, Locale.CHINA)
/**毫秒*/
var time = 0L
set(value) {
field = value
text = if (field <= 0) {
""
} else {
if (showShotTime) {
RUtils.getShotTimeString(field)
} else {
simpleFormat.format(Date(field))
}
}
}
/**缩短显示时间*/
var showShotTime = false
init {
val array = context.obtainStyledAttributes(attributeSet, R.styleable.TimeTextView)
val pattern = array.getString(R.styleable.TimeTextView_r_time_pattern)
val timeString = array.getString(R.styleable.TimeTextView_r_time)
showShotTime = array.getBoolean(R.styleable.TimeTextView_r_show_shot_time, showShotTime)
pattern?.let {
setPattern(it)
}
if (isInEditMode) {
time = nowTime()
}
timeString?.let {
time = timeString.toLong()
}
array.recycle()
}
/**重置模板样式*/
fun setPattern(pattern: String) {
simpleFormat.applyPattern(pattern)
time = time
}
} | apache-2.0 | 1a968278b0a35de39e13cdcc448a12e0 | 26.151515 | 114 | 0.578125 | 3.948936 | false | false | false | false |
MakinGiants/todayhistory | app/src/main/kotlin/com/makingiants/todayhistory/screens/today/TodayPresenter.kt | 1 | 2835 | package com.makingiants.todayhistory.screens.today
import android.support.annotation.VisibleForTesting
import com.makingiants.today.api.error_handling.ApiException
import com.makingiants.today.api.repository.history.HistoryRepository
import com.makingiants.today.api.repository.history.pojo.Event
import com.makingiants.todayhistory.utils.DateManager
import com.makingiants.todayhistory.utils.NetworkChecker
import com.makingiants.todayhistory.utils.Transformer
import io.reactivex.disposables.CompositeDisposable
open class TodayPresenter(var dateManager: DateManager,
val historyRepository: HistoryRepository,
val networkChecker: NetworkChecker) {
@VisibleForTesting val compositeDisposable = CompositeDisposable()
@VisibleForTesting var view: TodayView? = null
private var events: List<Event>? = null
fun attach(view: TodayView) {
this.view = view
view.initViews()
if (events == null) {
loadEvents(true)
} else {
view.showEvents(events!!)
}
}
fun unAttach() {
view = null
// compositeDisposable.clear()
}
fun onRefresh() = loadEvents()
@VisibleForTesting
fun loadEvents(isFistTime: Boolean = false) {
if (!(networkChecker.isNetworkConnectionAvailable())) {
view?.showErrorToast("There is no internet.")
return
}
if (isFistTime) {
view?.showEmptyViewProgress()
} else {
view?.showReloadProgress()
}
val subscription = historyRepository.get(dateManager.getTodayDay(), dateManager.getTodayMonth())
.compose(Transformer.applyIoSchedulers<List<Event>>())
.subscribe({ events: List<Event> ->
view?.hideErrorView()
view?.hideEmptyView()
view?.dismissEmptyViewProgress()
view?.dismissReloadProgress()
if (events.isEmpty()) {
if (this.events == null) {
view?.showEmptyView()
} else {
view?.showErrorToast("The loaded list is empty, retry latter.")
}
} else {
this.events = events
view?.showEvents(events)
}
}, { error: Throwable ->
view?.hideEmptyView()
view?.dismissEmptyViewProgress()
view?.dismissReloadProgress()
if (events == null) {
if (isFistTime || events == null || events!!.isEmpty()) {
val apiException = ApiException.from(error)
view?.showErrorView(apiException.name, apiException.text)
view?.hideEvents()
} else {
view?.showErrorDialog(error)
}
} else {
val apiException = ApiException.from(error)
view?.showErrorToast(apiException.text)
}
})
compositeDisposable.add(subscription)
}
}
| mit | c2c6ab87e880362c9c1838c9ee3559c3 | 30.853933 | 100 | 0.634921 | 4.780776 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/transport/ice/IceStatistics.kt | 1 | 2268 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.transport.ice
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.utils.stats.BucketStats
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.DoubleAdder
/**
* Keep ICE-related statistics (currently only RTT).
*/
class IceStatistics {
/** Stats for all harvesters */
private val combinedStats = Stats()
/** Stats by harvester name. */
private val statsByHarvesterName = ConcurrentHashMap<String, Stats>()
/** Add a round-trip-time measurement for a specific harvester */
fun add(harvesterName: String, rttMs: Double) {
combinedStats.add(rttMs = rttMs)
statsByHarvesterName.computeIfAbsent(harvesterName) { Stats() }.add(rttMs = rttMs)
}
fun toJson() = OrderedJsonObject().apply {
put("all", combinedStats.toJson())
statsByHarvesterName.forEach { (harvesterName, stats) ->
put(harvesterName, stats.toJson())
}
}
companion object {
val stats = IceStatistics()
}
private class Stats {
/** Histogram of RTTs */
val buckets = BucketStats(listOf(0, 10, 20, 40, 60, 80, 100, 150, 200, 250, 300, 500, 1000, Long.MAX_VALUE))
var sum = DoubleAdder()
var count = AtomicInteger()
fun add(rttMs: Double) {
sum.add(rttMs)
count.incrementAndGet()
buckets.addValue((rttMs + 0.5).toLong())
}
fun toJson() = OrderedJsonObject().apply {
put("average", sum.sum() / count.toDouble())
put("buckets", buckets.toJson())
}
}
}
| apache-2.0 | 30b844a0ac313874e6e519ae7f5217b9 | 32.352941 | 116 | 0.662698 | 3.98594 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/messages/MessagesEntity.kt | 1 | 2203 | package com.waz.zclient.storage.db.messages
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "Messages",
indices = [Index(name = "Messages_conv_time", value = ["conv_id", "time"])]
)
data class MessagesEntity(
@PrimaryKey
@ColumnInfo(name = "_id")
val id: String,
@ColumnInfo(name = "conv_id", defaultValue = "")
val conversationId: String,
@ColumnInfo(name = "msg_type", defaultValue = "")
val messageType: String,
@ColumnInfo(name = "user_id", defaultValue = "")
val userId: String,
@ColumnInfo(name = "client_id")
val clientId: String?,
@ColumnInfo(name = "error_code")
val errorCode: Long?,
@ColumnInfo(name = "content")
val content: String?,
@ColumnInfo(name = "protos", typeAffinity = ColumnInfo.BLOB)
val protos: ByteArray?,
@ColumnInfo(name = "time", defaultValue = "0")
val time: Long,
@ColumnInfo(name = "first_msg", defaultValue = "0")
val firstMessage: Boolean,
@ColumnInfo(name = "members")
val members: String?,
@ColumnInfo(name = "recipient")
val recipient: String?,
@ColumnInfo(name = "email")
val email: String?,
@ColumnInfo(name = "name")
val name: String?,
@ColumnInfo(name = "msg_state", defaultValue = "")
val messageState: String,
@ColumnInfo(name = "content_size", defaultValue = "0")
val contentSize: Int,
@ColumnInfo(name = "local_time", defaultValue = "0")
val localTime: Long,
@ColumnInfo(name = "edit_time", defaultValue = "0")
val editTime: Long,
@ColumnInfo(name = "ephemeral")
val ephemeral: Long?,
@ColumnInfo(name = "expiry_time")
val expiryTime: Long?,
@ColumnInfo(name = "expired", defaultValue = "0")
val expired: Boolean,
@ColumnInfo(name = "duration")
val duration: Long?,
@ColumnInfo(name = "quote")
val quote: String?,
@ColumnInfo(name = "quote_validity", defaultValue = "0")
val quoteValidity: Int,
@ColumnInfo(name = "force_read_receipts")
val forceReadReceipts: Int?,
@ColumnInfo(name = "asset_id")
val assetId: String?
)
| gpl-3.0 | 13e6b799e4154e5c2f67307a609e2a54 | 23.208791 | 79 | 0.639128 | 3.837979 | false | false | false | false |
stephanenicolas/toothpick | ktp/src/main/kotlin/toothpick/ktp/delegate/InjectDelegate.kt | 1 | 2607 | /*
* Copyright 2019 Stephane Nicolas
* Copyright 2019 Daniel Molinero Reguera
*
* 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 toothpick.ktp.delegate
import javax.inject.Provider
import kotlin.reflect.KProperty
import toothpick.Scope
/**
* Property delegate base class. It allows to delegate the creation of fields to KTP.
* A typical example is
*/
sealed class InjectDelegate<T : Any>(protected val clz: Class<T>, protected val name: String?) {
abstract val instance: T
abstract fun onEntryPointInjected(scope: Scope)
abstract fun isEntryPointInjected(): Boolean
operator fun getValue(thisRef: Any, property: KProperty<*>): T {
if (!isEntryPointInjected()) {
throw IllegalStateException("The dependency has not be injected yet.")
}
return instance
}
}
/**
* Delegate for fields that should be injected eagerly.
*/
class EagerDelegate<T : Any>(clz: Class<T>, name: String?) : InjectDelegate<T>(clz, name) {
override lateinit var instance: T
override fun onEntryPointInjected(scope: Scope) {
instance = scope.getInstance(clz, name)
}
override fun isEntryPointInjected() = this::instance.isInitialized
}
/**
* Delegate for fields that should be injected as a provider.
*/
class ProviderDelegate<T : Any>(clz: Class<T>, name: String?) : InjectDelegate<T>(clz, name) {
lateinit var provider: Provider<T>
override val instance: T
get() = provider.get()
override fun onEntryPointInjected(scope: Scope) {
provider = scope.getProvider(clz, name)
}
override fun isEntryPointInjected() = this::provider.isInitialized
}
/**
* Delegate for fields that should be injected lazily.
*/
class LazyDelegate<T : Any>(clz: Class<T>, name: String?) : InjectDelegate<T>(clz, name) {
lateinit var provider: Provider<T>
override val instance: T
get() = provider.get()
override fun onEntryPointInjected(scope: Scope) {
provider = scope.getLazy(clz, name)
}
override fun isEntryPointInjected() = this::provider.isInitialized
}
| apache-2.0 | 8ed9bf91c8d810658d66b96bc46579dc | 28.625 | 96 | 0.702723 | 4.239024 | false | false | false | false |
fantasy1022/FancyTrendView | app/src/main/java/com/fantasy1022/fancytrendapp/presentation/base/BasePresenter.kt | 1 | 1279 | /*
* Copyright 2017 Fantasy Fang
*
* 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.fantasy1022.fancytrendapp.presentation.base
/**
* Created by fantasy1022 on 2017/2/7.
*/
open class BasePresenter<T : MvpView> : MvpPresenter<T> {
var view: T? = null
private set
private val isViewAttached: Boolean
get() = view != null
override fun attachView(mvpView: T) {
view = mvpView
}
override fun detachView() {
view = null
}
fun checkViewAttached() {
if (!isViewAttached) {
throw MvpViewNotAttachedException()
}
}
class MvpViewNotAttachedException : RuntimeException("Please call Presenter.attachView(MvpView) before" + " requesting data to the Presenter")
}
| apache-2.0 | 5fafec2a084f7a91f7982f2846f32979 | 26.212766 | 146 | 0.688038 | 4.320946 | false | false | false | false |
actions-on-google/appactions-fitness-kotlin | app/src/main/java/com/devrel/android/fitactions/FitMainActivity.kt | 1 | 7841 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.devrel.android.fitactions
import android.app.assist.AssistContent
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.devrel.android.fitactions.BiiIntents.START_EXERCISE
import com.devrel.android.fitactions.BiiIntents.STOP_EXERCISE
import com.devrel.android.fitactions.home.FitStatsFragment
import com.devrel.android.fitactions.model.FitActivity
import com.devrel.android.fitactions.model.FitRepository
import com.devrel.android.fitactions.tracking.FitTrackingFragment
import com.devrel.android.fitactions.tracking.FitTrackingService
import org.json.JSONObject
/**
* Main activity responsible for the app navigation and handling Android intents.
*/
class FitMainActivity :
AppCompatActivity(), FitStatsFragment.FitStatsActions, FitTrackingFragment.FitTrackingActions {
private val TAG = "FitMainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fit_activity)
Log.d(TAG, "======= Here ========= %s")
// Logging for troubleshooting purposes
logIntent(intent)
// Handle the intent this activity was launched with.
intent?.handleIntent()
}
/**
* Handle new intents that are coming while the activity is on foreground since we set the
* launchMode to be singleTask, avoiding multiple instances of this activity to be created.
*
* See [launchMode](https://developer.android.com/guide/topics/manifest/activity-element#lmode)
*/
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.handleIntent()
}
/**
* For debugging Android intents
*/
fun logIntent(intent: Intent) {
val bundle: Bundle = intent.extras ?: return
Log.d(TAG, "======= logIntent ========= %s")
Log.d(TAG, "Logging intent data start")
bundle.keySet().forEach { key ->
Log.d(TAG, "[$key=${bundle.get(key)}]")
}
Log.d(TAG, "Logging intent data complete")
}
/**
* When a fragment is attached add the required callback methods.
*/
override fun onAttachFragment(fragment: Fragment) {
when (fragment) {
is FitStatsFragment -> fragment.actionsCallback = this
is FitTrackingFragment -> fragment.actionsCallback = this
}
}
/**
* When the user invokes an App Action while in your app, users will see a suggestion
* to share their foreground content.
*
* By implementing onProvideAssistContent(), you provide the Assistant with structured
* information about the current foreground content.
*
* This contextual information enables the Assistant to continue being helpful after the user
* enters your app.
*/
override fun onProvideAssistContent(outContent: AssistContent) {
super.onProvideAssistContent(outContent)
// JSON-LD object based on Schema.org structured data
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// This is just an example, more accurate information should be provided
outContent.structuredData = JSONObject()
.put("@type", "ExerciseObservation")
.put("name", "My last runs")
.put("url", "https://fit-actions.firebaseapp.com/stats")
.toString()
}
}
/**
* Callback method from the FitStatsFragment to indicate that the tracking activity flow
* should be shown.
*/
override fun onStartActivity() {
updateView(
newFragmentClass = FitTrackingFragment::class.java,
arguments = Bundle().apply {
putSerializable(FitTrackingFragment.PARAM_TYPE, FitActivity.Type.RUNNING)
},
toBackStack = true
)
}
/**
* Callback method when an activity stops.
* We could show a details screen, for now just go back to home screen.
*/
override fun onActivityStopped(activityId: String) {
if (supportFragmentManager.backStackEntryCount > 0) {
supportFragmentManager.popBackStack()
} else {
updateView(FitStatsFragment::class.java)
}
}
/**
* Handles the action from the intent base on the type.
*
* @receiver the intent to handle
*/
private fun Intent.handleIntent() {
when (action) {
// When the BII is matched, Intent.Action_VIEW will be used
Intent.ACTION_VIEW -> handleIntent(data)
// Otherwise start the app as you would normally do.
else -> showDefaultView()
}
}
/**
* Use extras provided by the intent to handle the different BIIs
*/
private fun handleIntent(data: Uri?) {
// path is normally used to indicate which view should be displayed
// i.e https://fit-actions.firebaseapp.com/start?exerciseType="Running" -> path = "start"
val startExercise = intent?.extras?.getString(START_EXERCISE)
val stopExercise = intent?.extras?.getString(STOP_EXERCISE)
if (startExercise != null){
val type = FitActivity.Type.find(startExercise)
val arguments = Bundle().apply {
putSerializable(FitTrackingFragment.PARAM_TYPE, type)
}
updateView(FitTrackingFragment::class.java, arguments)
} else if(stopExercise != null){
// Stop the tracking service if any and return to home screen.
stopService(Intent(this, FitTrackingService::class.java))
updateView(FitStatsFragment::class.java)
} else{
// path is not supported or invalid, start normal flow.
showDefaultView()
}
}
/**
* Show ongoing activity or stats if none
*/
private fun showDefaultView() {
val onGoing = FitRepository.getInstance(this).getOnGoingActivity().value
val fragmentClass = if (onGoing != null) {
FitTrackingFragment::class.java
} else {
FitStatsFragment::class.java
}
updateView(fragmentClass)
}
/**
* Utility method to update the Fragment with the given arguments.
*/
private fun updateView(
newFragmentClass: Class<out Fragment>,
arguments: Bundle? = null,
toBackStack: Boolean = false
) {
val currentFragment = supportFragmentManager.fragments.firstOrNull()
if (currentFragment != null && currentFragment::class.java == newFragmentClass) {
return
}
val fragment = supportFragmentManager.fragmentFactory.instantiate(
newFragmentClass.classLoader!!,
newFragmentClass.name
)
fragment.arguments = arguments
supportFragmentManager.beginTransaction().run {
replace(R.id.fitActivityContainer, fragment)
if (toBackStack) {
addToBackStack(null)
}
commit()
}
}
}
| apache-2.0 | fa5560946a65226b0b169fbc59db3002 | 33.54185 | 99 | 0.650045 | 4.729192 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/stubs/index/RsNamedElementIndex.kt | 2 | 2024 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.stubs.index
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndexKey
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.RsNamedElement
import org.rust.lang.core.psi.ext.containingCargoPackage
import org.rust.lang.core.resolve.STD_DERIVABLE_TRAITS
import org.rust.lang.core.stubs.RsFileStub
import org.rust.openapiext.ProjectCache
import org.rust.openapiext.getElements
class RsNamedElementIndex : StringStubIndexExtension<RsNamedElement>() {
override fun getVersion(): Int = RsFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<String, RsNamedElement> = KEY
companion object {
val KEY: StubIndexKey<String, RsNamedElement> =
StubIndexKey.createIndexKey("org.rust.lang.core.stubs.index.RustNamedElementIndex")
private val derivableTraitsCache = ProjectCache<String, Collection<RsTraitItem>>("derivableTraitsCache")
fun findDerivableTraits(project: Project, target: String): Collection<RsTraitItem> =
derivableTraitsCache.getOrPut(project, target) {
val stdTrait = STD_DERIVABLE_TRAITS[target]
getElements(KEY, target, project, GlobalSearchScope.allScope(project))
.mapNotNull { it as? RsTraitItem }
.filter { e ->
if (stdTrait == null) return@filter true
e.containingCargoPackage?.origin == PackageOrigin.STDLIB && e.containingMod.modName == stdTrait.modName
}
}
fun findElementsByName(project: Project, target: String): Collection<RsNamedElement> =
getElements(KEY, target, project, GlobalSearchScope.allScope(project))
}
}
| mit | 04c63fdc39b411b39261c805502e71f8 | 45 | 127 | 0.717885 | 4.487805 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/dao/PackageDatabase.kt | 1 | 5472 | package info.papdt.express.helper.dao
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.annotations.Expose
import java.io.IOException
import java.util.ArrayList
import info.papdt.express.helper.api.PackageApi
import info.papdt.express.helper.api.PushApi
import info.papdt.express.helper.model.BaseMessage
import info.papdt.express.helper.model.Kuaidi100Package
import info.papdt.express.helper.support.FileUtils
import info.papdt.express.helper.support.SettingsInstance
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.Exception
class PackageDatabase private constructor(private val mContext: Context) {
@Expose @Volatile
lateinit var data: ArrayList<Kuaidi100Package>
private set
@Expose
var dataVersion: String? = "5.0.0"
private set
@Expose @Volatile
var lastUpdateTime: Long = 0
private var lastRemovedData: Kuaidi100Package? = null
private var lastRemovedPosition = -1
init {
this.load()
}
fun load() {
var json: String
try {
try {
json = FileUtils.readFile(mContext, FILE_NAME)
} catch (e: IOException) {
json = "{\"data\":[], \"lastUpdateTime\":0}"
}
val obj = Gson().fromJson(json, PackageDatabase::class.java)
this.data = obj.data
this.lastUpdateTime = obj.lastUpdateTime
} catch (e: Exception) {
e.printStackTrace()
this.data = ArrayList()
}
}
fun restoreData(json: String) {
val obj = Gson().fromJson(json, PackageDatabase::class.java)
this.data = obj.data
this.lastUpdateTime = obj.lastUpdateTime
CoroutineScope(Dispatchers.IO).launch { PushApi.sync(getPackageIdList()) }
}
val backupData: String
get() {
if (dataVersion == null) {
dataVersion = "5.0.0"
}
return GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(this)
}
fun save(): Boolean {
try {
val gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
FileUtils.saveFile(mContext, FILE_NAME, gson.toJson(this))
return true
} catch (e: IOException) {
e.printStackTrace()
return false
}
}
@Synchronized
fun add(pack: Kuaidi100Package) {
data.add(pack)
CoroutineScope(Dispatchers.IO).launch { PushApi.add(pack.number!!, pack.companyType) }
}
@Synchronized
fun add(index: Int, pack: Kuaidi100Package) {
data.add(index, pack)
CoroutineScope(Dispatchers.IO).launch { PushApi.add(pack.number!!, pack.companyType) }
}
@Synchronized
operator fun set(index: Int, pack: Kuaidi100Package) {
data[index] = pack
}
@Synchronized
fun remove(index: Int) {
val removedItem = data.removeAt(index)
CoroutineScope(Dispatchers.IO).launch { PushApi.remove(removedItem.number!!) }
lastRemovedData = removedItem
lastRemovedPosition = index
}
@Synchronized
fun remove(pack: Kuaidi100Package) {
val nowPos = indexOf(pack)
remove(nowPos)
}
@Synchronized
fun undoLastRemoval(): Int {
if (lastRemovedData != null) {
val insertedPosition: Int = if (lastRemovedPosition >= 0 && lastRemovedPosition < data.size) {
lastRemovedPosition
} else {
data.size
}
data.add(insertedPosition, lastRemovedData!!)
lastRemovedData = null
lastRemovedPosition = -1
return insertedPosition
} else {
return -1
}
}
fun indexOf(p: Kuaidi100Package): Int {
return indexOf(p.number!!)
}
fun indexOf(number: String): Int {
return (0 until size()).firstOrNull { get(it).number == number } ?: -1
}
fun clear() {
data.clear()
}
fun size(): Int {
return data.size
}
operator fun get(index: Int): Kuaidi100Package {
return data[index]
}
fun getByNumber(number: String): Kuaidi100Package? {
return data.find { it.number == number }
}
fun getPackageIdList(): List<String> = data.map { "${it.number}+${it.companyType}" }
fun pullDataFromNetwork(shouldRefreshDelivered: Boolean) {
if (SettingsInstance.enablePush) {
CoroutineScope(Dispatchers.IO).launch { PushApi.sync(getPackageIdList()) }
}
for (i in 0 until size()) {
val pack = this[i]
if (!shouldRefreshDelivered && pack.getState() == Kuaidi100Package.STATUS_DELIVERED) {
continue
}
val newPack = PackageApi.getPackage(pack.number!!, pack.companyType)
if (newPack.code == BaseMessage.CODE_OKAY && newPack.data?.data != null) {
pack.applyNewData(newPack.data)
this[i] = pack
} else {
Log.e(TAG, "Kuaidi100Package " + pack.codeNumber + " couldn\'t get new info.")
}
}
}
fun readAll(): Int {
var count = 0
for (i in 0 until size()) {
if (data[i].unreadNew) {
count++
data[i] = Kuaidi100Package(data[i])
data[i].unreadNew = false
}
}
return count
}
companion object {
@SuppressLint("StaticFieldLeak")
@Volatile
private var sInstance: PackageDatabase? = null
private const val FILE_NAME = "packages.json"
private val TAG = PackageDatabase::class.java.simpleName
fun getInstance(context: Context): PackageDatabase {
if (sInstance == null) {
synchronized(PackageDatabase::class.java) {
if (sInstance == null) {
sInstance = PackageDatabase(
if (context is Application) context else context.applicationContext
)
}
}
}
return sInstance!!
}
}
}
| gpl-3.0 | 68c9776d4dc58a24822f4d2c16925c74 | 23.648649 | 99 | 0.691155 | 3.411471 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.