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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tipsy/javalin | javalin-openapi/src/test/java/io/javalin/plugin/openapi/TestOpenApiExample.kt | 1 | 5759 | package io.javalin.plugin.openapi
import io.javalin.Javalin
import io.javalin.plugin.openapi.dsl.document
import io.javalin.plugin.openapi.dsl.documented
import io.swagger.v3.oas.models.examples.Example
import io.swagger.v3.oas.models.info.Info
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
private data class ExampleUser(val name: String, val address: ExampleAddress)
private data class ExampleAddress(val street: String, val number: Int)
val examples = mapOf(
ExampleUser::class.java to mapOf(
"User example" to Example().apply {
summary = "A correctly configured user"
value = ExampleUser("John", ExampleAddress("Some street", 123))
},
"User example 2" to Example().apply {
summary = "Another correctly configured user"
value = ExampleUser("Dave", ExampleAddress("Some street", 123))
}
),
ExampleAddress::class.java to mapOf(
"Address example" to Example().apply {
summary = "A correctly configured address"
value = ExampleAddress("Some street", 123)
}
)
)
val expectedJson = """
{
"openapi" : "3.0.1",
"info" : { },
"paths" : {
"/user" : {
"get" : {
"summary" : "Get user",
"operationId" : "getUser",
"responses" : {
"200" : {
"description" : "OK",
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/ExampleUser"
},
"examples" : {
"User example" : {
"summary" : "A correctly configured user",
"value" : {
"name" : "John",
"address" : {
"street" : "Some street",
"number" : 123
}
}
},
"User example 2" : {
"summary" : "Another correctly configured user",
"value" : {
"name" : "Dave",
"address" : {
"street" : "Some street",
"number" : 123
}
}
}
}
}
}
}
}
}
},
"/address" : {
"get" : {
"summary" : "Get address",
"operationId" : "getAddress",
"responses" : {
"200" : {
"description" : "OK",
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/ExampleAddress"
},
"examples" : {
"Address example" : {
"summary" : "A correctly configured address",
"value" : {
"street" : "Some street",
"number" : 123
}
}
}
}
}
}
}
}
}
},
"components" : {
"schemas" : {
"ExampleAddress" : {
"required" : [ "number", "street" ],
"type" : "object",
"properties" : {
"street" : {
"type" : "string"
},
"number" : {
"type" : "integer",
"format" : "int32"
}
}
},
"ExampleUser" : {
"required" : [ "address", "name" ],
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"address" : {
"$ref" : "#/components/schemas/ExampleAddress"
}
}
}
}
}
}
""".trimIndent()
class TestOpenApiExample {
private fun createApp(openApiPlugin: OpenApiPlugin) = Javalin.create {
it.registerPlugin(openApiPlugin)
}.apply {
get("/user", documented(document().result<ExampleUser>("200")) {})
get("/address", documented(document().result<ExampleAddress>("200")) {})
}
@Test
fun `examples are generated when added in addExample, and class can have multiple examples`() {
val app = createApp(OpenApiPlugin(OpenApiOptions(Info()).apply {
addExample<ExampleUser>("User example", examples[ExampleUser::class.java]!!["User example"]!!)
addExample<ExampleUser>("User example 2", examples[ExampleUser::class.java]!!["User example 2"]!!)
addExample<ExampleAddress>("Address example", examples[ExampleAddress::class.java]!!["Address example"]!!)
}))
val openApiJson = JavalinOpenApi.createSchema(app).asJsonString()
assertThat(openApiJson).isEqualTo(expectedJson.formatJson())
openApiExamples.clear()
}
@Test
fun `examples are generated when added as a map`() {
val app = createApp(OpenApiPlugin(OpenApiOptions(Info()).apply {
examples(examples)
}))
val openApiJson = JavalinOpenApi.createSchema(app).asJsonString()
assertThat(openApiJson).isEqualTo(expectedJson.formatJson())
openApiExamples.clear()
}
}
| apache-2.0 | fbc71b670b00b695a11f072a72f83310 | 32.289017 | 118 | 0.435145 | 4.909633 | false | false | false | false |
aleksey-zhidkov/jeb-k | src/test/kotlin/jeb/ddsl/DirDescr.kt | 1 | 989 | package jeb.ddsl
import java.io.File
class DirDescr(name: File) : Node(name) {
private val nodes = arrayListOf<Node>()
fun file(name: String, content: () -> String) {
nodes.add(FileDescr(File(this.name, name), content))
}
fun dir(name: String, content: DirDescr.() -> Unit) {
val dir = DirDescr(File(this.name, name))
nodes.add(dir)
dir.content()
}
override fun create() {
name.mkdirs()
nodes.forEach { it.create() }
}
override fun contentEqualTo(file: File): Boolean {
if (file.isDirectory) {
val files = file.listFiles()
return files.all { f ->
val node = nodes.find { it.name.name == f.name }
node?.contentEqualTo(f) ?: false
}
} else {
return false
}
}
}
inline fun dir(name: File, content: DirDescr.() -> Unit): DirDescr {
val dir = DirDescr(name)
dir.content()
return dir
}
| apache-2.0 | 337011e07228424bbe6160b13904310b | 22.547619 | 68 | 0.544995 | 3.760456 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/roof_shape/AddRoofShape.kt | 1 | 2643 | package de.westnordost.streetcomplete.quests.roof_shape
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.CountryInfos
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BUILDING
class AddRoofShape(private val countryInfos: CountryInfos) : OsmElementQuestType<RoofShape> {
private val filter by lazy { """
ways, relations with (building:levels or roof:levels)
and !roof:shape and !3dr:type and !3dr:roof
and building and building!=no and building!=construction
""".toElementFilterExpression() }
override val commitMessage = "Add roof shapes"
override val wikiLink = "Key:roof:shape"
override val icon = R.drawable.ic_quest_roof_shape
override val defaultDisabledMessage = R.string.default_disabled_msg_roofShape
override val questTypeAchievements = listOf(BUILDING)
override fun getTitle(tags: Map<String, String>) = R.string.quest_roofShape_title
override fun createForm() = AddRoofShapeForm()
override fun applyAnswerTo(answer: RoofShape, changes: StringMapChangesBuilder) {
changes.add("roof:shape", answer.osmValue)
}
override fun getApplicableElements(mapData: MapDataWithGeometry) =
mapData.filter { element ->
filter.matches(element)
&& (
element.tags["roof:levels"]?.toFloatOrNull() ?: 0f > 0f
|| roofsAreUsuallyFlatAt(element, mapData) == false
)
}
override fun isApplicableTo(element: Element): Boolean? {
if (!filter.matches(element)) return false
/* if it has 0 roof levels, or the roof levels aren't specified,
the quest should only be shown in certain countries. But whether
the element is in a certain country cannot be ascertained without the element's geometry */
if (element.tags["roof:levels"]?.toFloatOrNull() ?: 0f == 0f) return null
return true
}
private fun roofsAreUsuallyFlatAt(element: Element, mapData: MapDataWithGeometry): Boolean? {
val center = mapData.getGeometry(element.type, element.id)?.center ?: return null
return countryInfos.get(center.longitude, center.latitude).isRoofsAreUsuallyFlat
}
}
| gpl-3.0 | 84373e233dd08eef41c93cb0f50c9117 | 45.368421 | 102 | 0.730609 | 4.636842 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/activity/AddGroupParticipantsActivity.kt | 1 | 5566 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.view.activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import com.toshi.R
import com.toshi.extensions.addHorizontalLineDivider
import com.toshi.extensions.isVisible
import com.toshi.extensions.toast
import com.toshi.model.local.User
import com.toshi.view.adapter.SelectGroupParticipantAdapter
import com.toshi.view.adapter.listeners.TextChangedListener
import com.toshi.viewModel.AddGroupParticipantsViewModel
import com.toshi.viewModel.ViewModelFactory.AddGroupParticipantsViewModelFactory
import kotlinx.android.synthetic.main.view_group_participants.*
class AddGroupParticipantsActivity : AppCompatActivity() {
companion object {
const val EXTRA__GROUP_ID = "extra_group_id"
}
private lateinit var viewModel: AddGroupParticipantsViewModel
private lateinit var userAdapter: SelectGroupParticipantAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.view_group_participants)
init()
}
private fun init() {
initView()
initViewModel()
initRecyclerView()
initClickListeners()
initObservers()
}
private fun initView() {
toolbarTitle.setText(R.string.add_participants)
next.setText(R.string.done)
}
private fun initViewModel() {
val groupId = getGroupIdFromIntent()
if (groupId == null) {
toast(R.string.invalid_group)
finish()
return
}
viewModel = ViewModelProviders.of(
this,
AddGroupParticipantsViewModelFactory(groupId)
).get(AddGroupParticipantsViewModel::class.java)
}
private fun initClickListeners() {
closeButton.setOnClickListener { finish() }
clearButton.setOnClickListener { search.text = null }
next.setOnClickListener { handleDoneClicked() }
}
private fun handleDoneClicked() {
val groupId = getGroupIdFromIntent()
groupId?.let { viewModel.updateGroup(it) } ?: toast(R.string.invalid_group)
}
private fun initRecyclerView() {
initAdapter()
searchResults.apply {
layoutManager = LinearLayoutManager(this.context)
itemAnimator = DefaultItemAnimator()
adapter = userAdapter
addHorizontalLineDivider()
}
}
private fun initAdapter() {
userAdapter = SelectGroupParticipantAdapter().setOnItemClickListener(this::handleUserClicked)
val selectedUsers = viewModel.selectedParticipants.value ?: emptyList()
userAdapter.setSelectedUsers(selectedUsers)
}
private fun handleUserClicked(user: User) {
userAdapter.addOrRemoveUser(user)
viewModel.toggleSelectedParticipant(user)
}
private fun initObservers() {
initSearch()
viewModel.searchResults.value.let { handleSearchResults(it.orEmpty()) }
viewModel.searchResults.observe(this, Observer { searchResults ->
searchResults?.let { handleSearchResults(it) }
})
viewModel.selectedParticipants.observe(this, Observer { selectedParticipants ->
selectedParticipants?.let { handleSelectedParticipants(it) }
})
viewModel.isUpdatingGroup.observe(this, Observer {
isUpdatingGroup -> isUpdatingGroup?.let { loadingSpinner.isVisible(it) }
})
viewModel.participantsAdded.observe(this, Observer { finish() })
viewModel.error.observe(this, Observer {
errorMessage -> errorMessage?.let { toast(it) }
})
}
private fun initSearch() {
search.addTextChangedListener(object : TextChangedListener() {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
clearButton.isVisible(s.toString().isNotEmpty())
viewModel.queryUpdated(s)
}
})
}
private fun handleSearchResults(searchResults: List<User>) = userAdapter.setUsers(searchResults)
private fun handleSelectedParticipants(selectedParticipants: List<User>) {
next.isVisible(selectedParticipants.isNotEmpty())
participants.text = getParticipantsAsString(selectedParticipants)
}
private fun getParticipantsAsString(selectedParticipants: List<User>): String {
return selectedParticipants.joinToString(
separator = ", ",
transform = { it.displayName }
)
}
private fun getGroupIdFromIntent(): String? = intent.getStringExtra(GroupInfoActivity.EXTRA__GROUP_ID)
} | gpl-3.0 | c05410382c1e699f9872cabe0ae3dd45 | 35.385621 | 106 | 0.690622 | 4.916961 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/NewPlayPlayerWinFragment.kt | 1 | 6146 | package com.boardgamegeek.ui
import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentNewPlayPlayerWinBinding
import com.boardgamegeek.databinding.RowNewPlayPlayerWinBinding
import com.boardgamegeek.entities.NewPlayPlayerEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.ui.dialog.NewPlayerScoreNumberPadDialogFragment
import com.boardgamegeek.ui.viewmodel.NewPlayViewModel
import kotlin.properties.Delegates
class NewPlayPlayerWinFragment : Fragment() {
private var _binding: FragmentNewPlayPlayerWinBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<NewPlayViewModel>()
private val adapter: PlayersAdapter by lazy { PlayersAdapter(requireActivity(), viewModel) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentNewPlayPlayerWinBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.adapter = adapter
viewModel.addedPlayers.observe(viewLifecycleOwner) { entity ->
adapter.players = entity.sortedBy { it.seat }
}
binding.nextButton.setOnClickListener {
viewModel.finishPlayerWin()
}
}
override fun onResume() {
super.onResume()
(activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_winners)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
@SuppressLint("NotifyDataSetChanged")
private class PlayersAdapter(private val activity: FragmentActivity, private val viewModel: NewPlayViewModel) :
RecyclerView.Adapter<PlayersAdapter.PlayersViewHolder>() {
var players: List<NewPlayPlayerEntity> by Delegates.observable(emptyList()) { _, _, _ ->
// using a DiffUtil causes too many crashes
notifyDataSetChanged()
}
init {
setHasStableIds(true)
}
override fun getItemCount() = players.size
override fun getItemId(position: Int): Long {
return players.getOrNull(position)?.id?.hashCode()?.toLong() ?: RecyclerView.NO_ID
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayersViewHolder {
return PlayersViewHolder(parent.inflate(R.layout.row_new_play_player_win))
}
override fun onBindViewHolder(holder: PlayersViewHolder, position: Int) {
holder.bind(position)
}
inner class PlayersViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = RowNewPlayPlayerWinBinding.bind(itemView)
fun bind(position: Int) {
val entity = players.getOrNull(position)
entity?.let { player ->
binding.nameView.text = player.name
binding.usernameView.setTextOrHide(player.username)
if (player.color.isBlank()) {
binding.colorView.isInvisible = true
binding.teamView.isVisible = false
binding.seatView.setTextColor(Color.TRANSPARENT.getTextColor())
} else {
val color = player.color.asColorRgb()
if (color == Color.TRANSPARENT) {
binding.colorView.isInvisible = true
binding.teamView.setTextOrHide(player.color)
} else {
binding.colorView.setColorViewValue(color)
binding.colorView.isVisible = true
binding.teamView.isVisible = false
}
binding.seatView.setTextColor(color.getTextColor())
}
if (player.seat == null) {
binding.sortView.setTextOrHide(player.sortOrder)
binding.seatView.isInvisible = true
} else {
binding.sortView.isVisible = false
binding.seatView.text = player.seat.toString()
binding.seatView.isVisible = true
}
binding.scoreView.text = player.getScoreDescription(itemView.context)
binding.scoreButton.setColorFilter(ContextCompat.getColor(itemView.context, R.color.button_under_text), PorterDuff.Mode.SRC_IN)
binding.scoreButton.setSelectableBackgroundBorderless()
binding.scoreButton.setOnClickListener { score(player) }
binding.winCheckBox.isChecked = player.isWin
binding.winCheckBox.setOnCheckedChangeListener { _, isChecked ->
viewModel.addWinToPlayer(player.id, isChecked)
binding.winCheckBox.setOnCheckedChangeListener { _, _ -> }
}
}
}
}
private fun score(player: NewPlayPlayerEntity) {
NewPlayerScoreNumberPadDialogFragment.newInstance(
player.id,
player.score,
player.color,
player.description
).show(activity.supportFragmentManager, "score_dialog")
}
}
}
| gpl-3.0 | e1a265a23bf54f6b50b8d92974faa796 | 39.701987 | 147 | 0.637162 | 5.414978 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/PageStore.kt | 2 | 12517 | package org.wordpress.android.fluxc.store
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.PostActionBuilder
import org.wordpress.android.fluxc.model.CauseOfOnPostChanged
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.page.PageModel
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.network.utils.CurrentDateUtils
import org.wordpress.android.fluxc.persistence.PostSqlUtils
import org.wordpress.android.fluxc.store.PageStore.OnPageChanged.Error
import org.wordpress.android.fluxc.store.PageStore.UploadRequestResult.ERROR_NON_EXISTING_PAGE
import org.wordpress.android.fluxc.store.PageStore.UploadRequestResult.SUCCESS
import org.wordpress.android.fluxc.store.PostStore.FetchPostsPayload
import org.wordpress.android.fluxc.store.PostStore.OnPostChanged
import org.wordpress.android.fluxc.store.PostStore.PostError
import org.wordpress.android.fluxc.store.PostStore.PostErrorType.UNKNOWN_POST
import org.wordpress.android.fluxc.store.PostStore.RemotePostPayload
import org.wordpress.android.fluxc.store.Store.OnChanged
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.DateTimeUtils
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
@Singleton
class PageStore @Inject constructor(
private val postStore: PostStore,
private val postSqlUtils: PostSqlUtils,
private val dispatcher: Dispatcher,
private val currentDateUtils: CurrentDateUtils,
private val coroutineEngine: CoroutineEngine
) {
companion object {
val PAGE_TYPES = listOf(
PostStatus.DRAFT,
PostStatus.PUBLISHED,
PostStatus.SCHEDULED,
PostStatus.PENDING,
PostStatus.PRIVATE,
PostStatus.TRASHED
)
}
private var postLoadContinuations: MutableList<Continuation<OnPageChanged>> = mutableListOf()
private var deletePostContinuation: Continuation<OnPageChanged>? = null
private var updatePostContinuation: Continuation<OnPageChanged>? = null
private var lastFetchTime: Calendar? = null
private var fetchingSite: SiteModel? = null
init {
dispatcher.register(this)
}
suspend fun getPageByLocalId(pageId: Int, site: SiteModel): PageModel? =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "getPageByLocalId") {
val post = postStore.getPostByLocalPostId(pageId)
return@withDefaultContext post?.let {
PageModel(it, site, getPageByRemoteId(it.parentId, site))
}
}
suspend fun getPageByRemoteId(remoteId: Long, site: SiteModel): PageModel? =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "getPageByRemoteId") {
if (remoteId <= 0L) {
return@withDefaultContext null
}
val post = postStore.getPostByRemotePostId(remoteId, site)
return@withDefaultContext post?.let {
PageModel(it, site, getPageByRemoteId(it.parentId, site))
}
}
suspend fun search(site: SiteModel, searchQuery: String): List<PageModel> =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "search") {
getPagesFromDb(site).filter {
it.title.toLowerCase(Locale.ROOT)
.contains(searchQuery.toLowerCase(Locale.ROOT))
}
}
suspend fun updatePageInDb(page: PageModel): OnPageChanged = suspendCoroutine { cont ->
val post = postStore.getPostByRemotePostId(page.remoteId, page.site)
?: postStore.getPostByLocalPostId(page.pageId)
if (post != null) {
post.updatePageData(page)
val updateAction = PostActionBuilder.newUpdatePostAction(post)
updatePostContinuation = cont
dispatcher.dispatch(updateAction)
} else {
cont.resume(Error(PostError(UNKNOWN_POST)))
}
}
suspend fun uploadPageToServer(page: PageModel): UploadRequestResult =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "uploadPageToServer") {
val post = postStore.getPostByRemotePostId(page.remoteId, page.site)
?: postStore.getPostByLocalPostId(page.pageId)
if (post != null) {
post.updatePageData(page)
val action = PostActionBuilder.newPushPostAction(RemotePostPayload(post, page.site))
dispatcher.dispatch(action)
return@withDefaultContext SUCCESS
} else {
return@withDefaultContext ERROR_NON_EXISTING_PAGE
}
}
enum class UploadRequestResult {
SUCCESS,
ERROR_NON_EXISTING_PAGE
}
suspend fun getPagesFromDb(site: SiteModel): List<PageModel> {
// We don't want to return data from the database when it's still being loaded
if (postLoadContinuations.isNotEmpty()) {
return listOf()
}
return coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "getPagesFromDb") {
val posts = postStore.getPagesForSite(site)
.asSequence()
.filterNotNull()
.filter { PAGE_TYPES.contains(PostStatus.fromPost(it)) }
.map {
// local DB pages have a non-unique remote ID value of 0
// to keep the apart we replace it with page ID (still unique)
// and make it negative (to easily tell it's a temporary value)
if (it.remotePostId == 0L) {
/**
* This hack is breaking the approach which we use for making sure we upload only changes
* which were explicitly confirmed by the user. We are modifying the PostModel and we need
* to make sure to retain the confirmation.
*/
val changesConfirmed = it.contentHashcode() == it.changesConfirmedContentHashcode
it.setRemotePostId(-it.id.toLong())
if (changesConfirmed) {
it.setChangesConfirmedContentHashcode(it.contentHashcode())
}
}
it
}
.associateBy { it.remotePostId }
return@withDefaultContext posts.map { getPageFromPost(it.key, site, posts, false) }
.filterNotNull()
.sortedBy { it.remoteId }
}
}
private fun getPageFromPost(
postId: Long,
site: SiteModel,
posts: Map<Long, PostModel>,
skipLocalPages: Boolean = true
): PageModel? {
if (skipLocalPages && (postId <= 0L || !posts.containsKey(postId))) {
return null
}
val post = posts[postId]!!
return PageModel(post, site, getPageFromPost(post.parentId, site, posts))
}
suspend fun deletePageFromServer(page: PageModel): OnPageChanged = suspendCoroutine { cont ->
val post = postStore.getPostByLocalPostId(page.pageId)
if (post != null) {
deletePostContinuation = cont
val payload = RemotePostPayload(post, page.site)
dispatcher.dispatch(PostActionBuilder.newDeletePostAction(payload))
} else {
cont.resume(Error(PostError(UNKNOWN_POST)))
}
}
suspend fun deletePageFromDb(page: PageModel): Boolean =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "deletePageFromDb") {
val post = postStore.getPostByLocalPostId(page.pageId)
return@withDefaultContext if (post != null) {
postSqlUtils.deletePost(post) > 0
} else {
false
}
}
suspend fun requestPagesFromServer(site: SiteModel, forced: Boolean): OnPageChanged {
if (!forced && hasRecentCall() && getPagesFromDb(site).isNotEmpty()) {
return OnPageChanged.Success
}
return suspendCoroutine { cont ->
fetchingSite = site
if (postLoadContinuations.isEmpty()) {
lastFetchTime = currentDateUtils.getCurrentCalendar()
fetchPages(site, false)
}
postLoadContinuations.add(cont)
}
}
private fun hasRecentCall(): Boolean {
val currentCalendar = currentDateUtils.getCurrentCalendar()
currentCalendar.add(Calendar.HOUR, -1)
return lastFetchTime?.after(currentCalendar) ?: false
}
/**
* Get local draft pages that have not been uploaded to the server yet.
*
* This returns [PostModel] instead of [PageModel] to accommodate the `UploadService` in WPAndroid which relies
* heavily on [PostModel]. When `UploadService` gets refactored, we should change this back to using [PageModel].
*/
suspend fun getLocalDraftPages(site: SiteModel): List<PostModel> =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "getLocalDraftPages") {
return@withDefaultContext postSqlUtils.getLocalDrafts(site.id, true)
}
/**
* Get pages that have not been uploaded to the server yet.
*
* This returns [PostModel] instead of [PageModel] to accommodate the `UploadService` in WPAndroid which relies
* heavily on [PostModel]. When `UploadService` gets refactored, we should change this back to using [PageModel].
*/
suspend fun getPagesWithLocalChanges(site: SiteModel): List<PostModel> =
coroutineEngine.withDefaultContext(AppLog.T.POSTS, this, "getPagesWithLocalChanges") {
return@withDefaultContext postSqlUtils.getPostsWithLocalChanges(site.id, true)
}
private fun fetchPages(site: SiteModel, loadMore: Boolean) {
val payload = FetchPostsPayload(site, loadMore, PAGE_TYPES)
dispatcher.dispatch(PostActionBuilder.newFetchPagesAction(payload))
}
@SuppressWarnings("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onPostChanged(event: OnPostChanged) {
when (event.causeOfChange) {
is CauseOfOnPostChanged.FetchPages -> {
if (event.canLoadMore && fetchingSite != null) {
fetchPages(fetchingSite!!, true)
} else {
val onPageChanged = event.toOnPageChangedEvent()
postLoadContinuations.forEach { it.resume(onPageChanged) }
postLoadContinuations.clear()
fetchingSite = null
}
}
is CauseOfOnPostChanged.DeletePost -> {
deletePostContinuation?.resume(event.toOnPageChangedEvent())
deletePostContinuation = null
}
is CauseOfOnPostChanged.UpdatePost -> {
updatePostContinuation?.resume(event.toOnPageChangedEvent())
updatePostContinuation = null
}
else -> {
}
}
}
private fun PostModel.updatePageData(page: PageModel) {
this.setId(page.pageId)
this.setTitle(page.title)
this.setStatus(page.status.toPostStatus().toString())
this.setParentId(page.parent?.remoteId ?: 0)
this.setRemotePostId(page.remoteId)
this.setDateCreated(DateTimeUtils.iso8601FromDate(page.date))
}
sealed class OnPageChanged : OnChanged<PostError>() {
object Success : OnPageChanged()
data class Error(val postError: PostError) : OnPageChanged() {
init {
this.error = postError
}
}
}
private fun OnPostChanged.toOnPageChangedEvent(): OnPageChanged {
return if (this.isError) Error(this.error) else OnPageChanged.Success
}
}
| gpl-2.0 | 419fa57b70c8c7b619587a479a261ff7 | 42.013746 | 118 | 0.630742 | 4.959192 | false | false | false | false |
BasinMC/Basin | faucet/src/main/kotlin/org/basinmc/faucet/extension/manifest/ExtensionFlags.kt | 1 | 1405 | /*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.faucet.extension.manifest
import org.basinmc.faucet.util.BitMask
/**
* Provides a list of valid extension flags which express additional information about a build.
*
* @author [Johannes Donath](mailto:[email protected])
*/
class ExtensionFlags(mask: Int) : BitMask<ExtensionFlags>(mask) {
override val definition = Companion
companion object : Definition<ExtensionFlags> {
// 1 - 8 are reserved
val PRIVATE = ExtensionFlags(16)
val COMMERCIAL = ExtensionFlags(32)
// 64 is reserved
val CI_BUILD = ExtensionFlags(128)
override val values = listOf(PRIVATE, COMMERCIAL, CI_BUILD)
override fun newInstance(mask: Int) = ExtensionFlags(mask)
}
}
| apache-2.0 | b186184a878fdfba8f6424b790a46bb2 | 32.452381 | 95 | 0.737367 | 4.132353 | false | false | false | false |
songzhw/Hello-kotlin | KotlinPlayground/src/main/kotlin/ca/six/klplay/okhttp/download/DownloadDemo.kt | 1 | 919 | package ca.six.klplay.okhttp.download
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import okhttp3.*
import java.io.IOException
import sun.security.krb5.Confounder.bytes
import com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.close
import okio.Okio
import okio.BufferedSink
import java.io.File
fun downloadPic() {
val request = Request.Builder()
.url("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2859174087,963187950&fm=23&gp=0.jpg")
.build()
val http = OkHttpClient.Builder().build()
val response = http.newCall(request).execute()
val downloadedFile = File("E:/tmp/test.jpg")
if(!downloadedFile.exists()){
downloadedFile.createNewFile()
}
val sink = Okio.buffer(Okio.sink(downloadedFile))
sink.writeAll(response.body()!!.source())
sink.close()
}
fun main(args: Array<String>) {
downloadPic()
} | apache-2.0 | 8aedcaf13a916c2e59523f9d32a665c0 | 26.058824 | 113 | 0.718172 | 3.403704 | false | false | false | false |
tommykw/TV | app/src/main/kotlin/com/github/tommykw/tv/util/Utils.kt | 1 | 1696 | package com.github.tommykw.tv.util
import android.content.Context
import android.graphics.Point
import android.view.WindowManager
import android.widget.Toast
class Utils {
companion object {
@JvmStatic
fun getDisplaySize(context: Context): Point {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val size = Point()
val display = wm.defaultDisplay.getSize(size)
return size
}
@JvmStatic
fun showToast(context: Context, msg: String) =
Toast.makeText(context, msg, Toast.LENGTH_LONG).show()
@JvmStatic
fun showToast(context: Context, resourceId: Int) =
Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show()
@JvmStatic
fun convertDpToPixel(ctx: Context, dp: Int) =
Math.round(dp.toFloat() * ctx.resources.displayMetrics.density)
@JvmStatic
fun formatMillis(millis: Int): String {
var millis = millis
var result = ""
val hr = millis / 3600000
millis %= 3600000
val min = millis / 60000
millis %= 60000
val sec = millis / 1000
if (hr > 0) {
result += "${hr}:"
}
if (min >= 0) {
if (min > 9) {
result += "${min}:"
} else {
result += "0${min}:"
}
}
if (sec > 9) {
result += sec
} else {
result += "0${sec}"
}
return result
}
}
} | apache-2.0 | add535836c537670b08a3b24a1d97bc5 | 28.77193 | 96 | 0.5 | 4.818182 | false | false | false | false |
googleapis/gapic-generator-kotlin | generator/src/test/kotlin/com/google/api/kotlin/generator/grpc/FunctionsImplTest.kt | 1 | 5714 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin.generator.grpc
import com.google.api.kotlin.ClientPluginOptions
import com.google.api.kotlin.DescriptorProto
import com.google.api.kotlin.FieldDescriptorProto
import com.google.api.kotlin.FileDescriptorProto
import com.google.api.kotlin.GeneratorContext
import com.google.api.kotlin.MethodDescriptorProto
import com.google.api.kotlin.ServiceDescriptorProto
import com.google.api.kotlin.asNormalizedString
import com.google.api.kotlin.config.Configuration
import com.google.api.kotlin.config.MethodOptions
import com.google.api.kotlin.config.ProtobufTypeMapper
import com.google.api.kotlin.config.ServiceOptions
import com.google.common.truth.Truth.assertThat
import com.google.protobuf.DescriptorProtos
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.anyOrNull
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.whenever
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import kotlin.test.BeforeTest
import kotlin.test.Test
/**
* Tests basic functionality.
*
* more complex tests use the test protos in [GRPCGeneratorTest].
*/
internal class FunctionsImplTest {
private val documentationGenerator: Documentation = mock()
private val unitTestGenerator: UnitTest = mock()
private val proto: DescriptorProtos.FileDescriptorProto = mock()
private val service: DescriptorProtos.ServiceDescriptorProto = mock()
private val meta: Configuration = mock()
private val options: ServiceOptions = mock()
private val types: ProtobufTypeMapper = mock()
private val ctx: GeneratorContext = mock()
@BeforeTest
fun before() {
reset(documentationGenerator, unitTestGenerator, proto, service, meta, options, types, ctx)
whenever(ctx.className).doReturn(ClassName("prepare", "me"))
whenever(ctx.proto).doReturn(proto)
whenever(ctx.service).doReturn(service)
whenever(ctx.typeMap).doReturn(types)
whenever(ctx.metadata).doReturn(meta)
whenever(ctx.metadata.get(any<String>())).doReturn(options)
whenever(ctx.commandLineOptions).doReturn(ClientPluginOptions(authGoogleCloud = true))
whenever(options.methods).doReturn(listOf<MethodOptions>())
whenever(documentationGenerator.getClientInitializer(ctx)).doReturn(CodeBlock.of("--INIT--"))
}
@Test
fun `Generates the prepare fun`() {
whenever(types.getKotlinType(".foo.bar.ZaInput")).doReturn(
ClassName("foo.bar", "ZaInput")
)
whenever(types.getKotlinType(".foo.bar.ZaOutput")).doReturn(
ClassName("foo.bar", "ZaOutput")
)
whenever(types.getProtoTypeDescriptor(any())).doReturn(DescriptorProto {
addField(FieldDescriptorProto {
name = "da_field"
type = DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING
})
})
whenever(
documentationGenerator.generateMethodKDoc(
eq(ctx), any(), any(), any(), anyOrNull(), any()
)
).doReturn(CodeBlock.of("some docs"))
val opts: ServiceOptions = mock()
whenever(meta.get(any<String>())).doReturn(opts)
whenever(meta.get(any<DescriptorProtos.ServiceDescriptorProto>())).doReturn(opts)
whenever(ctx.className).doReturn(ClassName("foo.bar", "ZaTest"))
whenever(ctx.proto).doReturn(
FileDescriptorProto {
name = "my-file"
})
whenever(ctx.service).doReturn(
ServiceDescriptorProto {
addMethod(MethodDescriptorProto {
name = "FunFunction"
inputType = ".foo.bar.ZaInput"
outputType = ".foo.bar.ZaOutput"
})
})
val result = FunctionsImpl(documentationGenerator, unitTestGenerator).generate(ctx)
val prepareFun = result.first { it.function.name == "prepare" }
assertThat(prepareFun.function.toString().asNormalizedString()).isEqualTo(
"""
|/**
|* Prepare for an API call by setting any desired options. For example:
|*
|* ```
|* --INIT--
|* val response = client.prepare {
|* withMetadata("my-custom-header", listOf("some", "thing"))
|* }.funFunction(request)
|* ```
|*
|* You may save the client returned by this call and reuse it if you
|* plan to make multiple requests with the same settings.
|*/
|fun prepare(init: com.google.api.kgax.grpc.ClientCallOptions.Builder.() -> kotlin.Unit): foo.bar.ZaTest {
| val optionsBuilder = com.google.api.kgax.grpc.ClientCallOptions.Builder(options)
| optionsBuilder.init()
| return foo.bar.ZaTest(channel, optionsBuilder.build())
|}
|""".asNormalizedString()
)
}
}
| apache-2.0 | 4726cb4288beb0b77f8d56e36c99bbd1 | 40.107914 | 118 | 0.671334 | 4.582197 | false | true | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/editor/autocompile/AutoCompileState.kt | 1 | 2895 | package nl.hannahsten.texifyidea.editor.autocompile
import com.intellij.execution.ExecutionManager
import com.intellij.execution.ExecutionTargetManager
import com.intellij.execution.RunManager
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import nl.hannahsten.texifyidea.run.latex.LatexRunConfiguration
/**
* State of autocompilation.
*
* Both the run configuration and the typedhandler should be able to access the same state, so we can run the correct run config for the correct file.
*/
object AutoCompileState {
/** Whether an autocompile is in progress. */
private var isCompiling = false
/** Whether the document has changed since the last triggered autocompile. */
private var hasChanged = false
/** Needed to get the selected run config. */
private var project: Project? = null
/**
* Tell the state the document has been changed by the user.
*/
@Synchronized
fun documentChanged(project: Project) {
this.project = project
// Remember that the document changed, so a compilation should be scheduled later
if (isCompiling) {
hasChanged = true
}
else {
scheduleCompilation()
}
}
/**
* Tell the state a compilation has just finished.
*/
@Synchronized
fun compileDone() {
// Only compile again if needed
if (hasChanged) {
scheduleCompilation()
}
else {
isCompiling = false
}
}
private fun scheduleCompilation() {
if (project == null) {
Notification("LaTeX", "Could not auto-compile", "Please make sure you have compiled the document first.", NotificationType.WARNING).notify(null)
return
}
isCompiling = true
hasChanged = false
// Get run configuration selected in the combobox and run that one
if (project!!.isDisposed) return
val runConfigSettings = RunManager.getInstance(project!!).selectedConfiguration
if (runConfigSettings?.configuration !is LatexRunConfiguration) {
Notification("LaTeX", "Could not auto-compile", "Please make sure you have a valid LaTeX run configuration selected.", NotificationType.WARNING).notify(null)
return
}
// Changing focus would interrupt the user during typing
(runConfigSettings.configuration as LatexRunConfiguration).allowFocusChange = false
ExecutionManager.getInstance(project!!).restartRunProfile(
project!!,
DefaultRunExecutor.getRunExecutorInstance(),
ExecutionTargetManager.getInstance(project!!).activeTarget,
runConfigSettings,
null
)
}
} | mit | df9c8df922dc7f4912f7dadc9f1e8a16 | 31.177778 | 169 | 0.673921 | 5.302198 | false | true | false | false |
SimonVT/cathode | trakt-api/src/main/java/net/simonvt/cathode/api/Authorization.kt | 1 | 1202 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.api
object Authorization {
private const val AUTHORIZATION_URL = "https://trakt.tv/oauth/authorize"
// TODO: Pass some secret as state?
@JvmStatic
fun getOAuthUri(applicationId: String, redirectUri: String): String {
return "$AUTHORIZATION_URL?response_type=code&client_id=$applicationId&redirect_uri=$redirectUri"
}
@JvmStatic
fun getOAuthUri(applicationId: String, redirectUri: String, username: String): String {
return "$AUTHORIZATION_URL?response_type=code&client_id=$applicationId&redirect_uri=$redirectUri&username=$username"
}
}
| apache-2.0 | 3b94ff109019014f8906cc48a77b24ab | 35.424242 | 120 | 0.74792 | 4.130584 | false | false | false | false |
Kushki/kushki-android | kushki/src/main/java/com/kushkipagos/auth/KushkiAuth.kt | 1 | 9741 | package com.kushkipagos.auth
import android.content.Context
import android.util.Log
import com.amplifyframework.AmplifyException
import com.amplifyframework.auth.AuthChannelEventName
import com.amplifyframework.auth.AuthException
import com.amplifyframework.auth.AuthUserAttribute
import com.amplifyframework.auth.AuthUserAttributeKey
import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin
import com.amplifyframework.auth.cognito.AWSCognitoAuthSession
import com.amplifyframework.auth.options.AuthSignUpOptions
import com.amplifyframework.auth.result.AuthSessionResult
import com.amplifyframework.auth.result.AuthSignInResult
import com.amplifyframework.auth.result.AuthSignUpResult
import com.amplifyframework.core.Amplify
import com.amplifyframework.core.AmplifyConfiguration
import com.amplifyframework.core.InitializationStatus
import com.amplifyframework.hub.HubChannel
import com.amplifyframework.hub.HubEvent
import org.json.JSONObject
import java.net.URL
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.atomic.AtomicReference
class KushkiAuth(context: Context?=null) {
private val jwtToken = AtomicReference("")
private var context: Context? = context
private var email: String? = null
private var user_name: String? = null
private var conSuccessFunction: ((String) -> Unit)? = null
init {
initAmpliFy()
listenToAuthEvents()
}
@Throws(AmplifyException::class)
fun requestKpayInit(email: String?, name: String?, saveTokenFunction: (token: String) -> Unit, onFail: (error: String) -> Unit) {
this.email = email
this.user_name = name
this.conSuccessFunction = saveTokenFunction;
checkAuthSession(saveTokenFunction, onFail)
}
fun confirmSignUp(codeFromEmail: String?) {
Amplify.Auth.confirmSignUp(
email!!,
codeFromEmail!!,
{ result: AuthSignUpResult ->
Log.i(
"AuthQuickstart",
if (result.isSignUpComplete) "Confirm signUp succeeded" else "Confirm sign up not complete"
)
}
) { error: AuthException -> Log.e("AuthQuickstart", error.toString()) }
}
fun confirmSignIn(codeFromEmail: String, onSuccess: (token: String) -> Unit, onFail: (error: String) -> Unit) {
Amplify.Auth.confirmSignIn(
codeFromEmail,
{ result: AuthSignInResult ->
Log.i(
"AuthQuickstart",
if (result.isSignInComplete) "Confirm signUp succeeded" else "Confirm sign in not complete"
)
Amplify.Auth.fetchAuthSession(
{result ->
val cognitoAuthSession = result as AWSCognitoAuthSession
when (cognitoAuthSession.identityId.type) {
AuthSessionResult.Type.SUCCESS -> {
val userPoolTokens = cognitoAuthSession.userPoolTokens.value
if (userPoolTokens != null) {
onSuccess(userPoolTokens.accessToken)
};
jwtToken.lazySet(userPoolTokens!!.accessToken)
}
AuthSessionResult.Type.FAILURE -> {
onFail("Fail to fetch user data");
}
}
Log.i("", "")
},
{error ->
onFail(error.toString());
})
}
) { error: AuthException -> Log.e("AuthQuickstart", error.toString()) }
}
private fun listenToAuthEvents() {
Amplify.Hub.subscribe(
HubChannel.AUTH
) { hubEvent: HubEvent<*> ->
if (hubEvent.name == InitializationStatus.SUCCEEDED.toString()) {
Log.i("AuthQuickstart", "Auth successfully initialized")
} else if (hubEvent.name == InitializationStatus.FAILED.toString()) {
Log.i("AuthQuickstart", "Auth failed to succeed")
} else {
when (AuthChannelEventName.valueOf(hubEvent.name)) {
AuthChannelEventName.SIGNED_IN -> {
Log.i("AuthQuickstart", "Auth just became signed in.")
}
AuthChannelEventName.SIGNED_OUT -> Log.i(
"AuthQuickstart",
"Auth just became signed out."
)
AuthChannelEventName.SESSION_EXPIRED -> Log.i(
"AuthQuickstart",
"Auth session just expired."
)
else -> Log.w(
"AuthQuickstart",
"Unhandled Auth Event: " + AuthChannelEventName.valueOf(hubEvent.name)
)
}
}
}
}
@Throws(AmplifyException::class)
fun initAmpliFy() {
val configFromKushki = URL("https://user-personal-wallet-amplify-config.s3.amazonaws.com/amplifyconfiguration.json").readText()
System.out.println(configFromKushki.toString())
val configurationJson = JSONObject(configFromKushki)
val configuration = AmplifyConfiguration.fromJson(configurationJson)
Amplify.addPlugin(AWSCognitoAuthPlugin())
Amplify.configure(configuration, context!!)
}
fun checkAuthSession(saveTokenFunction: (token: String) -> Unit, onFail: (error: String) -> Unit) {
Amplify.Auth.fetchAuthSession(
{ result ->
val cognitoAuthSession = result as AWSCognitoAuthSession
when (cognitoAuthSession.identityId.type) {
AuthSessionResult.Type.SUCCESS -> {
Log.i(
"AuthQuickStart",
"IdentityId: " + cognitoAuthSession.identityId.value
)
val userPoolTokens = cognitoAuthSession.userPoolTokens.value
if (userPoolTokens != null) {
saveTokenFunction(userPoolTokens.accessToken)
};
jwtToken.lazySet(userPoolTokens!!.accessToken)
}
AuthSessionResult.Type.FAILURE -> {
// paswordless
Log.i(
"AuthQuickStart",
"IdentityId not present because: " + cognitoAuthSession.identityId.error.toString()
)
singUpANewUser(saveTokenFunction, onFail)
}
}
}
) { error ->
Log.e("AmplifyQuickstart", error.toString())
onFail(error.toString())
}
}
fun singUpANewUser(saveTokenFunction: (token: String) -> Unit, onFail: (error: String) -> Unit) {
val array = ByteArray(30)
Random().nextBytes(array)
val userAttributes: LinkedList<AuthUserAttribute> = LinkedList()
val givenNameAttribute: AuthUserAttribute =
AuthUserAttribute(AuthUserAttributeKey.givenName(), this.user_name)
val preferredNameAttribute: AuthUserAttribute =
AuthUserAttribute(AuthUserAttributeKey.email(), this.email)
userAttributes.add(givenNameAttribute)
userAttributes.add(preferredNameAttribute)
val randomPassword = String(array, Charset.forName("UTF-8"))
val options = AuthSignUpOptions.builder().userAttributes(userAttributes).build()
Amplify.Auth.signUp(
email!!,
randomPassword,
options,
{ result: AuthSignUpResult ->
Log.i("AuthQuickStart", "Result: $result")
singInAnUser(saveTokenFunction, onFail)
},
{ _: AuthException? -> singInAnUser(saveTokenFunction, onFail) }
)
}
fun singInAnUser(onSuccess: (token: String) -> Unit, onFail: (error: String) -> Unit ) {
Amplify.Auth.signIn(
email,
null,
{ result: AuthSignInResult ->
if (result.isSignInComplete) {
Amplify.Auth.fetchAuthSession({
result ->
val cognitoAuthSession = result as AWSCognitoAuthSession
when (cognitoAuthSession.identityId.type) {
AuthSessionResult.Type.SUCCESS -> {
val userPoolTokens = cognitoAuthSession.userPoolTokens.value
if (userPoolTokens != null) {
onSuccess(userPoolTokens.accessToken)
};
jwtToken.lazySet(userPoolTokens!!.accessToken)
}
AuthSessionResult.Type.FAILURE -> {
onFail("Error while signIn of new user")
}
}
}, {error -> {
onFail(error.toString())
}})
}
Log.i(
"AuthQuickstart",
if (result.isSignInComplete) "Sign in succeeded" else "Sign in not complete"
)
}
) { error: AuthException -> Log.e("AuthQuickstart", error.toString()) }
}
fun getUserTokenReference(): AtomicReference<String> {
return this.jwtToken;
}
} | mit | 92dd3c6da3de2892d1849a2b3e7fe5e4 | 39.090535 | 135 | 0.54789 | 5.003082 | false | false | false | false |
PtrTeixeira/cookbook | cookbook/models/src/main/kotlin/Recipe.kt | 2 | 767 | package com.github.ptrteixeira.cookbook.core
/**
* Represents a Recipe in the domain com.github.ptrteixeira.cookbook.model of this project.
*
* @property [id] Identifier in the database for this recipe
* @property [name] Name of this recipe when displayed
* @property [ingredients] What goes into the recipe?
* @property [instructions] How do you make this? Interpreted more in paragraph style than step style
* @property [summary] Long description of the recipe
* @property [description] Short description of the recipe
*/
data class Recipe(
val id: Int,
val userId: String,
val name: String = "",
val ingredients: List<String> = listOf(),
val instructions: String = "",
val summary: String = "",
val description: String = ""
)
| mit | 845d503dce9838e0316ca9cde2c7829b | 35.52381 | 101 | 0.710561 | 4.015707 | false | false | false | false |
colriot/anko | dsl/src/org/jetbrains/android/anko/sources/sourceProviders.kt | 2 | 1824 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.sources
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.CompilationUnit
import org.jetbrains.android.anko.utils.getPackageName
import sun.plugin.dom.exception.InvalidStateException
import java.io.File
interface SourceProvider {
fun parse(fqName: String): CompilationUnit?
}
class AndroidHomeSourceProvider(version: Int) : SourceProvider {
private val baseDir: File
init {
val androidHome = System.getenv("ANDROID_HOME")
?: throw InvalidStateException("ANDROID_HOME environment variable is not defined")
baseDir = File(androidHome, "sources/android-$version")
if (!baseDir.exists()) throw InvalidStateException("${baseDir.absolutePath} does not exist")
}
override fun parse(fqName: String): CompilationUnit? {
val packageName = getPackageName(fqName)
val packageDir = File(baseDir, packageName.replace('.', '/'))
if (!packageDir.exists()) return null
val filename = fqName.substring(packageName.length + 1).substringBefore('.') + ".java"
val file = File(packageDir, filename)
if (!file.exists()) return null
return JavaParser.parse(file)
}
} | apache-2.0 | 0211b66f184b4ef8d540f9a132598a97 | 35.5 | 100 | 0.71875 | 4.459658 | false | false | false | false |
jereksel/LibreSubstratum | app/src/main/kotlin/com/jereksel/libresubstratum/activities/installed/InstalledPresenter.kt | 1 | 5742 | /*
* Copyright (C) 2017 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.activities.installed
import com.jereksel.libresubstratum.activities.installed.InstalledContract.Presenter
import com.jereksel.libresubstratum.data.InstalledOverlay
import com.jereksel.libresubstratum.domain.IActivityProxy
import com.jereksel.libresubstratum.domain.IPackageManager
import com.jereksel.libresubstratum.domain.Metrics
import com.jereksel.libresubstratum.domain.OverlayService
import com.jereksel.libresubstratum.extensions.getLogger
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.experimental.guava.await
class InstalledPresenter(
val packageManager: IPackageManager,
val overlayService: OverlayService,
val activityProxy: IActivityProxy,
val metrics: Metrics
) : Presenter() {
val log = getLogger()
private var subscription: Disposable? = null
private var overlays: MutableList<InstalledOverlay>? = null
private var filter = ""
private var state: MutableMap<String, Boolean>? = null
override fun getInstalledOverlays() {
val o = overlays
if (o != null) {
view.get()?.addOverlays(o)
return
}
subscription = Observable.fromCallable { packageManager.getInstalledOverlays() }
.subscribeOn(Schedulers.computation())
.observeOn(Schedulers.computation())
.map {
it.sortedWith(compareBy({ it.sourceThemeName.toLowerCase() }, { it.targetName.toLowerCase() }, { it.type1a },
{ it.type1b }, { it.type1c }, { it.type2 }, { it.type3 }))
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
overlays = it.toMutableList()
state = it.map { Pair(it.overlayId, false) }.toMap().toMutableMap()
view.get()?.addOverlays(getFilteredApps())
}
}
suspend override fun toggleOverlay(overlayId: String, enabled: Boolean) {
if (enabled) {
overlayService.enableOverlay(overlayId).await()
} else {
overlayService.disableOverlay(overlayId).await()
}
view.get()?.refreshRecyclerView()
if (overlayId.startsWith("com.android.systemui")) {
view.get()?.showSnackBar("This change requires SystemUI restart", "Restart SystemUI", { overlayService.restartSystemUI() })
}
}
private fun selectedOverlays() = (overlays ?: emptyList<InstalledOverlay>()).filter { overlay -> state?.get(overlay.overlayId) == true }
override suspend fun uninstallSelected() {
val toUninstall = selectedOverlays()
for (pckg in toUninstall) {
overlays?.remove(pckg)
view.get()?.updateOverlays(getFilteredApps())
overlayService.uninstallApk(pckg.overlayId).await()
}
}
override suspend fun enableSelected() {
selectedOverlays()
.map { it.overlayId }
.filter { overlayService.getOverlayInfo(it).await()?.enabled == false }
.forEach { overlayService.enableOverlay(it).await() }
deselectAll()
view.get()?.refreshRecyclerView()
}
override suspend fun disableSelected() {
selectedOverlays()
.map { it.overlayId }
.filter { overlayService.getOverlayInfo(it).await()?.enabled == true }
.forEach { overlayService.disableOverlay(it).await() }
deselectAll()
view.get()?.refreshRecyclerView()
}
override fun selectAll() {
getFilteredApps().forEach { state?.set(it.overlayId, true) }
view.get()?.refreshRecyclerView()
}
override fun deselectAll() {
getFilteredApps().forEach { state?.set(it.overlayId, false) }
view.get()?.refreshRecyclerView()
}
override fun getOverlayInfo(overlayId: String) = overlayService.getOverlayInfo(overlayId).get()
override fun openActivity(appId: String) = activityProxy.openActivityInSplit(appId)
override fun getState(overlayId: String) = state!![overlayId]!!
override fun setState(overlayId: String, isEnabled: Boolean) {
state?.set(overlayId, isEnabled)
}
override fun restartSystemUI() {
overlayService.restartSystemUI()
}
override fun setFilter(filter: String) {
this.filter = filter
view.get()?.updateOverlays(getFilteredApps())
}
fun getFilteredApps(): List<InstalledOverlay> {
val overlays = overlays
if (overlays == null) {
return listOf()
} else if (filter.isEmpty()) {
return overlays
} else {
return overlays.filter {
it.targetName.contains(filter, true) ||
it.sourceThemeName.contains(filter, true)
}
}
}
} | mit | 863ea8e1b71e92d92719bfb185507b31 | 33.596386 | 140 | 0.647684 | 4.805021 | false | false | false | false |
Kotlin/kotlin-coroutines | examples/suspendingSequence/suspendingSequence-example.kt | 1 | 1072 | package suspendingSequence
import context.*
import delay.*
import run.*
import util.*
import java.util.*
fun main(args: Array<String>) {
val context = newSingleThreadContext("MyThread")
runBlocking(context) {
// asynchronously generate a number every 500 ms
val seq = suspendingSequence(context) {
log("Starting generator")
for (i in 1..10) {
log("Generator yields $i")
yield(i)
val generatorSleep = 500L
log("Generator goes to sleep for $generatorSleep ms")
delay(generatorSleep)
}
log("Generator is done")
}
// simulate async work by sleeping randomly
val random = Random()
// consume asynchronous sequence with a regular for loop
for (value in seq) {
log("Consumer got value = $value")
val consumerSleep = random.nextInt(1000).toLong()
log("Consumer goes to sleep for $consumerSleep ms")
delay(consumerSleep)
}
}
}
| apache-2.0 | e3256dc4ff81281db086f246c5e8f0eb | 30.529412 | 69 | 0.574627 | 4.894977 | false | false | false | false |
stoman/competitive-programming | problems/2020adventofcode23b/submissions/accepted/Stefan.kt | 2 | 840 | import java.util.*
fun main() {
val s = Scanner(System.`in`)
val arr = MutableList(1_000_001) { -1 }
val cups = s.next().map { it.toString().toInt() }
var last = -1
for (i in cups + ((cups.size + 1)..1_000_000)) {
if (last != -1) {
arr[last] = i
}
last = i
}
arr[last] = cups[0]
var active = cups[0]
repeat(10_000_000) {
val sectionBegin = arr[active]
val sectionMiddle = arr[sectionBegin]
val sectionEnd = arr[sectionMiddle]
arr[active] = arr[sectionEnd]
var next = active
do {
next--
if (next <= 0) {
next = arr.size - 1
}
} while (next in setOf(sectionBegin, sectionMiddle, sectionEnd))
arr[sectionEnd] = arr[next]
arr[next] = sectionBegin
active = arr[active]
}
println(arr[1].toBigInteger() * arr[arr[1]].toBigInteger())
}
| mit | eccddf709cdcf3c1bdc89398d3c0d738 | 21.105263 | 68 | 0.571429 | 3.088235 | false | false | false | false |
apixandru/intellij-community | platform/lang-impl/src/com/intellij/formatting/FormatTextRanges.kt | 23 | 1382 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.formatting
import com.intellij.openapi.util.TextRange
import java.util.*
internal class FormatRangesStorage {
private val rangesByStartOffset: MutableList<FormatTextRange> = ArrayList()
fun add(range: TextRange, processHeadingWhitespace: Boolean) {
val formatRange = FormatTextRange(range, processHeadingWhitespace)
rangesByStartOffset.add(formatRange)
}
fun isWhiteSpaceReadOnly(range: TextRange): Boolean {
return rangesByStartOffset.find { !it.isWhitespaceReadOnly(range) } == null
}
fun isReadOnly(range: TextRange): Boolean {
return rangesByStartOffset.find { !it.isReadOnly(range) } == null
}
fun getRanges(): List<FormatTextRange> = rangesByStartOffset
fun isEmpty() = rangesByStartOffset.isEmpty()
} | apache-2.0 | 980e93067372e499689327386b717057 | 31.928571 | 79 | 0.749638 | 4.239264 | false | false | false | false |
damien5314/RhythmGameScoreCalculator | app/src/main/java/com/ddiehl/rgsc/ddrextreme/DDRExView.kt | 1 | 4013 | package com.ddiehl.rgsc.ddrextreme
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.widget.EditText
import android.widget.Switch
import butterknife.bindView
import com.ddiehl.rgsc.R
import com.ddiehl.rgsc.ScorePresenter
import com.ddiehl.rgsc.ScoreViewFragment
import com.ddiehl.rgsc.data.Score
class DDRExView : ScoreViewFragment() {
private val _marvelouses: EditText by bindView(R.id.ddrex_marvelouses)
private val _perfects: EditText by bindView(R.id.ddrex_perfects)
private val _greats: EditText by bindView(R.id.ddrex_greats)
private val _goods: EditText by bindView(R.id.ddrex_goods)
private val _boos: EditText by bindView(R.id.ddrex_boos)
private val _misses: EditText by bindView(R.id.ddrex_misses)
private val _holds: EditText by bindView(R.id.ddrex_holds)
private val _totalHolds: EditText by bindView(R.id.ddrex_total_holds)
private val _marvelousSwitch: Switch by bindView(R.id.ddrex_marvelous_switch)
var marvelouses: Int = 0; get() = getInputFrom(_marvelouses)
var perfects: Int = 0; get() = getInputFrom(_perfects)
var greats: Int = 0; get() = getInputFrom(_greats)
var goods: Int = 0; get() = getInputFrom(_goods)
var boos: Int = 0; get() = getInputFrom(_boos)
var misses: Int = 0; get() = getInputFrom(_misses)
var holds: Int = 0; get() = getInputFrom(_holds)
var totalHolds: Int = 0; get() = getInputFrom(_totalHolds)
var marvelousEnabled: Boolean
get() = _marvelousSwitch.isChecked
set(enabled) { _marvelousSwitch.isChecked = enabled }
override val calculatorLayoutResId: Int = R.layout.calculator_ddrex
override fun getPresenter(): ScorePresenter {
return DDRExPresenter(this)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_marvelousSwitch.setOnCheckedChangeListener({ compoundButton, checked ->
marvelousEnabled = checked
_marvelouses.isFocusable = checked
_marvelouses.isFocusableInTouchMode = checked
if (checked) {
// Enable marvelous field
_marvelouses.inputType = InputType.TYPE_CLASS_NUMBER
// Set next focus target for total holds field
_totalHolds.nextFocusDownId = _marvelouses.id
_totalHolds.nextFocusForwardId = _marvelouses.id
} else {
// Disable marvelous field and clear
_marvelouses.setText("")
_marvelouses.inputType = InputType.TYPE_NULL
// Set next focus target for total holds field
_totalHolds.nextFocusDownId = _perfects.id
_totalHolds.nextFocusForwardId = _perfects.id
}
_presenter.onScoreUpdated()
})
// Set initial state for switch
_marvelouses.setText("")
_marvelouses.inputType = InputType.TYPE_NULL
_marvelouses.isFocusable = false
_marvelouses.isFocusableInTouchMode = false
_marvelousSwitch.isChecked = false
}
override fun displayInput(score: Score) {
_marvelouses.setText(stripZero(score.elements[DDRExScore.MARVELOUSES]?.count))
_perfects.setText(stripZero(score.elements[DDRExScore.PERFECTS]?.count))
_greats.setText(stripZero(score.elements[DDRExScore.GREATS]?.count))
_goods.setText(stripZero(score.elements[DDRExScore.GOODS]?.count))
_boos.setText(stripZero(score.elements[DDRExScore.BOOS]?.count))
_misses.setText(stripZero(score.elements[DDRExScore.MISSES]?.count))
_holds.setText(stripZero(score.elements[DDRExScore.HOLDS]?.count))
_totalHolds.setText(stripZero(score.elements[DDRExScore.TOTAL_HOLDS]?.count))
}
fun showHoldsInvalid() {
_holds.error = getString(R.string.error_invalid_holds)
showScoreError()
}
override fun clearErrors() {
_holds.error = null
}
} | apache-2.0 | e6de1b341bcfd61edab01b29469f645f | 42.630435 | 86 | 0.678046 | 3.862368 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/status/BlockStatusUsersDialogFragment.kt | 1 | 2388 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.status
import android.app.Dialog
import android.os.Bundle
import android.support.v7.app.AlertDialog
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_STATUS
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.applyOnShow
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.model.referencedUsers
import de.vanita5.twittnuker.fragment.BaseDialogFragment
import de.vanita5.twittnuker.fragment.CreateUserBlockDialogFragment
import de.vanita5.twittnuker.model.ParcelableStatus
class BlockStatusUsersDialogFragment : BaseDialogFragment() {
private val status: ParcelableStatus get() = arguments.getParcelable(EXTRA_STATUS)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(context)
val referencedUsers = status.referencedUsers
val nameFirst = preferences[nameFirstKey]
val displayNames = referencedUsers.map {
userColorNameManager.getDisplayName(it, nameFirst)
}.toTypedArray()
builder.setTitle(R.string.action_status_block_users)
builder.setItems(displayNames) { _, which ->
CreateUserBlockDialogFragment.show(fragmentManager, referencedUsers[which])
}
val dialog = builder.create()
dialog.applyOnShow { applyTheme() }
return dialog
}
} | gpl-3.0 | 5e65cb85c35b7762da8e805bd20271b1 | 39.491525 | 87 | 0.760888 | 4.422222 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/NotificationButtonView.kt | 1 | 1594 | package org.wikipedia.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.view.isVisible
import androidx.core.widget.ImageViewCompat
import org.wikipedia.R
import org.wikipedia.databinding.ViewNotificationButtonBinding
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.ResourceUtil
class NotificationButtonView constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {
private val binding = ViewNotificationButtonBinding.inflate(LayoutInflater.from(context), this)
init {
layoutParams = ViewGroup.LayoutParams(DimenUtil.roundedDpToPx(48.0f), ViewGroup.LayoutParams.MATCH_PARENT)
setBackgroundResource(ResourceUtil.getThemedAttributeId(context, R.attr.selectableItemBackgroundBorderless))
isFocusable = true
}
fun setUnreadCount(count: Int) {
binding.unreadDot.setUnreadCount(count)
binding.unreadDot.isVisible = count > 0
}
fun runAnimation() {
startAnimation(AnimationUtils.loadAnimation(context, R.anim.tab_list_zoom_enter))
}
fun setIcon(@DrawableRes icon: Int) {
binding.iconImage.setImageResource(icon)
}
fun setColor(@ColorInt color: Int) {
ImageViewCompat.setImageTintList(binding.iconImage, ColorStateList.valueOf(color))
}
}
| apache-2.0 | caa381fdd8370078f2c5d0f476710e4e | 35.227273 | 119 | 0.783563 | 4.633721 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/activities/RoomFinderActivity.kt | 1 | 12308 | package com.sapuseven.untis.activities
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ImageSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.sapuseven.untis.R
import com.sapuseven.untis.adapters.RoomFinderAdapter
import com.sapuseven.untis.adapters.RoomFinderAdapterItem
import com.sapuseven.untis.data.databases.RoomfinderDatabase
import com.sapuseven.untis.data.databases.UserDatabase
import com.sapuseven.untis.data.timetable.TimegridItem
import com.sapuseven.untis.dialogs.ElementPickerDialog
import com.sapuseven.untis.dialogs.ErrorReportingDialog
import com.sapuseven.untis.helpers.ErrorMessageDictionary
import com.sapuseven.untis.helpers.timetable.TimetableDatabaseInterface
import com.sapuseven.untis.helpers.timetable.TimetableLoader
import com.sapuseven.untis.interfaces.TimetableDisplay
import com.sapuseven.untis.models.RoomFinderItem
import com.sapuseven.untis.models.untis.UntisDate
import com.sapuseven.untis.models.untis.masterdata.timegrid.Day
import com.sapuseven.untis.models.untis.masterdata.timegrid.Unit
import com.sapuseven.untis.models.untis.timetable.PeriodElement
import kotlinx.android.synthetic.main.activity_roomfinder.*
import org.joda.time.LocalDate
import org.joda.time.LocalDateTime
import org.joda.time.format.DateTimeFormat
import java.lang.ref.WeakReference
import java.util.*
import kotlin.collections.ArrayList
class RoomFinderActivity : BaseActivity(), ElementPickerDialog.ElementPickerDialogListener, RoomFinderAdapter.RoomFinderClickListener {
private var roomListMargins: Int = 0
private var hourIndex: Int = 0
private var maxHourIndex = 0
private var roomList: MutableList<RoomFinderAdapterItem> = ArrayList()
private var roomListAdapter = RoomFinderAdapter(this, this)
private var profileUser: UserDatabase.User? = null
private lateinit var userDatabase: UserDatabase
private lateinit var timetableDatabaseInterface: TimetableDatabaseInterface
private lateinit var roomFinderDatabase: RoomfinderDatabase
companion object {
const val EXTRA_LONG_PROFILE_ID = "com.sapuseven.untis.activities.profileid"
const val EXTRA_INT_ROOM_ID = "com.sapuseven.untis.activities.roomid"
const val EVENT_PICKER_TAG = "com.sapuseven.untis.activities.elementPicker"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_roomfinder)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
roomListMargins = (12 * resources.displayMetrics.density + 0.5f).toInt()
setupNoRoomsIndicator()
loadDatabases(intent.getLongExtra(EXTRA_LONG_PROFILE_ID, -1))
setupHourSelector()
setupRoomList()
refreshRoomList()
swiperefreshlayout_roomfinder_roomlist.setOnRefreshListener {
updateRooms()
}
}
private fun updateRooms() {
val roomsToLoad = roomList.map {
@Suppress("RemoveRedundantQualifierName")
PeriodElement(TimetableDatabaseInterface.Type.ROOM.toString(), it.id, it.id)
}
roomList.clear()
roomListAdapter.notifyDataSetChanged()
addRooms(roomsToLoad)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_roomfinder_actions, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.item_roomfinder_add -> {
showItemList()
false
}
else -> {
super.onOptionsItemSelected(item)
}
}
private fun loadDatabases(profileId: Long) {
userDatabase = UserDatabase.createInstance(this)
profileUser = userDatabase.getUser(profileId)
timetableDatabaseInterface = TimetableDatabaseInterface(userDatabase, profileUser?.id ?: -1)
roomFinderDatabase = RoomfinderDatabase.createInstance(this, profileId)
}
private fun setupHourSelector() {
maxHourIndex = -1 // maxIndex = -1 + length
profileUser?.let {
it.timeGrid.days.forEach { day ->
maxHourIndex += day.units.size
}
}
button_roomfinder_next.setOnClickListener {
if (hourIndex < maxHourIndex) {
hourIndex++
refreshRoomList()
refreshHourSelector()
}
}
button_roomfinder_previous.setOnClickListener {
if (hourIndex > 0) {
hourIndex--
refreshRoomList()
refreshHourSelector()
}
}
textview_roomfinder_currenthour.setOnClickListener {
hourIndex = calculateCurrentHourIndex()
refreshRoomList()
refreshHourSelector()
}
hourIndex = calculateCurrentHourIndex()
refreshHourSelector()
}
private fun calculateCurrentHourIndex(): Int {
profileUser?.let {
val now = LocalDateTime.now()
var index = 0
it.timeGrid.days.forEach { day ->
val dayDate = DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH).parseLocalDate(day.day)
if (dayDate.dayOfWeek == now.dayOfWeek)
day.units.forEach { unit ->
if (unit.endTime.toLocalTime().millisOfDay > now.millisOfDay)
return index
index++
}
else
index += day.units.size
}
}
return 0
}
private fun setupNoRoomsIndicator() {
val text = textview_roomfinder_roomlistempty.text.toString()
if (text.contains("+")) {
val ss = SpannableString(text)
val img = ContextCompat.getDrawable(this, R.drawable.all_add)
if (img != null) {
img.setBounds(0, 0, img.intrinsicWidth, img.intrinsicHeight)
ss.setSpan(ImageSpan(img, ImageSpan.ALIGN_BOTTOM),
text.indexOf("+"), text.indexOf("+") + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
}
textview_roomfinder_roomlistempty.text = ss
}
}
private fun setupRoomList() {
recyclerview_roomfinder_roomlist.layoutManager = LinearLayoutManager(this)
roomListAdapter = RoomFinderAdapter(this, this, roomList)
recyclerview_roomfinder_roomlist.adapter = roomListAdapter
roomFinderDatabase.getAllRooms().forEach {
roomList.add(RoomFinderAdapterItem(it.name, it.id, false, it.states))
}
}
override fun onDialogDismissed(dialog: DialogInterface?) {
// Nothing to do
}
override fun onPeriodElementClick(fragment: Fragment, element: PeriodElement?, useOrgId: Boolean) {
// Ignore single clicks, wait for onPositiveButtonClick instead
}
override fun onPositiveButtonClicked(dialog: ElementPickerDialog) {
addRooms(dialog.getSelectedItems())
}
override fun onClick(v: View) {
val intent = Intent()
intent.putExtra(EXTRA_INT_ROOM_ID, roomList[recyclerview_roomfinder_roomlist.getChildLayoutPosition(v)].id)
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onDeleteClick(position: Int) {
showDeleteItemDialog(position)
}
private fun addRooms(rooms: List<PeriodElement>) {
rooms.forEach { room ->
val roomName = timetableDatabaseInterface.getShortName(room.id, TimetableDatabaseInterface.Type.ROOM)
val item = RoomFinderAdapterItem(roomName, room.id, true)
item.hourIndex = hourIndex
if (roomList.contains(item)) return
roomList.add(item)
profileUser?.let { user ->
val startDate = UntisDate.fromLocalDate(LocalDate.now().withDayOfWeek(
DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH).parseDateTime(user.timeGrid.days.first().day).dayOfWeek
))
val endDate = UntisDate.fromLocalDate(LocalDate.now().withDayOfWeek(
DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH).parseDateTime(user.timeGrid.days.last().day).dayOfWeek
))
val proxyHost = preferences.defaultPrefs.getString("preference_connectivity_proxy_host", null)
TimetableLoader(WeakReference(this), object : TimetableDisplay {
override fun addTimetableItems(items: List<TimegridItem>, startDate: UntisDate, endDate: UntisDate, timestamp: Long) {
val states = mutableListOf<Boolean>()
profileUser?.let {
it.timeGrid.days.forEach { day ->
val dayDateTime = DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH).parseDateTime(day.day)
day.units.forEach { unit ->
val unitStartDateTime = unit.startTime.toLocalTime()
val unitEndDateTime = unit.endTime.toLocalTime()
var isOccupied = false
items.forEach allItems@{ item ->
if (item.startDateTime.dayOfWeek == dayDateTime.dayOfWeek)
if (item.startDateTime.millisOfDay <= unitEndDateTime.millisOfDay
&& item.endDateTime.millisOfDay >= unitStartDateTime.millisOfDay) {
isOccupied = true
return@allItems
}
}
states.add(isOccupied)
}
}
}
item.states = states.toList()
item.loading = false
refreshRoomList()
roomFinderDatabase.addRoom(RoomFinderItem(
room.id,
roomName,
item.states
))
}
override fun onTimetableLoadingError(requestId: Int, code: Int?, message: String?) {
roomList.remove(item)
refreshRoomList()
Snackbar.make(content_roomfinder, if (code != null) ErrorMessageDictionary.getErrorMessage(resources, code) else message
?: getString(R.string.all_error), Snackbar.LENGTH_INDEFINITE)
.setAction("Show") { ErrorReportingDialog(this@RoomFinderActivity).showRequestErrorDialog(requestId, code, message) }
.show()
}
}, user, timetableDatabaseInterface)
.load(TimetableLoader.TimetableLoaderTarget(startDate, endDate, room.id, room.type), TimetableLoader.FLAG_LOAD_SERVER, proxyHost)
}
}
refreshRoomList()
}
private fun refreshRoomList() {
if (roomList.isNotEmpty())
textview_roomfinder_roomlistempty.visibility = View.GONE
else // default to visible if empty
textview_roomfinder_roomlistempty.visibility = View.VISIBLE
if (roomList.find { it.loading } == null) swiperefreshlayout_roomfinder_roomlist.isRefreshing = false
roomListAdapter.currentHourIndex = hourIndex
roomList.sort()
roomListAdapter.notifyDataSetChanged()
}
private fun showItemList() {
ElementPickerDialog.newInstance(
timetableDatabaseInterface,
ElementPickerDialog.Companion.ElementPickerDialogConfig(
TimetableDatabaseInterface.Type.ROOM,
multiSelect = true,
hideTypeSelection = true,
positiveButtonText = getString(R.string.all_add))
).show(supportFragmentManager, EVENT_PICKER_TAG)
}
private fun showDeleteItemDialog(position: Int) {
MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.roomfinder_dialog_itemdelete_title, roomList[position]))
.setMessage(R.string.roomfinder_dialog_itemdelete_text)
.setPositiveButton(R.string.all_yes) { _, _ ->
if (roomFinderDatabase.deleteRoom(roomList[position].id)) {
roomList.removeAt(position)
roomListAdapter.notifyItemRemoved(position)
refreshRoomList()
}
}
.setNegativeButton(R.string.all_no) { dialog, _ -> dialog.dismiss() }
.show()
}
private fun refreshHourSelector() {
val unit = getUnitFromIndex(hourIndex)
unit?.let {
textview_roomfinder_currenthour.text = getString(R.string.roomfinder_current_hour, translateDay(unit.first.day), unit.second)
textview_roomfinder_currenthourtime.text = getString(
R.string.roomfinder_current_hour_time,
unit.third.startTime.toLocalTime().toString(DateTimeFormat.shortTime()),
unit.third.endTime.toLocalTime().toString(DateTimeFormat.shortTime())
)
}
button_roomfinder_previous.isEnabled = hourIndex != 0
button_roomfinder_next.isEnabled = hourIndex != maxHourIndex
}
private fun translateDay(day: String): String {
return DateTimeFormat.forPattern("EEEE").print(DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH).parseDateTime(day))
}
/**
* @return A triple of the day, the unit index of day (1-indexed) and the unit corresponding to the provided hour index.
*/
private fun getUnitFromIndex(index: Int): Triple<Day, Int, Unit>? {
profileUser?.let {
var indexCounter = index
it.timeGrid.days.forEach { day ->
if (indexCounter >= day.units.size)
indexCounter -= day.units.size
else
return Triple(day, indexCounter + 1, day.units[indexCounter])
}
}
return null
}
}
| gpl-3.0 | abb079d9f3d1570102e411821a4c8274 | 33.188889 | 135 | 0.749675 | 3.828305 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/view/CardHeaderView.kt | 1 | 3770 | package org.wikipedia.feed.view
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.widget.PopupMenu
import androidx.constraintlayout.widget.ConstraintLayout
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.databinding.ViewCardHeaderBinding
import org.wikipedia.feed.model.Card
import org.wikipedia.util.L10nUtil
class CardHeaderView constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) {
interface Callback {
fun onRequestDismissCard(card: Card): Boolean
fun onRequestEditCardLanguages(card: Card)
fun onRequestCustomize(card: Card)
}
private val binding = ViewCardHeaderBinding.inflate(LayoutInflater.from(context), this)
private var card: Card? = null
private var callback: Callback? = null
var titleView = binding.viewCardHeaderTitle
private set
init {
binding.viewListCardHeaderMenu.setOnClickListener { showOverflowMenu(it) }
}
private fun showOverflowMenu(anchorView: View) {
card?.let {
val menu = PopupMenu(anchorView.context, anchorView, Gravity.END)
menu.menuInflater.inflate(R.menu.menu_feed_card_header, menu.menu)
val editCardLangItem = menu.menu.findItem(R.id.menu_feed_card_edit_card_languages)
editCardLangItem.isVisible = it.type().contentType()?.run { isPerLanguage } ?: false
menu.setOnMenuItemClickListener(CardHeaderMenuClickListener())
menu.show()
}
}
fun setCard(card: Card): CardHeaderView {
this.card = card
return this
}
fun setCallback(callback: Callback?): CardHeaderView {
this.callback = callback
return this
}
fun setTitle(title: CharSequence?): CardHeaderView {
binding.viewCardHeaderTitle.text = title
return this
}
fun setTitle(@StringRes id: Int): CardHeaderView {
binding.viewCardHeaderTitle.setText(id)
return this
}
fun setLangCode(langCode: String?): CardHeaderView {
if (langCode.isNullOrEmpty() || WikipediaApp.instance.languageState.appLanguageCodes.size < 2) {
binding.viewListCardHeaderLangBackground.visibility = View.GONE
binding.viewListCardHeaderLangCode.visibility = View.GONE
L10nUtil.setConditionalLayoutDirection(this, WikipediaApp.instance.languageState.systemLanguageCode)
} else {
binding.viewListCardHeaderLangBackground.visibility = VISIBLE
binding.viewListCardHeaderLangCode.visibility = VISIBLE
binding.viewListCardHeaderLangCode.text = langCode
L10nUtil.setConditionalLayoutDirection(this, langCode)
}
return this
}
private inner class CardHeaderMenuClickListener : PopupMenu.OnMenuItemClickListener {
override fun onMenuItemClick(item: MenuItem): Boolean {
return card?.let {
when (item.itemId) {
R.id.menu_feed_card_dismiss -> {
callback?.onRequestDismissCard(it)
true
}
R.id.menu_feed_card_edit_card_languages -> {
callback?.onRequestEditCardLanguages(it)
true
}
R.id.menu_feed_card_customize -> {
callback?.onRequestCustomize(it)
true
}
else -> false
}
} ?: run { false }
}
}
}
| apache-2.0 | 1a74f0abe69d12cbd745b239252efebd | 35.601942 | 116 | 0.650928 | 4.967062 | false | false | false | false |
chadrick-kwag/datalabeling_app | app/src/main/java/com/example/chadrick/datalabeling/Fragments/SettingsFragment.kt | 1 | 3303 | package com.example.chadrick.datalabeling.Fragments
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.chadrick.datalabeling.MainActivity
import com.example.chadrick.datalabeling.Models.App
import com.example.chadrick.datalabeling.Models.SMitem
import com.example.chadrick.datalabeling.R
import com.example.chadrick.datalabeling.Adapters.SettingsMenuAdapter
import com.google.android.gms.auth.api.Auth
import kotlinx.android.synthetic.main.settings_layout.*
/**
* Created by chadrick on 17. 11. 13.
*/
class SettingsFragment : Fragment() {
private lateinit var smAdapter: SettingsMenuAdapter
private var initialized: Boolean = false
private val menulist: ArrayList<SMitem> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("bitcoin","settingsfragment created")
for( frag in fragmentManager.fragments){
Log.d("bitcoin","print frags in settingsfragment frag = "+frag.toString())
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (!initialized) {
menulist.add(SMitem(type = SMitem.TYPE_TOGGLE, title = "Night Mode"))
menulist.add(SMitem(type = SMitem.TYPE_PLAIN, title = "Logout", clickable = true,
titleColor = Color.parseColor("#ff0000"),
clickAction = ::asksignout
))
smAdapter = SettingsMenuAdapter(menulist)
initialized = true
}
return inflater?.inflate(R.layout.settings_layout, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// recycler view manage
settings_menu_rv.adapter = smAdapter
settings_menu_rv.layoutManager = LinearLayoutManager(App.applicationContext(), LinearLayoutManager.VERTICAL, false)
}
private fun asksignout() {
val alertbuilder = AlertDialog.Builder(activity)
alertbuilder.setMessage("Sign out for real?")
.setPositiveButton("Let's geddit", { x, y -> signout() })
.setNegativeButton("Nope", { x, y -> })
val alert = alertbuilder.create()
alert.show()
}
private fun signout() {
val googleapiclient = (activity as MainActivity).getGoogleApiClient()
val pendingresult = Auth.GoogleSignInApi.signOut(googleapiclient)
pendingresult.setResultCallback { status ->
if (status.isSuccess) {
gotoSignInFragment()
}
}
}
private fun gotoSignInFragment() {
fragmentManager.beginTransaction().replace(R.id.fragmentcontainer, SignInFragment()).commit()
val mainportalfrag = fragmentManager.findFragmentByTag("mainportal")
fragmentManager.beginTransaction().remove(mainportalfrag).commit()
fragmentManager.beginTransaction().remove(this).commit()
}
} | mit | 552271afb2c812e171ae13f1060f7799 | 32.373737 | 123 | 0.690887 | 4.62605 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/PaymentMethodOptionsParams.kt | 1 | 3297 | package com.stripe.android.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
sealed class PaymentMethodOptionsParams(
val type: PaymentMethod.Type
) : StripeParamsModel, Parcelable {
internal abstract fun createTypeParams(): List<Pair<String, Any?>>
override fun toParamMap(): Map<String, Any> {
val typeParams: Map<String, Any> = createTypeParams()
.fold(emptyMap()) { acc, (key, value) ->
acc.plus(
value?.let { mapOf(key to it) }.orEmpty()
)
}
return when {
typeParams.isNotEmpty() -> mapOf(type.code to typeParams)
else -> emptyMap()
}
}
@Parcelize
data class Card internal constructor(
var cvc: String? = null,
var network: String? = null,
var setupFutureUsage: ConfirmPaymentIntentParams.SetupFutureUsage? = null,
internal var moto: Boolean? = null
) : PaymentMethodOptionsParams(PaymentMethod.Type.Card) {
constructor(
cvc: String? = null,
network: String? = null,
setupFutureUsage: ConfirmPaymentIntentParams.SetupFutureUsage? = null
) : this(
cvc = cvc,
network = network,
setupFutureUsage = setupFutureUsage,
moto = null
)
override fun createTypeParams(): List<Pair<String, Any?>> {
return listOf(
PARAM_CVC to cvc,
PARAM_NETWORK to network,
PARAM_MOTO to moto,
PARAM_SETUP_FUTURE_USAGE to setupFutureUsage?.code
)
}
private companion object {
private const val PARAM_CVC = "cvc"
private const val PARAM_NETWORK = "network"
private const val PARAM_SETUP_FUTURE_USAGE = "setup_future_usage"
private const val PARAM_MOTO = "moto"
}
}
@Parcelize
data class Blik(
var code: String
) : PaymentMethodOptionsParams(PaymentMethod.Type.Blik) {
override fun createTypeParams(): List<Pair<String, Any?>> {
return listOf(
PARAM_CODE to code
)
}
internal companion object {
const val PARAM_CODE = "code"
}
}
@Parcelize
data class WeChatPay(
var appId: String
) : PaymentMethodOptionsParams(PaymentMethod.Type.WeChatPay) {
override fun createTypeParams(): List<Pair<String, Any?>> {
return listOf(
PARAM_CLIENT to "android",
PARAM_APP_ID to appId
)
}
internal companion object {
const val PARAM_CLIENT = "client"
const val PARAM_APP_ID = "app_id"
}
}
@Parcelize
data class USBankAccount(
var setupFutureUsage: ConfirmPaymentIntentParams.SetupFutureUsage? = null
) : PaymentMethodOptionsParams(PaymentMethod.Type.USBankAccount) {
override fun createTypeParams(): List<Pair<String, Any?>> {
return listOf(
PARAM_SETUP_FUTURE_USAGE to setupFutureUsage?.code
)
}
internal companion object {
const val PARAM_SETUP_FUTURE_USAGE = "setup_future_usage"
}
}
}
| mit | 42b2b3609c55096db27f917728a00706 | 29.813084 | 82 | 0.572338 | 4.987897 | false | false | false | false |
erickok/borefts2015 | android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/components/Exporter.kt | 1 | 1610 | package nl.brouwerijdemolen.borefts2013.gui.components
import arrow.core.getOrDefault
import arrow.core.getOrElse
import nl.brouwerijdemolen.borefts2013.gui.Repository
import okio.buffer
import okio.sink
import org.koin.core.KoinComponent
import org.koin.core.inject
import java.io.File
class Exporter : KoinComponent {
private val repository: Repository by inject()
suspend fun writeTo(csv: File) {
if (!csv.parentFile!!.exists()) {
csv.parentFile!!.mkdir()
}
if (csv.exists()) {
csv.delete()
}
csv.createNewFile()
csv.sink().buffer().use { sink ->
sink.writeUtf8("brewer,beer,style,festivalSpecial,abv,serving,untappd\n")
val styles = repository.styles().getOrElse { throw it }
repository.brewers().getOrDefault { emptyList() }.forEach { brewer ->
repository.brewerBeers(brewer.id).getOrDefault { emptyList() }.forEach { beer ->
val brewerName = brewer.shortName
val beerName = """"${beer.name}""""
val styleName = styles.firstOrNull { it.id == beer.styleId }?.name
val festival = if (beer.festivalBeer) "TRUE" else "FALSE"
val abv = beer.abv
val serving = beer.serving
val untappdLink = if (beer.untappdId != "-1") "https://untappd.com/b/b/${beer.untappdId}" else ""
sink.writeUtf8("$brewerName,$beerName,$styleName,$festival,$abv,$serving,$untappdLink\n")
}
}
}
}
} | gpl-3.0 | 3c53e15914003adbd31d4a2e97afb683 | 34.021739 | 117 | 0.589441 | 4.363144 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/AddTaskWidgetActivity.kt | 1 | 2842 | package com.habitrpg.android.habitica.ui.activities
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.habitrpg.android.habitica.databinding.WidgetConfigureAddTaskBinding
import com.habitrpg.android.habitica.models.tasks.TaskType
import com.habitrpg.android.habitica.widget.AddTaskWidgetProvider
class AddTaskWidgetActivity : AppCompatActivity() {
private var widgetId: Int = 0
private lateinit var binding: WidgetConfigureAddTaskBinding
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(Activity.RESULT_CANCELED)
binding = WidgetConfigureAddTaskBinding.inflate(layoutInflater)
setContentView(binding.root)
val intent = intent
val extras = intent.extras
if (extras != null) {
widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
}
// If this activity was started with an intent without an app widget ID,
// finish with an error.
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish()
}
binding.addHabitButton.setOnClickListener { addHabitSelected() }
binding.addDailyButton.setOnClickListener { addDailySelected() }
binding.addTodoButton.setOnClickListener { addToDoSelected() }
binding.addRewardButton.setOnClickListener { addRewardSelected() }
}
private fun addHabitSelected() {
finishWithSelection(TaskType.HABIT)
}
private fun addDailySelected() {
finishWithSelection(TaskType.DAILY)
}
private fun addToDoSelected() {
finishWithSelection(TaskType.TODO)
}
private fun addRewardSelected() {
finishWithSelection(TaskType.REWARD)
}
private fun finishWithSelection(selectedTaskType: TaskType) {
storeSelectedTaskType(selectedTaskType)
val resultValue = Intent()
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
setResult(Activity.RESULT_OK, resultValue)
finish()
val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, AddTaskWidgetProvider::class.java)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(widgetId))
sendBroadcast(intent)
}
private fun storeSelectedTaskType(selectedTaskType: TaskType) {
PreferenceManager.getDefaultSharedPreferences(this).edit {
putString("add_task_widget_$widgetId", selectedTaskType.value)
}
}
}
| gpl-3.0 | 25c1417106f4718e0c18955b9e54aa67 | 34.435897 | 116 | 0.708304 | 5.021201 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/bubbles/__BubblesLayoutCoordinator.kt | 1 | 3558 | package com.exyui.android.debugbottle.components.bubbles
import android.view.View
import android.view.WindowManager
/**
* Created by yuriel on 9/22/16.
*/
internal object __BubblesLayoutCoordinator {
private var trashView: __BubbleTrashLayout? = null
private var windowManager: WindowManager? = null
private var bubblesService: __BubblesService? = null
fun notifyBubblePositionChanged(bubble: __BubbleLayout,
@Suppress("UNUSED_PARAMETER") x: Int,
@Suppress("UNUSED_PARAMETER") y: Int) {
trashView?.let {
it.visibility = View.VISIBLE
if (checkIfBubbleIsOverTrash(bubble)) {
it.applyMagnetism()
//it.vibrate()
applyTrashMagnetismToBubble(bubble)
} else {
it.releaseMagnetism()
}
}
}
private fun applyTrashMagnetismToBubble(bubble: __BubbleLayout) {
getTrashContent()?.let {
val trashCenterX = it.left + it.measuredWidth / 2
val trashCenterY = it.top + it.measuredHeight / 2
val x = trashCenterX - bubble.measuredWidth / 2
val y = trashCenterY - bubble.measuredHeight / 2
bubble.getViewParams().x = x
bubble.getViewParams().y = y
windowManager!!.updateViewLayout(bubble, bubble.getViewParams())
}
}
private fun checkIfBubbleIsOverTrash(bubble: __BubbleLayout): Boolean {
return if (trashView?.visibility == View.VISIBLE) {
getTrashContent()?.let {
val trashWidth = it.measuredWidth
val trashHeight = it.measuredHeight
val trashLeft = it.left - trashWidth / 2
val trashRight = it.left + trashWidth + trashWidth / 2
val trashTop = it.top - trashHeight / 2
val trashBottom = it.top + trashHeight + trashHeight / 2
val bubbleWidth = bubble.measuredWidth
val bubbleHeight = bubble.measuredHeight
val bubbleLeft = bubble.getViewParams().x
val bubbleRight = bubbleLeft + bubbleWidth
val bubbleTop = bubble.getViewParams().y
val bubbleBottom = bubbleTop + bubbleHeight
if (bubbleLeft >= trashLeft && bubbleRight <= trashRight) {
bubbleTop >= trashTop && bubbleBottom <= trashBottom
} else {
false
}
}?: false
} else {
false
}
}
fun notifyBubbleRelease(bubble: __BubbleLayout) {
if (trashView != null) {
if (checkIfBubbleIsOverTrash(bubble)) {
bubblesService?.removeBubble(bubble)
}
trashView?.visibility = View.GONE
}
}
class Builder(service: __BubblesService) {
private val layoutCoordinator: __BubblesLayoutCoordinator = __BubblesLayoutCoordinator
init {
layoutCoordinator.bubblesService = service
}
fun setTrashView(trashView: __BubbleTrashLayout): Builder {
layoutCoordinator.trashView = trashView
return this
}
fun setWindowManager(windowManager: WindowManager): Builder {
layoutCoordinator.windowManager = windowManager
return this
}
fun build(): __BubblesLayoutCoordinator = layoutCoordinator
}
private fun getTrashContent(): View? = trashView?.getChildAt(0)
} | apache-2.0 | eb0fd83c4496104d2ce719503379cab6 | 35.690722 | 94 | 0.579258 | 5.018336 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/nbt/Nbt.kt | 1 | 6992 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt
import com.demonwav.mcdev.nbt.tags.NbtTag
import com.demonwav.mcdev.nbt.tags.NbtTypeId
import com.demonwav.mcdev.nbt.tags.RootCompound
import com.demonwav.mcdev.nbt.tags.TagByte
import com.demonwav.mcdev.nbt.tags.TagByteArray
import com.demonwav.mcdev.nbt.tags.TagCompound
import com.demonwav.mcdev.nbt.tags.TagDouble
import com.demonwav.mcdev.nbt.tags.TagEnd
import com.demonwav.mcdev.nbt.tags.TagFloat
import com.demonwav.mcdev.nbt.tags.TagInt
import com.demonwav.mcdev.nbt.tags.TagIntArray
import com.demonwav.mcdev.nbt.tags.TagList
import com.demonwav.mcdev.nbt.tags.TagLong
import com.demonwav.mcdev.nbt.tags.TagLongArray
import com.demonwav.mcdev.nbt.tags.TagShort
import com.demonwav.mcdev.nbt.tags.TagString
import java.io.DataInputStream
import java.io.InputStream
import java.util.zip.GZIPInputStream
import java.util.zip.ZipException
object Nbt {
private fun getActualInputStream(stream: InputStream): Pair<DataInputStream, Boolean> {
return try {
DataInputStream(GZIPInputStream(stream)) to true
} catch (e: ZipException) {
stream.reset()
DataInputStream(stream) to false
}
}
/**
* Parse the NBT file from the InputStream and return the root TagCompound for the NBT file. This method closes the stream when
* it is finished with it.
*/
@Throws(MalformedNbtFileException::class)
fun buildTagTree(inputStream: InputStream, timeout: Long): Pair<RootCompound, Boolean> {
try {
val (stream, isCompressed) = getActualInputStream(inputStream)
stream.use {
val tagIdByte = stream.readByte()
val tagId = NbtTypeId.getById(tagIdByte)
?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
if (tagId != NbtTypeId.COMPOUND) {
throw MalformedNbtFileException("Root tag in NBT file is not a compound.")
}
val start = System.currentTimeMillis()
return RootCompound(stream.readUTF(), stream.readCompoundTag(start, timeout).tagMap) to isCompressed
}
} catch (e: Throwable) {
if (e is MalformedNbtFileException) {
throw e
} else {
throw MalformedNbtFileException("Error reading file", e)
}
}
}
private fun DataInputStream.readCompoundTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val tagMap = HashMap<String, NbtTag>()
var tagIdByte = this.readByte()
var tagId =
NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
while (tagId != NbtTypeId.END) {
val name = this.readUTF()
tagMap[name] = this.readTag(tagId, start, timeout)
tagIdByte = this.readByte()
tagId =
NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
}
return@checkTimeout TagCompound(tagMap)
}
private fun DataInputStream.readByteTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagByte(this.readByte()) }
private fun DataInputStream.readShortTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagShort(this.readShort()) }
private fun DataInputStream.readIntTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagInt(this.readInt()) }
private fun DataInputStream.readLongTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagLong(this.readLong()) }
private fun DataInputStream.readFloatTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagFloat(this.readFloat()) }
private fun DataInputStream.readDoubleTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagDouble(this.readDouble()) }
private fun DataInputStream.readStringTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagString(this.readUTF()) }
private fun DataInputStream.readListTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val tagIdByte = this.readByte()
val tagId =
NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
val length = this.readInt()
if (length <= 0) {
return@checkTimeout TagList(tagId, emptyList())
}
val list = List(length) {
this.readTag(tagId, start, timeout)
}
return@checkTimeout TagList(tagId, list)
}
private fun DataInputStream.readByteArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val bytes = ByteArray(length)
this.readFully(bytes)
return@checkTimeout TagByteArray(bytes)
}
private fun DataInputStream.readIntArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val ints = IntArray(length) {
this.readInt()
}
return@checkTimeout TagIntArray(ints)
}
private fun DataInputStream.readLongArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val longs = LongArray(length) {
this.readLong()
}
return@checkTimeout TagLongArray(longs)
}
private fun DataInputStream.readTag(tagId: NbtTypeId, start: Long, timeout: Long): NbtTag {
return when (tagId) {
NbtTypeId.END -> TagEnd
NbtTypeId.BYTE -> this.readByteTag(start, timeout)
NbtTypeId.SHORT -> this.readShortTag(start, timeout)
NbtTypeId.INT -> this.readIntTag(start, timeout)
NbtTypeId.LONG -> this.readLongTag(start, timeout)
NbtTypeId.FLOAT -> this.readFloatTag(start, timeout)
NbtTypeId.DOUBLE -> this.readDoubleTag(start, timeout)
NbtTypeId.BYTE_ARRAY -> this.readByteArrayTag(start, timeout)
NbtTypeId.STRING -> this.readStringTag(start, timeout)
NbtTypeId.LIST -> this.readListTag(start, timeout)
NbtTypeId.COMPOUND -> this.readCompoundTag(start, timeout)
NbtTypeId.INT_ARRAY -> this.readIntArrayTag(start, timeout)
NbtTypeId.LONG_ARRAY -> this.readLongArrayTag(start, timeout)
}
}
private inline fun <T : Any> checkTimeout(start: Long, timeout: Long, action: () -> T): T {
val now = System.currentTimeMillis()
val took = now - start
if (took > timeout) {
throw NbtFileParseTimeoutException("NBT parse timeout exceeded - Parse time: $took, Timeout: $timeout.")
}
return action()
}
}
| mit | a91d476c75bc070c37b1cc50f0cfa3a3 | 36.191489 | 131 | 0.656035 | 4.300123 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/security/TokenEncryptionCache.kt | 1 | 3709 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.security
import com.fasterxml.jackson.databind.ObjectMapper
import dk.etiktak.backend.util.CryptoUtil
import org.slf4j.LoggerFactory
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.crypto.encrypt.TextEncryptor
open class TokenEncryptionCache {
private val logger = LoggerFactory.getLogger(TokenEncryptionCache::class.java)
companion object {
val sharedInstance = TokenEncryptionCache()
val encryptorCount = 2
}
private var textEncryptors = arrayListOf<TextEncryptor>()
constructor() {
for (i in 1..encryptorCount) {
generateNewEncryptor()
}
}
/**
* Encrypts the given token cache entry with first text encryptor.
*
* @param tokenCacheEntry Token cache entry
* @return Encrypted token
*/
fun encryptToken(tokenCacheEntry: TokenCacheEntry): String {
val jsonString = ObjectMapper().writeValueAsString(tokenCacheEntry)
return textEncryptors[0].encrypt(jsonString)
}
/**
* Decrypts the given token with the text encryptor at the given index.
*
* @param token Token
* @return Decrypted token cache entry
*/
fun decryptToken(token: String): TokenCacheEntry {
for (i in 0..(TokenEncryptionCache.encryptorCount - 1)) {
try {
val jsonString = textEncryptors[i].decrypt(token)
return ObjectMapper().readValue(jsonString, TokenCacheEntry::class.java)
} catch (e: Exception) {
logger.debug("Could not decrypt token", e)
}
}
throw BadCredentialsException("Invalid token")
}
/**
* Generates a new encryptor. Rolls the encryptor cache.
*/
fun generateNewEncryptor() {
logger.info("Creating new token encryptor")
// Create new encryptor
textEncryptors.add(0, CryptoUtil().createTextEncryptor())
// Remove last
if (textEncryptors.size > encryptorCount) {
textEncryptors.remove(textEncryptors.last())
}
}
} | bsd-3-clause | d8a4219c362fb83ea422475390ba3fad | 38.892473 | 88 | 0.701806 | 4.798189 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/pdf/util/PdfUtil.kt | 1 | 7102 | package org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util
import com.itextpdf.text.Chunk
import com.itextpdf.text.Font
import com.itextpdf.text.Rectangle
object PdfUtil {
private const val NON_BREAKING_SPACE = '\u00A0'
private const val TEXT_PADDING_HORIZONTAL = 1
fun String.splitToLineChunks(font: Font, textColumnWidth: Float): List<Chunk> {
val availableTextWidth = textColumnWidth - 2 * TEXT_PADDING_HORIZONTAL
val padded = StringUtil.padTurnsUniformly(this, NON_BREAKING_SPACE.toString())
return padded.split("\n").dropLastWhile { it.isEmpty() }
.flatMap { it.splitLineToChunks(font, availableTextWidth) }
.map { it.toLineWrapChunk(font) }
}
private tailrec fun String.splitLineToChunks(font: Font, availableTextWidth: Float, acc: List<String> = listOf()): List<String> {
if (isEmpty()) {
return acc
}
// Walk past all whitespace that comes immediately after
// the last line wrap we just inserted.
if (first() == ' ') {
return drop(1)
.splitLineToChunks(font, availableTextWidth, acc)
}
val optimalCutIndex = optimalCutIndex(font, availableTextWidth)
val substring = substring(0, optimalCutIndex).padNbsp()
.fillToWidthMax(NON_BREAKING_SPACE.toString(), font, availableTextWidth)
return substring(optimalCutIndex)
.splitLineToChunks(font, availableTextWidth, acc + substring)
}
private fun String.padNbsp() = NON_BREAKING_SPACE + this + NON_BREAKING_SPACE
private fun String.optimalCutIndex(font: Font, availableTextWidth: Float): Int {
val endIndex = longestFittingSubstringIndex(font, availableTextWidth, 0)
// If we're not at the end of the text, make sure we're not cutting
// a word (or turn) in half by walking backwards until we're right before a turn.
if (endIndex < length) {
return tryBackwardsWordEndIndex(endIndex)
}
return endIndex
}
private fun String.longestFittingSubstringIndex(font: Font, maxWidth: Float, fallback: Int): Int {
val searchRange = 0..length
val endpoint = searchRange.findLast {
val substring = substring(0, it).padNbsp()
val substringWidth = font.baseFont.getWidthPoint(substring, font.size)
substringWidth <= maxWidth
}
return endpoint ?: fallback
}
private fun String.tryBackwardsWordEndIndex(endIndex: Int = lastIndex, fallback: Int = endIndex): Int {
for (perfectFitIndex in endIndex downTo 0) {
// Another dirty hack for sq1: turns only line up
// nicely if every line starts with a (x,y). We ensure this
// by forcing every line to end with a /.
val isSquareOne = "/" in this
// Any spaces added for padding after a turn are considered part of
// that turn because they're actually NON_BREAKING_SPACE, not a ' '.
val terminatingChar = if (isSquareOne) '/' else ' '
val indexBias = if (isSquareOne) 1 else 0
if (this[perfectFitIndex - indexBias] == terminatingChar) {
return perfectFitIndex
}
}
// We walked all the way to the beginning of the line
// without finding a good breaking point.
// Give up and break in the middle of a word =(.
return fallback
}
private tailrec fun String.fillToWidthMax(padding: String, font: Font, maxLength: Float): String {
// Add $padding until the substring takes up as much space as is available on a line.
val paddedString = this + padding
val substringWidth = font.baseFont.getWidthPoint(paddedString, font.size)
if (substringWidth > maxLength) {
// substring is now too big for our line, so remove the last character.
return this
}
return paddedString.fillToWidthMax(padding, font, maxLength)
}
private fun String.toLineWrapChunk(font: Font) = Chunk(this).apply {
this.font = font
// Force a line wrap!
append("\n")
}
const val FITTEXT_FONTSIZE_PRECISION = 0.1f
/**
* Adapted from ColumnText.java in the itextpdf 5.3.0 source code.
* Added the newlinesAllowed argument.
*
* Fits the text to some rectangle adjusting the font size as needed.
* @param font the font to use
* @param text the text
* @param availableArea the rectangle where the text must fit
* @param maxFontSize the maximum font size
* @param newlinesAllowed output text can be split into lines
* @param leadingMultiplier leading multiplier between lines
*
* @return the calculated font size that makes the text fit
*/
fun fitText(font: Font, text: String, availableArea: Rectangle, maxFontSize: Float, newlinesAllowed: Boolean, leadingMultiplier: Float = 1f): Float {
return binarySearchDec(1f, maxFontSize, FITTEXT_FONTSIZE_PRECISION) {
val iterFont = Font(font.baseFont, it)
val lineChunks = text.splitToLineChunks(iterFont, availableArea.width)
// The font size seems to be a pretty good estimate for how
// much vertical space a row actually takes up.
val heightPerLine = it * leadingMultiplier
val totalHeight = lineChunks.size.toFloat() * heightPerLine
val shouldDecrease = totalHeight > availableArea.height
// If newlines are NOT allowed, but we had to split the text into more than
// one line, then our current guess is too large.
val mustDecrease = !newlinesAllowed && lineChunks.size > 1
shouldDecrease || mustDecrease
}
}
tailrec fun binarySearchInc(min: Float, max: Float, precision: Float, shouldIncrease: (Float) -> Boolean): Float {
if (max - min < precision) {
// Ground recursion: We have converged arbitrarily close to some target value.
return max
}
val potentialFontSize = (min + max) / 2f
val iterationShouldIncrease = shouldIncrease(potentialFontSize)
return if (iterationShouldIncrease) {
binarySearchInc(potentialFontSize, max, precision, shouldIncrease)
} else {
binarySearchInc(min, potentialFontSize, precision, shouldIncrease)
}
}
tailrec fun binarySearchDec(min: Float, max: Float, precision: Float, shouldDecrease: (Float) -> Boolean): Float {
if (max - min < precision) {
// Ground recursion: We have converged arbitrarily close to some target value.
return min
}
val potentialFontSize = (min + max) / 2f
val iterationShouldDecrease = shouldDecrease(potentialFontSize)
return if (iterationShouldDecrease) {
binarySearchDec(min, potentialFontSize, precision, shouldDecrease)
} else {
binarySearchDec(potentialFontSize, max, precision, shouldDecrease)
}
}
}
| gpl-3.0 | 50b8de4981a43b1efd0f2cd7e5e032b2 | 38.898876 | 153 | 0.647282 | 4.512071 | false | false | false | false |
mitallast/netty-queue | src/main/java/org/mitallast/queue/crdt/replication/DefaultReplicator.kt | 1 | 7795 | package org.mitallast.queue.crdt.replication
import com.google.inject.Inject
import com.google.inject.assistedinject.Assisted
import com.typesafe.config.Config
import gnu.trove.impl.sync.TSynchronizedLongLongMap
import gnu.trove.map.hash.TLongLongHashMap
import io.vavr.collection.Vector
import org.mitallast.queue.common.codec.Message
import org.mitallast.queue.common.component.AbstractLifecycleComponent
import org.mitallast.queue.common.events.EventBus
import org.mitallast.queue.common.logging.LoggingService
import org.mitallast.queue.crdt.bucket.Bucket
import org.mitallast.queue.crdt.event.ClosedLogSynced
import org.mitallast.queue.crdt.protocol.AppendEntries
import org.mitallast.queue.crdt.protocol.AppendRejected
import org.mitallast.queue.crdt.protocol.AppendSuccessful
import org.mitallast.queue.crdt.routing.RoutingReplica
import org.mitallast.queue.crdt.routing.fsm.RoutingTableFSM
import org.mitallast.queue.transport.TransportService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
class DefaultReplicator @Inject constructor(
config: Config,
logging: LoggingService,
private val fsm: RoutingTableFSM,
private val eventBus: EventBus,
private val transportService: TransportService,
@param:Assisted private val bucket: Bucket
) : AbstractLifecycleComponent(logging), Replicator {
private val lock = ReentrantLock()
private val scheduler = Executors.newSingleThreadScheduledExecutor()
private val replicationIndex = TSynchronizedLongLongMap(TLongLongHashMap(32, 0.5f, 0, 0))
private val replicationTimeout = TSynchronizedLongLongMap(TLongLongHashMap(32, 0.5f, 0, 0))
private val timeout = config.getDuration("crdt.timeout", TimeUnit.MILLISECONDS)
@Volatile private var open = true
private fun initialize() {
val routingTable = fsm.get()
val routingBucket = routingTable.buckets.get(this.bucket.index())
val replicas = routingBucket.replicas.remove(bucket.replica()).values()
for (replica in replicas) {
replicationTimeout.put(replica.id, System.currentTimeMillis() + timeout)
val appendEntries = AppendEntries(bucket.index(), bucket.replica(), 0, Vector.empty())
transportService.send(replica.member, appendEntries)
}
scheduler.scheduleWithFixedDelay({
lock.lock()
try {
maybeSendEntries()
} finally {
lock.unlock()
}
}, timeout, timeout, TimeUnit.MILLISECONDS)
}
override fun append(id: Long, event: Message) {
lock.lock()
try {
if (!open) {
throw IllegalStateException("closed")
}
bucket.log().append(id, event)
maybeSendEntries()
} finally {
lock.unlock()
}
}
override fun successful(message: AppendSuccessful) {
lock.lock()
try {
if (logger.isDebugEnabled) {
logger.debug("[replica={}:{}] append successful from={}:{} last={}",
bucket.index(), bucket.replica(),
message.bucket, message.replica, message.index)
}
if (replicationIndex.get(message.replica) < message.index) {
replicationIndex.put(message.replica, message.index)
}
replicationTimeout.put(message.replica, 0)
maybeSendEntries(message.replica)
maybeSync()
} finally {
lock.unlock()
}
}
override fun rejected(message: AppendRejected) {
lock.lock()
try {
logger.warn("[replica={}:{}] append rejected from={}:{} last={}",
bucket.index(), bucket.replica(),
message.bucket, message.replica, message.index)
if (replicationIndex.get(message.replica) < message.index) {
replicationIndex.put(message.replica, message.index)
}
replicationTimeout.put(message.replica, 0)
maybeSendEntries(message.replica)
maybeSync()
} finally {
lock.unlock()
}
}
override fun open() {
lock.lock()
try {
open = true
} finally {
lock.unlock()
}
}
override fun closeAndSync() {
lock.lock()
try {
open = false
maybeSync()
} finally {
lock.unlock()
}
}
private fun maybeSendEntries() {
val routingTable = fsm.get()
val routingBucket = routingTable.buckets.get(this.bucket.index())
routingBucket.replicas.remove(bucket.replica())
.values().forEach { this.maybeSendEntries(it) }
}
private fun maybeSendEntries(replica: Long) {
val routingTable = fsm.get()
val routingBucket = routingTable.buckets.get(bucket.index())
routingBucket.replicas.get(replica).forEach { this.maybeSendEntries(it) }
}
private fun maybeSendEntries(replica: RoutingReplica) {
if (replica.id == bucket.replica()) { // do not send to self
return
}
val timeout = replicationTimeout.get(replica.id)
if (timeout == 0L) {
if (logger.isTraceEnabled) {
logger.trace("[replica={}:{}] no request in progress at {}:{}",
bucket.index(), bucket.replica(),
bucket.index(), replica.id)
}
sendEntries(replica)
} else if (timeout < System.currentTimeMillis()) {
logger.warn("[replica={}:{}] request timeout at {}:{}",
bucket.index(), bucket.replica(),
bucket.index(), replica.id)
sendEntries(replica)
} else {
if (logger.isTraceEnabled) {
logger.trace("[replica={}:{}] request in progress to {}:{}",
bucket.index(), bucket.replica(),
bucket.index(), replica.id)
}
}
}
private fun sendEntries(replica: RoutingReplica) {
val prev = replicationIndex.get(replica.id)
val log = bucket.log()
val append = log.entriesFrom(prev).take(10000)
if (append.nonEmpty()) {
if (logger.isDebugEnabled) {
logger.debug("[replica={}:{}] send append to={}:{} prev={} entries: {}",
bucket.index(), bucket.replica(),
bucket.index(), replica.id, prev, append)
}
replicationTimeout.put(replica.id, System.currentTimeMillis() + timeout)
transportService.send(replica.member, AppendEntries(bucket.index(), bucket.replica(), prev, append))
} else {
if (logger.isTraceEnabled) {
logger.trace("no new entries")
}
}
}
private fun maybeSync() {
if (!open) {
val last = bucket.log().index()
val routingTable = fsm.get()
val routingBucket = routingTable.buckets.get(bucket.index())
val replicas = routingBucket.replicas.remove(bucket.replica()).values()
if (replicas.isEmpty) { // no replica
return
}
for (replica in replicas) {
if (replicationIndex.get(replica.id) != last) {
return // not synced
}
}
eventBus.trigger(ClosedLogSynced(bucket.index(), bucket.replica()))
}
}
override fun doStart() {
lock.lock()
try {
initialize()
} finally {
lock.unlock()
}
}
override fun doStop() {}
override fun doClose() {}
}
| mit | 12145e3f5bc9e699cb241af60df06646 | 34.431818 | 112 | 0.59474 | 4.667665 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/util/CrashReportExceptionHandler.kt | 1 | 4164 | package de.westnordost.streetcomplete.util
import android.app.Activity
import android.content.Context
import android.os.Build
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import de.westnordost.streetcomplete.BuildConfig
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.toast
import java.io.IOException
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/** Exception handler that takes care of asking the user to send the report of the last crash
* to the email address [mailReportTo].
* When a crash occurs, the stack trace is saved to [crashReportFile] so that it can be accessed
* on next startup */
@Singleton class CrashReportExceptionHandler @Inject constructor(
private val appCtx: Context,
private val mailReportTo: String,
private val crashReportFile: String
) : Thread.UncaughtExceptionHandler {
private var defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null
fun install(): Boolean {
val installerPackageName = appCtx.packageManager.getInstallerPackageName(appCtx.packageName)
// developer. Don't need this functionality (it might even interfere with unit tests)
if (installerPackageName == null) return false
// don't need this for google play users: they have their own crash reports
if (installerPackageName == "com.android.vending") return false
val ueh = Thread.getDefaultUncaughtExceptionHandler()
check(ueh !is CrashReportExceptionHandler) { "May not install several CrashReportExceptionHandlers!" }
defaultUncaughtExceptionHandler = ueh
Thread.setDefaultUncaughtExceptionHandler(this)
return true
}
fun askUserToSendCrashReportIfExists(activityCtx: Activity) {
if (hasCrashReport()) {
val reportText = readCrashReportFromFile()
deleteCrashReport()
askUserToSendErrorReport(activityCtx, R.string.crash_title, reportText)
}
}
fun askUserToSendErrorReport(activityCtx: Activity, @StringRes titleResourceId: Int, e: Exception) {
val stackTrace = StringWriter()
e.printStackTrace(PrintWriter(stackTrace))
askUserToSendErrorReport(activityCtx, titleResourceId, stackTrace.toString())
}
private fun askUserToSendErrorReport(activityCtx: Activity, @StringRes titleResourceId: Int, error: String?) {
val report = """
Describe how to reproduce it here:
$error
"""
AlertDialog.Builder(activityCtx)
.setTitle(titleResourceId)
.setMessage(R.string.crash_message)
.setPositiveButton(R.string.crash_compose_email) { _, _ ->
sendEmail(activityCtx, mailReportTo, "Error Report", report)
}
.setNegativeButton(android.R.string.no) { _, _ ->
activityCtx.toast("\uD83D\uDE22")
}
.setCancelable(false)
.show()
}
override fun uncaughtException(t: Thread, e: Throwable) {
val stackTrace = StringWriter()
e.printStackTrace(PrintWriter(stackTrace))
writeCrashReportToFile("""
Thread: ${t.name}
App version: ${BuildConfig.VERSION_NAME}
Device: ${Build.BRAND} ${Build.DEVICE}, Android ${Build.VERSION.RELEASE}
Locale: ${Locale.getDefault()}
Stack trace:
$stackTrace
"""
)
defaultUncaughtExceptionHandler!!.uncaughtException(t, e)
}
private fun writeCrashReportToFile(text: String) {
try {
appCtx.openFileOutput(crashReportFile, Context.MODE_PRIVATE).bufferedWriter().use { it.write(text) }
} catch (ignored: IOException) {
}
}
private fun hasCrashReport(): Boolean = appCtx.fileList().contains(crashReportFile)
private fun readCrashReportFromFile(): String? {
try {
return appCtx.openFileInput(crashReportFile).bufferedReader().use { it.readText() }
} catch (ignore: IOException) {
}
return null
}
private fun deleteCrashReport() {
appCtx.deleteFile(crashReportFile)
}
}
| gpl-3.0 | 2b7fcac1bbb220c2a79bb598673b9edc | 35.208696 | 114 | 0.699328 | 4.769759 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/coroutines/asyncIterator.kt | 2 | 3257 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
interface AsyncGenerator<in T> {
suspend fun yield(value: T)
}
interface AsyncSequence<out T> {
operator fun iterator(): AsyncIterator<T>
}
interface AsyncIterator<out T> {
operator suspend fun hasNext(): Boolean
operator suspend fun next(): T
}
fun <T> asyncGenerate(block: suspend AsyncGenerator<T>.() -> Unit): AsyncSequence<T> = object : AsyncSequence<T> {
override fun iterator(): AsyncIterator<T> {
val iterator = AsyncGeneratorIterator<T>()
iterator.nextStep = block.createCoroutine(receiver = iterator, completion = iterator)
return iterator
}
}
class AsyncGeneratorIterator<T>: AsyncIterator<T>, AsyncGenerator<T>, Continuation<Unit> {
var computedNext = false
var nextValue: T? = null
var nextStep: Continuation<Unit>? = null
// if (computesNext) computeContinuation is Continuation<T>
// if (!computesNext) computeContinuation is Continuation<Boolean>
var computesNext = false
var computeContinuation: Continuation<*>? = null
override val context = EmptyCoroutineContext
suspend fun computeHasNext(): Boolean = suspendCoroutineOrReturn { c ->
computesNext = false
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
suspend fun computeNext(): T = suspendCoroutineOrReturn { c ->
computesNext = true
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
@Suppress("UNCHECKED_CAST")
fun resumeIterator(exception: Throwable?) {
if (exception != null) {
done()
computeContinuation!!.resumeWithException(exception)
return
}
if (computesNext) {
computedNext = false
(computeContinuation as Continuation<T>).resume(nextValue as T)
} else {
(computeContinuation as Continuation<Boolean>).resume(nextStep != null)
}
}
override suspend fun hasNext(): Boolean {
if (!computedNext) return computeHasNext()
return nextStep != null
}
override suspend fun next(): T {
if (!computedNext) return computeNext()
computedNext = false
return nextValue as T
}
private fun done() {
computedNext = true
nextStep = null
}
// Completion continuation implementation
override fun resume(value: Unit) {
done()
resumeIterator(null)
}
override fun resumeWithException(exception: Throwable) {
done()
resumeIterator(exception)
}
// Generator implementation
override suspend fun yield(value: T): Unit = suspendCoroutineOrReturn { c ->
computedNext = true
nextValue = value
nextStep = c
resumeIterator(null)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun box(): String {
val seq = asyncGenerate {
yield("O")
yield("K")
}
var res = ""
builder {
for (i in seq) {
res += i
}
}
return res
}
| apache-2.0 | 69db6b382c9132c85b122804c648b5dd | 25.056 | 114 | 0.632177 | 4.686331 | false | false | false | false |
walleth/walleth | app/src/online/java/org/walleth/workers/RelayTransactionWorker.kt | 1 | 2855 | package org.walleth.workers
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import org.kethereum.extensions.transactions.encode
import org.kethereum.model.ChainId
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.komputing.khex.extensions.toHexString
import org.walleth.data.AppDatabase
import org.walleth.data.KEY_TX_HASH
import org.walleth.data.rpc.RPCProvider
import org.walleth.data.transactions.TransactionEntity
import org.walleth.data.transactions.setHash
import timber.log.Timber
class RelayTransactionWorker(appContext: Context, workerParams: WorkerParameters)
: CoroutineWorker(appContext, workerParams), KoinComponent {
private val appDatabase: AppDatabase by inject()
private val rpcProvider: RPCProvider by inject()
override suspend fun doWork(): Result {
val txHash = inputData.getString(KEY_TX_HASH)
val transaction: TransactionEntity? = txHash?.let { appDatabase.transactions.getByHash(it) }
if (transaction == null) {
Timber.i("Cannot load address with $txHash")
return Result.failure()
}
val chain = transaction.transaction.chain
val rpc = chain?.let { rpcProvider.getForChain(ChainId(it)) }
if (rpc == null) {
transaction.setError("RPC not found for chain $chain")
return Result.failure()
}
try {
val result = rpc.sendRawTransaction(transaction.transaction.encode(transaction.signatureData).toHexString())
return if (result != null) {
transaction.setHash(if (!result.startsWith("0x")) "0x$result" else result)
transaction.transactionState.eventLog = transaction.transactionState.eventLog ?: "" + "relayed"
markSuccess(transaction)
} else {
transaction.setError("Could not (yet) relay transaction")
Result.retry()
}
} catch (e: Exception) {
return if (e.message == "Transaction with the same hash was already imported." || e.message?.startsWith("known transaction") == true) {
markSuccess(transaction)
} else {
transaction.transactionState.eventLog = transaction.transactionState.eventLog ?: "" + "ERROR: ${e.message}\n"
transaction.setError(e.message)
Result.failure()
}
}
}
private fun markSuccess(transaction: TransactionEntity): Result {
transaction.transactionState.relayed = "via RPC"
transaction.setError(null)
return Result.success()
}
private fun TransactionEntity.setError(message: String?) {
transactionState.error = message
appDatabase.transactions.upsert(this)
}
} | gpl-3.0 | ec883b1b236551232803982bcb247116 | 34.7 | 147 | 0.670053 | 4.73466 | false | false | false | false |
modcrafters/Bush-Master-Core | src/main/kotlin/net/ndrei/bushmaster/integrations/PlantsBushFactory.kt | 1 | 2303 | package net.ndrei.bushmaster.integrations
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraft.world.WorldServer
import net.ndrei.bushmaster.BushMasterCore
import net.ndrei.bushmaster.api.IHarvestable
import net.ndrei.bushmaster.api.IHarvestableFactory
import net.ndrei.bushmaster.couldBe
import net.ndrei.bushmaster.loot
import net.ndrei.bushmaster.testBoolProperty
class PlantsBushFactory : IHarvestableFactory {
override fun getHarvestable(world: World, pos: BlockPos, state: IBlockState) =
when {
PlantsBushWrapper.canHarvest(state) -> PlantsBushWrapper
else -> null
}
object PlantsBushWrapper: IHarvestable {
fun canHarvest(state: IBlockState) =
state.block.javaClass.couldBe("shadows.plants2.block.forgotten.BlockBushLeaves")
// state.block.javaClass.couldBe("shadows.plants2.block.BlockEnumHarvestBush")
override fun canBeHarvested(worldIn: World, pos: BlockPos, state: IBlockState) =
this.canHarvest(state) && state.testBoolProperty("fruit")
override fun harvest(loot: MutableList<ItemStack>, worldIn: World, pos: BlockPos, state: IBlockState, simulate: Boolean) {
val block = state.block
if (!simulate && (worldIn is WorldServer)) {
val fake = BushMasterCore.getFakePlayer(worldIn)
block.onBlockActivated(worldIn, pos, state, fake, EnumHand.MAIN_HAND, EnumFacing.UP, .5f, .5f, .5f)
fake.loot(loot)
// pos.collect(loot, worldIn, 1) // @shadows said it's fine :)
}
// else if (!simulate && (block is IShearable)) {
// val shears = ItemStack(Items.SHEARS)
// if (block.isShearable(shears, worldIn, pos)) {
// loot.addAll(block.onSheared(shears, worldIn, pos, 1))
// }
// else {
// loot.addAll(NonNullList.create<ItemStack>().also {
// block.getDrops(it, worldIn, pos, state, 1)
// })
// }
// }
}
}
}
| mit | eea78d165df33e559dbd8eaab2938b93 | 42.45283 | 130 | 0.642206 | 3.950257 | false | false | false | false |
rlac/unitconverter | app/src/main/kotlin/au/id/rlac/unitconverter/app/MainActivity.kt | 1 | 2673 | package au.id.rlac.unitconverter.app
import android.app.Fragment
import android.app.FragmentManager
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v13.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import au.id.rlac.unitconverter.R
import au.id.rlac.unitconverter.converter.UnitConverter
import au.id.rlac.util.android.delegates.viewById
import au.id.rlac.util.android.isLollipop
class MainActivity : AppCompatActivity() {
val tabs: TabLayout by viewById(R.id.tabs)
val pager: ViewPager by viewById(R.id.pager)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
val adapter = TabPageAdapter(getFragmentManager())
pager.setAdapter(adapter)
tabs.setTabMode(TabLayout.MODE_SCROLLABLE)
tabs.setupWithViewPager(pager)
fun onPageChanged(position: Int) {
val theme = UnitConverter.Theme(
this@MainActivity,
adapter.positionToConverter(position))
tabs.setBackgroundColor(theme.colorPrimary)
if (isLollipop) getWindow().setStatusBarColor(theme.colorPrimaryDark)
}
pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
onPageChanged(position)
Preferences.lastConverter = adapter.positionToConverter(position)
}
})
if (savedInstanceState == null) {
pager.setCurrentItem(adapter.converterToPosition(Preferences.lastConverter))
}
onPageChanged(pager.getCurrentItem())
}
inner class TabPageAdapter(val fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment =
ConverterFragment(positionToConverter(position))
override fun getCount(): Int = 5
override fun getPageTitle(position: Int): CharSequence =
getString(positionToConverter(position).displayNameResId)
fun converterToPosition(uc: UnitConverter) =
when (uc) {
UnitConverter.LENGTH -> 0
UnitConverter.ENERGY -> 1
UnitConverter.MASS -> 2
UnitConverter.TEMPERATURE -> 3
UnitConverter.VOLUME -> 4
else -> throw IndexOutOfBoundsException()
}
fun positionToConverter(position: Int): UnitConverter =
when (position) {
0 -> UnitConverter.LENGTH
1 -> UnitConverter.ENERGY
2 -> UnitConverter.MASS
3 -> UnitConverter.TEMPERATURE
4 -> UnitConverter.VOLUME
else -> throw IndexOutOfBoundsException()
}
}
}
| apache-2.0 | f0277bab7efa7c424478732fa2745c25 | 32 | 83 | 0.716423 | 4.608621 | false | false | false | false |
duncte123/SkyBot | src/main/kotlin/ml/duncte123/skybot/commands/utils/RoleInfoCommand.kt | 1 | 3942 | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.utils
import com.jagrosh.jdautilities.commons.utils.FinderUtil
import me.duncte123.botcommons.messaging.EmbedUtils
import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed
import me.duncte123.botcommons.messaging.MessageUtils.sendMsg
import ml.duncte123.skybot.extensions.parseTimeCreated
import ml.duncte123.skybot.extensions.toEmoji
import ml.duncte123.skybot.objects.command.Command
import ml.duncte123.skybot.objects.command.CommandCategory
import ml.duncte123.skybot.objects.command.CommandContext
import ml.duncte123.skybot.utils.AirUtils.colorToHex
import net.dv8tion.jda.api.entities.Role
class RoleInfoCommand : Command() {
init {
this.category = CommandCategory.UTILS
this.name = "roleinfo"
this.aliases = arrayOf("role", "ri")
this.help = "Displays info about a specified role or the highest role that you have"
this.usage = "[@role]"
}
override fun execute(ctx: CommandContext) {
// Obtain the list of target roles
// If the arguments are empty we will use the roles that the member has
// otherwise we will pick the one that is mentioned
val roles: List<Role> = if (ctx.args.isEmpty()) {
ctx.member.roles
} else {
FinderUtil.findRoles(ctx.argsRaw, ctx.jdaGuild)
}
// If there are no roles found we need to send an error message with a small hint
if (roles.isEmpty()) {
sendMsg(
ctx,
"""No roles found, make sure that you have a role or are typing the name of a role on this server
|Hint: you can use `${ctx.prefix}roles` to get a list of the roles in this server
""".trimMargin()
)
return
}
val role = roles[0]
val perms = role.permissions.joinToString { it.getName() }
val memberCount = ctx.jdaGuild.findMembersWithRoles(role).get().size
val times = role.parseTimeCreated()
val tags = role.tags
val botDisp = if (tags.isBot) "\n**Bot:** <@${tags.botIdLong}>" else ""
val embed = EmbedUtils.getDefaultEmbed()
.setColor(role.colorRaw)
.setDescription(
"""__Role info for ${role.asMention}__
|
|**Color:** ${colorToHex(role.colorRaw)}
|**Id:** ${role.id}
|**Name:** ${role.name}
|**Created:** ${times.first} (${times.second})
|**Position:** ${role.position}
|**Members with this role:** $memberCount
|**Managed:** ${role.isManaged.toEmoji()}
|**Bot role:** ${tags.isBot.toEmoji()}$botDisp
|**Boost role:** ${tags.isBoost.toEmoji()}
|**Integration role:** ${tags.isIntegration.toEmoji()}
|**Hoisted:** ${role.isHoisted.toEmoji()}
|**Mentionable:** ${role.isMentionable.toEmoji()}
|**Permissions:** $perms
""".trimMargin()
)
sendEmbed(ctx, embed, true)
}
}
| agpl-3.0 | 92ca88c862ad648249ce4ed23594e128 | 40.494737 | 113 | 0.6276 | 4.308197 | false | false | false | false |
Kaljurand/K6nele | app/src/main/java/ee/ioc/phon/android/speak/demo/AbstractRecognizerDemoActivity.kt | 1 | 6205 | /*
* Copyright 2011-2018, Institute of Cybernetics at Tallinn University of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ee.ioc.phon.android.speak.demo
import androidx.appcompat.app.AppCompatActivity
import android.content.Intent
import android.content.pm.ResolveInfo
import android.speech.RecognizerIntent
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import ee.ioc.phon.android.speak.R
import ee.ioc.phon.android.speak.activity.GrammarListActivity
import ee.ioc.phon.android.speak.provider.Grammar
import ee.ioc.phon.android.speak.utils.Utils
import ee.ioc.phon.android.speechutils.Extras
import java.util.*
/**
* This demo shows how to create an input to RecognizerIntent.ACTION_RECOGNIZE_SPEECH
* and how to respond to its output (list of matched words or an error code). This is
* an abstract class, the UI part is in the extensions of this class.
*
* @author Kaarel Kaljurand
*/
abstract class AbstractRecognizerDemoActivity : AppCompatActivity() {
private var mGrammarId: Long = 0
private val grammarName: String?
get() = Utils.idToValue(this, Grammar.Columns.CONTENT_URI, Grammar.Columns._ID, Grammar.Columns.NAME, mGrammarId)
private val grammarUrl: String?
get() = Utils.idToValue(this, Grammar.Columns.CONTENT_URI, Grammar.Columns._ID, Grammar.Columns.URL, mGrammarId)
private val grammarTargetLang: String?
get() = Utils.idToValue(this, Grammar.Columns.CONTENT_URI, Grammar.Columns._ID, Grammar.Columns.LANG, mGrammarId)
protected abstract fun onSuccess(intent: Intent?)
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.demo_grammar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuDemoGrammarAssign -> {
val intent = Intent(this@AbstractRecognizerDemoActivity, GrammarListActivity::class.java)
startActivityForResult(intent, ACTIVITY_SELECT_GRAMMAR_URL)
return true
}
else -> return super.onContextItemSelected(item)
}
}
protected open fun onCancel() {
toast(getString(R.string.errorResultCanceled))
finish()
}
protected open fun onError(errorCode: Int) {
toast(getErrorMessage(errorCode))
finish()
}
protected fun getErrorMessage(errorCode: Int): String {
when (errorCode) {
RecognizerIntent.RESULT_AUDIO_ERROR -> return getString(R.string.errorResultAudioError)
RecognizerIntent.RESULT_CLIENT_ERROR -> return getString(R.string.errorResultClientError)
RecognizerIntent.RESULT_NETWORK_ERROR -> return getString(R.string.errorResultNetworkError)
RecognizerIntent.RESULT_SERVER_ERROR -> return getString(R.string.errorResultServerError)
RecognizerIntent.RESULT_NO_MATCH -> return getString(R.string.errorResultNoMatch)
else -> return "Unknown error"
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == ACTIVITY_SELECT_GRAMMAR_URL) {
if (resultCode != AppCompatActivity.RESULT_OK) {
return
}
val grammarUri = data?.data
if (grammarUri == null) {
toast(getString(R.string.errorFailedGetGrammarUrl))
} else {
mGrammarId = java.lang.Long.parseLong(grammarUri.pathSegments[1])
toast(String.format(getString(R.string.toastAssignGrammar),
Utils.idToValue(this, Grammar.Columns.CONTENT_URI, Grammar.Columns._ID, Grammar.Columns.NAME, mGrammarId)))
}
} else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) {
if (resultCode == AppCompatActivity.RESULT_OK) {
onSuccess(data)
} else if (resultCode == AppCompatActivity.RESULT_CANCELED) {
onCancel()
} else {
onError(resultCode)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
protected fun getRecognizers(intent: Intent): List<ResolveInfo> {
val pm = packageManager
return pm.queryIntentActivities(intent, 0)
}
protected fun createRecognizerIntent(action: String): Intent {
val intent = Intent(action)
val prompt: String
if (mGrammarId == 0L) {
val phrasesDemo = resources.getStringArray(R.array.phrasesDemo)
val phraseDemo = phrasesDemo[Random().nextInt(phrasesDemo.size)]
intent.putExtra(Extras.EXTRA_PHRASE, phraseDemo)
prompt = String.format(getString(R.string.promptDemo), phraseDemo)
} else {
val grammarTargetLang = grammarTargetLang
intent.putExtra(Extras.EXTRA_GRAMMAR_URL, grammarUrl)
intent.putExtra(Extras.EXTRA_GRAMMAR_TARGET_LANG, grammarTargetLang)
prompt = "Speak $grammarName to $grammarTargetLang"
}
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt)
intent.putExtra(Extras.EXTRA_VOICE_PROMPT, prompt)
return intent
}
protected fun launchRecognizerIntent(intent: Intent) {
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE)
}
protected fun toast(message: String) {
Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()
}
companion object {
private val VOICE_RECOGNITION_REQUEST_CODE = 1234
private val ACTIVITY_SELECT_GRAMMAR_URL = 1
}
} | apache-2.0 | 74f6426ac5a6aba91dc071f06e03c593 | 37.7875 | 131 | 0.679291 | 4.419516 | false | false | false | false |
JoeSteven/HuaBan | app/src/main/java/com/joe/zatuji/repo/bean/request/UserUpdateParams.kt | 1 | 588 | package com.joe.zatuji.repo.bean.request
import com.google.gson.annotations.SerializedName
import com.joe.zatuji.repo.bean.Relation
/**
* Description:
* author:Joey
* date:2018/11/20
*/
data class UserUpdateParams(@SerializedName("nickname")val nickName: String? = null,
@SerializedName("avatar")val avatar: String? = null,
@SerializedName("cdn")val cdn: String? = null,
@SerializedName("email")val email: String? = null,
@SerializedName("tag")val tag: Relation? = null) | apache-2.0 | aed961251db7d70ff9930b7f3c124027 | 38.266667 | 84 | 0.607143 | 4.323529 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/util/wizard/WizardManager.kt | 1 | 1991 | package org.wordpress.android.util.wizard
import androidx.lifecycle.LiveData
import org.wordpress.android.viewmodel.SingleLiveEvent
private const val DEFAULT_STEP_INDEX = -1
class WizardManager<T : WizardStep>(
private val steps: List<T>
) {
private var currentStepIndex: Int = DEFAULT_STEP_INDEX
val stepsCount = steps.size
val currentStep: Int
get() = currentStepIndex
private val _navigatorLiveData = SingleLiveEvent<T>()
val navigatorLiveData: LiveData<T> = _navigatorLiveData
@Suppress("UseCheckOrError")
fun showNextStep() {
if (isIndexValid(++currentStepIndex)) {
_navigatorLiveData.value = steps[currentStepIndex]
} else {
throw IllegalStateException("Invalid index.")
}
}
fun onBackPressed() {
--currentStepIndex
}
private fun isIndexValid(currentStepIndex: Int): Boolean {
return currentStepIndex >= 0 && currentStepIndex < steps.size
}
fun isLastStep(): Boolean {
return !isIndexValid(currentStepIndex + 1)
}
@Suppress("UseCheckOrError")
fun stepPosition(T: WizardStep): Int {
return if (steps.contains(T)) {
steps.indexOf(T) + 1
} else {
throw IllegalStateException("Step $T is not present.")
}
}
@Suppress("UseCheckOrError")
fun setCurrentStepIndex(stepIndex: Int) {
if (!isIndexValid(stepIndex)) {
throw IllegalStateException("Invalid index.")
}
currentStepIndex = stepIndex
}
}
/**
* Marker interface representing a single step/screen in a wizard
*/
interface WizardStep
/**
* Marker interface representing a state which contains all gathered data from the user input.
*/
interface WizardState
/**
* Navigation target containing all the data needed for navigating the user to a next screen of the wizard.
*/
class WizardNavigationTarget<S : WizardStep, T : WizardState>(val wizardStep: S, val wizardState: T)
| gpl-2.0 | d8ebb35d8e6611ad42db65f7c7d559aa | 27.042254 | 107 | 0.671522 | 4.608796 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/InterfaceTraverser.kt | 1 | 5092 | // 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.codegen
import com.intellij.workspaceModel.codegen.deft.model.DefType
import com.intellij.workspaceModel.codegen.deft.model.KtInterfaceKind
import com.intellij.workspaceModel.codegen.deft.model.WsData
import com.intellij.workspaceModel.codegen.deft.*
import com.intellij.workspaceModel.codegen.deft.Field
class InterfaceTraverser(
val simpleTypes: List<DefType>
) {
fun traverse(myInterface: DefType, visitor: InterfaceVisitor): Boolean {
for (field in myInterface.structure.declaredFields) {
val res = traverseField(field, visitor, field.name, myInterface.def.kind)
if (!res) return false
}
return true
}
private fun traverseField(field: Field<*, *>, visitor: InterfaceVisitor, varName: String, kind: KtInterfaceKind?): Boolean {
return traverseType(field.type, visitor, varName, kind)
}
private fun traverseType(type: ValueType<*>, visitor: InterfaceVisitor, varName: String, kind: KtInterfaceKind?): Boolean {
when (type) {
is TBoolean -> return visitor.visitBoolean(varName)
is TInt -> return visitor.visitInt(varName)
is TString -> return visitor.visitString(varName)
is TCollection<*, *> -> {
val itemVarName = "_$varName"
val shouldProcessList = visitor.visitListStart(varName, itemVarName, type.elementType)
if (!shouldProcessList) return false
val traversingResult = traverseType(type.elementType, visitor, itemVarName, kind)
return visitor.visitListEnd(varName, itemVarName, traversingResult, type.elementType)
}
is TMap<*, *> -> {
val keyVarName = "key_$varName"
val valueVarName = "value_$varName"
val shouldProcessMap = visitor.visitMapStart(varName, keyVarName, valueVarName, type.keyType, type.valueType)
if (!shouldProcessMap) return false
val keyTraverseResult = traverseType(type.keyType, visitor, keyVarName, kind)
val valueTraverseResult = traverseType(type.valueType, visitor, valueVarName, kind)
return visitor.visitMapEnd(varName, keyVarName, valueVarName, type.keyType, type.valueType,
keyTraverseResult && valueTraverseResult)
}
is TOptional<*> -> {
val notNullVarName = "_$varName"
var continueProcess = visitor.visitOptionalStart(varName, notNullVarName, type.type)
if (!continueProcess) return false
continueProcess = traverseType(type.type, visitor, notNullVarName, kind)
return visitor.visitOptionalEnd(varName, notNullVarName, type.type, continueProcess)
}
is TBlob<*> -> {
val foundType = simpleTypes.find { it.name == type.javaSimpleName }
if (foundType == null) {
return visitor.visitUnknownBlob(varName, type.javaSimpleName)
} else {
if (kind == WsData) {
var process = visitor.visitDataClassStart(varName, type.javaSimpleName, foundType)
if (!process) return false
process = traverse(foundType, visitor)
return visitor.visitDataClassEnd(varName, type.javaSimpleName, process, foundType)
}
return false
/*
var process = visitor.visitKnownBlobStart(varName, type.javaSimpleName)
if (!process) return false
process = traverse(foundType, visitor)
return visitor.visitKnownBlobFinish(varName, type.javaSimpleName, process)
*/
}
}
else -> {}
}
return true
}
}
interface InterfaceVisitor {
fun visitBoolean(varName: String): Boolean
fun visitInt(varName: String): Boolean
fun visitString(varName: String): Boolean
fun visitListStart(varName: String, itemVarName: String, listArgumentType: ValueType<*>): Boolean
fun visitListEnd(varName: String, itemVarName: String, traverseResult: Boolean, listArgumentType: ValueType<*>): Boolean
fun visitMapStart(varName: String, keyVarName: String, valueVarName: String, keyType: ValueType<*>, valueType: ValueType<*>): Boolean
fun visitMapEnd(varName: String,
keyVarName: String,
valueVarName: String,
keyType: ValueType<*>,
valueType: ValueType<*>,
traverseResult: Boolean): Boolean
fun visitOptionalStart(varName: String, notNullVarName: String, type: ValueType<*>): Boolean
fun visitOptionalEnd(varName: String, notNullVarName: String, type: ValueType<*>, traverseResult: Boolean): Boolean
fun visitUnknownBlob(varName: String, javaSimpleName: String): Boolean
fun visitKnownBlobStart(varName: String, javaSimpleName: String): Boolean
fun visitKnownBlobFinish(varName: String, javaSimpleName: String, traverseResult: Boolean): Boolean
fun visitDataClassStart(varName: String, javaSimpleName: String, foundType: DefType): Boolean
fun visitDataClassEnd(varName: String, javaSimpleName: String, traverseResult: Boolean, foundType: DefType): Boolean
}
| apache-2.0 | f850324f4cf889733a181bc63e6b63fc | 43.278261 | 135 | 0.701296 | 4.583258 | false | false | false | false |
android/nowinandroid | core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstAuthorsRepository.kt | 1 | 2899 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.data.repository
import com.google.samples.apps.nowinandroid.core.data.Synchronizer
import com.google.samples.apps.nowinandroid.core.data.changeListSync
import com.google.samples.apps.nowinandroid.core.data.model.asEntity
import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel
import com.google.samples.apps.nowinandroid.core.datastore.ChangeListVersions
import com.google.samples.apps.nowinandroid.core.model.data.Author
import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
/**
* Disk storage backed implementation of the [AuthorsRepository].
* Reads are exclusively from local storage to support offline access.
*/
class OfflineFirstAuthorsRepository @Inject constructor(
private val authorDao: AuthorDao,
private val network: NiaNetworkDataSource,
) : AuthorsRepository {
override fun getAuthorStream(id: String): Flow<Author> =
authorDao.getAuthorEntityStream(id).map {
it.asExternalModel()
}
override fun getAuthorsStream(): Flow<List<Author>> =
authorDao.getAuthorEntitiesStream()
.map { it.map(AuthorEntity::asExternalModel) }
override suspend fun syncWith(synchronizer: Synchronizer): Boolean =
synchronizer.changeListSync(
versionReader = ChangeListVersions::authorVersion,
changeListFetcher = { currentVersion ->
network.getAuthorChangeList(after = currentVersion)
},
versionUpdater = { latestVersion ->
copy(authorVersion = latestVersion)
},
modelDeleter = authorDao::deleteAuthors,
modelUpdater = { changedIds ->
val networkAuthors = network.getAuthors(ids = changedIds)
authorDao.upsertAuthors(
entities = networkAuthors.map(NetworkAuthor::asEntity)
)
}
)
}
| apache-2.0 | 2cbfde8709ab2423498ca6d221e0aef4 | 41.632353 | 79 | 0.729217 | 4.536776 | false | false | false | false |
carltonwhitehead/crispy-fish | library/src/test/kotlin/org/coner/crispyfish/util/ResultConditions.kt | 1 | 1459 | package org.coner.crispyfish.util
import org.assertj.core.api.Condition
import org.assertj.core.condition.AllOf
import org.coner.crispyfish.model.Result
import java.util.function.Predicate
object ResultConditions {
fun positionEquals(position: Int) = Condition<Result>(
Predicate{ result -> result.position == position },
"result.position == %d",
position
)
fun driverNumbersEqual(category: String?, handicap: String, number: String) = Condition<Result>(
Predicate { result ->
(result.driver?.category?.abbreviation ?: "").equals(category, ignoreCase = true)
&& result.driver?.handicap?.abbreviation.equals(handicap, ignoreCase = true)
&& result.driver?.number == number
},
"result.driver == %s",
"${category ?: ""}$handicap $number"
)
fun driverNameNotNullOrEmpty(): Condition<Result> {
return Condition(Predicate{ result ->
!result.driver?.firstName.isNullOrBlank()
&& !result.driver?.lastName.isNullOrBlank()
}, "result.driver first and last last names are not null or blank")
}
fun driverFinished(position: Int, category: String?, handicap: String, number: String): Condition<Result> {
return AllOf.allOf(
positionEquals(position),
driverNumbersEqual(category, handicap, number)
)
}
}
| gpl-2.0 | 101ce5f10a8360f39b22db417c7994ec | 36.410256 | 111 | 0.620973 | 4.559375 | false | false | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/grammar/tabs/rules/component/GrazieDescriptionComponent.kt | 8 | 3040 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.ui.grammar.tabs.rules.component
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.ide.ui.components.dsl.padding
import com.intellij.grazie.ide.ui.components.dsl.panel
import com.intellij.grazie.ide.ui.components.utils.GrazieLinkLabel
import com.intellij.grazie.jlanguage.Lang
import com.intellij.grazie.text.Rule
import com.intellij.grazie.utils.html
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.layout.migLayout.*
import com.intellij.util.ui.HTMLEditorKitBuilder
import com.intellij.util.ui.JBUI
import kotlinx.html.unsafe
import net.miginfocom.layout.CC
import net.miginfocom.swing.MigLayout
import org.jetbrains.annotations.NotNull
import java.awt.BorderLayout
import javax.swing.JEditorPane
import javax.swing.ScrollPaneConstants
class GrazieDescriptionComponent {
private val description = JEditorPane().apply {
editorKit = HTMLEditorKitBuilder.simple()
isEditable = false
isOpaque = true
border = null
background = null
addHyperlinkListener(BrowserHyperlinkListener())
}
private val link = GrazieLinkLabel(msg("grazie.settings.grammar.rule.description")).apply {
component.isVisible = false
}
val listener: (Any) -> Unit
get() = { selection ->
val url = if (selection is Rule) selection.url else null
if (url != null) {
link.listener = LinkListener { _: @NotNull LinkLabel<Any?>, _: Any? -> BrowserUtil.browse(url) }
}
link.component.isVisible = url != null
val content = getDescriptionPaneContent(selection)
description.text = content
description.isVisible = content.isNotBlank()
}
val component = panel(MigLayout(createLayoutConstraints().flowY().fillX().gridGapY("7"))) {
border = padding(JBUI.insets(30, 20, 0, 0))
add(link.component, CC().grow().hideMode(3))
val descriptionPanel = JBPanelWithEmptyText(BorderLayout(0, 0)).withEmptyText(msg("grazie.settings.grammar.rule.no-description"))
descriptionPanel.add(description)
add(ScrollPaneFactory.createScrollPane(descriptionPanel, SideBorder.NONE).also {
it.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
}, CC().grow().push())
}
@NlsSafe
private fun getDescriptionPaneContent(meta: Any): String = when (meta) {
is Lang -> html { unsafe { +msg("grazie.settings.grammar.rule.language.template", meta.nativeName) } }
is String -> html { unsafe { +msg("grazie.settings.grammar.rule.category.template", meta) } }
is Rule -> meta.description
else -> ""
}
}
| apache-2.0 | ab9b4dd2b13997a551ffe04a694c91f1 | 40.081081 | 140 | 0.755921 | 4.14734 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/StubBasedPackageMemberDeclarationProvider.kt | 1 | 4680 | // 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.stubindex.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils
import org.jetbrains.kotlin.idea.stubindex.*
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.idea.vfilefinder.KotlinPackageSourcesMemberNamesIndex
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.safeNameForLazyResolve
import org.jetbrains.kotlin.resolve.lazy.data.KtClassInfoUtil
import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo
import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo
import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
class StubBasedPackageMemberDeclarationProvider(
private val fqName: FqName,
private val project: Project,
private val searchScope: GlobalSearchScope
) : PackageMemberDeclarationProvider {
override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List<KtDeclaration> {
val fqNameAsString = fqName.asString()
val result = ArrayList<KtDeclaration>()
fun addFromIndex(index: KotlinStringStubIndexExtension<out KtNamedDeclaration>) {
index.processElements(fqNameAsString, project, searchScope) {
if (nameFilter(it.nameAsSafeName)) {
result.add(it)
}
true
}
}
if (kindFilter.acceptsKinds(DescriptorKindFilter.CLASSIFIERS_MASK)) {
addFromIndex(KotlinTopLevelClassByPackageIndex)
addFromIndex(KotlinTopLevelTypeAliasByPackageIndex)
}
if (kindFilter.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
addFromIndex(KotlinTopLevelFunctionByPackageIndex)
}
if (kindFilter.acceptsKinds(DescriptorKindFilter.VARIABLES_MASK)) {
addFromIndex(KotlinTopLevelPropertyByPackageIndex)
}
return result
}
private val declarationNames_: Set<Name> by lazy(LazyThreadSafetyMode.PUBLICATION) {
FileBasedIndex.getInstance()
.getValues(KotlinPackageSourcesMemberNamesIndex.KEY, fqName.asString(), searchScope)
.flatMapTo(hashSetOf()) {
it.map { stringName -> Name.identifier(stringName).safeNameForLazyResolve() }
}
}
override fun getDeclarationNames() = declarationNames_
override fun getClassOrObjectDeclarations(name: Name): Collection<KtClassOrObjectInfo<*>> = runReadAction {
KotlinFullClassNameIndex.get(childName(name), project, searchScope)
.map { KtClassInfoUtil.createClassOrObjectInfo(it) }
}
override fun getScriptDeclarations(name: Name): Collection<KtScriptInfo> = runReadAction {
KotlinScriptFqnIndex.get(childName(name), project, searchScope)
.map(::KtScriptInfo)
}
override fun getFunctionDeclarations(name: Name): Collection<KtNamedFunction> {
return runReadAction {
KotlinTopLevelFunctionFqnNameIndex.get(childName(name), project, searchScope)
}
}
override fun getPropertyDeclarations(name: Name): Collection<KtProperty> {
return runReadAction {
KotlinTopLevelPropertyFqnNameIndex.get(childName(name), project, searchScope)
}
}
override fun getDestructuringDeclarationsEntries(name: Name): Collection<KtDestructuringDeclarationEntry> {
return emptyList()
}
override fun getAllDeclaredSubPackages(nameFilter: (Name) -> Boolean): Collection<FqName> {
return KotlinPackageIndexUtils.getSubPackageFqNames(fqName, searchScope, nameFilter)
}
override fun getPackageFiles(): Collection<KtFile> {
return KotlinPackageIndexUtils.findFilesWithExactPackage(fqName, searchScope, project)
}
override fun containsFile(file: KtFile): Boolean {
return searchScope.contains(file.virtualFile ?: return false)
}
override fun getTypeAliasDeclarations(name: Name): Collection<KtTypeAlias> {
return KotlinTopLevelTypeAliasFqNameIndex.get(childName(name), project, searchScope)
}
private fun childName(name: Name): String {
return fqName.child(name.safeNameForLazyResolve()).asString()
}
}
| apache-2.0 | 690f0f4831f4a2eab6abfe970f66e418 | 40.415929 | 158 | 0.735684 | 5.081433 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/contacts/LetterHeaderDecoration.kt | 2 | 2920 | package org.thoughtcrime.securesms.contacts
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.util.ViewUtil
/**
* ItemDecoration which paints a letter header at the appropriate location above a LetterHeaderItem.
*/
class LetterHeaderDecoration(private val context: Context, private val hideDecoration: () -> Boolean) : RecyclerView.ItemDecoration() {
private val textBounds = Rect()
private val bounds = Rect()
private val padTop = ViewUtil.dpToPx(16)
private val padStart = context.resources.getDimensionPixelSize(R.dimen.dsl_settings_gutter)
private var dividerHeight = -1
private val textPaint = Paint().apply {
color = ContextCompat.getColor(context, R.color.signal_text_primary)
isAntiAlias = true
style = Paint.Style.FILL
typeface = Typeface.create("sans-serif-medium", Typeface.BOLD)
textAlign = Paint.Align.LEFT
textSize = ViewUtil.spToPx(16f).toFloat()
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val viewHolder = parent.getChildViewHolder(view)
if (hideDecoration() || viewHolder !is LetterHeaderItem || viewHolder.getHeaderLetter() == null) {
outRect.set(0, 0, 0, 0)
return
}
if (dividerHeight == -1) {
val v = LayoutInflater.from(context).inflate(R.layout.dsl_section_header, parent, false)
v.measure(0, 0)
dividerHeight = v.measuredHeight
}
outRect.set(0, dividerHeight, 0, 0)
}
override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (hideDecoration()) {
return
}
val childCount = parent.childCount
val isRtl = parent.layoutDirection == View.LAYOUT_DIRECTION_RTL
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val holder = parent.getChildViewHolder(child)
val headerLetter = if (holder is LetterHeaderItem) holder.getHeaderLetter() else null
if (headerLetter != null) {
parent.getDecoratedBoundsWithMargins(child, bounds)
textPaint.getTextBounds(headerLetter, 0, headerLetter.length, textBounds)
val x = if (isRtl) getLayoutBoundsRTL() else getLayoutBoundsLTR()
val y = bounds.top + padTop - textBounds.top
canvas.save()
canvas.drawText(headerLetter, x.toFloat(), y.toFloat(), textPaint)
canvas.restore()
}
}
}
private fun getLayoutBoundsLTR() = bounds.left + padStart
private fun getLayoutBoundsRTL() = bounds.right - padStart - textBounds.width()
interface LetterHeaderItem {
fun getHeaderLetter(): String?
}
}
| gpl-3.0 | d34e8a8dc7981c02f121aeec34f4a5a0 | 32.953488 | 135 | 0.723288 | 4.287812 | false | false | false | false |
jk1/intellij-community | java/compiler/impl/src/com/intellij/build/output/KotlincOutputParser.kt | 3 | 6296 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.openapi.util.text.StringUtil
import java.io.File
import java.lang.IllegalStateException
import java.util.function.Consumer
import java.util.regex.Pattern
/**
* TODO should be moved to the kotlin plugin
*
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private val COMPILER_MESSAGES_GROUP = "Kotlin compiler"
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<MessageEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
val colonIndex2 = lineWoSeverity.colon().skipDriveOnWin(lineWoSeverity)
if (colonIndex2 >= 0) {
val path = lineWoSeverity.substringBeforeAndTrim(colonIndex2)
val file = File(path)
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "java")) {
return addMessage(createMessage(reader.buildId, getMessageKind(severity), lineWoSeverity.amendNextLinesIfNeeded(reader), line), consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(colonIndex2)
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex3)
val matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
val relatedNextLines = "".amendNextLinesIfNeeded(reader)
val message = lineWoPath.substringAfterAndTrim(colonIndex3) + relatedNextLines
val details = lineWoSeverity + relatedNextLines
if (matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.buildId, getMessageKind(severity), message, path, lineNumber.toInt(), symbolNumberText, details), consumer)
}
}
return addMessage(createMessage(reader.buildId, getMessageKind(severity), message, details), consumer)
}
else {
val text = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.buildId, getMessageKind(severity), text, text), consumer)
}
}
return false
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null) {
if (nextLine.isNextMessage()) {
reader.pushBack()
break
}
else {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.startsWith(this, "Note: ") // Next javac info message candidate
|| StringUtil.containsIgnoreCase(this, "FAILURE")
|| StringUtil.containsIgnoreCase(this, "FAILED")
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
private fun getMessageKind(kind: String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun Int.skipDriveOnWin(line: String): Int {
return if (this == 1) line.indexOf(COLON, this + 1) else this
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + "Error while annotation processing"
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(buildId: Any, messageKind: MessageEvent.Kind, text: String, detail: String): MessageEvent {
return MessageEventImpl(buildId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail)
}
private fun createMessageWithLocation(
buildId: Any,
messageKind: MessageEvent.Kind,
text: String,
file: String,
lineNumber: Int,
columnIndex: Int,
detail: String
): FileMessageEventImpl {
return FileMessageEventImpl(buildId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail,
FilePosition(File(file), lineNumber - 1, columnIndex - 1))
}
} | apache-2.0 | 714199d0683779839ec0ab1eca666b3b | 39.10828 | 145 | 0.708069 | 4.702016 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/swift/CartFileBuilder.kt | 1 | 722 | package org.roylance.yaclib.core.services.swift
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.utilities.SwiftUtilities
class CartFileBuilder : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val file = YaclibModel.File.newBuilder()
.setFileExtension(YaclibModel.FileExtension.NONE_EXT)
.setFileToWrite(InitialTemplate)
.setFileName("Cartfile")
.setFullDirectoryLocation("")
.build()
return file
}
private val InitialTemplate = """github "apple/swift-protobuf" == ${SwiftUtilities.SwiftProtobufVersion}
github "Alamofire/Alamofire" == ${SwiftUtilities.AlamoFireVersion}
"""
} | mit | 5bb7f8a2264775f498d8d49c896b384b | 33.428571 | 106 | 0.747922 | 4.102273 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/presenter/HomePresenter.kt | 1 | 2741 | /*
* Ad Free
* Copyright (c) 2017 by abertschi, www.abertschi.ch
* See the file "LICENSE" for the full license governing this code.
*/
package ch.abertschi.adfree.presenter
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import ch.abertschi.adfree.BuildConfig
import ch.abertschi.adfree.model.PreferencesFactory
import ch.abertschi.adfree.model.RemoteManager
import ch.abertschi.adfree.model.RemoteSetting
import ch.abertschi.adfree.view.home.HomeView
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
/**
* Created by abertschi on 15.04.17.
*/
class HomePresenter(val homeView: HomeView, val preferencesFactory: PreferencesFactory,
val remoteManager: RemoteManager)
: AnkoLogger {
private var isInit: Boolean = false
private var remoteSetting: RemoteSetting? = null
fun onCreate(context: Context) {
isInit = true
showPermissionRequiredIfNecessary(context)
remoteManager.getRemoteSettingsObservable()
.subscribe { onRemoteSettingUpdate(it)}
}
private fun onRemoteSettingUpdate(s: RemoteSetting) {
remoteSetting = s
info { "current version code: " + BuildConfig.VERSION_CODE }
info { "setting version code: " + s.versionCode }
// info { s.toString() }
if (s.versionCode > BuildConfig.VERSION_CODE && s.versionNotify) {
info { "new version available. showing ui element to update" }
homeView.showUpdateMessage(true)
}
}
fun onResume(context: Context) {
showPermissionRequiredIfNecessary(context)
}
fun hasNotificationPermission(context: Context): Boolean {
val permission =
Settings.Secure.getString(context.contentResolver,
"enabled_notification_listeners")
if (permission == null || !permission.contains(context.packageName)) {
return false
}
return true
}
private fun showPermissionRequiredIfNecessary(context: Context) {
if (hasNotificationPermission(context)) {
homeView.showEnjoyAdFree()
} else {
homeView.showPermissionRequired()
}
}
fun onUpdateMessageClicked() {
val browserIntent = Intent(Intent.ACTION_VIEW,
Uri.parse(remoteSetting?.versionUrl))
this.homeView.startActivity(browserIntent)
}
fun onTroubleshooting() {
val url = "https://abertschi.github.io/ad-free/troubleshooting/troubleshooting.html"
val browserIntent = Intent(Intent.ACTION_VIEW,
Uri.parse(url))
this.homeView.startActivity(browserIntent)
}
} | apache-2.0 | ed0be3a4b9b5aaa069e1a041f1b79b4e | 29.808989 | 92 | 0.674571 | 4.560732 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/String/MutableStringVec4.kt | 1 | 44992 | package glm
data class MutableStringVec4(var x: String, var y: String, var z: String, var w: String) {
// Initializes each element by evaluating init from 0 until 3
constructor(init: (Int) -> String) : this(init(0), init(1), init(2), init(3))
operator fun get(idx: Int): String = when (idx) {
0 -> x
1 -> y
2 -> z
3 -> w
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
operator fun set(idx: Int, value: String) = when (idx) {
0 -> x = value
1 -> y = value
2 -> z = value
3 -> w = value
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
inline fun map(func: (String) -> String): MutableStringVec4 = MutableStringVec4(func(x), func(y), func(z), func(w))
fun toList(): List<String> = listOf(x, y, z, w)
// Predefined vector constants
companion object Constants {
val zero: MutableStringVec4 get() = MutableStringVec4("", "", "", "")
}
// Conversions to Float
inline fun toVec(conv: (String) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
inline fun toVec2(conv: (String) -> Float): Vec2 = Vec2(conv(x), conv(y))
inline fun toVec3(conv: (String) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
inline fun toVec4(conv: (String) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Float
inline fun toMutableVec(conv: (String) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableVec2(conv: (String) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
inline fun toMutableVec3(conv: (String) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
inline fun toMutableVec4(conv: (String) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
inline fun toDoubleVec(conv: (String) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toDoubleVec2(conv: (String) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
inline fun toDoubleVec3(conv: (String) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
inline fun toDoubleVec4(conv: (String) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
inline fun toMutableDoubleVec(conv: (String) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableDoubleVec2(conv: (String) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
inline fun toMutableDoubleVec3(conv: (String) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
inline fun toMutableDoubleVec4(conv: (String) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
inline fun toIntVec(conv: (String) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toIntVec2(conv: (String) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
inline fun toIntVec3(conv: (String) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
inline fun toIntVec4(conv: (String) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
inline fun toMutableIntVec(conv: (String) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableIntVec2(conv: (String) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
inline fun toMutableIntVec3(conv: (String) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
inline fun toMutableIntVec4(conv: (String) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
inline fun toLongVec(conv: (String) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toLongVec2(conv: (String) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
inline fun toLongVec3(conv: (String) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
inline fun toLongVec4(conv: (String) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
inline fun toMutableLongVec(conv: (String) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableLongVec2(conv: (String) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
inline fun toMutableLongVec3(conv: (String) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
inline fun toMutableLongVec4(conv: (String) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
inline fun toShortVec(conv: (String) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toShortVec2(conv: (String) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
inline fun toShortVec3(conv: (String) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
inline fun toShortVec4(conv: (String) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
inline fun toMutableShortVec(conv: (String) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableShortVec2(conv: (String) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
inline fun toMutableShortVec3(conv: (String) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
inline fun toMutableShortVec4(conv: (String) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
inline fun toByteVec(conv: (String) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toByteVec2(conv: (String) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
inline fun toByteVec3(conv: (String) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
inline fun toByteVec4(conv: (String) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
inline fun toMutableByteVec(conv: (String) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableByteVec2(conv: (String) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
inline fun toMutableByteVec3(conv: (String) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
inline fun toMutableByteVec4(conv: (String) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
inline fun toCharVec(conv: (String) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toCharVec2(conv: (String) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
inline fun toCharVec3(conv: (String) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
inline fun toCharVec4(conv: (String) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
inline fun toMutableCharVec(conv: (String) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
inline fun toMutableCharVec2(conv: (String) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
inline fun toMutableCharVec3(conv: (String) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
inline fun toMutableCharVec4(conv: (String) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toBoolVec(): BoolVec4 = BoolVec4(x != "", y != "", z != "", w != "")
inline fun toBoolVec(conv: (String) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != "", y != "")
inline fun toBoolVec2(conv: (String) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != "", y != "", z != "")
inline fun toBoolVec3(conv: (String) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(): BoolVec4 = BoolVec4(x != "", y != "", z != "", w != "")
inline fun toBoolVec4(conv: (String) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec4 = MutableBoolVec4(x != "", y != "", z != "", w != "")
inline fun toMutableBoolVec(conv: (String) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != "", y != "")
inline fun toMutableBoolVec2(conv: (String) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != "", y != "", z != "")
inline fun toMutableBoolVec3(conv: (String) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(): MutableBoolVec4 = MutableBoolVec4(x != "", y != "", z != "", w != "")
inline fun toMutableBoolVec4(conv: (String) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toStringVec(): StringVec4 = StringVec4(x, y, z, w)
inline fun toStringVec(conv: (String) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
fun toStringVec2(): StringVec2 = StringVec2(x, y)
inline fun toStringVec2(conv: (String) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x, y, z)
inline fun toStringVec3(conv: (String) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(): StringVec4 = StringVec4(x, y, z, w)
inline fun toStringVec4(conv: (String) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toMutableStringVec(): MutableStringVec4 = MutableStringVec4(x, y, z, w)
inline fun toMutableStringVec(conv: (String) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x, y)
inline fun toMutableStringVec2(conv: (String) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x, y, z)
inline fun toMutableStringVec3(conv: (String) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(): MutableStringVec4 = MutableStringVec4(x, y, z, w)
inline fun toMutableStringVec4(conv: (String) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toTVec(conv: (String) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toTVec2(conv: (String) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (String) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(conv: (String) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (String) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toMutableTVec2(conv: (String) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (String) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(conv: (String) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: MutableStringVec2 get() = MutableStringVec2(x, x)
var xy: MutableStringVec2
get() = MutableStringVec2(x, y)
set(value) {
x = value.x
y = value.y
}
var xz: MutableStringVec2
get() = MutableStringVec2(x, z)
set(value) {
x = value.x
z = value.y
}
var xw: MutableStringVec2
get() = MutableStringVec2(x, w)
set(value) {
x = value.x
w = value.y
}
var yx: MutableStringVec2
get() = MutableStringVec2(y, x)
set(value) {
y = value.x
x = value.y
}
val yy: MutableStringVec2 get() = MutableStringVec2(y, y)
var yz: MutableStringVec2
get() = MutableStringVec2(y, z)
set(value) {
y = value.x
z = value.y
}
var yw: MutableStringVec2
get() = MutableStringVec2(y, w)
set(value) {
y = value.x
w = value.y
}
var zx: MutableStringVec2
get() = MutableStringVec2(z, x)
set(value) {
z = value.x
x = value.y
}
var zy: MutableStringVec2
get() = MutableStringVec2(z, y)
set(value) {
z = value.x
y = value.y
}
val zz: MutableStringVec2 get() = MutableStringVec2(z, z)
var zw: MutableStringVec2
get() = MutableStringVec2(z, w)
set(value) {
z = value.x
w = value.y
}
var wx: MutableStringVec2
get() = MutableStringVec2(w, x)
set(value) {
w = value.x
x = value.y
}
var wy: MutableStringVec2
get() = MutableStringVec2(w, y)
set(value) {
w = value.x
y = value.y
}
var wz: MutableStringVec2
get() = MutableStringVec2(w, z)
set(value) {
w = value.x
z = value.y
}
val ww: MutableStringVec2 get() = MutableStringVec2(w, w)
val xxx: MutableStringVec3 get() = MutableStringVec3(x, x, x)
val xxy: MutableStringVec3 get() = MutableStringVec3(x, x, y)
val xxz: MutableStringVec3 get() = MutableStringVec3(x, x, z)
val xxw: MutableStringVec3 get() = MutableStringVec3(x, x, w)
val xyx: MutableStringVec3 get() = MutableStringVec3(x, y, x)
val xyy: MutableStringVec3 get() = MutableStringVec3(x, y, y)
var xyz: MutableStringVec3
get() = MutableStringVec3(x, y, z)
set(value) {
x = value.x
y = value.y
z = value.z
}
var xyw: MutableStringVec3
get() = MutableStringVec3(x, y, w)
set(value) {
x = value.x
y = value.y
w = value.z
}
val xzx: MutableStringVec3 get() = MutableStringVec3(x, z, x)
var xzy: MutableStringVec3
get() = MutableStringVec3(x, z, y)
set(value) {
x = value.x
z = value.y
y = value.z
}
val xzz: MutableStringVec3 get() = MutableStringVec3(x, z, z)
var xzw: MutableStringVec3
get() = MutableStringVec3(x, z, w)
set(value) {
x = value.x
z = value.y
w = value.z
}
val xwx: MutableStringVec3 get() = MutableStringVec3(x, w, x)
var xwy: MutableStringVec3
get() = MutableStringVec3(x, w, y)
set(value) {
x = value.x
w = value.y
y = value.z
}
var xwz: MutableStringVec3
get() = MutableStringVec3(x, w, z)
set(value) {
x = value.x
w = value.y
z = value.z
}
val xww: MutableStringVec3 get() = MutableStringVec3(x, w, w)
val yxx: MutableStringVec3 get() = MutableStringVec3(y, x, x)
val yxy: MutableStringVec3 get() = MutableStringVec3(y, x, y)
var yxz: MutableStringVec3
get() = MutableStringVec3(y, x, z)
set(value) {
y = value.x
x = value.y
z = value.z
}
var yxw: MutableStringVec3
get() = MutableStringVec3(y, x, w)
set(value) {
y = value.x
x = value.y
w = value.z
}
val yyx: MutableStringVec3 get() = MutableStringVec3(y, y, x)
val yyy: MutableStringVec3 get() = MutableStringVec3(y, y, y)
val yyz: MutableStringVec3 get() = MutableStringVec3(y, y, z)
val yyw: MutableStringVec3 get() = MutableStringVec3(y, y, w)
var yzx: MutableStringVec3
get() = MutableStringVec3(y, z, x)
set(value) {
y = value.x
z = value.y
x = value.z
}
val yzy: MutableStringVec3 get() = MutableStringVec3(y, z, y)
val yzz: MutableStringVec3 get() = MutableStringVec3(y, z, z)
var yzw: MutableStringVec3
get() = MutableStringVec3(y, z, w)
set(value) {
y = value.x
z = value.y
w = value.z
}
var ywx: MutableStringVec3
get() = MutableStringVec3(y, w, x)
set(value) {
y = value.x
w = value.y
x = value.z
}
val ywy: MutableStringVec3 get() = MutableStringVec3(y, w, y)
var ywz: MutableStringVec3
get() = MutableStringVec3(y, w, z)
set(value) {
y = value.x
w = value.y
z = value.z
}
val yww: MutableStringVec3 get() = MutableStringVec3(y, w, w)
val zxx: MutableStringVec3 get() = MutableStringVec3(z, x, x)
var zxy: MutableStringVec3
get() = MutableStringVec3(z, x, y)
set(value) {
z = value.x
x = value.y
y = value.z
}
val zxz: MutableStringVec3 get() = MutableStringVec3(z, x, z)
var zxw: MutableStringVec3
get() = MutableStringVec3(z, x, w)
set(value) {
z = value.x
x = value.y
w = value.z
}
var zyx: MutableStringVec3
get() = MutableStringVec3(z, y, x)
set(value) {
z = value.x
y = value.y
x = value.z
}
val zyy: MutableStringVec3 get() = MutableStringVec3(z, y, y)
val zyz: MutableStringVec3 get() = MutableStringVec3(z, y, z)
var zyw: MutableStringVec3
get() = MutableStringVec3(z, y, w)
set(value) {
z = value.x
y = value.y
w = value.z
}
val zzx: MutableStringVec3 get() = MutableStringVec3(z, z, x)
val zzy: MutableStringVec3 get() = MutableStringVec3(z, z, y)
val zzz: MutableStringVec3 get() = MutableStringVec3(z, z, z)
val zzw: MutableStringVec3 get() = MutableStringVec3(z, z, w)
var zwx: MutableStringVec3
get() = MutableStringVec3(z, w, x)
set(value) {
z = value.x
w = value.y
x = value.z
}
var zwy: MutableStringVec3
get() = MutableStringVec3(z, w, y)
set(value) {
z = value.x
w = value.y
y = value.z
}
val zwz: MutableStringVec3 get() = MutableStringVec3(z, w, z)
val zww: MutableStringVec3 get() = MutableStringVec3(z, w, w)
val wxx: MutableStringVec3 get() = MutableStringVec3(w, x, x)
var wxy: MutableStringVec3
get() = MutableStringVec3(w, x, y)
set(value) {
w = value.x
x = value.y
y = value.z
}
var wxz: MutableStringVec3
get() = MutableStringVec3(w, x, z)
set(value) {
w = value.x
x = value.y
z = value.z
}
val wxw: MutableStringVec3 get() = MutableStringVec3(w, x, w)
var wyx: MutableStringVec3
get() = MutableStringVec3(w, y, x)
set(value) {
w = value.x
y = value.y
x = value.z
}
val wyy: MutableStringVec3 get() = MutableStringVec3(w, y, y)
var wyz: MutableStringVec3
get() = MutableStringVec3(w, y, z)
set(value) {
w = value.x
y = value.y
z = value.z
}
val wyw: MutableStringVec3 get() = MutableStringVec3(w, y, w)
var wzx: MutableStringVec3
get() = MutableStringVec3(w, z, x)
set(value) {
w = value.x
z = value.y
x = value.z
}
var wzy: MutableStringVec3
get() = MutableStringVec3(w, z, y)
set(value) {
w = value.x
z = value.y
y = value.z
}
val wzz: MutableStringVec3 get() = MutableStringVec3(w, z, z)
val wzw: MutableStringVec3 get() = MutableStringVec3(w, z, w)
val wwx: MutableStringVec3 get() = MutableStringVec3(w, w, x)
val wwy: MutableStringVec3 get() = MutableStringVec3(w, w, y)
val wwz: MutableStringVec3 get() = MutableStringVec3(w, w, z)
val www: MutableStringVec3 get() = MutableStringVec3(w, w, w)
val xxxx: MutableStringVec4 get() = MutableStringVec4(x, x, x, x)
val xxxy: MutableStringVec4 get() = MutableStringVec4(x, x, x, y)
val xxxz: MutableStringVec4 get() = MutableStringVec4(x, x, x, z)
val xxxw: MutableStringVec4 get() = MutableStringVec4(x, x, x, w)
val xxyx: MutableStringVec4 get() = MutableStringVec4(x, x, y, x)
val xxyy: MutableStringVec4 get() = MutableStringVec4(x, x, y, y)
val xxyz: MutableStringVec4 get() = MutableStringVec4(x, x, y, z)
val xxyw: MutableStringVec4 get() = MutableStringVec4(x, x, y, w)
val xxzx: MutableStringVec4 get() = MutableStringVec4(x, x, z, x)
val xxzy: MutableStringVec4 get() = MutableStringVec4(x, x, z, y)
val xxzz: MutableStringVec4 get() = MutableStringVec4(x, x, z, z)
val xxzw: MutableStringVec4 get() = MutableStringVec4(x, x, z, w)
val xxwx: MutableStringVec4 get() = MutableStringVec4(x, x, w, x)
val xxwy: MutableStringVec4 get() = MutableStringVec4(x, x, w, y)
val xxwz: MutableStringVec4 get() = MutableStringVec4(x, x, w, z)
val xxww: MutableStringVec4 get() = MutableStringVec4(x, x, w, w)
val xyxx: MutableStringVec4 get() = MutableStringVec4(x, y, x, x)
val xyxy: MutableStringVec4 get() = MutableStringVec4(x, y, x, y)
val xyxz: MutableStringVec4 get() = MutableStringVec4(x, y, x, z)
val xyxw: MutableStringVec4 get() = MutableStringVec4(x, y, x, w)
val xyyx: MutableStringVec4 get() = MutableStringVec4(x, y, y, x)
val xyyy: MutableStringVec4 get() = MutableStringVec4(x, y, y, y)
val xyyz: MutableStringVec4 get() = MutableStringVec4(x, y, y, z)
val xyyw: MutableStringVec4 get() = MutableStringVec4(x, y, y, w)
val xyzx: MutableStringVec4 get() = MutableStringVec4(x, y, z, x)
val xyzy: MutableStringVec4 get() = MutableStringVec4(x, y, z, y)
val xyzz: MutableStringVec4 get() = MutableStringVec4(x, y, z, z)
var xyzw: MutableStringVec4
get() = MutableStringVec4(x, y, z, w)
set(value) {
x = value.x
y = value.y
z = value.z
w = value.w
}
val xywx: MutableStringVec4 get() = MutableStringVec4(x, y, w, x)
val xywy: MutableStringVec4 get() = MutableStringVec4(x, y, w, y)
var xywz: MutableStringVec4
get() = MutableStringVec4(x, y, w, z)
set(value) {
x = value.x
y = value.y
w = value.z
z = value.w
}
val xyww: MutableStringVec4 get() = MutableStringVec4(x, y, w, w)
val xzxx: MutableStringVec4 get() = MutableStringVec4(x, z, x, x)
val xzxy: MutableStringVec4 get() = MutableStringVec4(x, z, x, y)
val xzxz: MutableStringVec4 get() = MutableStringVec4(x, z, x, z)
val xzxw: MutableStringVec4 get() = MutableStringVec4(x, z, x, w)
val xzyx: MutableStringVec4 get() = MutableStringVec4(x, z, y, x)
val xzyy: MutableStringVec4 get() = MutableStringVec4(x, z, y, y)
val xzyz: MutableStringVec4 get() = MutableStringVec4(x, z, y, z)
var xzyw: MutableStringVec4
get() = MutableStringVec4(x, z, y, w)
set(value) {
x = value.x
z = value.y
y = value.z
w = value.w
}
val xzzx: MutableStringVec4 get() = MutableStringVec4(x, z, z, x)
val xzzy: MutableStringVec4 get() = MutableStringVec4(x, z, z, y)
val xzzz: MutableStringVec4 get() = MutableStringVec4(x, z, z, z)
val xzzw: MutableStringVec4 get() = MutableStringVec4(x, z, z, w)
val xzwx: MutableStringVec4 get() = MutableStringVec4(x, z, w, x)
var xzwy: MutableStringVec4
get() = MutableStringVec4(x, z, w, y)
set(value) {
x = value.x
z = value.y
w = value.z
y = value.w
}
val xzwz: MutableStringVec4 get() = MutableStringVec4(x, z, w, z)
val xzww: MutableStringVec4 get() = MutableStringVec4(x, z, w, w)
val xwxx: MutableStringVec4 get() = MutableStringVec4(x, w, x, x)
val xwxy: MutableStringVec4 get() = MutableStringVec4(x, w, x, y)
val xwxz: MutableStringVec4 get() = MutableStringVec4(x, w, x, z)
val xwxw: MutableStringVec4 get() = MutableStringVec4(x, w, x, w)
val xwyx: MutableStringVec4 get() = MutableStringVec4(x, w, y, x)
val xwyy: MutableStringVec4 get() = MutableStringVec4(x, w, y, y)
var xwyz: MutableStringVec4
get() = MutableStringVec4(x, w, y, z)
set(value) {
x = value.x
w = value.y
y = value.z
z = value.w
}
val xwyw: MutableStringVec4 get() = MutableStringVec4(x, w, y, w)
val xwzx: MutableStringVec4 get() = MutableStringVec4(x, w, z, x)
var xwzy: MutableStringVec4
get() = MutableStringVec4(x, w, z, y)
set(value) {
x = value.x
w = value.y
z = value.z
y = value.w
}
val xwzz: MutableStringVec4 get() = MutableStringVec4(x, w, z, z)
val xwzw: MutableStringVec4 get() = MutableStringVec4(x, w, z, w)
val xwwx: MutableStringVec4 get() = MutableStringVec4(x, w, w, x)
val xwwy: MutableStringVec4 get() = MutableStringVec4(x, w, w, y)
val xwwz: MutableStringVec4 get() = MutableStringVec4(x, w, w, z)
val xwww: MutableStringVec4 get() = MutableStringVec4(x, w, w, w)
val yxxx: MutableStringVec4 get() = MutableStringVec4(y, x, x, x)
val yxxy: MutableStringVec4 get() = MutableStringVec4(y, x, x, y)
val yxxz: MutableStringVec4 get() = MutableStringVec4(y, x, x, z)
val yxxw: MutableStringVec4 get() = MutableStringVec4(y, x, x, w)
val yxyx: MutableStringVec4 get() = MutableStringVec4(y, x, y, x)
val yxyy: MutableStringVec4 get() = MutableStringVec4(y, x, y, y)
val yxyz: MutableStringVec4 get() = MutableStringVec4(y, x, y, z)
val yxyw: MutableStringVec4 get() = MutableStringVec4(y, x, y, w)
val yxzx: MutableStringVec4 get() = MutableStringVec4(y, x, z, x)
val yxzy: MutableStringVec4 get() = MutableStringVec4(y, x, z, y)
val yxzz: MutableStringVec4 get() = MutableStringVec4(y, x, z, z)
var yxzw: MutableStringVec4
get() = MutableStringVec4(y, x, z, w)
set(value) {
y = value.x
x = value.y
z = value.z
w = value.w
}
val yxwx: MutableStringVec4 get() = MutableStringVec4(y, x, w, x)
val yxwy: MutableStringVec4 get() = MutableStringVec4(y, x, w, y)
var yxwz: MutableStringVec4
get() = MutableStringVec4(y, x, w, z)
set(value) {
y = value.x
x = value.y
w = value.z
z = value.w
}
val yxww: MutableStringVec4 get() = MutableStringVec4(y, x, w, w)
val yyxx: MutableStringVec4 get() = MutableStringVec4(y, y, x, x)
val yyxy: MutableStringVec4 get() = MutableStringVec4(y, y, x, y)
val yyxz: MutableStringVec4 get() = MutableStringVec4(y, y, x, z)
val yyxw: MutableStringVec4 get() = MutableStringVec4(y, y, x, w)
val yyyx: MutableStringVec4 get() = MutableStringVec4(y, y, y, x)
val yyyy: MutableStringVec4 get() = MutableStringVec4(y, y, y, y)
val yyyz: MutableStringVec4 get() = MutableStringVec4(y, y, y, z)
val yyyw: MutableStringVec4 get() = MutableStringVec4(y, y, y, w)
val yyzx: MutableStringVec4 get() = MutableStringVec4(y, y, z, x)
val yyzy: MutableStringVec4 get() = MutableStringVec4(y, y, z, y)
val yyzz: MutableStringVec4 get() = MutableStringVec4(y, y, z, z)
val yyzw: MutableStringVec4 get() = MutableStringVec4(y, y, z, w)
val yywx: MutableStringVec4 get() = MutableStringVec4(y, y, w, x)
val yywy: MutableStringVec4 get() = MutableStringVec4(y, y, w, y)
val yywz: MutableStringVec4 get() = MutableStringVec4(y, y, w, z)
val yyww: MutableStringVec4 get() = MutableStringVec4(y, y, w, w)
val yzxx: MutableStringVec4 get() = MutableStringVec4(y, z, x, x)
val yzxy: MutableStringVec4 get() = MutableStringVec4(y, z, x, y)
val yzxz: MutableStringVec4 get() = MutableStringVec4(y, z, x, z)
var yzxw: MutableStringVec4
get() = MutableStringVec4(y, z, x, w)
set(value) {
y = value.x
z = value.y
x = value.z
w = value.w
}
val yzyx: MutableStringVec4 get() = MutableStringVec4(y, z, y, x)
val yzyy: MutableStringVec4 get() = MutableStringVec4(y, z, y, y)
val yzyz: MutableStringVec4 get() = MutableStringVec4(y, z, y, z)
val yzyw: MutableStringVec4 get() = MutableStringVec4(y, z, y, w)
val yzzx: MutableStringVec4 get() = MutableStringVec4(y, z, z, x)
val yzzy: MutableStringVec4 get() = MutableStringVec4(y, z, z, y)
val yzzz: MutableStringVec4 get() = MutableStringVec4(y, z, z, z)
val yzzw: MutableStringVec4 get() = MutableStringVec4(y, z, z, w)
var yzwx: MutableStringVec4
get() = MutableStringVec4(y, z, w, x)
set(value) {
y = value.x
z = value.y
w = value.z
x = value.w
}
val yzwy: MutableStringVec4 get() = MutableStringVec4(y, z, w, y)
val yzwz: MutableStringVec4 get() = MutableStringVec4(y, z, w, z)
val yzww: MutableStringVec4 get() = MutableStringVec4(y, z, w, w)
val ywxx: MutableStringVec4 get() = MutableStringVec4(y, w, x, x)
val ywxy: MutableStringVec4 get() = MutableStringVec4(y, w, x, y)
var ywxz: MutableStringVec4
get() = MutableStringVec4(y, w, x, z)
set(value) {
y = value.x
w = value.y
x = value.z
z = value.w
}
val ywxw: MutableStringVec4 get() = MutableStringVec4(y, w, x, w)
val ywyx: MutableStringVec4 get() = MutableStringVec4(y, w, y, x)
val ywyy: MutableStringVec4 get() = MutableStringVec4(y, w, y, y)
val ywyz: MutableStringVec4 get() = MutableStringVec4(y, w, y, z)
val ywyw: MutableStringVec4 get() = MutableStringVec4(y, w, y, w)
var ywzx: MutableStringVec4
get() = MutableStringVec4(y, w, z, x)
set(value) {
y = value.x
w = value.y
z = value.z
x = value.w
}
val ywzy: MutableStringVec4 get() = MutableStringVec4(y, w, z, y)
val ywzz: MutableStringVec4 get() = MutableStringVec4(y, w, z, z)
val ywzw: MutableStringVec4 get() = MutableStringVec4(y, w, z, w)
val ywwx: MutableStringVec4 get() = MutableStringVec4(y, w, w, x)
val ywwy: MutableStringVec4 get() = MutableStringVec4(y, w, w, y)
val ywwz: MutableStringVec4 get() = MutableStringVec4(y, w, w, z)
val ywww: MutableStringVec4 get() = MutableStringVec4(y, w, w, w)
val zxxx: MutableStringVec4 get() = MutableStringVec4(z, x, x, x)
val zxxy: MutableStringVec4 get() = MutableStringVec4(z, x, x, y)
val zxxz: MutableStringVec4 get() = MutableStringVec4(z, x, x, z)
val zxxw: MutableStringVec4 get() = MutableStringVec4(z, x, x, w)
val zxyx: MutableStringVec4 get() = MutableStringVec4(z, x, y, x)
val zxyy: MutableStringVec4 get() = MutableStringVec4(z, x, y, y)
val zxyz: MutableStringVec4 get() = MutableStringVec4(z, x, y, z)
var zxyw: MutableStringVec4
get() = MutableStringVec4(z, x, y, w)
set(value) {
z = value.x
x = value.y
y = value.z
w = value.w
}
val zxzx: MutableStringVec4 get() = MutableStringVec4(z, x, z, x)
val zxzy: MutableStringVec4 get() = MutableStringVec4(z, x, z, y)
val zxzz: MutableStringVec4 get() = MutableStringVec4(z, x, z, z)
val zxzw: MutableStringVec4 get() = MutableStringVec4(z, x, z, w)
val zxwx: MutableStringVec4 get() = MutableStringVec4(z, x, w, x)
var zxwy: MutableStringVec4
get() = MutableStringVec4(z, x, w, y)
set(value) {
z = value.x
x = value.y
w = value.z
y = value.w
}
val zxwz: MutableStringVec4 get() = MutableStringVec4(z, x, w, z)
val zxww: MutableStringVec4 get() = MutableStringVec4(z, x, w, w)
val zyxx: MutableStringVec4 get() = MutableStringVec4(z, y, x, x)
val zyxy: MutableStringVec4 get() = MutableStringVec4(z, y, x, y)
val zyxz: MutableStringVec4 get() = MutableStringVec4(z, y, x, z)
var zyxw: MutableStringVec4
get() = MutableStringVec4(z, y, x, w)
set(value) {
z = value.x
y = value.y
x = value.z
w = value.w
}
val zyyx: MutableStringVec4 get() = MutableStringVec4(z, y, y, x)
val zyyy: MutableStringVec4 get() = MutableStringVec4(z, y, y, y)
val zyyz: MutableStringVec4 get() = MutableStringVec4(z, y, y, z)
val zyyw: MutableStringVec4 get() = MutableStringVec4(z, y, y, w)
val zyzx: MutableStringVec4 get() = MutableStringVec4(z, y, z, x)
val zyzy: MutableStringVec4 get() = MutableStringVec4(z, y, z, y)
val zyzz: MutableStringVec4 get() = MutableStringVec4(z, y, z, z)
val zyzw: MutableStringVec4 get() = MutableStringVec4(z, y, z, w)
var zywx: MutableStringVec4
get() = MutableStringVec4(z, y, w, x)
set(value) {
z = value.x
y = value.y
w = value.z
x = value.w
}
val zywy: MutableStringVec4 get() = MutableStringVec4(z, y, w, y)
val zywz: MutableStringVec4 get() = MutableStringVec4(z, y, w, z)
val zyww: MutableStringVec4 get() = MutableStringVec4(z, y, w, w)
val zzxx: MutableStringVec4 get() = MutableStringVec4(z, z, x, x)
val zzxy: MutableStringVec4 get() = MutableStringVec4(z, z, x, y)
val zzxz: MutableStringVec4 get() = MutableStringVec4(z, z, x, z)
val zzxw: MutableStringVec4 get() = MutableStringVec4(z, z, x, w)
val zzyx: MutableStringVec4 get() = MutableStringVec4(z, z, y, x)
val zzyy: MutableStringVec4 get() = MutableStringVec4(z, z, y, y)
val zzyz: MutableStringVec4 get() = MutableStringVec4(z, z, y, z)
val zzyw: MutableStringVec4 get() = MutableStringVec4(z, z, y, w)
val zzzx: MutableStringVec4 get() = MutableStringVec4(z, z, z, x)
val zzzy: MutableStringVec4 get() = MutableStringVec4(z, z, z, y)
val zzzz: MutableStringVec4 get() = MutableStringVec4(z, z, z, z)
val zzzw: MutableStringVec4 get() = MutableStringVec4(z, z, z, w)
val zzwx: MutableStringVec4 get() = MutableStringVec4(z, z, w, x)
val zzwy: MutableStringVec4 get() = MutableStringVec4(z, z, w, y)
val zzwz: MutableStringVec4 get() = MutableStringVec4(z, z, w, z)
val zzww: MutableStringVec4 get() = MutableStringVec4(z, z, w, w)
val zwxx: MutableStringVec4 get() = MutableStringVec4(z, w, x, x)
var zwxy: MutableStringVec4
get() = MutableStringVec4(z, w, x, y)
set(value) {
z = value.x
w = value.y
x = value.z
y = value.w
}
val zwxz: MutableStringVec4 get() = MutableStringVec4(z, w, x, z)
val zwxw: MutableStringVec4 get() = MutableStringVec4(z, w, x, w)
var zwyx: MutableStringVec4
get() = MutableStringVec4(z, w, y, x)
set(value) {
z = value.x
w = value.y
y = value.z
x = value.w
}
val zwyy: MutableStringVec4 get() = MutableStringVec4(z, w, y, y)
val zwyz: MutableStringVec4 get() = MutableStringVec4(z, w, y, z)
val zwyw: MutableStringVec4 get() = MutableStringVec4(z, w, y, w)
val zwzx: MutableStringVec4 get() = MutableStringVec4(z, w, z, x)
val zwzy: MutableStringVec4 get() = MutableStringVec4(z, w, z, y)
val zwzz: MutableStringVec4 get() = MutableStringVec4(z, w, z, z)
val zwzw: MutableStringVec4 get() = MutableStringVec4(z, w, z, w)
val zwwx: MutableStringVec4 get() = MutableStringVec4(z, w, w, x)
val zwwy: MutableStringVec4 get() = MutableStringVec4(z, w, w, y)
val zwwz: MutableStringVec4 get() = MutableStringVec4(z, w, w, z)
val zwww: MutableStringVec4 get() = MutableStringVec4(z, w, w, w)
val wxxx: MutableStringVec4 get() = MutableStringVec4(w, x, x, x)
val wxxy: MutableStringVec4 get() = MutableStringVec4(w, x, x, y)
val wxxz: MutableStringVec4 get() = MutableStringVec4(w, x, x, z)
val wxxw: MutableStringVec4 get() = MutableStringVec4(w, x, x, w)
val wxyx: MutableStringVec4 get() = MutableStringVec4(w, x, y, x)
val wxyy: MutableStringVec4 get() = MutableStringVec4(w, x, y, y)
var wxyz: MutableStringVec4
get() = MutableStringVec4(w, x, y, z)
set(value) {
w = value.x
x = value.y
y = value.z
z = value.w
}
val wxyw: MutableStringVec4 get() = MutableStringVec4(w, x, y, w)
val wxzx: MutableStringVec4 get() = MutableStringVec4(w, x, z, x)
var wxzy: MutableStringVec4
get() = MutableStringVec4(w, x, z, y)
set(value) {
w = value.x
x = value.y
z = value.z
y = value.w
}
val wxzz: MutableStringVec4 get() = MutableStringVec4(w, x, z, z)
val wxzw: MutableStringVec4 get() = MutableStringVec4(w, x, z, w)
val wxwx: MutableStringVec4 get() = MutableStringVec4(w, x, w, x)
val wxwy: MutableStringVec4 get() = MutableStringVec4(w, x, w, y)
val wxwz: MutableStringVec4 get() = MutableStringVec4(w, x, w, z)
val wxww: MutableStringVec4 get() = MutableStringVec4(w, x, w, w)
val wyxx: MutableStringVec4 get() = MutableStringVec4(w, y, x, x)
val wyxy: MutableStringVec4 get() = MutableStringVec4(w, y, x, y)
var wyxz: MutableStringVec4
get() = MutableStringVec4(w, y, x, z)
set(value) {
w = value.x
y = value.y
x = value.z
z = value.w
}
val wyxw: MutableStringVec4 get() = MutableStringVec4(w, y, x, w)
val wyyx: MutableStringVec4 get() = MutableStringVec4(w, y, y, x)
val wyyy: MutableStringVec4 get() = MutableStringVec4(w, y, y, y)
val wyyz: MutableStringVec4 get() = MutableStringVec4(w, y, y, z)
val wyyw: MutableStringVec4 get() = MutableStringVec4(w, y, y, w)
var wyzx: MutableStringVec4
get() = MutableStringVec4(w, y, z, x)
set(value) {
w = value.x
y = value.y
z = value.z
x = value.w
}
val wyzy: MutableStringVec4 get() = MutableStringVec4(w, y, z, y)
val wyzz: MutableStringVec4 get() = MutableStringVec4(w, y, z, z)
val wyzw: MutableStringVec4 get() = MutableStringVec4(w, y, z, w)
val wywx: MutableStringVec4 get() = MutableStringVec4(w, y, w, x)
val wywy: MutableStringVec4 get() = MutableStringVec4(w, y, w, y)
val wywz: MutableStringVec4 get() = MutableStringVec4(w, y, w, z)
val wyww: MutableStringVec4 get() = MutableStringVec4(w, y, w, w)
val wzxx: MutableStringVec4 get() = MutableStringVec4(w, z, x, x)
var wzxy: MutableStringVec4
get() = MutableStringVec4(w, z, x, y)
set(value) {
w = value.x
z = value.y
x = value.z
y = value.w
}
val wzxz: MutableStringVec4 get() = MutableStringVec4(w, z, x, z)
val wzxw: MutableStringVec4 get() = MutableStringVec4(w, z, x, w)
var wzyx: MutableStringVec4
get() = MutableStringVec4(w, z, y, x)
set(value) {
w = value.x
z = value.y
y = value.z
x = value.w
}
val wzyy: MutableStringVec4 get() = MutableStringVec4(w, z, y, y)
val wzyz: MutableStringVec4 get() = MutableStringVec4(w, z, y, z)
val wzyw: MutableStringVec4 get() = MutableStringVec4(w, z, y, w)
val wzzx: MutableStringVec4 get() = MutableStringVec4(w, z, z, x)
val wzzy: MutableStringVec4 get() = MutableStringVec4(w, z, z, y)
val wzzz: MutableStringVec4 get() = MutableStringVec4(w, z, z, z)
val wzzw: MutableStringVec4 get() = MutableStringVec4(w, z, z, w)
val wzwx: MutableStringVec4 get() = MutableStringVec4(w, z, w, x)
val wzwy: MutableStringVec4 get() = MutableStringVec4(w, z, w, y)
val wzwz: MutableStringVec4 get() = MutableStringVec4(w, z, w, z)
val wzww: MutableStringVec4 get() = MutableStringVec4(w, z, w, w)
val wwxx: MutableStringVec4 get() = MutableStringVec4(w, w, x, x)
val wwxy: MutableStringVec4 get() = MutableStringVec4(w, w, x, y)
val wwxz: MutableStringVec4 get() = MutableStringVec4(w, w, x, z)
val wwxw: MutableStringVec4 get() = MutableStringVec4(w, w, x, w)
val wwyx: MutableStringVec4 get() = MutableStringVec4(w, w, y, x)
val wwyy: MutableStringVec4 get() = MutableStringVec4(w, w, y, y)
val wwyz: MutableStringVec4 get() = MutableStringVec4(w, w, y, z)
val wwyw: MutableStringVec4 get() = MutableStringVec4(w, w, y, w)
val wwzx: MutableStringVec4 get() = MutableStringVec4(w, w, z, x)
val wwzy: MutableStringVec4 get() = MutableStringVec4(w, w, z, y)
val wwzz: MutableStringVec4 get() = MutableStringVec4(w, w, z, z)
val wwzw: MutableStringVec4 get() = MutableStringVec4(w, w, z, w)
val wwwx: MutableStringVec4 get() = MutableStringVec4(w, w, w, x)
val wwwy: MutableStringVec4 get() = MutableStringVec4(w, w, w, y)
val wwwz: MutableStringVec4 get() = MutableStringVec4(w, w, w, z)
val wwww: MutableStringVec4 get() = MutableStringVec4(w, w, w, w)
}
val swizzle: Swizzle get() = Swizzle()
}
fun mutableVecOf(x: String, y: String, z: String, w: String): MutableStringVec4 = MutableStringVec4(x, y, z, w)
| mit | f9b3d96ff7c64675b4955bca0d863ba9 | 49.838418 | 135 | 0.57039 | 3.789438 | false | false | false | false |
g1144146/sds_for_kotlin | src/main/kotlin/sds/util/DescriptorParser.kt | 1 | 3672 | package sds.util
import kotlin.text.Regex
import kotlin.text.MatchResult
object DescriptorParser {
private const val OBJ: String = """L[a-z\.]*[0-9a-zA-Z_\$\.]+"""
private const val LANG: String = "java.lang"
private val langPackage: Array<String> = arrayOf(
"$LANG.annotation", "$LANG.instrument", "$LANG.invoke",
"$LANG.management", "$LANG.reflect", "$LANG.ref"
)
fun parse(desc: String): String = parse(desc, false)
fun parse(desc: String, isFieldSignature: Boolean): String {
val obj: String = """($OBJ|\[$OBJ)"""
val prim: String = """(B|C|D|F|I|J|S|Z|V|\[+B|\[+C|\[+D|\[+F|\[+I|\[+J|\[+S|\[+Z)"""
val paren: String = """(\(|\))"""
val generics: String = """(T[A-Z]|\[+T[A-Z])"""
val colon: String = "(;:|::|:)"
val wildCard: String = """(\+|\*)"""
val diamond: String = "(<|>)"
val replaced: String = desc.replace("/", ".").replace(";>", ">").replace(";)", ")")
val regex: Regex = """$obj|$prim|$paren|$generics|$colon|$wildCard|$diamond|([A-Z])|(;)""".toRegex()
var beforeParen = true
val parsed: String = regex.findAll(replaced).map({ matched: MatchResult ->
val m: String = matched.value
val len: Int = m.length
when {
m.startsWith("[") -> {
val last: Int = m.lastIndexOf("[") + 1
when {
m.matches(prim.toRegex()) -> {
val type: String = parsePrimitive(m.substring(len - 1))
type.substring(0, type.length - 1)
}
else -> {
val type: String = m.substring(last + 1, len)
removeLangPrefix(type)
}
} + (0 until last).map { "[]" }
.reduce { str_1: String, str_2: String -> str_1 + str_2 }
}
m.startsWith("L") or m.matches("T[A-Z]+".toRegex()) -> {
removeLangPrefix(m.substring(1, len))
}
m.matches("""\(|\)|<|>""".toRegex()) -> {
beforeParen = (! ((m == "(") or (m == ")")))
m
}
m == ";:" -> " & "
m.matches("::|:".toRegex()) -> " extends "
m == "*" -> " ? "
m == "+" -> "? extends "
m == ";" -> ","
m.matches("[A-Z]".toRegex()) and isFieldSignature && beforeParen -> m
parsePrimitive(m).isNotEmpty() -> parsePrimitive(m)
else -> ""
}
}).reduce { matched_1: String, matched_2: String -> matched_1 + matched_2 }
return arrayOf(parsed)
.map { s: String -> if(s.endsWith(",")) s.substring(0, s.length - 1) else s }
.map { s: String -> if(s.contains(",)")) s.replace(",)", ")") else s }[0]
}
fun removeLangPrefix(desc: String): String =
if(! desc.startsWith(LANG) or langPackage.filter({ desc.startsWith(it) }).isNotEmpty())
desc
else desc.replace("$LANG.", "")
private fun parsePrimitive(desc: String): String = when(desc) {
"B" -> "byte,"
"C" -> "char,"
"D" -> "double,"
"F" -> "float,"
"I" -> "int,"
"J" -> "long,"
"S" -> "short,"
"Z" -> "boolean,"
"V" -> "void"
else -> ""
}
} | apache-2.0 | d918d5ba56dd4ed18214ca9118ff591f | 43.253012 | 108 | 0.412309 | 3.948387 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/di/modules/ApiModule.kt | 1 | 1372 | package com.ashish.movieguide.di.modules
import com.ashish.movieguide.data.api.AuthApi
import com.ashish.movieguide.data.api.MovieApi
import com.ashish.movieguide.data.api.OMDbApi
import com.ashish.movieguide.data.api.PeopleApi
import com.ashish.movieguide.data.api.SearchApi
import com.ashish.movieguide.data.api.TVShowApi
import dagger.Module
import dagger.Provides
import retrofit2.Retrofit
import javax.inject.Named
import javax.inject.Singleton
/**
* Created by Ashish on Dec 27.
*/
@Module
object ApiModule {
@Provides
@Singleton
@JvmStatic
fun provideAuthApi(retrofit: Retrofit): AuthApi = retrofit.create(AuthApi::class.java)
@Provides
@Singleton
@JvmStatic
fun provideMovieApi(retrofit: Retrofit): MovieApi = retrofit.create(MovieApi::class.java)
@Provides
@Singleton
@JvmStatic
fun provideTVShowApi(retrofit: Retrofit): TVShowApi = retrofit.create(TVShowApi::class.java)
@Provides
@Singleton
@JvmStatic
fun providePeopleApi(retrofit: Retrofit): PeopleApi = retrofit.create(PeopleApi::class.java)
@Provides
@Singleton
@JvmStatic
fun provideSearchApi(retrofit: Retrofit): SearchApi = retrofit.create(SearchApi::class.java)
@Provides
@Singleton
@JvmStatic
fun provideOMDbApi(@Named("omdb") retrofit: Retrofit): OMDbApi = retrofit.create(OMDbApi::class.java)
} | apache-2.0 | 20409e18e0a301bbb9354ee639d5b412 | 26.46 | 105 | 0.753644 | 3.942529 | false | false | false | false |
lucasgcampos/kotlin-for-android-developers | KotlinAndroid/app/src/main/java/com/lucasgcampos/kotlinandroid/data/db/DbDataMapper.kt | 1 | 886 | package com.lucasgcampos.kotlinandroid.data.db
import com.lucasgcampos.kotlinandroid.domain.model.Forecast
import com.lucasgcampos.kotlinandroid.domain.model.ForecastList
class DbDataMapper {
fun convertFromDomain(forecast: ForecastList) = with(forecast) {
val daily = dailyForecast.map { convertDayFromDomain(id, it) }
CityForecast(id, city, country, daily)
}
private fun convertDayFromDomain(cityId: Long, forecast: Forecast) = with(forecast) {
DayForecast(date, description, high, low, iconUrl, cityId)
}
fun convertToDomain(forecast: CityForecast) = with(forecast) {
val daily = dailyForecast.map { convertDayToDomain(it) }
ForecastList(_id, city, country, daily)
}
private fun convertDayToDomain(dayForecast: DayForecast) = with(dayForecast) {
Forecast(date, description, high, low, iconUrl)
}
} | mit | f735cfe222893807736c17df2641e121 | 34.48 | 89 | 0.72009 | 3.973094 | false | false | false | false |
fabianonline/telegram_backup | src/main/kotlin/de/fabianonline/telegram_backup/DatabaseUpdates.kt | 1 | 16659 | package de.fabianonline.telegram_backup
import java.util.HashMap
import java.util.LinkedHashMap
import java.util.LinkedList
import java.sql.Connection
import java.sql.SQLException
import java.sql.Statement
import java.sql.Types
import java.sql.ResultSet
import java.sql.PreparedStatement
import com.github.badoualy.telegram.tl.api.*
import com.github.badoualy.telegram.tl.core.TLVector
import org.slf4j.LoggerFactory
import org.slf4j.Logger
import de.fabianonline.telegram_backup.mediafilemanager.FileManagerFactory
import de.fabianonline.telegram_backup.mediafilemanager.AbstractMediaFileManager
import com.github.salomonbrys.kotson.*
import com.google.gson.*
class DatabaseUpdates(protected var conn: Connection, protected var db: Database) {
private val maxPossibleVersion: Int
get() = updates.size
init {
logger.debug("Registering Database Updates...")
register(DB_Update_1(conn, db))
register(DB_Update_2(conn, db))
register(DB_Update_3(conn, db))
register(DB_Update_4(conn, db))
register(DB_Update_5(conn, db))
register(DB_Update_6(conn, db))
register(DB_Update_7(conn, db))
register(DB_Update_8(conn, db))
register(DB_Update_9(conn, db))
register(DB_Update_10(conn, db))
register(DB_Update_11(conn, db))
}
fun doUpdates() {
try {
val stmt = conn.createStatement()
logger.debug("DatabaseUpdate.doUpdates running")
logger.debug("Getting current database version")
var version: Int
logger.debug("Checking if table database_versions exists")
val table_count = db.queryInt("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='database_versions'")
if (table_count == 0) {
logger.debug("Table does not exist")
version = 0
} else {
logger.debug("Table exists. Checking max version")
version = db.queryInt("SELECT MAX(version) FROM database_versions")
}
logger.debug("version: {}", version)
System.out.println("Database version: " + version)
logger.debug("Max available database version is {}", maxPossibleVersion)
if (version == 0) {
logger.debug("Looking for DatabaseUpdate with create_query...")
// This is a fresh database - so we search for the latest available version with a create_query
// and use this as a shortcut.
var update: DatabaseUpdate? = null
for (i in maxPossibleVersion downTo 1) {
update = getUpdateToVersion(i)
logger.trace("Looking at DatabaseUpdate version {}", update.version)
if (update.create_query != null) break
update = null
}
if (update != null) {
logger.debug("Found DatabaseUpdate version {} with create_query.", update.version)
for (query in update.create_query!!) stmt.execute(query)
stmt.execute("INSERT INTO database_versions (version) VALUES (${update.version})")
version = update.version
}
}
if (version < maxPossibleVersion) {
logger.debug("Update is necessary. {} => {}.", version, maxPossibleVersion)
var backup = false
for (i in version + 1..maxPossibleVersion) {
if (getUpdateToVersion(i).needsBackup) {
logger.debug("Update to version {} needs a backup", i)
backup = true
}
}
if (backup) {
if (version > 0) {
logger.debug("Performing backup")
db.backupDatabase(version)
} else {
logger.debug("NOT performing a backup, because we are creating a fresh database and don't need a backup of that.")
}
}
logger.debug("Applying updates")
try {
for (i in version + 1..maxPossibleVersion) {
getUpdateToVersion(i).doUpdate()
}
} catch (e: SQLException) {
throw RuntimeException(e)
}
println("Cleaning up the database (this might take some time)...")
try { stmt.executeUpdate("VACUUM") } catch (t: Throwable) { logger.debug("Exception during VACUUMing: {}", t) }
} else {
logger.debug("No update necessary.")
}
} catch (e: SQLException) {
throw RuntimeException(e)
}
}
private fun getUpdateToVersion(i: Int): DatabaseUpdate {
return updates.get(i - 1)
}
private fun register(d: DatabaseUpdate) {
logger.debug("Registering {} as update to version {}", d.javaClass, d.version)
if (d.version != updates.size + 1) {
throw RuntimeException("Tried to register DB update to version ${d.version}, but would need update to version ${updates.size + 1}")
}
updates.add(d)
}
companion object {
private val logger = LoggerFactory.getLogger(DatabaseUpdates::class.java)
private val updates = LinkedList<DatabaseUpdate>()
}
}
internal abstract class DatabaseUpdate(protected var conn: Connection, protected var db: Database) {
protected var stmt: Statement
abstract val version: Int
init {
try {
stmt = conn.createStatement()
} catch (e: SQLException) {
throw RuntimeException(e)
}
}
@Throws(SQLException::class)
fun doUpdate() {
logger.debug("Applying update to version {}", version)
System.out.println(" Updating to version $version...")
_doUpdate()
logger.debug("Saving current database version to the db")
stmt.executeUpdate("INSERT INTO database_versions (version) VALUES ($version)")
}
@Throws(SQLException::class)
protected abstract fun _doUpdate()
open val needsBackup = false
@Throws(SQLException::class)
protected fun execute(sql: String) {
logger.debug("Executing: {}", sql)
stmt.executeUpdate(sql)
}
companion object {
protected val logger = LoggerFactory.getLogger(DatabaseUpdate::class.java)
}
open val create_query: List<String>? = null
}
internal class DB_Update_1(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 1
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate("CREATE TABLE messages ("
+ "id INTEGER PRIMARY KEY ASC, "
+ "dialog_id INTEGER, "
+ "to_id INTEGER, "
+ "from_id INTEGER, "
+ "from_type TEXT, "
+ "text TEXT, "
+ "time TEXT, "
+ "has_media BOOLEAN, "
+ "sticker TEXT, "
+ "data BLOB,"
+ "type TEXT)")
stmt.executeUpdate("CREATE TABLE dialogs ("
+ "id INTEGER PRIMARY KEY ASC, "
+ "name TEXT, "
+ "type TEXT)")
stmt.executeUpdate("CREATE TABLE people ("
+ "id INTEGER PRIMARY KEY ASC, "
+ "first_name TEXT, "
+ "last_name TEXT, "
+ "username TEXT, "
+ "type TEXT)")
stmt.executeUpdate("CREATE TABLE database_versions (" + "version INTEGER)")
}
}
internal class DB_Update_2(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 2
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate("ALTER TABLE people RENAME TO 'users'")
stmt.executeUpdate("ALTER TABLE users ADD COLUMN phone TEXT")
}
}
internal class DB_Update_3(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 3
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate("ALTER TABLE dialogs RENAME TO 'chats'")
}
}
internal class DB_Update_4(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 4
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate("CREATE TABLE messages_new (id INTEGER PRIMARY KEY ASC, dialog_id INTEGER, to_id INTEGER, from_id INTEGER, from_type TEXT, text TEXT, time INTEGER, has_media BOOLEAN, sticker TEXT, data BLOB, type TEXT);")
stmt.executeUpdate("INSERT INTO messages_new SELECT * FROM messages")
stmt.executeUpdate("DROP TABLE messages")
stmt.executeUpdate("ALTER TABLE messages_new RENAME TO 'messages'")
}
}
internal class DB_Update_5(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 5
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate("CREATE TABLE runs (id INTEGER PRIMARY KEY ASC, time INTEGER, start_id INTEGER, end_id INTEGER, count_missing INTEGER)")
}
}
internal class DB_Update_6(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 6
override val needsBackup = true
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate(
"CREATE TABLE messages_new (\n" +
" id INTEGER PRIMARY KEY ASC,\n" +
" message_type TEXT,\n" +
" dialog_id INTEGER,\n" +
" chat_id INTEGER,\n" +
" sender_id INTEGER,\n" +
" fwd_from_id INTEGER,\n" +
" text TEXT,\n" +
" time INTEGER,\n" +
" has_media BOOLEAN,\n" +
" media_type TEXT,\n" +
" media_file TEXT,\n" +
" media_size INTEGER,\n" +
" media_json TEXT,\n" +
" markup_json TEXT,\n" +
" data BLOB)")
val mappings = LinkedHashMap<String, String>()
mappings.put("id", "id")
mappings.put("message_type", "type")
mappings.put("dialog_id", "CASE from_type WHEN 'user' THEN dialog_id ELSE NULL END")
mappings.put("chat_id", "CASE from_type WHEN 'chat' THEN dialog_id ELSE NULL END")
mappings.put("sender_id", "from_id")
mappings.put("text", "text")
mappings.put("time", "time")
mappings.put("has_media", "has_media")
mappings.put("data", "data")
val query = StringBuilder("INSERT INTO messages_new\n(")
var first: Boolean
first = true
for (s in mappings.keys) {
if (!first) query.append(", ")
query.append(s)
first = false
}
query.append(")\nSELECT \n")
first = true
for (s in mappings.values) {
if (!first) query.append(", ")
query.append(s)
first = false
}
query.append("\nFROM messages")
stmt.executeUpdate(query.toString())
System.out.println(" Updating the data (this might take some time)...")
val rs = stmt.executeQuery("SELECT id, data FROM messages_new")
val ps = conn.prepareStatement("UPDATE messages_new SET fwd_from_id=?, media_type=?, media_file=?, media_size=? WHERE id=?")
while (rs.next()) {
ps.setInt(5, rs.getInt(1))
val msg = Database.bytesToTLMessage(rs.getBytes(2))
if (msg == null || msg.getFwdFrom() == null) {
ps.setNull(1, Types.INTEGER)
} else {
ps.setInt(1, msg.getFwdFrom().getFromId())
}
val f = FileManagerFactory.getFileManager(msg, db.file_base, settings = null)
if (f == null) {
ps.setNull(2, Types.VARCHAR)
ps.setNull(3, Types.VARCHAR)
ps.setNull(4, Types.INTEGER)
} else {
ps.setString(2, f.name)
ps.setString(3, f.targetFilename)
ps.setInt(4, f.size)
}
ps.addBatch()
}
rs.close()
conn.setAutoCommit(false)
ps.executeBatch()
ps.close()
conn.commit()
conn.setAutoCommit(true)
stmt.executeUpdate("DROP TABLE messages")
stmt.executeUpdate("ALTER TABLE messages_new RENAME TO messages")
}
}
internal class DB_Update_7(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 7
override val needsBackup = true
@Throws(SQLException::class)
override fun _doUpdate() {
stmt.executeUpdate("ALTER TABLE messages ADD COLUMN api_layer INTEGER")
stmt.executeUpdate("UPDATE messages SET api_layer=51")
}
}
internal class DB_Update_8(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 8
override val needsBackup = true
@Throws(SQLException::class)
override fun _doUpdate() {
execute("ALTER TABLE messages ADD COLUMN source_type TEXT")
execute("ALTER TABLE messages ADD COLUMN source_id INTEGER")
execute("update messages set source_type='dialog', source_id=dialog_id where dialog_id is not null")
execute("update messages set source_type='group', source_id=chat_id where chat_id is not null")
execute("CREATE TABLE messages_new (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"message_id INTEGER," +
"message_type TEXT," +
"source_type TEXT," +
"source_id INTEGER," +
"sender_id INTEGER," +
"fwd_from_id INTEGER," +
"text TEXT," +
"time INTEGER," +
"has_media BOOLEAN," +
"media_type TEXT," +
"media_file TEXT," +
"media_size INTEGER," +
"media_json TEXT," +
"markup_json TEXT," +
"data BLOB," +
"api_layer INTEGER)")
execute("INSERT INTO messages_new" +
"(message_id, message_type, source_type, source_id, sender_id, fwd_from_id, text, time, has_media, media_type," +
"media_file, media_size, media_json, markup_json, data, api_layer)" +
"SELECT " +
"id, message_type, source_type, source_id, sender_id, fwd_from_id, text, time, has_media, media_type," +
"media_file, media_size, media_json, markup_json, data, api_layer FROM messages")
execute("DROP TABLE messages")
execute("ALTER TABLE messages_new RENAME TO 'messages'")
execute("CREATE UNIQUE INDEX unique_messages ON messages (source_type, source_id, message_id)")
}
}
internal class DB_Update_9(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 9
override val needsBackup = true
override val create_query = listOf(
"CREATE TABLE \"chats\" (id INTEGER PRIMARY KEY ASC, name TEXT, type TEXT);",
"CREATE TABLE \"users\" (id INTEGER PRIMARY KEY ASC, first_name TEXT, last_name TEXT, username TEXT, type TEXT, phone TEXT);",
"CREATE TABLE database_versions (version INTEGER);",
"CREATE TABLE runs (id INTEGER PRIMARY KEY ASC, time INTEGER, start_id INTEGER, end_id INTEGER, count_missing INTEGER);",
"CREATE TABLE \"messages\" (id INTEGER PRIMARY KEY AUTOINCREMENT,message_id INTEGER,message_type TEXT,source_type TEXT,source_id INTEGER,sender_id INTEGER,fwd_from_id INTEGER,text TEXT,time INTEGER,has_media BOOLEAN,media_type TEXT,media_file TEXT,media_size INTEGER,media_json TEXT,markup_json TEXT,data BLOB,api_layer INTEGER);",
"CREATE UNIQUE INDEX unique_messages ON messages (source_type, source_id, message_id);"
)
@Throws(SQLException::class)
override fun _doUpdate() {
val logger = LoggerFactory.getLogger(DB_Update_9::class.java)
println(" Updating supergroup channel message data (this might take some time)...")
print(" ")
val count = db.queryInt("SELECT COUNT(*) FROM messages WHERE source_type='channel' and sender_id IS NULL and api_layer=53")
logger.debug("Found $count candidates for conversion")
val limit = 5000
var offset = 0
var i = 0
while (offset < count) {
logger.debug("Querying with limit $limit and offset $offset")
val rs = stmt.executeQuery("SELECT id, data, source_id FROM messages WHERE source_type='channel' and sender_id IS NULL and api_layer=53 ORDER BY id LIMIT ${limit} OFFSET ${offset}")
val messages = TLVector<TLAbsMessage>()
val messages_to_delete = mutableListOf<Int>()
while (rs.next()) {
val msg = Database.bytesToTLMessage(rs.getBytes(2))
if (msg!!.getFromId() != null) {
i++
messages.add(msg)
messages_to_delete.add(rs.getInt(1))
}
}
rs.close()
db.saveMessages(messages, api_layer=53, source_type=MessageSource.SUPERGROUP, settings=null)
execute("DELETE FROM messages WHERE id IN (" + messages_to_delete.joinToString() + ")")
print(".")
offset += limit
}
println()
logger.info("Converted ${i} of ${count} messages.")
}
}
internal class DB_Update_10(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version: Int
get() = 10
@Throws(SQLException::class)
override fun _doUpdate() {
execute("CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)")
}
}
internal class DB_Update_11(conn: Connection, db: Database) : DatabaseUpdate(conn, db) {
override val version = 11
val logger = LoggerFactory.getLogger(DB_Update_11::class.java)
override fun _doUpdate() {
execute("ALTER TABLE messages ADD COLUMN json TEXT NULL")
execute("ALTER TABLE chats ADD COLUMN json TEXT NULL")
execute("ALTER TABLE chats ADD COLUMN api_layer INTEGER NULL")
execute("ALTER TABLE users ADD COLUMN json TEXT NULL")
execute("ALTER TABLE users ADD COLUMN api_layer INTEGER NULL")
val limit = 5000
var offset = 0
var i: Int
val ps = conn.prepareStatement("UPDATE messages SET json=? WHERE id=?")
println(" Updating messages to add their JSON representation to the database. This might take a few moments...")
print(" ")
do {
i = 0
logger.debug("Querying with limit $limit, offset is now $offset")
val rs = db.executeQuery("SELECT id, data FROM messages WHERE json IS NULL AND api_layer=53 LIMIT $limit")
while (rs.next()) {
i++
val id = rs.getInt(1)
val msg = Database.bytesToTLMessage(rs.getBytes(2))
val json = if (msg==null) Gson().toJson(null) else msg.toJson()
ps.setString(1, json)
ps.setInt(2, id)
ps.addBatch()
}
rs.close()
conn.setAutoCommit(false)
ps.executeBatch()
ps.clearBatch()
conn.commit()
conn.setAutoCommit(true)
offset += limit
print(".")
} while (i >= limit)
println()
ps.close()
}
}
| gpl-3.0 | 71491618405a52bf3b7e44f00c071d2f | 32.38477 | 333 | 0.685155 | 3.365455 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityAttributeLegendSetLinkTableInfo.kt | 1 | 3283 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity
import org.hisp.dhis.android.core.arch.db.stores.projections.internal.LinkTableChildProjection
import org.hisp.dhis.android.core.arch.db.tableinfos.TableInfo
import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper
import org.hisp.dhis.android.core.common.CoreColumns
import org.hisp.dhis.android.core.legendset.LegendSetTableInfo
class TrackedEntityAttributeLegendSetLinkTableInfo {
companion object {
val TABLE_INFO: TableInfo = object : TableInfo() {
override fun name(): String {
return "TrackedEntityAttributeLegendSetLink"
}
override fun columns(): CoreColumns {
return Columns()
}
}
val CHILD_PROJECTION = LinkTableChildProjection(
LegendSetTableInfo.TABLE_INFO,
Columns.TRACKED_ENTITY_ATTRIBUTE,
Columns.LEGEND_SET
)
}
class Columns : CoreColumns() {
override fun all(): Array<String> {
return CollectionsHelper.appendInNewArray(
super.all(),
TRACKED_ENTITY_ATTRIBUTE,
LEGEND_SET,
SORT_ORDER
)
}
override fun whereUpdate(): Array<String> {
return CollectionsHelper.appendInNewArray(
super.all(),
TRACKED_ENTITY_ATTRIBUTE,
LEGEND_SET,
SORT_ORDER
)
}
companion object {
const val TRACKED_ENTITY_ATTRIBUTE = "trackedEntityAttribute"
const val LEGEND_SET = "legendSet"
const val SORT_ORDER = "sortOrder"
}
}
}
| bsd-3-clause | 5a069963a0be6dbc47dc7cfaac910163 | 39.036585 | 94 | 0.681998 | 4.730548 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/richtext/RichTextUtil.kt | 1 | 3979 | package org.wikipedia.richtext
import android.text.*
import android.text.style.URLSpan
import android.widget.TextView
import androidx.annotation.IntRange
import androidx.core.text.getSpans
import androidx.core.text.toSpannable
import androidx.core.text.toSpanned
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
object RichTextUtil {
/**
* Apply only the spans from src to dst specific by spans.
*
* @see {@link android.text.TextUtils.copySpansFrom}
*/
private fun copySpans(src: Spanned, dst: Spannable, spans: Collection<Any?>) {
for (span in spans) {
val start = src.getSpanStart(span)
val end = src.getSpanEnd(span)
val flags = src.getSpanFlags(span)
dst.setSpan(span, start, end, flags)
}
}
/** Strips all rich text except spans used to provide compositional hints. */
fun stripRichText(str: CharSequence, start: Int, end: Int): CharSequence {
val plainText = str.toString()
val ret = plainText.toSpannable()
if (str is Spanned) {
val keyboardHintSpans = getComposingSpans(str, start, end)
copySpans(str, ret, keyboardHintSpans)
}
return ret
}
/**
* @return Temporary spans, often applied by the keyboard to provide hints such as typos.
*
* @see {@link android.view.inputmethod.BaseInputConnection.removeComposingSpans}
*/
private fun getComposingSpans(spanned: Spanned, start: Int, end: Int): List<Any?> {
return getSpans(spanned, start, end).filter { isComposingSpan(spanned, it) }
}
fun getSpans(spanned: Spanned, start: Int, end: Int): Array<out Any> {
return spanned.getSpans(start, end)
}
private fun isComposingSpan(spanned: Spanned, span: Any?): Boolean {
return spanned.getSpanFlags(span) and Spanned.SPAN_COMPOSING == Spanned.SPAN_COMPOSING
}
fun removeUnderlinesFromLinks(textView: TextView) {
val text = textView.text
if (text is Spanned) {
val spannable = text.toSpannable()
removeUnderlinesFromLinks(spannable, spannable.getSpans(0, spannable.length, URLSpan::class.java))
textView.text = spannable
}
}
private fun removeUnderlinesFromLinks(spannable: Spannable, spans: Array<URLSpan>) {
for (span in spans) {
val start = spannable.getSpanStart(span)
val end = spannable.getSpanEnd(span)
spannable.removeSpan(span)
spannable.setSpan(URLSpanNoUnderline(span.url), start, end, 0)
}
}
fun removeUnderlinesFromLinksAndMakeBold(textView: TextView) {
val text = textView.text
if (text is Spanned) {
val spannable = text.toSpannable()
removeUnderlinesFromLinksAndMakeBold(spannable, spannable.getSpans(0, spannable.length, URLSpan::class.java))
textView.text = spannable
}
}
private fun removeUnderlinesFromLinksAndMakeBold(spannable: Spannable, spans: Array<URLSpan>) {
for (span in spans) {
val start = spannable.getSpanStart(span)
val end = spannable.getSpanEnd(span)
spannable.removeSpan(span)
spannable.setSpan(URLSpanBoldNoUnderline(span.url), start, end, 0)
}
}
fun stripHtml(html: String): String {
return StringUtil.fromHtml(html).toString()
}
fun remove(text: CharSequence, @IntRange(from = 1) start: Int, end: Int): CharSequence {
try {
return TextUtils.concat(text.subSequence(0, start - 1), text.subSequence(end, text.length)).toSpanned()
} catch (e: Exception) {
// A number of possible exceptions can be thrown by the system from handling even
// slightly malformed spans or paragraphs, so let's ignore them for now and just
// return the original text.
L.e(e)
}
return text
}
}
| apache-2.0 | 1705001a45cff2794fa8a3061210a13d | 36.186916 | 121 | 0.647148 | 4.329706 | false | false | false | false |
google/android-auto-companion-app | android/app/src/main/kotlin/com/google/automotive/companion/Converter.kt | 1 | 3555 | /*
* 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.automotive.companion
import com.google.android.libraries.car.trustagent.AssociatedCar
import com.google.android.libraries.car.trustagent.Car
import io.flutter.plugin.common.MethodCall
import java.util.UUID
// This file contains functions/extensions that convert between common types used by the Android SDK
// and flutter method channel.
/** Default value used when an [AssociatedCar] has `null` name. */
private const val DEFAULT_CAR_NAME = "Default car name"
/** Puts parameters in a map with the expected key as method channel arguments. */
internal fun convertCarInfoToMap(deviceId: String, name: String?) =
mapOf(
ConnectedDeviceConstants.CAR_ID_KEY to deviceId,
ConnectedDeviceConstants.CAR_NAME_KEY to name
)
/** Creates method channel arguments as a map of device ID and name of [Car] */
internal fun Car.toMap() =
mapOf(
ConnectedDeviceConstants.CAR_ID_KEY to deviceId.toString(),
ConnectedDeviceConstants.CAR_NAME_KEY to (name ?: DEFAULT_CAR_NAME)
)
/** Creates method channel arguments as a map of device ID and name of [AssociatedCar] */
internal fun AssociatedCar.toMap() =
mapOf(
ConnectedDeviceConstants.CAR_ID_KEY to deviceId.toString(),
ConnectedDeviceConstants.CAR_NAME_KEY to (name ?: DEFAULT_CAR_NAME)
)
/** Casts [arguments] as a map. Throws exception if any value is not of specified type. */
// As inline so we can retrieve reified type parameters for error logging.
private inline fun <reified K, reified V> castArgumentsAsMap(arguments: Any): Map<K, V> {
check(arguments is Map<*, *>) { "Expected arguments of type Map." }
check(arguments.entries.all { (it.key is K) and (it.value is V) }) {
"Expected arguments to contain key type ${K::class} and value type ${V::class}"
}
@Suppress("UNCHECKED_CAST")
// This cast is safe because it's checked in the condition above.
return arguments as Map<K, V>
}
/** Retrieves an argument by [key]. */
private fun MethodCall.getValueByKey(key: String): String {
val arguments = castArgumentsAsMap<String, String>(arguments)
return arguments.getValue(key)
}
/** Retrieves argument - device ID. */
internal val MethodCall.argumentDeviceId: UUID
get() {
val carId = getValueByKey(ConnectedDeviceConstants.CAR_ID_KEY)
return UUID.fromString(carId)
}
/** Retrieves argument - device name. */
internal val MethodCall.argumentName: String
get() = getValueByKey(ConnectedDeviceConstants.CAR_NAME_KEY)
/** Retrieves argument - whether trusted device requires the phone to be unlocked. */
internal val MethodCall.argumentIsDeviceUnlockRequired: Boolean
get() = getValueByKey(TrustedDeviceConstants.IS_DEVICE_UNLOCK_REQUIRED_KEY).toBoolean()
/** Retrieves argument - whether trusted device shows a notification when unlocking the phone. */
internal val MethodCall.argumentShowShowUnlockNotification: Boolean
get() = getValueByKey(TrustedDeviceConstants.SHOULD_SHOW_UNLOCK_NOTIFICATION_KEY).toBoolean()
| apache-2.0 | b10f24ff7e9d756b7aadebf3dcd1e380 | 39.862069 | 100 | 0.75218 | 4.109827 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/util/Tapper.kt | 1 | 2394 | package tripleklay.util
import euklid.f.Point
import klay.core.Event
import klay.scene.Pointer
/**
* Detects taps on a layer. This is a simple implementation using a threshold distance. If the
* pointer is dragged less than the threshold, a call to [.onTap] is generated.
*/
open class Tapper : Pointer.Listener {
/** Square of the threshold distance for this tapper, defaults to
* [.DEFAULT_TAP_DIST_SQ]. */
var maxTapDistSq = DEFAULT_TAP_DIST_SQ
/**
* Called when a tap occurs. This is a simpler version of [.onTap], for
* subclasses that don't require the event position.
*/
fun onTap() {}
/**
* Called when a tap occurs. By default, this just calls [.onTap]. Subclasses
* overriding needn't call super.
* @param where the pointer's end position
*/
open fun onTap(where: Event.XY) {
onTap()
}
override fun onStart(iact: Pointer.Interaction) {
_tracking = Tracking(iact.event!!)
}
override fun onEnd(iact: Pointer.Interaction) {
if (_tracking == null) return
_tracking!!.drag(iact.event!!)
if (_tracking!!.maxMovedSq < maxTapDistSq) onTap(iact.event!!)
_tracking = null
}
override fun onDrag(iact: Pointer.Interaction) {
if (_tracking == null) return
_tracking!!.drag(iact.event!!)
}
override fun onCancel(iact: Pointer.Interaction?) {
_tracking = null
}
/** Represents tracking info for tap detection. */
protected class Tracking(where: Event.XY) {
var start: Point
var startTime: Double = 0.toDouble()
var maxMovedSq: Float = 0.toFloat()
init {
start = Point(where.x, where.y)
startTime = where.time
}
fun drag(where: Event.XY) {
maxMovedSq = maxOf(maxMovedSq, dist(where))
}
fun dist(where: Event.XY): Float {
val x = where.x - start.x
val y = where.y - start.y
return x * x + y * y
}
}
/** Data for current tracking, if any. */
protected var _tracking: Tracking? = null
companion object {
/** Default threshold distance. */
val DEFAULT_TAP_DIST = 15f
/** Default threshold distance, set to [.DEFAULT_TAP_DIST] squared. */
val DEFAULT_TAP_DIST_SQ = DEFAULT_TAP_DIST * DEFAULT_TAP_DIST
}
}
| apache-2.0 | fcb6080c09b812dcc59f05ae26aea530 | 27.5 | 94 | 0.598997 | 4.057627 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/run/compile/Solc.kt | 1 | 5683 | package me.serce.solidity.ide.run.compile
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.execution.ParametersListUtil
import me.serce.solidity.ide.settings.SoliditySettings
import me.serce.solidity.ide.settings.SoliditySettingsListener
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import java.io.File
import java.net.URLClassLoader
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.util.concurrent.TimeUnit
object Solc {
private var solcExecutable : File? = null
private val log = logger<Solc>()
init {
ApplicationManager.getApplication().messageBus.connect().subscribe(SoliditySettingsListener.TOPIC, object : SoliditySettingsListener {
override fun settingsChanged() {
updateSolcExecutable()
}
})
updateSolcExecutable()
}
private fun updateSolcExecutable() {
val evm = SoliditySettings.instance.pathToEvm
val standaloneSolc = SoliditySettings.instance.solcPath
solcExecutable = when {
evm.isNotBlank() && SoliditySettings.instance.useSolcEthereum -> {
extractSolc(SoliditySettings.instance.pathToEvm)
}
standaloneSolc.isNotBlank() && !SoliditySettings.instance.useSolcEthereum -> {
File(standaloneSolc)
}
else -> null
}
}
fun extractSolc(path: String): File? {
URLClassLoader(SoliditySettings.getUrls(path).map { it.toUri().toURL() }.toTypedArray()).use { classLoader ->
val os = when {
SystemInfoRt.isLinux -> "linux"
SystemInfoRt.isWindows -> "win"
SystemInfoRt.isMac -> "mac"
else -> {
throw IllegalStateException("Unknown OS name: ${SystemInfoRt.OS_NAME}")
}
}
try {
val solcResDir = "/native/$os/solc"
val tmpDir = File(System.getProperty("java.io.tmpdir"), "solc")
tmpDir.mkdirs()
// for some reason, we have to load any class to be able to read any resource from the jar
val someClass = classLoader.loadClass("org.ethereum.util.blockchain.StandaloneBlockchain")
val fileListStream = someClass.getResourceAsStream("$solcResDir/file.list") ?: run {
log.error("can't read file list")
return null
}
val fileList = StreamUtil.readText(fileListStream, Charset.defaultCharset())
val files = fileList.split("\n")
.map { it.trim() }
.map {
val dest = File(tmpDir, it)
Files.copy(someClass.getResourceAsStream("$solcResDir/$it"), dest.toPath(), StandardCopyOption.REPLACE_EXISTING)
dest
}
val solcExec = files.first()
solcExec.setExecutable(true)
return solcExec
} catch (e: Exception) {
log.error("exception occurred while extracting solc", e)
return null
}
}
}
fun isEnabled() : Boolean {
return solcExecutable != null && solcExecutable!!.exists()
}
fun getVersion(executable: File?): String {
executable?.apply {
val output: String
try {
val proc = ProcessBuilder(absolutePath, "--version")
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.start()
proc.waitFor(10, TimeUnit.SECONDS)
output = proc.inputStream.bufferedReader().readText()
} catch (e: Exception) {
return ""
}
val prefix = "Version: "
return output.split("\n").firstOrNull { it.startsWith(prefix) }?.substring(prefix.length) ?: ""
}
return ""
}
fun getVersion(): String {
return getVersion(solcExecutable)
}
fun compile(sources: List<File>, outputDir: File, baseDir: VirtualFile): SolcResult {
val solc = solcExecutable ?: throw IllegalStateException("No solc instance was found")
val additionalParams = ParametersListUtil.parse(SoliditySettings.instance.solcAdditionalOptions)
val pb = ProcessBuilder(arrayListOf(solc.canonicalPath, "--allow-paths=${baseDir.path}", "--abi", "--bin", "--overwrite", "-o", outputDir.absolutePath) + additionalParams + sources.map {
Paths.get(baseDir.canonicalPath).relativize(Paths.get(it.path)).toString().replace('\\', '/')
})
pb
.directory(File(baseDir.path))
.environment()["LD_LIBRARY_PATH"] = solc.parentFile.canonicalPath
val solcProc = pb.start()
val outputPromise = runAsync2 { StreamUtil.readText(solcProc.inputStream, Charset.defaultCharset()) }
val errorPromise = runAsync2 { StreamUtil.readText(solcProc.errorStream, Charset.defaultCharset()) }
if (!solcProc.waitFor(30, TimeUnit.SECONDS)) {
solcProc.destroyForcibly()
return SolcResult(false, "Failed to wait for solc to complete in 30 seconds", -1)
}
val output = outputPromise.blockingGet(500)
val error = errorPromise.blockingGet(500)
val messages = "$output\n$error"
val exitValue = solcProc.exitValue()
return SolcResult(exitValue == 0, messages, exitValue)
}
}
inline fun <T> runAsync2(crossinline runnable: () -> T): Promise<T> {
val promise = AsyncPromise<T>()
AppExecutorUtil.getAppExecutorService().execute {
val result = try {
runnable()
}
catch (e: Throwable) {
promise.setError(e)
return@execute
}
promise.setResult(result)
}
return promise
}
class SolcResult(val success: Boolean, val messages: String, val exitCode: Int)
| mit | 69ba7d0b35010c4413ebc949d7ac66d8 | 35.197452 | 190 | 0.68309 | 4.279367 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/dynamodb/src/main/kotlin/com/kotlin/dynamodb/DynamoDBScanItemsFilter.kt | 1 | 3714 | // snippet-sourcedescription:[DynamoDBScanItems.kt demonstrates how to return items from an Amazon DynamoDB table using a filter expression.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon DynamoDB]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.dynamodb
// snippet-start:[dynamodb.kotlin.scan_items_filter.import]
import aws.sdk.kotlin.services.dynamodb.DynamoDbClient
import aws.sdk.kotlin.services.dynamodb.model.AttributeValue
import aws.sdk.kotlin.services.dynamodb.model.ScanRequest
import java.util.HashMap
import kotlin.system.exitProcess
// snippet-end:[dynamodb.kotlin.scan_items_filter.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<tableName>
Where:
tableName - The Amazon DynamoDB table to scan (for example, Music3).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val tableName = args[0]
scanItemsUsingFilter(tableName)
}
// snippet-start:[dynamodb.kotlin.scan_items_filter.main]
suspend fun scanItemsUsingFilter(tableNameVal: String) {
val myMap = HashMap<String, String>()
myMap.put("#archive2", "archive")
val myExMap = HashMap<String, AttributeValue>()
myExMap.put(":val", AttributeValue.S("Open"))
val request = ScanRequest {
this.expressionAttributeNames = myMap
this.expressionAttributeValues = myExMap
tableName = tableNameVal
filterExpression = "#archive2 = :val"
}
DynamoDbClient { region = "us-east-1" }.use { ddb ->
val response = ddb.scan(request)
println("#######################################")
response.items?.forEach { item ->
item.keys.forEach { key ->
when (key) {
"date" -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
}
"status" -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
}
"username" -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
}
"archive" -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
}
"description" -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
}
"id" -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
}
else -> {
val myVal = splitMyString(item[key].toString())
println(myVal)
println("#######################################")
}
}
}
}
}
}
fun splitMyString(str: String): String {
val del1 = "="
val del2 = ")"
val parts = str.split(del1, del2)
val myVal = parts[1]
return myVal
}
// snippet-end:[dynamodb.kotlin.scan_items_filter.main]
| apache-2.0 | a8f5389f2d5ee39fd87c7e1617e7b86c | 30.295652 | 141 | 0.525579 | 4.562654 | false | false | false | false |
airbnb/epoxy | epoxy-adapter/src/main/java/com/airbnb/epoxy/preload/EpoxyModelPreloader.kt | 1 | 5945 | package com.airbnb.epoxy.preload
import android.view.View
import com.airbnb.epoxy.EpoxyModel
/**
* Describes how view content for an EpoxyModel should be preloaded.
*
* @param T The type of EpoxyModel that this preloader applies to
* @param U The type of view metadata to provide to the request builder.
* @param P The type of [PreloadRequestHolder] that will execute the preload request
*/
abstract class EpoxyModelPreloader<T : EpoxyModel<*>, U : ViewMetadata?, P : PreloadRequestHolder>(
val modelType: Class<T>,
/**
* A list of view ids, one for each view that should be preloaded.
* This should be left empty if the EpoxyModel's type uses the [Preloadable] interface.
*/
val preloadableViewIds: List<Int>
) {
/**
* An optional signature to differentiate views within the same model. This is useful if your EpoxyModel can contain varying amounts of preloadable views,
* or preloadable views of varying sizes.
*
* By default the model's class, span size, and layout resource, are used to differentiate views. This signature allows additional differentiation.
* For example, if your EpoxyModel shows an preloadable view that varies between portrait or landscape, this orientation will affect the view dimensions.
* In this case you could return a boolean here to differentiate the two cases so that the preloaded data has the correct orientation.
*
* The returned object can be anything, but it must implement [Object.hashCode]
*/
open fun viewSignature(epoxyModel: T): Any? = null
/**
* Provide optional metadata about a view. This can be used in [EpoxyModelPreloader.buildRequest]
*
* A preload request works best if it exactly matches the actual request (in order to match cache keys exactly)
* Things such as request transformations, thumbnails, or crop type can affect the cache key.
* If your preloadable view is configurable you can capture those options via this metadata.
*/
abstract fun buildViewMetadata(view: View): U
/**
* Start a preload request with the given target.
*
* @param epoxyModel The EpoxyModel whose content is being preloaded.
* @param preloadTarget The target to ues to create and store the request.
* @param viewData Information about the view that will hold the preloaded content.
*/
abstract fun startPreload(
epoxyModel: T,
preloadTarget: P,
viewData: ViewData<U>
)
companion object {
/**
* Helper to create a [EpoxyModelPreloader].
*
* @param viewSignature see [EpoxyModelPreloader.viewSignature]
* @param preloadableViewIds see [EpoxyModelPreloader.preloadableViewIds]
* @param viewMetadata see [EpoxyModelPreloader.buildViewMetadata]
* @param doPreload see [EpoxyModelPreloader.startPreload]
*/
inline fun <reified T : EpoxyModel<*>, P : PreloadRequestHolder> with(
preloadableViewIds: List<Int> = emptyList(),
noinline doPreload: (epoxyModel: T, preloadTarget: P, viewData: ViewData<ViewMetadata?>) -> Unit
): EpoxyModelPreloader<T, ViewMetadata?, P> =
with(
preloadableViewIds,
viewMetadata = { ViewMetadata.getDefault(it) },
viewSignature = { null },
doPreload = doPreload
)
/**
* Helper to create a [EpoxyModelPreloader].
*
* @param viewSignature see [EpoxyModelPreloader.viewSignature]
* @param preloadableViewIds see [EpoxyModelPreloader.preloadableViewIds]
* @param viewMetadata see [EpoxyModelPreloader.buildViewMetadata]
* @param doPreload see [EpoxyModelPreloader.startPreload]
*/
inline fun <reified T : EpoxyModel<*>, U : ViewMetadata?, P : PreloadRequestHolder> with(
preloadableViewIds: List<Int> = emptyList(),
noinline viewMetadata: (View) -> U,
noinline viewSignature: (T) -> Any? = { _ -> null },
noinline doPreload: (epoxyModel: T, preloadTarget: P, viewData: ViewData<U>) -> Unit
): EpoxyModelPreloader<T, U, P> =
with(
preloadableViewIds = preloadableViewIds,
epoxyModelClass = T::class.java,
viewMetadata = viewMetadata,
viewSignature = viewSignature,
doPreload = doPreload
)
/**
* Helper to create a [EpoxyModelPreloader]. This is similar to the other helper methods but not inlined so it can be used with Java.
*
* @param epoxyModelClass The specific type of EpoxyModel that this preloader is for.
* @param viewSignature see [EpoxyModelPreloader.viewSignature]
* @param preloadableViewIds see [EpoxyModelPreloader.preloadableViewIds]
* @param viewMetadata see [EpoxyModelPreloader.buildViewMetadata]
* @param doPreload see [EpoxyModelPreloader.startPreload]
*/
fun <T : EpoxyModel<*>, U : ViewMetadata?, P : PreloadRequestHolder> with(
preloadableViewIds: List<Int> = emptyList(),
epoxyModelClass: Class<T>,
viewMetadata: (View) -> U,
viewSignature: (T) -> Any? = { _ -> null },
doPreload: (epoxyModel: T, preloadTarget: P, viewData: ViewData<U>) -> Unit
): EpoxyModelPreloader<T, U, P> = object : EpoxyModelPreloader<T, U, P>(
modelType = epoxyModelClass,
preloadableViewIds = preloadableViewIds
) {
override fun buildViewMetadata(view: View) = viewMetadata(view)
override fun viewSignature(epoxyModel: T) = viewSignature(epoxyModel)
override fun startPreload(epoxyModel: T, preloadTarget: P, viewData: ViewData<U>) {
doPreload(epoxyModel, preloadTarget, viewData)
}
}
}
}
| apache-2.0 | ef728217a256da62b3182c1bfbe7f954 | 44.730769 | 158 | 0.655004 | 4.829407 | false | false | false | false |
millross/pac4j-async | vertx-pac4j-async-demo/src/test/kotlin/org/pac4j/async/vertx/config/TestPac4jConfigFactory.kt | 1 | 1716 | package org.pac4j.async.vertx.config
import org.pac4j.async.core.authorization.generator.AsyncAuthorizationGenerator
import org.pac4j.async.core.client.AsyncDirectClient
import org.pac4j.async.core.client.AsyncIndirectClient
import org.pac4j.async.core.config.AsyncConfig
import org.pac4j.async.vertx.CALLBACK_URL
import org.pac4j.async.vertx.TEST_CLIENT_NAME
import org.pac4j.async.vertx.client.TestDirectClient
import org.pac4j.async.vertx.client.TestIndirectClient
import org.pac4j.async.vertx.context.VertxAsyncWebContext
import org.pac4j.core.client.Clients
import org.pac4j.core.credentials.Credentials
import org.pac4j.core.profile.CommonProfile
/**
* Factory class to be used for creating test configs based on direct/indirect clients
*/
class TestPac4jConfigFactory {
fun indirectClientConfig(): AsyncConfig<Void, CommonProfile, VertxAsyncWebContext> {
val config = AsyncConfig<Void, CommonProfile, VertxAsyncWebContext>()
val client = TestIndirectClient()
client.setName(TEST_CLIENT_NAME)
val clients = Clients<AsyncIndirectClient<out Credentials, out CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>>(CALLBACK_URL, client)
config.setClients(clients)
return config
}
fun directClientConfig(): AsyncConfig<Void, CommonProfile, VertxAsyncWebContext> {
val config = AsyncConfig<Void, CommonProfile, VertxAsyncWebContext>()
val client = TestDirectClient("ABC")
client.setName(TEST_CLIENT_NAME)
val clients = Clients<AsyncDirectClient<out Credentials, out CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>>(CALLBACK_URL, client)
config.setClients(clients)
return config
}
} | apache-2.0 | de3c36651c7a34c375e4b515b61caa07 | 43.025641 | 152 | 0.77972 | 4.018735 | false | true | false | false |
imageprocessor/cv4j | app/src/main/java/com/cv4j/app/fragment/PaintFragment.kt | 1 | 2164 | package com.cv4j.app.fragment
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cv4j.app.R
import com.cv4j.app.app.BaseFragment
import com.cv4j.core.filters.OilPaintFilter
import com.cv4j.core.filters.StrokeAreaFilter
import com.cv4j.rxjava.RxImageData.Companion.bitmap
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_paint.*
/**
*
* @FileName:
* com.cv4j.app.fragment.PaintFragment
* @author: Tony Shen
* @date: 2020-05-04 12:54
* @version: V1.0 <描述当前版本功能>
*/
class PaintFragment : BaseFragment() {
private var mType = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bundle: Bundle? = arguments
if (bundle != null) {
mType = bundle.getInt(PAINT_TYPE)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_paint, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initData()
}
private fun initData() {
val res: Resources = getResources()
val bitmap = BitmapFactory.decodeResource(res, R.drawable.test_oil_paint)
when (mType) {
OIL_PAINT_TYPE -> bitmap(bitmap).addFilter(OilPaintFilter()).into(image)
PENCIL_PAINT_TYPE -> bitmap(bitmap).addFilter(StrokeAreaFilter()).into(image)
else -> image.setImageBitmap(bitmap)
}
}
companion object {
private const val PAINT_TYPE = "type"
private const val OIL_PAINT_TYPE = 1
private const val PENCIL_PAINT_TYPE = 2
fun newInstance(type: Int): PaintFragment {
val args = Bundle()
args.putInt(PAINT_TYPE, type)
val fragment = PaintFragment()
fragment.arguments = args
return fragment
}
}
} | apache-2.0 | 7fde807b2ea011827dd7ee26aecf3938 | 30.602941 | 175 | 0.67784 | 4.037594 | false | false | false | false |
ssseasonnn/RxDownload | rxdownload4/src/main/java/zlc/season/rxdownload4/task/Task.kt | 1 | 885 | package zlc.season.rxdownload4.task
import zlc.season.rxdownload4.DEFAULT_SAVE_PATH
import zlc.season.rxdownload4.utils.getFileNameFromUrl
open class Task(
var url: String,
var taskName: String = getFileNameFromUrl(url),
var saveName: String = "",
var savePath: String = DEFAULT_SAVE_PATH,
var extraInfo: String = ""
) {
/**
* Each task with unique tag.
*/
open fun tag() = url
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this === other) return true
return if (other is Task) {
tag() == other.tag()
} else {
false
}
}
override fun hashCode(): Int {
return tag().hashCode()
}
open fun isEmpty(): Boolean {
return taskName.isEmpty() || saveName.isEmpty() || savePath.isEmpty()
}
} | apache-2.0 | 23c176f6413f00d18b873e8ea22dcc64 | 21.717949 | 77 | 0.576271 | 4.23445 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/AnalysisApiBasedInlineUtil.kt | 2 | 4023 | // 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.debugger.core
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.KtFunctionCall
import org.jetbrains.kotlin.analysis.api.calls.KtSuccessCallInfo
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.analysis.api.symbols.KtConstructorSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.*
object AnalysisApiBasedInlineUtil {
fun KtAnalysisSession.isInlinedArgument(argument: KtFunction, checkNonLocalReturn: Boolean): Boolean {
val argumentSymbol = getInlineArgumentSymbol(argument) ?: return false
val argumentType = argumentSymbol.returnType
return !argumentSymbol.isNoinline && isNotNullableFunctionType(argumentType) &&
(!checkNonLocalReturn || !argumentSymbol.isCrossinline)
}
private fun KtAnalysisSession.getInlineArgumentSymbol(argument: KtFunction): KtValueParameterSymbol? {
if (argument !is KtFunctionLiteral && argument !is KtNamedFunction) return null
val parentCall = KtPsiUtil.getParentCallIfPresent(argument) as? KtCallExpression ?: return null
val call = getResolvedFunctionCall(parentCall) ?: return null
val callSymbol = call.partiallyAppliedSymbol.symbol
if (!callSymbol.isInline() && !callSymbol.isArrayConstructorWithLambda()) return null
val valueArgument = parentCall.getValueArgumentForExpression(argument) ?: return null
return call.argumentMapping[valueArgument.getArgumentExpression()]?.symbol
}
fun KtAnalysisSession.getResolvedFunctionCall(callExpression: KtCallExpression): KtFunctionCall<*>? {
val callInfo = callExpression.resolveCall() as? KtSuccessCallInfo ?: return null
return callInfo.call as? KtFunctionCall<*>
}
private fun KtFunctionLikeSymbol.isInline(): Boolean =
this is KtFunctionSymbol && isInline
private fun KtAnalysisSession.isNotNullableFunctionType(type: KtType): Boolean =
(type.isFunctionType || type.isSuspendFunctionType) && !type.isMarkedNullable
private fun KtFunctionLikeSymbol.isArrayConstructorWithLambda(): Boolean =
this is KtConstructorSymbol && valueParameters.size == 2 && returnType.isArrayOrPrimitiveArray()
private fun KtType.isArrayOrPrimitiveArray(): Boolean =
isClassTypeWithClassId(StandardClassIds.Array) ||
StandardClassIds.elementTypeByPrimitiveArrayType.keys.any { isClassTypeWithClassId(it) }
private fun KtType.isClassTypeWithClassId(classId: ClassId): Boolean =
this is KtNonErrorClassType && this.classId == classId
// Copied from org.jetbrains.kotlin.resolve.calls.util.callUtil.kt
fun KtCallExpression.getValueArgumentForExpression(expression: KtExpression): ValueArgument? {
fun KtElement.deparenthesizeStructurally(): KtElement? {
val deparenthesized = if (this is KtExpression) KtPsiUtil.deparenthesizeOnce(this) else this
return when {
deparenthesized != this -> deparenthesized
this is KtLambdaExpression -> this.functionLiteral
this is KtFunctionLiteral -> this.bodyExpression
else -> null
}
}
fun KtElement.isParenthesizedExpression() = generateSequence(this) { it.deparenthesizeStructurally() }.any { it == expression }
return valueArguments.firstOrNull { it?.getArgumentExpression()?.isParenthesizedExpression() ?: false }
}
}
| apache-2.0 | 67f61b39aea068cc3cb3eacc50559311 | 52.64 | 135 | 0.758389 | 5.224675 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/FriendSystem.kt | 1 | 2510 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Method2
@DependsOn(LoginType::class)
class FriendSystem : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.any { it.type == type<LoginType>() } }
class loginType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<LoginType>() }
}
@DependsOn(FriendsList::class)
class friendsList : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<FriendsList>() }
}
@DependsOn(IgnoreList::class)
class ignoreList : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<IgnoreList>() }
}
@MethodParameters()
@DependsOn(UserList.clear::class, FriendsList::class)
class clear : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.instructions.any { it.isMethod && it.methodOwner == type<FriendsList>() && it.methodType == method<UserList.clear>().type } }
}
@DependsOn(ignoreList::class)
@MethodParameters("name")
class removeIgnore : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(String::class.type) }
.and { it.instructions.any { it.isField && it.fieldId == field<ignoreList>().id } }
}
@DependsOn(friendsList::class)
@MethodParameters("name")
class removeFriend : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(String::class.type) }
.and { it.instructions.any { it.isField && it.fieldId == field<friendsList>().id } }
}
} | mit | 9977fad5fc135e1601ab3824ecfd572d | 43.052632 | 151 | 0.7 | 4.176373 | false | false | false | false |
JetBrains/intellij-community | java/java-impl/src/com/intellij/codeInsight/hints/JavaImplicitTypeDeclarativeInlayHintsProvider.kt | 1 | 1679 | // 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.hints
import com.intellij.codeInsight.hints.declarative.*
import com.intellij.codeInsight.hints.declarative.InlayHintsCollector
import com.intellij.codeInsight.hints.declarative.InlayHintsProvider
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
class JavaImplicitTypeDeclarativeInlayHintsProvider : InlayHintsProvider {
companion object {
const val PROVIDER_ID : String = "java.implicit.types"
}
override fun createCollector(file: PsiFile, editor: Editor): InlayHintsCollector {
return Collector()
}
private class Collector : SharedBypassCollector {
override fun collectFromElement(element: PsiElement, sink: InlayTreeSink) {
if (element is PsiLocalVariable) {
val initializer = element.initializer ?: return
val identifier = element.identifyingElement ?: return
if (initializer is PsiLiteral ||
initializer is PsiPolyadicExpression ||
initializer is PsiNewExpression ||
initializer is PsiTypeCastExpression) {
return
}
if (!element.typeElement.isInferredType) return
val type = element.type
if (type == PsiPrimitiveType.NULL) return
sink.addPresentation(InlineInlayPosition(identifier.textRange.endOffset, true), hasBackground = true) {
text(": ")
JavaTypeHintsFactory.typeHint(type, this)
}
}
}
}
override fun createCollectorForPreview(file: PsiFile, editor: Editor): InlayHintsCollector {
return Collector()
}
} | apache-2.0 | 3785785a92a3a8b8011fe22d3f195472 | 37.181818 | 120 | 0.721263 | 5.026946 | false | false | false | false |
JetBrains/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/GitLabToolWindowTabController.kt | 1 | 6003 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui
import com.intellij.collaboration.async.collectScoped
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.collaboration.ui.CollaborationToolsUIUtil.isDefault
import com.intellij.collaboration.ui.util.bindDisabled
import com.intellij.collaboration.ui.util.bindVisibility
import com.intellij.collaboration.util.URIUtil
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.content.Content
import git4idea.remote.hosting.ui.RepositoryAndAccountSelectorComponentFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.plugins.gitlab.api.GitLabApiManager
import org.jetbrains.plugins.gitlab.api.GitLabProjectCoordinates
import org.jetbrains.plugins.gitlab.authentication.GitLabLoginUtil
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsDetailsProvider
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabToolWindowTabViewModel.NestedViewModel
import org.jetbrains.plugins.gitlab.mergerequest.ui.list.GitLabMergeRequestsPanelFactory
import org.jetbrains.plugins.gitlab.util.GitLabBundle
import org.jetbrains.plugins.gitlab.util.GitLabProjectMapping
import java.awt.BorderLayout
import java.awt.event.ActionEvent
import javax.swing.*
internal class GitLabToolWindowTabController(private val project: Project,
scope: CoroutineScope,
tabVm: GitLabToolWindowTabViewModel,
private val content: Content) {
init {
scope.launch {
tabVm.nestedViewModelState.collectScoped { scope, vm ->
content.displayName = GitLabBundle.message("title.merge.requests")
val component = when (vm) {
is NestedViewModel.Selectors -> createSelectorsComponent(scope, vm)
is NestedViewModel.MergeRequests -> createMergeRequestsComponent(project, scope, vm)
}
CollaborationToolsUIUtil.setComponentPreservingFocus(content, component)
}
}
}
private fun createSelectorsComponent(scope: CoroutineScope, vm: NestedViewModel.Selectors): JComponent {
val accountsDetailsProvider = GitLabAccountsDetailsProvider(scope) {
// TODO: separate loader
service<GitLabAccountManager>().findCredentials(it)?.let(service<GitLabApiManager>()::getClient)
}
val selectorVm = vm.selectorVm
val selectors = RepositoryAndAccountSelectorComponentFactory(selectorVm).create(
scope = scope,
repoNamer = { mapping ->
val allProjects = vm.selectorVm.repositoriesState.value.map { it.repository }
getProjectDisplayName(allProjects, mapping.repository)
},
detailsProvider = accountsDetailsProvider,
accountsPopupActionsSupplier = { createPopupLoginActions(selectorVm, it) },
credsMissingText = GitLabBundle.message("account.token.missing"),
submitActionText = GitLabBundle.message("view.merge.requests.button"),
loginButtons = createLoginButtons(scope, selectorVm)
)
scope.launch {
selectorVm.loginRequestsFlow.collect { req ->
val account = req.account
if (account == null) {
val (newAccount, token) = GitLabLoginUtil.logInViaToken(project, selectors, req.repo.repository.serverPath) { server, name ->
req.accounts.none { it.server == server || it.name == name }
} ?: return@collect
req.login(newAccount, token)
}
else {
val token = GitLabLoginUtil.updateToken(project, selectors, account) { server, name ->
req.accounts.none { it.server == server || it.name == name }
} ?: return@collect
req.login(account, token)
}
}
}
return JPanel(BorderLayout()).apply {
add(selectors, BorderLayout.NORTH)
}
}
private fun createMergeRequestsComponent(project: Project, scope: CoroutineScope, vm: NestedViewModel.MergeRequests): JComponent =
GitLabMergeRequestsPanelFactory().create(project, scope, vm.listVm)
private fun createLoginButtons(scope: CoroutineScope, vm: GitLabRepositoryAndAccountSelectorViewModel)
: List<JButton> {
return listOf(
JButton(CollaborationToolsBundle.message("login.button")).apply {
isDefault = true
isOpaque = false
addActionListener {
vm.requestTokenLogin(false, true)
}
bindDisabled(scope, vm.busyState)
bindVisibility(scope, vm.tokenLoginAvailableState)
}
)
}
private fun createPopupLoginActions(vm: GitLabRepositoryAndAccountSelectorViewModel, mapping: GitLabProjectMapping?): List<Action> {
if (mapping == null) return emptyList()
return listOf(object : AbstractAction(CollaborationToolsBundle.message("login.button")) {
override fun actionPerformed(e: ActionEvent?) {
vm.requestTokenLogin(true, false)
}
})
}
private fun getProjectDisplayName(allProjects: List<GitLabProjectCoordinates>, project: GitLabProjectCoordinates): @NlsSafe String {
val showServer = needToShowServer(allProjects)
val builder = StringBuilder()
if (showServer) builder.append(URIUtil.toStringWithoutScheme(project.serverPath.toURI())).append("/")
builder.append(project.projectPath.owner).append("/")
builder.append(project.projectPath.name)
return builder.toString()
}
private fun needToShowServer(projects: List<GitLabProjectCoordinates>): Boolean {
if (projects.size <= 1) return false
val firstServer = projects.first().serverPath
return projects.any { it.serverPath != firstServer }
}
} | apache-2.0 | 1b06e402186f293e8b927eb6c9288b2f | 42.824818 | 135 | 0.734633 | 4.810096 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/ApolloCompiler.kt | 1 | 8857 | package com.apollographql.apollo3.compiler
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.api.QueryDocumentMinifier
import com.apollographql.apollo3.ast.GQLDefinition
import com.apollographql.apollo3.ast.GQLDocument
import com.apollographql.apollo3.ast.GQLFragmentDefinition
import com.apollographql.apollo3.ast.GQLOperationDefinition
import com.apollographql.apollo3.ast.GQLScalarTypeDefinition
import com.apollographql.apollo3.ast.Issue
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.ast.checkKeyFields
import com.apollographql.apollo3.ast.checkNoErrors
import com.apollographql.apollo3.ast.parseAsGQLDocument
import com.apollographql.apollo3.ast.transformation.addRequiredFields
import com.apollographql.apollo3.ast.validateAsExecutable
import com.apollographql.apollo3.compiler.codegen.java.JavaCodeGen
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinCodeGen
import com.apollographql.apollo3.compiler.ir.IrBuilder
import com.apollographql.apollo3.compiler.ir.dumpTo
import com.apollographql.apollo3.compiler.operationoutput.OperationDescriptor
import okio.buffer
import okio.source
import java.io.File
@ApolloExperimental
object ApolloCompiler {
interface Logger {
fun warning(message: String)
}
fun write(
options: Options,
): CompilerMetadata {
val executableFiles = options.executableFiles
val outputDir = options.outputDir
val testDir = options.testDir
val debugDir = options.debugDir
val schema = options.schema
if (options.targetLanguage == TargetLanguage.JAVA && options.codegenModels != MODELS_OPERATION_BASED) {
error("Java codegen does not support ${options.codegenModels}. Only $MODELS_OPERATION_BASED is supported.")
}
if (options.targetLanguage == TargetLanguage.JAVA && !options.flattenModels) {
error("Java codegen does not support nested models as it could trigger name clashes when a nested class has the same name as an " +
"enclosing one.")
}
checkCustomScalars(schema, options.customScalarsMapping)
outputDir.deleteRecursively()
outputDir.mkdirs()
debugDir?.deleteRecursively()
debugDir?.mkdirs()
/**
* Step 1: parse the documents
*/
val definitions = mutableListOf<GQLDefinition>()
val parseIssues = mutableListOf<Issue>()
executableFiles.map { file ->
val parseResult = file.source().buffer().parseAsGQLDocument(file.path)
if (parseResult.issues.isNotEmpty()) {
parseIssues.addAll(parseResult.issues)
} else {
// We can force cast here because we're guaranteed the parsing step will produce either issues
// or a value
definitions.addAll(parseResult.value!!.definitions)
}
}
// Parsing issues are fatal
parseIssues.checkNoErrors()
val incomingFragments = options.incomingCompilerMetadata.flatMap { it.fragments }
/**
* Step 2, GraphQL validation
*/
val validationResult = GQLDocument(
definitions = definitions + incomingFragments,
filePath = null
).validateAsExecutable(options.schema)
validationResult.issues.checkNoErrors()
if (options.codegenModels == MODELS_RESPONSE_BASED) {
findConditionalFragments(definitions).checkNoErrors()
}
val warnings = validationResult.issues.filter {
it.severity == Issue.Severity.WARNING && (it !is Issue.DeprecatedUsage || options.warnOnDeprecatedUsages)
}
warnings.forEach {
// Using this format, IntelliJ will parse the warning and display it in the 'run' panel
options.logger.warning("w: ${it.sourceLocation.pretty()}: Apollo: ${it.message}")
}
if (options.failOnWarnings && warnings.isNotEmpty()) {
throw IllegalStateException("Apollo: Warnings found and 'failOnWarnings' is true, aborting.")
}
/**
* Step 3, Modify the AST to add typename and key fields
*/
val fragments = definitions.filterIsInstance<GQLFragmentDefinition>().map {
addRequiredFields(it, options.schema)
}
val operations = definitions.filterIsInstance<GQLOperationDefinition>().map {
addRequiredFields(it, options.schema)
}
// Remember the fragments with the possibly updated fragments
val allFragmentDefinitions = (fragments + incomingFragments).associateBy { it.name }
operations.forEach {
checkKeyFields(it, options.schema, allFragmentDefinitions)
}
fragments.forEach {
checkKeyFields(it, options.schema, allFragmentDefinitions)
}
var alwaysGenerateTypesMatching = options.alwaysGenerateTypesMatching
if (options.generateSchema) {
// If we generate the __Schema class, we need all types for possibleTypes to work
alwaysGenerateTypesMatching = alwaysGenerateTypesMatching + ".*"
}
/**
* Build the IR
*/
val ir = IrBuilder(
schema = options.schema,
operationDefinitions = operations,
alwaysGenerateResponseBasedDataModelGroup = options.generateTestBuilders,
fragmentDefinitions = fragments,
allFragmentDefinitions = allFragmentDefinitions,
alwaysGenerateTypesMatching = alwaysGenerateTypesMatching,
customScalarsMapping = options.customScalarsMapping,
codegenModels = options.codegenModels,
generateOptionalOperationVariables = options.generateOptionalOperationVariables
).build()
if (debugDir != null) {
ir.dumpTo(File(debugDir, "ir.json"))
}
val operationOutput = ir.operations.map {
OperationDescriptor(
name = it.name,
source = QueryDocumentMinifier.minify(it.sourceWithFragments)
)
}.let {
options.operationOutputGenerator.generate(it)
}
check(operationOutput.size == operations.size) {
"""The number of operation IDs (${operationOutput.size}) should match the number of operations (${operations.size}).
|Check that all your IDs are unique.
""".trimMargin()
}
if (options.operationOutputFile != null) {
options.operationOutputFile.writeText(operationOutput.toJson(" "))
}
/**
* Write the generated models
*/
val outputResolverInfo = when (options.targetLanguage) {
TargetLanguage.JAVA -> {
JavaCodeGen(
ir = ir,
resolverInfos = options.incomingCompilerMetadata.map { it.resolverInfo },
operationOutput = operationOutput,
useSemanticNaming = options.useSemanticNaming,
packageNameGenerator = options.packageNameGenerator,
schemaPackageName = options.schemaPackageName,
generateFragmentImplementations = options.generateFragmentImplementations,
generateQueryDocument = options.generateQueryDocument,
generateSchema = options.generateSchema,
flatten = options.flattenModels,
).write(outputDir = outputDir)
}
else -> {
KotlinCodeGen(
ir = ir,
resolverInfos = options.incomingCompilerMetadata.map { it.resolverInfo },
generateAsInternal = options.generateAsInternal,
operationOutput = operationOutput,
useSemanticNaming = options.useSemanticNaming,
packageNameGenerator = options.packageNameGenerator,
schemaPackageName = options.schemaPackageName,
generateFilterNotNull = options.generateFilterNotNull,
generateFragmentImplementations = options.generateFragmentImplementations,
generateQueryDocument = options.generateQueryDocument,
generateSchema = options.generateSchema,
generateTestBuilders = options.generateTestBuilders,
flatten = options.flattenModels,
sealedClassesForEnumsMatching = options.sealedClassesForEnumsMatching,
targetLanguageVersion = options.targetLanguage,
).write(outputDir = outputDir, testDir = testDir)
}
}
return CompilerMetadata(
fragments = fragments,
resolverInfo = outputResolverInfo,
)
}
private fun checkCustomScalars(schema: Schema, customScalarsMapping: Map<String, String>) {
/**
* Generate the mapping for all custom scalars
*
* If the user specified a mapping, use it, else fallback to [Any]
*/
val schemaScalars = schema
.typeDefinitions
.values
.filterIsInstance<GQLScalarTypeDefinition>()
.filter { !it.isBuiltIn() }
.map { type -> type.name }
.toSet()
val unknownScalars = customScalarsMapping.keys.subtract(schemaScalars)
check(unknownScalars.isEmpty()) {
"Apollo: unknown custom scalar(s) in customScalarsMapping: ${unknownScalars.joinToString(",")}"
}
}
val NoOpLogger = object : Logger {
override fun warning(message: String) {
}
}
}
| mit | fd5453ac04978b37fd17d253ed0a9316 | 36.058577 | 137 | 0.708705 | 4.915094 | false | false | false | false |
allotria/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/SvgRenderer.kt | 4 | 6302 | // 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
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.ui.LafIconLookup
import org.apache.batik.anim.dom.SVGDOMImplementation
import org.apache.batik.dom.GenericDOMImplementation
import org.apache.batik.svggen.*
import org.w3c.dom.Element
import java.awt.Component
import java.awt.Image
import java.io.StringWriter
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.Icon
import javax.xml.transform.OutputKeys
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
// jFreeSvg produces not so compact and readable SVG as batik
internal class SvgRenderer(val svgFileDir: Path) {
private val xmlTransformer = TransformerFactory.newInstance().newTransformer()
private val xmlFactory = GenericDOMImplementation.getDOMImplementation().createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null)
private val context = SVGGeneratorContext.createDefault(xmlFactory)
init {
xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml")
xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes")
xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
xmlTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")
context.imageHandler = object : ImageHandlerBase64Encoder() {
override fun handleImage(image: Image, imageElement: Element, generatorContext: SVGGeneratorContext) {
imageElement.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", findImagePath(image))
}
private fun findImagePath(image: Image): String {
fun isImage(iconWrapper: Icon): Boolean {
if (iconWrapper === AllIcons.Actions.Stub) {
return false
}
val thatImage = (iconWrapper as IconLoader.CachedImageIcon).doGetRealIcon()?.image
return thatImage === image
}
for (name in arrayOf("checkBox", "radio", "gear.png", "gearPlain.png", "gearPlain.svg", "spinnerRight")) {
val iconWrapper = when (name) {
"gear.png", "gearPlain.png", "gearPlain.svg" -> IconLoader.getIcon("/general/$name", SvgRenderer::class.java)
else -> LafIconLookup.findIcon(name)
} ?: continue
if (isImage(iconWrapper)) {
return getIconRelativePath(iconWrapper.toString())
}
}
for (name in arrayOf("checkBox", "radio")) {
val iconWrapper = LafIconLookup.findIcon(name, selected = true) ?: continue
if (isImage(iconWrapper)) {
return getIconRelativePath(iconWrapper.toString())
}
}
throw RuntimeException("unknown image")
}
}
context.errorHandler = object: ErrorHandler {
override fun handleError(error: SVGGraphics2DIOException) = throw error
override fun handleError(error: SVGGraphics2DRuntimeException) = throw error
}
class PrefixInfo {
var currentId = 0
}
context.idGenerator = object : SVGIDGenerator() {
private val prefixMap = HashMap<String, PrefixInfo>()
override fun generateID(prefix: String): String {
val info = prefixMap.getOrPut(prefix) { PrefixInfo() }
return "${if (prefix == "clipPath") "" else prefix}${info.currentId++}"
}
}
}
private fun getIconRelativePath(outputPath: String): String {
for ((moduleName, relativePath) in mapOf("intellij.platform.icons" to "platform/icons/src",
"intellij.platform.ide.impl" to "platform/platform-impl/src")) {
val index = outputPath.indexOf(moduleName)
if (index > 0) {
val iconPath = Paths.get(PathManagerEx.getCommunityHomePath(), relativePath, outputPath.substring(index + moduleName.length + 1 /* slash */))
assertThat(iconPath).exists()
return FileUtilRt.toSystemIndependentName(svgFileDir.relativize(iconPath).toString())
}
}
throw RuntimeException("unknown icon location ($outputPath)")
}
// CSS (style) not used - attributes more readable and shorter
// separate styles (in the defs) also not suitable, so, we keep it simple as is
private fun svgGraphicsToString(svgGenerator: SVGGraphics2D, component: Component): String {
val writer = StringWriter()
writer.use {
val root = svgGenerator.root
root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SVGSyntax.SVG_NAMESPACE_URI)
@Suppress("SpellCheckingInspection")
root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink")
root.setAttributeNS(null, "viewBox", "0 0 ${component.width} ${component.height}")
xmlTransformer.transform(DOMSource(root), StreamResult(writer))
}
// xlink is not used in some files and optimize imports on commit can modify file, so, as simple solution, disable inspection
val result = "<!--suppress XmlUnusedNamespaceDeclaration -->\n" + writer
.toString()
// Remember
// no idea why transformer/batik doesn't escape it correctly
.replace(">", ">&")
return if (SystemInfo.isWindows) StringUtilRt.convertLineSeparators(result) else result
}
fun render(component: Component): String {
val svgGenerator = SvgGraphics2dWithDeviceConfiguration(context)
component.paint(svgGenerator)
return svgGraphicsToString(svgGenerator, component)
}
}
private class SvgGraphics2dWithDeviceConfiguration : SVGGraphics2D {
constructor(context: SVGGeneratorContext) : super(context, false) {
}
private constructor(g: SvgGraphics2dWithDeviceConfiguration): super(g)
override fun getDeviceConfiguration() = null
override fun create() = SvgGraphics2dWithDeviceConfiguration(this)
} | apache-2.0 | 194ede0c82ba902294a55233ac142a26 | 40.741722 | 149 | 0.7139 | 4.313484 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/sdk/PySdkRendering.kt | 3 | 4542 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.icons.AllIcons
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.LayeredIcon
import com.jetbrains.python.PyBundle
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import javax.swing.Icon
val noInterpreterMarker: String = "<${PyBundle.message("python.sdk.there.is.no.interpreter")}>"
fun name(sdk: Sdk): Triple<String?, String, String?> = name(sdk, sdk.name)
/**
* Returns modifier that shortly describes that is wrong with passed [sdk], [name] and additional info.
*/
fun name(sdk: Sdk, name: String): Triple<String?, String, String?> {
val modifier = when {
PythonSdkUtil.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) -> "invalid"
PythonSdkType.isIncompleteRemote(sdk) -> "incomplete"
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> "unsupported"
else -> null
}
val providedForSdk = PySdkProvider.EP_NAME.extensions
.mapNotNull { it.getSdkAdditionalText(sdk) }
.firstOrNull()
val secondary = providedForSdk ?: if (PythonSdkType.isRunAsRootViaSudo(sdk)) "[sudo]" else null
return Triple(modifier, name, secondary)
}
/**
* Returns a path to be rendered as the sdk's path.
*
* Initial value is taken from the [sdk],
* then it is converted to a path relative to the user home directory.
*
* Returns null if the initial path or the relative value are presented in the sdk's name.
*
* @see FileUtil.getLocationRelativeToUserHome
*/
fun path(sdk: Sdk): String? {
val name = sdk.name
val homePath = sdk.homePath ?: return null
return homePath.let { FileUtil.getLocationRelativeToUserHome(it) }.takeIf { homePath !in name && it !in name }
}
/**
* Returns an icon to be used as the sdk's icon.
*
* Result is wrapped with [AllIcons.Actions.Cancel]
* if the sdk is local and does not exist, or remote and incomplete or has invalid credentials, or is not supported.
*
* @see PythonSdkUtil.isInvalid
* @see PythonSdkType.isIncompleteRemote
* @see PythonSdkType.hasInvalidRemoteCredentials
* @see LanguageLevel.SUPPORTED_LEVELS
*/
fun icon(sdk: Sdk): Icon? {
val flavor = PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath)
val icon = if (flavor != null) flavor.icon else (sdk.sdkType as? SdkType)?.icon ?: return null
val providedIcon = PySdkProvider.EP_NAME.extensions
.mapNotNull { it.getSdkIcon(sdk) }
.firstOrNull()
return when {
PythonSdkUtil.isInvalid(sdk) ||
PythonSdkType.isIncompleteRemote(sdk) ||
PythonSdkType.hasInvalidRemoteCredentials(sdk) ||
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) ->
wrapIconWithWarningDecorator(icon)
sdk is PyDetectedSdk -> IconLoader.getTransparentIcon(icon)
providedIcon != null -> providedIcon
else -> icon
}
}
/**
* Groups valid sdks associated with the [module] by types.
* Virtual environments, pipenv and conda environments are considered as [PyRenderedSdkType.VIRTUALENV].
* Remote interpreters are considered as [PyRenderedSdkType.REMOTE].
* All the others are considered as [PyRenderedSdkType.SYSTEM].
*
* @see Sdk.isAssociatedWithAnotherModule
* @see PythonSdkUtil.isVirtualEnv
* @see PythonSdkUtil.isCondaVirtualEnv
* @see PythonSdkUtil.isRemote
* @see PyRenderedSdkType
*/
fun groupModuleSdksByTypes(allSdks: List<Sdk>, module: Module?, invalid: (Sdk) -> Boolean): Map<PyRenderedSdkType, List<Sdk>> {
return allSdks
.asSequence()
.filter { !it.isAssociatedWithAnotherModule(module) && !invalid(it) }
.groupBy {
when {
PythonSdkUtil.isVirtualEnv(it) || PythonSdkUtil.isCondaVirtualEnv(it) -> PyRenderedSdkType.VIRTUALENV
PythonSdkUtil.isRemote(it) -> PyRenderedSdkType.REMOTE
else -> PyRenderedSdkType.SYSTEM
}
}
}
/**
* Order is important, sdks are rendered in the same order as the types are defined.
*
* @see groupModuleSdksByTypes
*/
enum class PyRenderedSdkType {
VIRTUALENV, SYSTEM, REMOTE
}
private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon =
LayeredIcon(2).apply {
setIcon(icon, 0)
setIcon(AllIcons.Actions.Cancel, 1)
}
| apache-2.0 | 0b9126c89109625ca577b39aab67de56 | 35.336 | 140 | 0.745046 | 4.256795 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/build/output/KotlincOutputParser.kt | 3 | 8010 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.BuildEventsNls
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.lang.LangBundle
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.NonNls
import java.io.File
import java.util.function.Consumer
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private val COMPILER_MESSAGES_GROUP: @BuildEventsNls.Title String
@BuildEventsNls.Title
get() = LangBundle.message("build.event.title.kotlin.compiler")
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<in BuildEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
val colonIndex2 = lineWoSeverity.colon().skipDriveOnWin(lineWoSeverity)
if (colonIndex2 < 0) return false
val path = lineWoSeverity.substringBeforeAndTrim(colonIndex2)
val file = File(path)
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "kts" && fileExtension != "java")) { //NON-NLS
val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(colonIndex2)
var lineWoPositionIndex = -1
var matcher: Matcher? = null
if (lineWoPath.startsWith('(')) {
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
lineWoPositionIndex = colonIndex3
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(lineWoPositionIndex)
matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
else {
val colonIndex4 = lineWoPath.colon(1)
if (colonIndex4 >= 0) {
lineWoPositionIndex = colonIndex4
}
else {
lineWoPositionIndex = lineWoPath.colon()
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex4)
matcher = LINE_COLON_COLUMN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
if (lineWoPositionIndex >= 0) {
val relatedNextLines = "".amendNextLinesIfNeeded(reader)
val message = lineWoPath.substringAfterAndTrim(lineWoPositionIndex) + relatedNextLines
val details = line + relatedNextLines
if (matcher != null && matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.parentEventId, getMessageKind(severity), message, path, lineNumber.toInt(), symbolNumberText, details), consumer)
}
}
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), message, details), consumer)
}
else {
val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer)
}
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private val LINE_COLON_COLUMN_POSITION_PATTERN = Pattern.compile("([0-9]*):([0-9]*)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null) {
if (nextLine.isNextMessage()) {
reader.pushBack()
break
}
else {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.startsWith(this, "Note: ") // Next javac info message candidate //NON-NLS
|| StringUtil.startsWith(this, "> Task :") // Next gradle message candidate //NON-NLS
|| StringUtil.containsIgnoreCase(this, "FAILURE") //NON-NLS
|| StringUtil.containsIgnoreCase(this, "FAILED") //NON-NLS
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
@NonNls
private fun getMessageKind(kind: @NonNls String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun String.colon(skip: Int): Int {
var index = -1
repeat(skip + 1) {
index = indexOf(COLON, index + 1)
if (index < 0) return index
}
return index
}
private fun Int.skipDriveOnWin(line: String): Int {
return if (this == 1) line.indexOf(COLON, this + 1) else this
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT
get() =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + LangBundle.message("kapterror.error.while.annotation.processing")
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<in MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(parentId: Any,
messageKind: MessageEvent.Kind,
text: @BuildEventsNls.Message String,
detail: @BuildEventsNls.Description String): MessageEvent {
return MessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail) //NON-NLS
}
private fun createMessageWithLocation(
parentId: Any,
messageKind: MessageEvent.Kind,
text: @BuildEventsNls.Message String,
file: String,
lineNumber: Int,
columnIndex: Int,
detail: @BuildEventsNls.Description String
): FileMessageEventImpl {
return FileMessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail, //NON-NLS
FilePosition(File(file), lineNumber - 1, columnIndex - 1))
}
} | apache-2.0 | cf25a9be70d5e18ca661262dfad1093f | 39.459596 | 140 | 0.699126 | 4.670554 | false | false | false | false |
square/okio | okio/src/commonMain/kotlin/okio/Utf8.kt | 1 | 16550 | /*
* Copyright (C) 2017 Square, 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.
*/
/**
* Okio assumes most applications use UTF-8 exclusively, and offers optimized implementations of
* common operations on UTF-8 strings.
*
* <table border="1" cellspacing="0" cellpadding="3" summary="">
* <tr>
* <th></th>
* <th>[ByteString]</th>
* <th>[Buffer], [BufferedSink], [BufferedSource]</th>
* </tr>
* <tr>
* <td>Encode a string</td>
* <td>[ByteString.encodeUtf8]</td>
* <td>[BufferedSink.writeUtf8]</td>
* </tr>
* <tr>
* <td>Encode a code point</td>
* <td></td>
* <td>[BufferedSink.writeUtf8CodePoint]</td>
* </tr>
* <tr>
* <td>Decode a string</td>
* <td>[ByteString.utf8]</td>
* <td>[BufferedSource.readUtf8], [BufferedSource.readUtf8]</td>
* </tr>
* <tr>
* <td>Decode a code point</td>
* <td></td>
* <td>[BufferedSource.readUtf8CodePoint]</td>
* </tr>
* <tr>
* <td>Decode until the next `\r\n` or `\n`</td>
* <td></td>
* <td>[BufferedSource.readUtf8LineStrict],
* [BufferedSource.readUtf8LineStrict]</td>
* </tr>
* <tr>
* <td>Decode until the next `\r\n`, `\n`, or `EOF`</td>
* <td></td>
* <td>[BufferedSource.readUtf8Line]</td>
* </tr>
* <tr>
* <td>Measure the bytes in a UTF-8 string</td>
* <td colspan="2">[Utf8.size], [Utf8.size]</td>
* </tr>
* </table>
*/
@file:JvmName("Utf8")
package okio
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
/**
* Returns the number of bytes used to encode the slice of `string` as UTF-8 when using
* [BufferedSink.writeUtf8].
*/
@JvmOverloads
@JvmName("size")
fun String.utf8Size(beginIndex: Int = 0, endIndex: Int = length): Long {
require(beginIndex >= 0) { "beginIndex < 0: $beginIndex" }
require(endIndex >= beginIndex) { "endIndex < beginIndex: $endIndex < $beginIndex" }
require(endIndex <= length) { "endIndex > string.length: $endIndex > $length" }
var result = 0L
var i = beginIndex
while (i < endIndex) {
val c = this[i].code
if (c < 0x80) {
// A 7-bit character with 1 byte.
result++
i++
} else if (c < 0x800) {
// An 11-bit character with 2 bytes.
result += 2
i++
} else if (c < 0xd800 || c > 0xdfff) {
// A 16-bit character with 3 bytes.
result += 3
i++
} else {
val low = if (i + 1 < endIndex) this[i + 1].code else 0
if (c > 0xdbff || low < 0xdc00 || low > 0xdfff) {
// A malformed surrogate, which yields '?'.
result++
i++
} else {
// A 21-bit character with 4 bytes.
result += 4
i += 2
}
}
}
return result
}
internal const val REPLACEMENT_BYTE: Byte = '?'.code.toByte()
internal const val REPLACEMENT_CHARACTER: Char = '\ufffd'
internal const val REPLACEMENT_CODE_POINT: Int = REPLACEMENT_CHARACTER.code
@Suppress("NOTHING_TO_INLINE") // Syntactic sugar.
internal inline fun isIsoControl(codePoint: Int): Boolean =
(codePoint in 0x00..0x1F) || (codePoint in 0x7F..0x9F)
@Suppress("NOTHING_TO_INLINE") // Syntactic sugar.
internal inline fun isUtf8Continuation(byte: Byte): Boolean {
// 0b10xxxxxx
return byte and 0xc0 == 0x80
}
// TODO combine with Buffer.writeUtf8?
// TODO combine with Buffer.writeUtf8CodePoint?
internal inline fun String.processUtf8Bytes(
beginIndex: Int,
endIndex: Int,
yield: (Byte) -> Unit
) {
// Transcode a UTF-16 String to UTF-8 bytes.
var index = beginIndex
while (index < endIndex) {
val c = this[index]
when {
c < '\u0080' -> {
// Emit a 7-bit character with 1 byte.
yield(c.code.toByte()) // 0xxxxxxx
index++
// Assume there is going to be more ASCII
while (index < endIndex && this[index] < '\u0080') {
yield(this[index++].code.toByte())
}
}
c < '\u0800' -> {
// Emit a 11-bit character with 2 bytes.
/* ktlint-disable no-multi-spaces */
yield((c.code shr 6 or 0xc0).toByte()) // 110xxxxx
yield((c.code and 0x3f or 0x80).toByte()) // 10xxxxxx
/* ktlint-enable no-multi-spaces */
index++
}
c !in '\ud800'..'\udfff' -> {
// Emit a 16-bit character with 3 bytes.
/* ktlint-disable no-multi-spaces */
yield((c.code shr 12 or 0xe0).toByte()) // 1110xxxx
yield((c.code shr 6 and 0x3f or 0x80).toByte()) // 10xxxxxx
yield((c.code and 0x3f or 0x80).toByte()) // 10xxxxxx
/* ktlint-enable no-multi-spaces */
index++
}
else -> {
// c is a surrogate. Make sure it is a high surrogate & that its successor is a low
// surrogate. If not, the UTF-16 is invalid, in which case we emit a replacement
// byte.
if (c > '\udbff' ||
endIndex <= index + 1 ||
this[index + 1] !in '\udc00'..'\udfff'
) {
yield(REPLACEMENT_BYTE)
index++
} else {
// UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits)
// UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits)
// Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits)
val codePoint = (
((c.code shl 10) + this[index + 1].code) +
(0x010000 - (0xd800 shl 10) - 0xdc00)
)
// Emit a 21-bit character with 4 bytes.
/* ktlint-disable no-multi-spaces */
yield((codePoint shr 18 or 0xf0).toByte()) // 11110xxx
yield((codePoint shr 12 and 0x3f or 0x80).toByte()) // 10xxxxxx
yield((codePoint shr 6 and 0x3f or 0x80).toByte()) // 10xxyyyy
yield((codePoint and 0x3f or 0x80).toByte()) // 10yyyyyy
/* ktlint-enable no-multi-spaces */
index += 2
}
}
}
}
}
// TODO combine with Buffer.readUtf8CodePoint?
internal inline fun ByteArray.processUtf8CodePoints(
beginIndex: Int,
endIndex: Int,
yield: (Int) -> Unit
) {
var index = beginIndex
while (index < endIndex) {
val b0 = this[index]
when {
b0 >= 0 -> {
// 0b0xxxxxxx
yield(b0.toInt())
index++
// Assume there is going to be more ASCII
while (index < endIndex && this[index] >= 0) {
yield(this[index++].toInt())
}
}
b0 shr 5 == -2 -> {
// 0b110xxxxx
index += process2Utf8Bytes(index, endIndex) { yield(it) }
}
b0 shr 4 == -2 -> {
// 0b1110xxxx
index += process3Utf8Bytes(index, endIndex) { yield(it) }
}
b0 shr 3 == -2 -> {
// 0b11110xxx
index += process4Utf8Bytes(index, endIndex) { yield(it) }
}
else -> {
// 0b10xxxxxx - Unexpected continuation
// 0b111111xxx - Unknown encoding
yield(REPLACEMENT_CODE_POINT)
index++
}
}
}
}
// Value added to the high UTF-16 surrogate after shifting
internal const val HIGH_SURROGATE_HEADER = 0xd800 - (0x010000 ushr 10)
// Value added to the low UTF-16 surrogate after masking
internal const val LOG_SURROGATE_HEADER = 0xdc00
// TODO combine with Buffer.readUtf8?
internal inline fun ByteArray.processUtf16Chars(
beginIndex: Int,
endIndex: Int,
yield: (Char) -> Unit
) {
var index = beginIndex
while (index < endIndex) {
val b0 = this[index]
when {
b0 >= 0 -> {
// 0b0xxxxxxx
yield(b0.toInt().toChar())
index++
// Assume there is going to be more ASCII
// This is almost double the performance of the outer loop
while (index < endIndex && this[index] >= 0) {
yield(this[index++].toInt().toChar())
}
}
b0 shr 5 == -2 -> {
// 0b110xxxxx
index += process2Utf8Bytes(index, endIndex) { yield(it.toChar()) }
}
b0 shr 4 == -2 -> {
// 0b1110xxxx
index += process3Utf8Bytes(index, endIndex) { yield(it.toChar()) }
}
b0 shr 3 == -2 -> {
// 0b11110xxx
index += process4Utf8Bytes(index, endIndex) { codePoint ->
if (codePoint != REPLACEMENT_CODE_POINT) {
// Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits)
// UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits)
// UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits)
/* ktlint-disable no-multi-spaces paren-spacing */
yield(((codePoint ushr 10 ) + HIGH_SURROGATE_HEADER).toChar())
/* ktlint-enable no-multi-spaces paren-spacing */
yield(((codePoint and 0x03ff) + LOG_SURROGATE_HEADER).toChar())
} else {
yield(REPLACEMENT_CHARACTER)
}
}
}
else -> {
// 0b10xxxxxx - Unexpected continuation
// 0b111111xxx - Unknown encoding
yield(REPLACEMENT_CHARACTER)
index++
}
}
}
}
// ===== UTF-8 Encoding and Decoding ===== //
/*
The following 3 methods take advantage of using XOR on 2's complement store
numbers to quickly and efficiently combine the important data of UTF-8 encoded
bytes. This will be best explained using an example, so lets take the following
encoded character '∇' = \u2207.
Using the Unicode code point for this character, 0x2207, we will split the
binary representation into 3 sections as follows:
0x2207 = 0b0010 0010 0000 0111
xxxx yyyy yyzz zzzz
Now take each section of bits and add the appropriate header:
utf8(0x2207) = 0b1110 xxxx 0b10yy yyyy 0b10zz zzzz
= 0b1110 0010 0b1000 1000 0b1000 0111
= 0xe2 0x88 0x87
We have now just encoded this as a 3 byte UTF-8 character. More information
about different sizes of characters can be found here:
https://en.wikipedia.org/wiki/UTF-8
Encoding was pretty easy, but decoding is a bit more complicated. We need to
first determine the number of bytes used to represent the character, strip all
the headers, and then combine all the bits into a single integer. Let's use the
character we just encoded and work backwards, taking advantage of 2's complement
integer representation and the XOR function.
Let's look at the decimal representation of these bytes:
0xe2, 0x88, 0x87 = -30, -120, -121
The first interesting thing to notice is that UTF-8 headers all start with 1 -
except for ASCII which is encoded as a single byte - which means all UTF-8 bytes
will be negative. So converting these to integers results in a lot of 1's added
because they are store as 2's complement:
0xe2 = -30 = 0xffff ffe2
0x88 = -120 = 0xffff ff88
0x87 = -121 = 0xffff ff87
Now let's XOR these with their corresponding UTF-8 byte headers to see what
happens:
0xffff ffe2 xor 0xffff ffe0 = 0x0000 0002
0xffff ff88 xor 0xffff ff80 = 0x0000 0008
0xffff ff87 xor 0xffff ff80 = 0x0000 0007
***This is why we must first convert the byte header mask to a byte and then
back to an integer, so it is properly converted to a 2's complement negative
number which can be applied to each byte.***
Now let's look at the binary representation to see how we can combine these to
create the Unicode code point:
0b0000 0010 0b0000 1000 0b0000 0111
0b1110 xxxx 0b10yy yyyy 0b10zz zzzz
Combining each section will require some bit shifting, but then they can just
be OR'd together. They can also be XOR'd together which makes use of a single,
COMMUTATIVE, operator through the entire calculation.
<< 12 = 00000010
<< 6 = 00001000
<< 0 = 00000111
XOR = 00000010001000000111
code point = 0b0010 0010 0000 0111
= 0x2207
And there we have it! The decoded UTF-8 character '∇'! And because the XOR
operator is commutative, we can re-arrange all this XOR and shifting to create
a single mask that can be applied to 3-byte UTF-8 characters after their bytes
have been shifted and XOR'd together.
*/
// Mask used to remove byte headers from a 2 byte encoded UTF-8 character
internal const val MASK_2BYTES = 0x0f80
// MASK_2BYTES =
// (0xc0.toByte() shl 6) xor
// (0x80.toByte().toInt())
internal inline fun ByteArray.process2Utf8Bytes(
beginIndex: Int,
endIndex: Int,
yield: (Int) -> Unit
): Int {
if (endIndex <= beginIndex + 1) {
yield(REPLACEMENT_CODE_POINT)
// Only 1 byte remaining - underflow
return 1
}
val b0 = this[beginIndex]
val b1 = this[beginIndex + 1]
if (!isUtf8Continuation(b1)) {
yield(REPLACEMENT_CODE_POINT)
return 1
}
val codePoint =
(
MASK_2BYTES
xor (b1.toInt())
xor (b0.toInt() shl 6)
)
when {
codePoint < 0x80 -> {
yield(REPLACEMENT_CODE_POINT) // Reject overlong code points.
}
else -> {
yield(codePoint)
}
}
return 2
}
// Mask used to remove byte headers from a 3 byte encoded UTF-8 character
internal const val MASK_3BYTES = -0x01e080
// MASK_3BYTES =
// (0xe0.toByte() shl 12) xor
// (0x80.toByte() shl 6) xor
// (0x80.toByte().toInt())
internal inline fun ByteArray.process3Utf8Bytes(
beginIndex: Int,
endIndex: Int,
yield: (Int) -> Unit
): Int {
if (endIndex <= beginIndex + 2) {
// At least 2 bytes remaining
yield(REPLACEMENT_CODE_POINT)
if (endIndex <= beginIndex + 1 || !isUtf8Continuation(this[beginIndex + 1])) {
// Only 1 byte remaining - underflow
// Or 2nd byte is not a continuation - malformed
return 1
} else {
// Only 2 bytes remaining - underflow
return 2
}
}
val b0 = this[beginIndex]
val b1 = this[beginIndex + 1]
if (!isUtf8Continuation(b1)) {
yield(REPLACEMENT_CODE_POINT)
return 1
}
val b2 = this[beginIndex + 2]
if (!isUtf8Continuation(b2)) {
yield(REPLACEMENT_CODE_POINT)
return 2
}
val codePoint =
(
MASK_3BYTES
xor (b2.toInt())
xor (b1.toInt() shl 6)
xor (b0.toInt() shl 12)
)
when {
codePoint < 0x800 -> {
yield(REPLACEMENT_CODE_POINT) // Reject overlong code points.
}
codePoint in 0xd800..0xdfff -> {
yield(REPLACEMENT_CODE_POINT) // Reject partial surrogates.
}
else -> {
yield(codePoint)
}
}
return 3
}
// Mask used to remove byte headers from a 4 byte encoded UTF-8 character
internal const val MASK_4BYTES = 0x381f80
// MASK_4BYTES =
// (0xf0.toByte() shl 18) xor
// (0x80.toByte() shl 12) xor
// (0x80.toByte() shl 6) xor
// (0x80.toByte().toInt())
internal inline fun ByteArray.process4Utf8Bytes(
beginIndex: Int,
endIndex: Int,
yield: (Int) -> Unit
): Int {
if (endIndex <= beginIndex + 3) {
// At least 3 bytes remaining
yield(REPLACEMENT_CODE_POINT)
if (endIndex <= beginIndex + 1 || !isUtf8Continuation(this[beginIndex + 1])) {
// Only 1 byte remaining - underflow
// Or 2nd byte is not a continuation - malformed
return 1
} else if (endIndex <= beginIndex + 2 || !isUtf8Continuation(this[beginIndex + 2])) {
// Only 2 bytes remaining - underflow
// Or 3rd byte is not a continuation - malformed
return 2
} else {
// Only 3 bytes remaining - underflow
return 3
}
}
val b0 = this[beginIndex]
val b1 = this[beginIndex + 1]
if (!isUtf8Continuation(b1)) {
yield(REPLACEMENT_CODE_POINT)
return 1
}
val b2 = this[beginIndex + 2]
if (!isUtf8Continuation(b2)) {
yield(REPLACEMENT_CODE_POINT)
return 2
}
val b3 = this[beginIndex + 3]
if (!isUtf8Continuation(b3)) {
yield(REPLACEMENT_CODE_POINT)
return 3
}
val codePoint =
(
MASK_4BYTES
xor (b3.toInt())
xor (b2.toInt() shl 6)
xor (b1.toInt() shl 12)
xor (b0.toInt() shl 18)
)
when {
codePoint > 0x10ffff -> {
yield(REPLACEMENT_CODE_POINT) // Reject code points larger than the Unicode maximum.
}
codePoint in 0xd800..0xdfff -> {
yield(REPLACEMENT_CODE_POINT) // Reject partial surrogates.
}
codePoint < 0x10000 -> {
yield(REPLACEMENT_CODE_POINT) // Reject overlong code points.
}
else -> {
yield(codePoint)
}
}
return 4
}
| apache-2.0 | 2abcd92c7e34332500c444c6b582a900 | 28.705566 | 96 | 0.615678 | 3.57365 | false | false | false | false |
ncipollo/android-viper | sample/src/main/kotlin/viper/sample/ui/presenters/UserPresenter.kt | 1 | 1434 | package viper.sample.ui.presenters
import android.os.Bundle
import rx.Observable
import rx.Subscription
import viper.presenters.FragmentPresenter
import viper.sample.model.interactors.SampleInteractors
import viper.sample.ui.fragments.UserView
import viper.sample.ui.router.SampleFlow
/**
* Handles the presentation of the user fragment.
* Created by Nick Cipollo on 12/16/16.
*/
class UserPresenter : FragmentPresenter<UserView, SampleInteractors>() {
val UPDATE_DONE_ENABLED = 1
var userSub: Subscription? = null
override fun onTakeView(view: UserView) {
super.onTakeView(view)
validateUser(view.user)
userSub = view.onUserChanged
.subscribe {
validateUser(it.toString())
}
}
override fun onDropView() {
super.onDropView()
userSub?.unsubscribe()
userSub = null
}
fun validateUser(user:String) {
val valid = isUserValid(user)
stop(UPDATE_DONE_ENABLED)
restartableFirst(UPDATE_DONE_ENABLED,
{ Observable.just(valid) },
{ view, enabled -> view.doneEnabled = enabled })
start(UPDATE_DONE_ENABLED)
}
fun isUserValid(user:String) = user.isNotEmpty()
fun selectUser(user: String) {
val args = Bundle()
args.putString(SampleFlow.ARGS_USER, user)
moveToNextScreen(SampleFlow.SCREEN_REPOS, args)
}
} | mit | 14c19206ae8147a6bf0d5347a34c4eb4 | 27.137255 | 72 | 0.655509 | 4.180758 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/searchview/SearchViewAssertions.kt | 1 | 1581 | package com.agoda.kakao.searchview
import android.os.Build
import android.view.View
import android.widget.SearchView
import androidx.annotation.RequiresApi
import androidx.annotation.StringRes
import androidx.test.espresso.matcher.BoundedMatcher
import com.agoda.kakao.common.assertions.BaseAssertions
import com.agoda.kakao.common.utilities.getResourceString
import org.hamcrest.Description
import org.hamcrest.Matcher
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
interface SearchViewAssertions : BaseAssertions {
fun hasHint(hint: String): Matcher<View> = object : BoundedMatcher<View, SearchView>(SearchView::class.java), Matcher<View> {
var realHint: String? = null
override fun describeTo(description: Description) {
description.appendText("with SearchView hint: $hint, but was: $realHint")
}
override fun matchesSafely(item: SearchView): Boolean {
return item.queryHint?.toString() == hint
}
}
fun hasHint(@StringRes queryHintId: Int): Matcher<View> = hasHint(getResourceString(queryHintId))
fun hasQuery(query: String): Matcher<View> = object : BoundedMatcher<View, SearchView>(SearchView::class.java), Matcher<View> {
var foundQuery: String? = null
override fun describeTo(description: Description) {
description.appendText("with SearchView query: $query, but was: $foundQuery")
}
override fun matchesSafely(item: SearchView): Boolean {
foundQuery = item.query.toString()
return foundQuery == query
}
}
}
| apache-2.0 | c6eec9b2ffb1a7db165ff2ccfd7be42c | 36.642857 | 131 | 0.7179 | 4.556196 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/objcexport/ObjCExport.kt | 1 | 6944 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.objcexport
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.getPackageFragments
import org.jetbrains.kotlin.backend.konan.llvm.CodeGenerator
import org.jetbrains.kotlin.backend.konan.llvm.objcexport.ObjCExportCodeGenerator
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.target.CompilerOutputKind
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.isSubpackageOf
internal class ObjCExport(val context: Context) {
private val target get() = context.config.targetManager.target
internal fun produceObjCFramework() {
if (context.config.produce != CompilerOutputKind.FRAMEWORK) return
val headerGenerator = ObjCExportHeaderGenerator(context)
headerGenerator.translateModule()
val namer = headerGenerator.namer
val mapper = headerGenerator.mapper
val framework = File(context.config.outputFile)
val frameworkContents = when (target) {
KonanTarget.IPHONE, KonanTarget.IPHONE_SIM -> framework
KonanTarget.MACBOOK -> framework.child("Versions/A")
else -> error(target)
}
val headers = frameworkContents.child("Headers")
val frameworkName = framework.name.removeSuffix(".framework")
val headerName = frameworkName + ".h"
val header = headers.child(headerName)
headers.mkdirs()
header.writeLines(headerGenerator.build())
val modules = frameworkContents.child("Modules")
modules.mkdirs()
val moduleMap = """
|framework module $frameworkName {
| umbrella header "$headerName"
|
| export *
| module * { export * }
|}
""".trimMargin()
modules.child("module.modulemap").writeBytes(moduleMap.toByteArray())
emitInfoPlist(frameworkContents, frameworkName)
if (target == KonanTarget.MACBOOK) {
framework.child("Versions/Current").createAsSymlink("A")
for (child in listOf(frameworkName, "Headers", "Modules", "Resources")) {
framework.child(child).createAsSymlink("Versions/Current/$child")
}
}
val objCCodeGenerator = ObjCExportCodeGenerator(CodeGenerator(context), namer, mapper)
objCCodeGenerator.emitRtti(headerGenerator.generatedClasses, headerGenerator.topLevel)
}
private fun emitInfoPlist(frameworkContents: File, name: String) {
val directory = when (target) {
KonanTarget.IPHONE,
KonanTarget.IPHONE_SIM -> frameworkContents
KonanTarget.MACBOOK -> frameworkContents.child("Resources").also { it.mkdirs() }
else -> error(target)
}
val file = directory.child("Info.plist")
val bundleExecutable = name
val pkg = context.moduleDescriptor.guessMainPackage() // TODO: consider showing warning if it is root.
val bundleId = pkg.child(Name.identifier(name)).asString()
val platform = when (target) {
KonanTarget.IPHONE -> "iPhoneOS"
KonanTarget.IPHONE_SIM -> "iPhoneSimulator"
KonanTarget.MACBOOK -> "MacOSX"
else -> error(target)
}
val minimumOsVersion = context.config.distribution.targetProperties.osVersionMin!!
val contents = StringBuilder()
contents.append("""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>$bundleExecutable</string>
<key>CFBundleIdentifier</key>
<string>$bundleId</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$name</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>$platform</string>
</array>
<key>CFBundleVersion</key>
<string>1</string>
""".trimIndent())
contents.append(when (target) {
KonanTarget.IPHONE,
KonanTarget.IPHONE_SIM -> """
| <key>MinimumOSVersion</key>
| <string>$minimumOsVersion</string>
| <key>UIDeviceFamily</key>
| <array>
| <integer>1</integer>
| <integer>2</integer>
| </array>
""".trimMargin()
KonanTarget.MACBOOK -> ""
else -> error(target)
})
if (target == KonanTarget.IPHONE) {
contents.append("""
| <key>UIRequiredDeviceCapabilities</key>
| <array>
| <string>arm64</string>
| </array>
""".trimMargin()
)
}
contents.append("""
</dict>
</plist>
""".trimIndent())
// TODO: Xcode also add some number of DT* keys.
file.writeBytes(contents.toString().toByteArray())
}
}
internal fun ModuleDescriptor.guessMainPackage(): FqName {
val allPackages = this.getPackageFragments() // Includes also all parent packages, e.g. the root one.
val nonEmptyPackages = allPackages
.filter { it.getMemberScope().getContributedDescriptors().isNotEmpty() }
.map { it.fqName }.distinct()
return allPackages.map { it.fqName }.distinct()
.filter { candidate -> nonEmptyPackages.all { it.isSubpackageOf(candidate) } }
// Now there are all common ancestors of non-empty packages. Longest of them is the least common accessor:
.maxBy { it.asString().length }!!
}
| apache-2.0 | 70452390f58e1f6fd379db3f36c04236 | 36.73913 | 118 | 0.611031 | 4.641711 | false | false | false | false |
JuliusKunze/kotlin-native | Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmNativeMem.kt | 1 | 4451 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlinx.cinterop
import sun.misc.Unsafe
private val NativePointed.address: Long
get() = this.rawPtr
private enum class DataModel(val pointerSize: Long) {
_32BIT(4),
_64BIT(8)
}
private val dataModel: DataModel = when (System.getProperty("sun.arch.data.model")) {
null -> TODO()
"32" -> DataModel._32BIT
"64" -> DataModel._64BIT
else -> throw IllegalStateException()
}
// Must be only used in interop, contains host pointer size, not target!
@PublishedApi
internal val pointerSize: Int = dataModel.pointerSize.toInt()
@PublishedApi
internal object nativeMemUtils {
fun getByte(mem: NativePointed) = unsafe.getByte(mem.address)
fun putByte(mem: NativePointed, value: Byte) = unsafe.putByte(mem.address, value)
fun getShort(mem: NativePointed) = unsafe.getShort(mem.address)
fun putShort(mem: NativePointed, value: Short) = unsafe.putShort(mem.address, value)
fun getInt(mem: NativePointed) = unsafe.getInt(mem.address)
fun putInt(mem: NativePointed, value: Int) = unsafe.putInt(mem.address, value)
fun getLong(mem: NativePointed) = unsafe.getLong(mem.address)
fun putLong(mem: NativePointed, value: Long) = unsafe.putLong(mem.address, value)
fun getFloat(mem: NativePointed) = unsafe.getFloat(mem.address)
fun putFloat(mem: NativePointed, value: Float) = unsafe.putFloat(mem.address, value)
fun getDouble(mem: NativePointed) = unsafe.getDouble(mem.address)
fun putDouble(mem: NativePointed, value: Double) = unsafe.putDouble(mem.address, value)
fun getNativePtr(mem: NativePointed): NativePtr = when (dataModel) {
DataModel._32BIT -> getInt(mem).toLong()
DataModel._64BIT -> getLong(mem)
}
fun putNativePtr(mem: NativePointed, value: NativePtr) = when (dataModel) {
DataModel._32BIT -> putInt(mem, value.toInt())
DataModel._64BIT -> putLong(mem, value)
}
fun getByteArray(source: NativePointed, dest: ByteArray, length: Int) {
val clazz = ByteArray::class.java
val baseOffset = unsafe.arrayBaseOffset(clazz).toLong();
unsafe.copyMemory(null, source.address, dest, baseOffset, length.toLong())
}
fun putByteArray(source: ByteArray, dest: NativePointed, length: Int) {
val clazz = ByteArray::class.java
val baseOffset = unsafe.arrayBaseOffset(clazz).toLong();
unsafe.copyMemory(source, baseOffset, null, dest.address, length.toLong())
}
fun getCharArray(source: NativePointed, dest: CharArray, length: Int) {
val clazz = CharArray::class.java
val baseOffset = unsafe.arrayBaseOffset(clazz).toLong();
unsafe.copyMemory(null, source.address, dest, baseOffset, length.toLong() * 2)
}
fun putCharArray(source: CharArray, dest: NativePointed, length: Int) {
val clazz = CharArray::class.java
val baseOffset = unsafe.arrayBaseOffset(clazz).toLong();
unsafe.copyMemory(source, baseOffset, null, dest.address, length.toLong() * 2)
}
fun zeroMemory(dest: NativePointed, length: Int): Unit = unsafe.setMemory(dest.address, length.toLong(), 0)
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
inline fun<reified T> allocateInstance(): T {
return unsafe.allocateInstance(T::class.java) as T
}
fun alloc(size: Long, align: Int): NativePointed {
val address = unsafe.allocateMemory(
if (size == 0L) 1L else size // It is a hack: `sun.misc.Unsafe` can't allocate zero bytes
)
if (address % align != 0L) TODO(align.toString())
return interpretOpaquePointed(address)
}
fun free(mem: NativePtr) {
unsafe.freeMemory(mem)
}
private val unsafe = with(Unsafe::class.java.getDeclaredField("theUnsafe")) {
isAccessible = true
return@with this.get(null) as Unsafe
}
}
| apache-2.0 | ef24950d1b0e929e5775d839a9b74145 | 36.720339 | 111 | 0.690182 | 4.00991 | false | false | false | false |
byoutline/kickmaterial | app/src/main/java/com/byoutline/kickmaterial/features/projectlist/FABBehaviour.kt | 1 | 1970 | /**
* Based on: https://github.com/sitepoint-editors/FloatingActionButton_Animation_Project
*/
package com.byoutline.kickmaterial.features.projectlist
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.View
import android.view.ViewPropertyAnimator
import android.view.animation.LinearInterpolator
import com.byoutline.kickmaterial.KickMaterialApp
class FABBehaviour(context: Context, attrs: AttributeSet) : FloatingActionButton.Behavior() {
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
//child -> Floating Action Button
val translation: ViewPropertyAnimator? = when {
dyConsumed > 0 -> {
val layoutParams = child.layoutParams as CoordinatorLayout.LayoutParams
val fab_bottomMargin = layoutParams.bottomMargin
child.animate().translationY((child.height + fab_bottomMargin).toFloat())
}
dyConsumed < 0 -> child.animate().translationY(0f)
else -> null
}
translation?.multiplyDuration()?.setInterpolator(LinearInterpolator())?.start()
}
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, nestedScrollAxes: Int, type: Int): Boolean {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
}
}
private fun ViewPropertyAnimator.multiplyDuration(): ViewPropertyAnimator {
return setDuration((duration * KickMaterialApp.component.getAnimationDurationMultiplier()))
} | apache-2.0 | d31531683f17cc54c20349890e6d4800 | 48.275 | 197 | 0.753807 | 5.353261 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/userDataModuleInfoUtil.kt | 3 | 3098 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.LIBRARY_KEY
import org.jetbrains.kotlin.idea.MODULE_ROOT_TYPE_KEY
import org.jetbrains.kotlin.idea.SDK_KEY
import org.jetbrains.kotlin.idea.caches.project.UserDataModuleContainer.ForPsiElement
import org.jetbrains.kotlin.idea.caches.project.UserDataModuleContainer.ForVirtualFile
import org.jetbrains.kotlin.idea.core.getSourceType
import org.jetbrains.kotlin.utils.addIfNotNull
// This file declares non-exported API for overriding module info with user-data
private sealed class UserDataModuleContainer {
abstract fun <T> getUserData(key: Key<T>): T?
abstract fun getModule(): Module?
data class ForVirtualFile(val virtualFile: VirtualFile, val project: Project) : UserDataModuleContainer() {
override fun <T> getUserData(key: Key<T>): T? = virtualFile.getUserData(key)
override fun getModule(): Module? = ModuleUtilCore.findModuleForFile(virtualFile, project)
}
data class ForPsiElement(val psiElement: PsiElement) : UserDataModuleContainer() {
override fun <T> getUserData(key: Key<T>): T? {
return psiElement.getUserData(key)
?: psiElement.containingFile?.getUserData(key)
?: psiElement.containingFile?.originalFile?.virtualFile?.getUserData(key)
}
override fun getModule(): Module? = ModuleUtilCore.findModuleForPsiElement(psiElement)
}
}
private fun collectModuleInfoByUserData(
project: Project,
container: UserDataModuleContainer
): List<IdeaModuleInfo> {
fun forModule(): ModuleSourceInfo? {
val rootType = container.getUserData(MODULE_ROOT_TYPE_KEY) ?: return null
val module = container.getModule() ?: return null
return when (rootType.getSourceType()) {
null -> null
SourceType.PRODUCTION -> module.productionSourceInfo()
SourceType.TEST -> module.testSourceInfo()
}
}
val result = mutableListOf<IdeaModuleInfo>()
result.addIfNotNull(forModule())
val library = container.getUserData(LIBRARY_KEY)
if (library != null) {
result.addAll(createLibraryInfo(project, library))
}
val sdk = container.getUserData(SDK_KEY)
if (sdk != null) {
result.add(SdkInfo(project, sdk))
}
return result
}
fun collectModuleInfoByUserData(
project: Project,
virtualFile: VirtualFile
): List<IdeaModuleInfo> = collectModuleInfoByUserData(project, ForVirtualFile(virtualFile, project))
fun collectModuleInfoByUserData(
psiElement: PsiElement
): List<IdeaModuleInfo> = collectModuleInfoByUserData(psiElement.project, ForPsiElement(psiElement))
| apache-2.0 | ae4bbc4377224e7b55abc6ee088f0b0c | 36.780488 | 158 | 0.738864 | 4.52924 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl-constraintlayout/src/androidMain/kotlin/splitties/views/dsl/constraintlayout/ConstraintLayout.kt | 1 | 1582 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.views.dsl.constraintlayout
import androidx.constraintlayout.widget.ConstraintLayout
import splitties.views.dsl.core.matchParent
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* **A LESS CAPITALIZED ALIAS** to [ConstraintLayout.LayoutParams.MATCH_CONSTRAINT] that is only
* visible inside [ConstraintLayout]s.
*/
@Suppress("unused")
inline val ConstraintLayout.matchConstraints
get() = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT
inline fun ConstraintLayout.lParams(
width: Int = matchConstraints,
height: Int = matchConstraints,
initParams: ConstraintLayout.LayoutParams.() -> Unit = {}
): ConstraintLayout.LayoutParams {
contract { callsInPlace(initParams, InvocationKind.EXACTLY_ONCE) }
return createConstraintLayoutParams(width, height).apply(initParams).also { it.validate() }
}
@PublishedApi
internal fun ConstraintLayout.createConstraintLayoutParams(
width: Int,
height: Int
): ConstraintLayout.LayoutParams {
val matchParentWidth = width == matchParent
val matchParentHeight = height == matchParent
val realWidth = if (matchParentWidth) matchConstraints else width
val realHeight = if (matchParentHeight) matchConstraints else height
return ConstraintLayout.LayoutParams(realWidth, realHeight).apply {
if (matchParentWidth) centerHorizontally()
if (matchParentHeight) centerVertically()
}
}
| apache-2.0 | 4a9b6c8e2a118cbf7630f07853296484 | 34.954545 | 109 | 0.771176 | 4.750751 | false | false | false | false |
mglukhikh/intellij-community | platform/projectModel-api/src/com/intellij/openapi/project/ProjectUtilCore.kt | 1 | 2446 | // 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.
@file:JvmName("ProjectUtilCore")
package com.intellij.openapi.project
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileProvider
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PlatformUtils
fun displayUrlRelativeToProject(file: VirtualFile, url: String, project: Project, includeFilePath: Boolean, moduleOnTheLeft: Boolean): String {
var result = url
if (includeFilePath) {
val projectHomeUrl = project.baseDir?.presentableUrl
result = when {
projectHomeUrl != null && result.startsWith(projectHomeUrl) -> "...${result.substring(projectHomeUrl.length)}"
else -> FileUtil.getLocationRelativeToUserHome(file.presentableUrl)
}
}
if (file.fileSystem is LocalFileProvider) {
@Suppress("DEPRECATION") val localFile = (file.fileSystem as LocalFileProvider).getLocalVirtualFileFor(file)
if (localFile != null) {
val libraryEntry = LibraryUtil.findLibraryEntry(file, project)
when {
libraryEntry is JdkOrderEntry -> return "$result [${libraryEntry.jdkName}]"
libraryEntry != null -> return "$result [${libraryEntry.presentableName}]"
}
}
}
if (PlatformUtils.isCidr() || PlatformUtils.isRider()) // see PredefinedSearchScopeProviderImpl.getPredefinedScopes for the other place to fix.
return result
val module = ModuleUtilCore.findModuleForFile(file, project)
return when {
module == null -> result
moduleOnTheLeft -> "[${module.name}] $result"
else -> "$result [${module.name}]"
}
}
interface ProjectFileStoreOptionManager {
val isStoredExternally: Boolean
}
val Project.isExternalStorageEnabled: Boolean
get() {
val key = "com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManager"
val manager = picoContainer.getComponentInstance(key) as? ProjectFileStoreOptionManager ?: return false
return manager.isStoredExternally || Registry.`is`("store.imported.project.elements.separately", ApplicationManager.getApplication().isUnitTestMode)
} | apache-2.0 | 292d47bc13bdd9b05e413db4b6dbabb5 | 41.929825 | 152 | 0.763287 | 4.65019 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt | 2 | 14854 | // 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.debugger.evaluate.compilation
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.kotlin.backend.common.output.OutputFile
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.KotlinCodegenFacade
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationStatus
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_FUNCTION_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CompiledCodeFragmentData.MethodSignature
import org.jetbrains.kotlin.idea.debugger.evaluate.getResolutionFacadeForCodeFragment
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo
import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo
import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor
import org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.MemberScopeImpl
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.utils.Printer
class CodeFragmentCodegenException(val reason: Exception) : Exception()
class CodeFragmentCompiler(private val executionContext: ExecutionContext, private val status: EvaluationStatus) {
companion object {
fun useIRFragmentCompiler(): Boolean =
Registry.get("debugger.kotlin.evaluator.use.jvm.ir.backend").asBoolean()
}
data class CompilationResult(
val classes: List<ClassToLoad>,
val parameterInfo: CodeFragmentParameterInfo,
val localFunctionSuffixes: Map<CodeFragmentParameter.Dumb, String>,
val mainMethodSignature: MethodSignature
)
fun compile(
codeFragment: KtCodeFragment, filesToCompile: List<KtFile>,
bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor
): CompilationResult {
val result = ReadAction.nonBlocking<Result<CompilationResult>> {
try {
Result.success(doCompile(codeFragment, filesToCompile, bindingContext, moduleDescriptor))
} catch (ex: ProcessCanceledException) {
throw ex
} catch (ex: Exception) {
Result.failure(ex)
}
}.executeSynchronously()
return result.getOrThrow()
}
private fun initBackend(codeFragment: KtCodeFragment): FragmentCompilerCodegen {
return if (useIRFragmentCompiler()) {
IRFragmentCompilerCodegen()
} else {
OldFragmentCompilerCodegen(codeFragment)
}
}
private fun doCompile(
codeFragment: KtCodeFragment, filesToCompile: List<KtFile>,
bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor
): CompilationResult {
require(codeFragment is KtBlockCodeFragment || codeFragment is KtExpressionCodeFragment) {
"Unsupported code fragment type: $codeFragment"
}
val project = codeFragment.project
val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment)
@OptIn(FrontendInternals::class)
val resolveSession = resolutionFacade.getFrontendService(ResolveSession::class.java)
val moduleDescriptorWrapper = EvaluatorModuleDescriptor(codeFragment, moduleDescriptor, filesToCompile, resolveSession)
val defaultReturnType = moduleDescriptor.builtIns.unitType
val returnType = getReturnType(codeFragment, bindingContext, defaultReturnType)
val fragmentCompilerBackend = initBackend(codeFragment)
val compilerConfiguration = CompilerConfiguration().apply {
languageVersionSettings = codeFragment.languageVersionSettings
fragmentCompilerBackend.configureCompiler(this)
}
val parameterInfo = fragmentCompilerBackend.computeFragmentParameters(executionContext, codeFragment, bindingContext, status)
val (classDescriptor, methodDescriptor) = createDescriptorsForCodeFragment(
codeFragment, Name.identifier(GENERATED_CLASS_NAME), Name.identifier(GENERATED_FUNCTION_NAME),
parameterInfo, returnType, moduleDescriptorWrapper.packageFragmentForEvaluator
)
fragmentCompilerBackend.initCodegen(classDescriptor, methodDescriptor, parameterInfo)
val generationState = GenerationState.Builder(
project, ClassBuilderFactories.BINARIES, moduleDescriptorWrapper,
bindingContext, filesToCompile, compilerConfiguration
).apply {
fragmentCompilerBackend.configureGenerationState(
this,
bindingContext,
compilerConfiguration,
classDescriptor,
methodDescriptor,
parameterInfo
)
generateDeclaredClassFilter(GeneratedClassFilterForCodeFragment(codeFragment))
}.build()
try {
KotlinCodegenFacade.compileCorrectFiles(generationState)
return fragmentCompilerBackend.extractResult(methodDescriptor, parameterInfo, generationState).also {
generationState.destroy()
}
} catch (e: ProcessCanceledException) {
throw e
} catch (e: Exception) {
throw CodeFragmentCodegenException(e)
} finally {
fragmentCompilerBackend.cleanupCodegen()
}
}
private class GeneratedClassFilterForCodeFragment(private val codeFragment: KtCodeFragment) : GenerationState.GenerateClassFilter() {
override fun shouldGeneratePackagePart(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") file: KtFile) = file == codeFragment
override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject) = true
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) = processingClassOrObject.containingFile == codeFragment
override fun shouldGenerateCodeFragment(script: KtCodeFragment) = script == this.codeFragment
override fun shouldGenerateScript(script: KtScript) = false
}
private fun getReturnType(
codeFragment: KtCodeFragment,
bindingContext: BindingContext,
defaultReturnType: SimpleType
): KotlinType {
return when (codeFragment) {
is KtExpressionCodeFragment -> {
val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, codeFragment.getContentElement()]
typeInfo?.type ?: defaultReturnType
}
is KtBlockCodeFragment -> {
val blockExpression = codeFragment.getContentElement()
val lastStatement = blockExpression.statements.lastOrNull() ?: return defaultReturnType
val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, lastStatement]
typeInfo?.type ?: defaultReturnType
}
else -> defaultReturnType
}
}
private fun createDescriptorsForCodeFragment(
declaration: KtCodeFragment,
className: Name,
methodName: Name,
parameterInfo: CodeFragmentParameterInfo,
returnType: KotlinType,
packageFragmentDescriptor: PackageFragmentDescriptor
): Pair<ClassDescriptor, FunctionDescriptor> {
val classDescriptor = ClassDescriptorImpl(
packageFragmentDescriptor, className, Modality.FINAL, ClassKind.OBJECT,
emptyList(),
KotlinSourceElement(declaration),
false,
LockBasedStorageManager.NO_LOCKS
)
val methodDescriptor = SimpleFunctionDescriptorImpl.create(
classDescriptor, Annotations.EMPTY, methodName,
CallableMemberDescriptor.Kind.SYNTHESIZED, classDescriptor.source
)
val parameters = parameterInfo.parameters.mapIndexed { index, parameter ->
ValueParameterDescriptorImpl(
methodDescriptor, null, index, Annotations.EMPTY, Name.identifier("p$index"),
parameter.targetType,
declaresDefaultValue = false,
isCrossinline = false,
isNoinline = false,
varargElementType = null,
source = SourceElement.NO_SOURCE
)
}
methodDescriptor.initialize(
null, classDescriptor.thisAsReceiverParameter, emptyList(), emptyList(),
parameters, returnType, Modality.FINAL, DescriptorVisibilities.PUBLIC
)
val memberScope = EvaluatorMemberScopeForMethod(methodDescriptor)
val constructor = ClassConstructorDescriptorImpl.create(classDescriptor, Annotations.EMPTY, true, classDescriptor.source)
classDescriptor.initialize(memberScope, setOf(constructor), constructor)
return Pair(classDescriptor, methodDescriptor)
}
}
private class EvaluatorMemberScopeForMethod(private val methodDescriptor: SimpleFunctionDescriptor) : MemberScopeImpl() {
override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> {
return if (name == methodDescriptor.name) {
listOf(methodDescriptor)
} else {
emptyList()
}
}
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
return if (kindFilter.accepts(methodDescriptor) && nameFilter(methodDescriptor.name)) {
listOf(methodDescriptor)
} else {
emptyList()
}
}
override fun getFunctionNames() = setOf(methodDescriptor.name)
override fun printScopeStructure(p: Printer) {
p.println(this::class.java.simpleName)
}
}
private class EvaluatorModuleDescriptor(
val codeFragment: KtCodeFragment,
val moduleDescriptor: ModuleDescriptor,
filesToCompile: List<KtFile>,
resolveSession: ResolveSession
) : ModuleDescriptor by moduleDescriptor {
private val declarationProvider = object : PackageMemberDeclarationProvider {
private val rootPackageFiles =
filesToCompile.filter { it.packageFqName == FqName.ROOT } + codeFragment
override fun getPackageFiles() = rootPackageFiles
override fun containsFile(file: KtFile) = file in rootPackageFiles
override fun getDeclarationNames() = emptySet<Name>()
override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean) = emptyList<KtDeclaration>()
override fun getClassOrObjectDeclarations(name: Name) = emptyList<KtClassOrObjectInfo<*>>()
override fun getAllDeclaredSubPackages(nameFilter: (Name) -> Boolean) = emptyList<FqName>()
override fun getFunctionDeclarations(name: Name) = emptyList<KtNamedFunction>()
override fun getPropertyDeclarations(name: Name) = emptyList<KtProperty>()
override fun getTypeAliasDeclarations(name: Name) = emptyList<KtTypeAlias>()
override fun getDestructuringDeclarationsEntries(name: Name) = emptyList<KtDestructuringDeclarationEntry>()
override fun getScriptDeclarations(name: Name) = emptyList<KtScriptInfo>()
}
// NOTE: Without this override, psi2ir complains when introducing new symbol
// when creating an IrFileImpl in `createEmptyIrFile`.
override fun getOriginal(): DeclarationDescriptor {
return this
}
val packageFragmentForEvaluator = LazyPackageDescriptor(this, FqName.ROOT, resolveSession, declarationProvider)
val rootPackageDescriptorWrapper: PackageViewDescriptor =
object : DeclarationDescriptorImpl(Annotations.EMPTY, FqName.ROOT.shortNameOrSpecial()), PackageViewDescriptor {
private val rootPackageDescriptor = moduleDescriptor.safeGetPackage(FqName.ROOT)
override fun getContainingDeclaration() = rootPackageDescriptor.containingDeclaration
override val fqName get() = rootPackageDescriptor.fqName
override val module get() = this@EvaluatorModuleDescriptor
override val memberScope by lazy {
if (fragments.isEmpty()) {
MemberScope.Empty
} else {
val scopes = fragments.map { it.getMemberScope() } + SubpackagesScope(module, fqName)
ChainedMemberScope.create("package view scope for $fqName in ${module.name}", scopes)
}
}
override val fragments = listOf(packageFragmentForEvaluator)
override fun <R, D> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R {
return visitor.visitPackageViewDescriptor(this, data)
}
}
override fun getPackage(fqName: FqName): PackageViewDescriptor =
if (fqName != FqName.ROOT) {
moduleDescriptor.safeGetPackage(fqName)
} else {
rootPackageDescriptorWrapper
}
private fun ModuleDescriptor.safeGetPackage(fqName: FqName): PackageViewDescriptor =
try {
getPackage(fqName)
} catch (e: InvalidModuleException) {
throw ProcessCanceledException(e)
}
}
internal val OutputFile.internalClassName: String
get() = relativePath.removeSuffix(".class").replace('/', '.')
| apache-2.0 | e9d46b747dce508b92329fde27489762 | 44.987616 | 158 | 0.719133 | 5.873468 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonMachineLearning.kt | 1 | 5404 | package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.machinelearning.AbstractAmazonMachineLearning
import com.amazonaws.services.machinelearning.AmazonMachineLearning
import com.amazonaws.services.machinelearning.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAmazonMachineLearning(val context: IacContext) : AbstractAmazonMachineLearning(), AmazonMachineLearning {
override fun addTags(request: AddTagsRequest): AddTagsResult {
return with (context) {
request.registerWithAutoName()
makeProxy<AddTagsRequest, AddTagsResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
AddTagsRequest::getResourceId to AddTagsResult::getResourceId,
AddTagsRequest::getResourceType to AddTagsResult::getResourceType
)
)
}
}
override fun createBatchPrediction(request: CreateBatchPredictionRequest): CreateBatchPredictionResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateBatchPredictionRequest, CreateBatchPredictionResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateBatchPredictionRequest::getBatchPredictionId to CreateBatchPredictionResult::getBatchPredictionId
)
)
}
}
override fun createDataSourceFromRDS(request: CreateDataSourceFromRDSRequest): CreateDataSourceFromRDSResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDataSourceFromRDSRequest, CreateDataSourceFromRDSResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateDataSourceFromRDSRequest::getDataSourceId to CreateDataSourceFromRDSResult::getDataSourceId
)
)
}
}
override fun createDataSourceFromRedshift(request: CreateDataSourceFromRedshiftRequest): CreateDataSourceFromRedshiftResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDataSourceFromRedshiftRequest, CreateDataSourceFromRedshiftResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateDataSourceFromRedshiftRequest::getDataSourceId to CreateDataSourceFromRedshiftResult::getDataSourceId
)
)
}
}
override fun createDataSourceFromS3(request: CreateDataSourceFromS3Request): CreateDataSourceFromS3Result {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDataSourceFromS3Request, CreateDataSourceFromS3Result>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateDataSourceFromS3Request::getDataSourceId to CreateDataSourceFromS3Result::getDataSourceId
)
)
}
}
override fun createEvaluation(request: CreateEvaluationRequest): CreateEvaluationResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateEvaluationRequest, CreateEvaluationResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateEvaluationRequest::getEvaluationId to CreateEvaluationResult::getEvaluationId
)
)
}
}
override fun createMLModel(request: CreateMLModelRequest): CreateMLModelResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateMLModelRequest, CreateMLModelResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateMLModelRequest::getMLModelId to CreateMLModelResult::getMLModelId
)
)
}
}
override fun createRealtimeEndpoint(request: CreateRealtimeEndpointRequest): CreateRealtimeEndpointResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateRealtimeEndpointRequest, CreateRealtimeEndpointResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateRealtimeEndpointRequest::getMLModelId to CreateRealtimeEndpointResult::getMLModelId
)
)
}
}
}
class DeferredAmazonMachineLearning(context: IacContext) : BaseDeferredAmazonMachineLearning(context)
| mit | 1aa90ea8355fbebb75f3319c88827620 | 41.551181 | 129 | 0.628238 | 5.810753 | false | false | false | false |
tensorflow/examples | lite/examples/audio_classification/android/app/src/main/java/org/tensorflow/lite/examples/audio/AudioClassificationHelper.kt | 1 | 5189 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.audio
import android.content.Context
import android.media.AudioRecord
import android.os.SystemClock
import android.util.Log
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
import org.tensorflow.lite.examples.audio.fragments.AudioClassificationListener
import org.tensorflow.lite.support.audio.TensorAudio
import org.tensorflow.lite.task.audio.classifier.AudioClassifier
import org.tensorflow.lite.task.core.BaseOptions
class AudioClassificationHelper(
val context: Context,
val listener: AudioClassificationListener,
var currentModel: String = YAMNET_MODEL,
var classificationThreshold: Float = DISPLAY_THRESHOLD,
var overlap: Float = DEFAULT_OVERLAP_VALUE,
var numOfResults: Int = DEFAULT_NUM_OF_RESULTS,
var currentDelegate: Int = 0,
var numThreads: Int = 2
) {
private lateinit var classifier: AudioClassifier
private lateinit var tensorAudio: TensorAudio
private lateinit var recorder: AudioRecord
private lateinit var executor: ScheduledThreadPoolExecutor
private val classifyRunnable = Runnable {
classifyAudio()
}
init {
initClassifier()
}
fun initClassifier() {
// Set general detection options, e.g. number of used threads
val baseOptionsBuilder = BaseOptions.builder()
.setNumThreads(numThreads)
// Use the specified hardware for running the model. Default to CPU.
// Possible to also use a GPU delegate, but this requires that the classifier be created
// on the same thread that is using the classifier, which is outside of the scope of this
// sample's design.
when (currentDelegate) {
DELEGATE_CPU -> {
// Default
}
DELEGATE_NNAPI -> {
baseOptionsBuilder.useNnapi()
}
}
// Configures a set of parameters for the classifier and what results will be returned.
val options = AudioClassifier.AudioClassifierOptions.builder()
.setScoreThreshold(classificationThreshold)
.setMaxResults(numOfResults)
.setBaseOptions(baseOptionsBuilder.build())
.build()
try {
// Create the classifier and required supporting objects
classifier = AudioClassifier.createFromFileAndOptions(context, currentModel, options)
tensorAudio = classifier.createInputTensorAudio()
recorder = classifier.createAudioRecord()
startAudioClassification()
} catch (e: IllegalStateException) {
listener.onError(
"Audio Classifier failed to initialize. See error logs for details"
)
Log.e("AudioClassification", "TFLite failed to load with error: " + e.message)
}
}
fun startAudioClassification() {
if (recorder.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
return
}
recorder.startRecording()
executor = ScheduledThreadPoolExecutor(1)
// Each model will expect a specific audio recording length. This formula calculates that
// length using the input buffer size and tensor format sample rate.
// For example, YAMNET expects 0.975 second length recordings.
// This needs to be in milliseconds to avoid the required Long value dropping decimals.
val lengthInMilliSeconds = ((classifier.requiredInputBufferSize * 1.0f) /
classifier.requiredTensorAudioFormat.sampleRate) * 1000
val interval = (lengthInMilliSeconds * (1 - overlap)).toLong()
executor.scheduleAtFixedRate(
classifyRunnable,
0,
interval,
TimeUnit.MILLISECONDS)
}
private fun classifyAudio() {
tensorAudio.load(recorder)
var inferenceTime = SystemClock.uptimeMillis()
val output = classifier.classify(tensorAudio)
inferenceTime = SystemClock.uptimeMillis() - inferenceTime
listener.onResult(output[0].categories, inferenceTime)
}
fun stopAudioClassification() {
recorder.stop()
executor.shutdownNow()
}
companion object {
const val DELEGATE_CPU = 0
const val DELEGATE_NNAPI = 1
const val DISPLAY_THRESHOLD = 0.3f
const val DEFAULT_NUM_OF_RESULTS = 2
const val DEFAULT_OVERLAP_VALUE = 0.5f
const val YAMNET_MODEL = "yamnet.tflite"
const val SPEECH_COMMAND_MODEL = "speech.tflite"
}
}
| apache-2.0 | bd30f524dbe9cfec3fc75f1c0618473b | 36.330935 | 97 | 0.682212 | 4.831471 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/application/util.kt | 1 | 1679 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.util.concurrency.AppExecutorUtil
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Runnable
import org.jetbrains.annotations.ApiStatus
import kotlin.coroutines.CoroutineContext
@JvmOverloads
inline fun runInAllowSaveMode(isSaveAllowed: Boolean = true, task: () -> Unit) {
val app = ApplicationManagerEx.getApplicationEx()
if (isSaveAllowed == app.isSaveAllowed) {
task()
return
}
app.isSaveAllowed = isSaveAllowed
try {
task()
}
finally {
app.isSaveAllowed = !isSaveAllowed
}
}
/**
* Execute coroutine on pooled thread. Uncaught error will be logged.
*
* @see com.intellij.openapi.application.Application.executeOnPooledThread
*/
@Suppress("unused") // unused receiver
val Dispatchers.ApplicationThreadPool: CoroutineDispatcher
@ApiStatus.Experimental
get() = ApplicationThreadPoolDispatcher
// no need to implement isDispatchNeeded - Kotlin correctly uses the same thread if coroutines executes sequentially,
// and if launch/async is used, it is correct and expected that coroutine will be dispatched to another pooled thread.
private object ApplicationThreadPoolDispatcher : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
AppExecutorUtil.getAppExecutorService().execute(block)
}
override fun toString() = AppExecutorUtil.getAppExecutorService().toString()
} | apache-2.0 | 4481b85da970ebe2abf109c08f2714c4 | 34.744681 | 140 | 0.789756 | 4.716292 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/network/Requests.kt | 2 | 921 | package eu.kanade.tachiyomi.data.network
import okhttp3.*
import java.util.concurrent.TimeUnit.MINUTES
private val DEFAULT_CACHE_CONTROL = CacheControl.Builder().maxAge(10, MINUTES).build()
private val DEFAULT_HEADERS = Headers.Builder().build()
private val DEFAULT_BODY: RequestBody = FormBody.Builder().build()
fun GET(url: String,
headers: Headers = DEFAULT_HEADERS,
cache: CacheControl = DEFAULT_CACHE_CONTROL): Request {
return Request.Builder()
.url(url)
.headers(headers)
.cacheControl(cache)
.build()
}
fun POST(url: String,
headers: Headers = DEFAULT_HEADERS,
body: RequestBody = DEFAULT_BODY,
cache: CacheControl = DEFAULT_CACHE_CONTROL): Request {
return Request.Builder()
.url(url)
.post(body)
.headers(headers)
.cacheControl(cache)
.build()
}
| gpl-3.0 | 66ca04880244f20fda1d259f04d0bc43 | 27.78125 | 86 | 0.630836 | 4.283721 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/operators.kt | 2 | 5529 | // 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.nj2k.tree
import com.intellij.psi.JavaTokenType
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.nj2k.types.JKType
interface JKOperator {
val token: JKOperatorToken
val returnType: JKType
}
interface JKOperatorToken {
val text: String
@Suppress("MemberVisibilityCanBePrivate", "SpellCheckingInspection")
companion object {
fun fromElementType(elementType: IElementType) = elementTypeToToken.getValue(elementType)
val RANGE = JKKtSingleValueOperatorToken(KtTokens.RANGE)
val DIV = JKKtSingleValueOperatorToken(KtTokens.DIV)
val MINUS = JKKtSingleValueOperatorToken(KtTokens.MINUS)
val ANDAND = JKKtSingleValueOperatorToken(KtTokens.ANDAND)
val OROR = JKKtSingleValueOperatorToken(KtTokens.OROR)
val PLUS = JKKtSingleValueOperatorToken(KtTokens.PLUS)
val MUL = JKKtSingleValueOperatorToken(KtTokens.MUL)
val GT = JKKtSingleValueOperatorToken(KtTokens.GT)
val GTEQ = JKKtSingleValueOperatorToken(KtTokens.GTEQ)
val LT = JKKtSingleValueOperatorToken(KtTokens.LT)
val LTEQ = JKKtSingleValueOperatorToken(KtTokens.LTEQ)
val PERC = JKKtSingleValueOperatorToken(KtTokens.PERC)
val EQ = JKKtSingleValueOperatorToken(KtTokens.EQ)
val EQEQ = JKKtSingleValueOperatorToken(KtTokens.EQEQ)
val EXCLEQ = JKKtSingleValueOperatorToken(KtTokens.EXCLEQ)
val PLUSEQ = JKKtSingleValueOperatorToken(KtTokens.PLUSEQ)
val MINUSEQ = JKKtSingleValueOperatorToken(KtTokens.MINUSEQ)
val DIVEQ = JKKtSingleValueOperatorToken(KtTokens.DIVEQ)
val MULTEQ = JKKtSingleValueOperatorToken(KtTokens.MULTEQ)
val PERCEQ = JKKtSingleValueOperatorToken(KtTokens.PERCEQ)
val PLUSPLUS = JKKtSingleValueOperatorToken(KtTokens.PLUSPLUS)
val MINUSMINUS = JKKtSingleValueOperatorToken(KtTokens.MINUSMINUS)
val EXCL = JKKtSingleValueOperatorToken(KtTokens.EXCL)
val EQEQEQ = JKKtSingleValueOperatorToken(KtTokens.EQEQEQ)
val EXCLEQEQEQ = JKKtSingleValueOperatorToken(KtTokens.EXCLEQEQEQ)
val ELVIS = JKKtSingleValueOperatorToken(KtTokens.ELVIS)
val AND = JKKtWordOperatorToken("and")
val OR = JKKtWordOperatorToken("or")
val XOR = JKKtWordOperatorToken("xor")
val USHR = JKKtWordOperatorToken("ushr")
val SHR = JKKtWordOperatorToken("shr")
val SHL = JKKtWordOperatorToken("shl")
val ANDEQ = JKJavaOperatorToken(JavaTokenType.ANDEQ)
val OREQ = JKJavaOperatorToken(JavaTokenType.OREQ)
val XOREQ = JKJavaOperatorToken(JavaTokenType.XOREQ)
val LTLTEQ = JKJavaOperatorToken(JavaTokenType.LTLTEQ)
val GTGTEQ = JKJavaOperatorToken(JavaTokenType.GTGTEQ)
val GTGTGTEQ = JKJavaOperatorToken(JavaTokenType.GTGTGTEQ)
private val elementTypeToToken: Map<IElementType, JKOperatorToken> = mapOf(
JavaTokenType.DIV to DIV,
JavaTokenType.MINUS to MINUS,
JavaTokenType.ANDAND to ANDAND,
JavaTokenType.OROR to OROR,
JavaTokenType.PLUS to PLUS,
JavaTokenType.ASTERISK to MUL,
JavaTokenType.GT to GT,
JavaTokenType.GE to GTEQ,
JavaTokenType.LT to LT,
JavaTokenType.LE to LTEQ,
JavaTokenType.PERC to PERC,
JavaTokenType.EQ to EQ,
JavaTokenType.EQEQ to EQEQ,
JavaTokenType.NE to EXCLEQ,
JavaTokenType.PLUSEQ to PLUSEQ,
JavaTokenType.MINUSEQ to MINUSEQ,
JavaTokenType.DIVEQ to DIVEQ,
JavaTokenType.ASTERISKEQ to MULTEQ,
JavaTokenType.PLUSPLUS to PLUSPLUS,
JavaTokenType.MINUSMINUS to MINUSMINUS,
JavaTokenType.EXCL to EXCL,
KtTokens.EQEQEQ to EQEQEQ,
KtTokens.EXCLEQEQEQ to EXCLEQEQEQ,
JavaTokenType.AND to AND,
JavaTokenType.OR to OR,
JavaTokenType.XOR to XOR,
JavaTokenType.GTGTGT to USHR,
JavaTokenType.GTGT to SHR,
JavaTokenType.LTLT to SHL,
JavaTokenType.ANDEQ to ANDEQ,
JavaTokenType.OREQ to OREQ,
JavaTokenType.XOREQ to XOREQ,
JavaTokenType.PERCEQ to PERCEQ,
JavaTokenType.LTLTEQ to LTLTEQ,
JavaTokenType.GTGTEQ to GTGTEQ,
JavaTokenType.GTGTGTEQ to GTGTGTEQ
)
}
}
class JKKtWordOperatorToken(override val text: String) : JKKtOperatorToken
class JKKtOperatorImpl(override val token: JKOperatorToken, override val returnType: JKType) : JKOperator
interface JKKtOperatorToken : JKOperatorToken
class JKJavaOperatorToken(val psiToken: IElementType) : JKOperatorToken {
override val text: String
get() = error("Java token should not be printed, it should be replaces with corresponding Kotlin one")
}
class JKKtSingleValueOperatorToken(val psiToken: KtSingleValueToken) : JKKtOperatorToken {
override val text: String = psiToken.value
}
object JKKtSpreadOperatorToken : JKKtOperatorToken {
override val text: String = "*"
}
class JKKtSpreadOperator(override val returnType: JKType) : JKOperator {
override val token: JKOperatorToken = JKKtSpreadOperatorToken
}
| apache-2.0 | 8111e09f78879b40954a6264bc973027 | 39.955556 | 158 | 0.710074 | 4.774611 | false | false | false | false |
siosio/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/common/ContextSimilarityUtil.kt | 1 | 3901 | // 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.completion.ml.common
import com.intellij.internal.ml.WordsSplitter
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiNamedElement
import kotlin.math.max
object ContextSimilarityUtil {
private val WORDS_SPLITTER = WordsSplitter.Builder.identifiers().build()
private val STEMMING_WORDS_SPLITTER = WordsSplitter.Builder.identifiers().withStemming().build()
val LINE_SIMILARITY_SCORER_KEY: Key<ContextSimilarityScoringFunction> = Key.create("LINE_SIMILARITY_SCORER")
val PARENT_SIMILARITY_SCORER_KEY: Key<ContextSimilarityScoringFunction> = Key.create("PARENT_SIMILARITY_SCORER")
fun createLineSimilarityScoringFunction(line: String): ContextSimilarityScoringFunction =
ContextSimilarityScoringFunction(StringUtil.getWordsIn(line))
fun createParentSimilarityScoringFunction(element: PsiElement?): ContextSimilarityScoringFunction {
var curElement = element
val parents = mutableListOf<String>()
while (curElement != null && curElement !is PsiFile) {
if (curElement is PsiNamedElement) {
val name = curElement.name
if (name != null) parents.add(name)
}
curElement = curElement.parent
}
return ContextSimilarityScoringFunction(parents)
}
class ContextSimilarityScoringFunction(words: List<String>) {
private val tokens: List<List<String>> = words.map { WORDS_SPLITTER.split(it) }
private val stemmedTokens: List<List<String>> = words.map { STEMMING_WORDS_SPLITTER.split(it) }
fun scorePrefixSimilarity(value: String): Similarity = calculatePrefixSimilarity(tokens, value)
fun scoreStemmedSimilarity(value: String): Similarity = calculateStemmedSimilarity(stemmedTokens, value)
}
class Similarity {
private var sumSimilarity: Double = 0.0
private var count: Int = 0
private var maxSimilarity: Double = 0.0
private var fullSimilarity: Double = 0.0
fun addSimilarityValue(value: Double) {
sumSimilarity += value
maxSimilarity = max(maxSimilarity, value)
count++
}
fun addFullSimilarityValue(value: Double) {
fullSimilarity = max(fullSimilarity, value)
}
fun meanSimilarity(): Double = if (count == 0) 0.0 else sumSimilarity / count
fun maxSimilarity(): Double = maxSimilarity
fun fullSimilarity(): Double = fullSimilarity
}
fun calculatePrefixSimilarity(tokens: List<List<String>>, lookupString: String): Similarity {
val result = Similarity()
val lookupWords = WORDS_SPLITTER.split(lookupString)
if (lookupWords.isEmpty()) return result
for (tokenWords in tokens) {
var tokenSimilarity = 0.0
var tokenFullSimilarity = 0.0
for (word in lookupWords) {
tokenSimilarity += word.length.downTo(1).find { prefixLength ->
tokenWords.any {
it.startsWith(word.substring(0, prefixLength), true)
}
} ?: 0
if (tokenWords.any { it.equals(word, true) }) tokenFullSimilarity++
}
result.addSimilarityValue(tokenSimilarity / lookupString.length)
result.addFullSimilarityValue(tokenFullSimilarity / lookupWords.size)
}
return result
}
fun calculateStemmedSimilarity(tokens: List<List<String>>, lookupString: String): Similarity {
val result = Similarity()
val lookupWords = STEMMING_WORDS_SPLITTER.split(lookupString)
if (lookupWords.isEmpty()) return result
for (tokenWords in tokens) {
var matchedWords = 0.0
for (word in lookupWords) {
if (tokenWords.any { it.equals(word, true) }) matchedWords++
}
result.addSimilarityValue(matchedWords / lookupWords.size)
}
return result
}
} | apache-2.0 | d96e61bd0be6b8cd3781829258556b3c | 39.226804 | 140 | 0.725199 | 4.226436 | false | false | false | false |
siosio/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/EditorCodingAssistanceLesson.kt | 1 | 4195 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson.general.assistance
import com.intellij.ide.IdeBundle
import com.intellij.ui.HyperlinkLabel
import org.apache.commons.lang.StringEscapeUtils
import org.jetbrains.annotations.Nls
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.util.PerformActionUtil
import java.awt.Rectangle
import javax.swing.JEditorPane
abstract class EditorCodingAssistanceLesson(private val sample: LessonSample) :
KLesson("CodeAssistance.EditorCodingAssistance", LessonsBundle.message("editor.coding.assistance.lesson.name")) {
protected abstract val errorIntentionText: String
protected abstract val warningIntentionText: String
protected abstract val errorFixedText: String
protected abstract val warningFixedText: String
protected abstract val variableNameToHighlight: String
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
actionTask("GotoNextError") {
restoreIfModifiedOrMoved()
LessonsBundle.message("editor.coding.assistance.goto.next.error", action(it))
}
task("ShowIntentionActions") {
text(getFixErrorTaskText())
stateCheck { editor.document.charsSequence.contains(errorFixedText) }
restoreIfModifiedOrMoved()
test {
Thread.sleep(500)
invokeIntention(errorIntentionText)
}
}
task("GotoNextError") {
text(LessonsBundle.message("editor.coding.assistance.goto.next.warning", action(it)))
trigger(it)
restoreIfModifiedOrMoved()
test {
Thread.sleep(500)
actions(it)
}
}
// instantly close error description popup after GotoNextError action
prepareRuntimeTask {
PerformActionUtil.performAction("EditorPopupMenu", editor, project)
}
task("ShowErrorDescription") {
text(LessonsBundle.message("editor.coding.assistance.show.warning.description", action(it)))
// escapeHtml required in case of hieroglyph localization
val inspectionInfoLabelText = StringEscapeUtils.escapeHtml(IdeBundle.message("inspection.message.inspection.info"))
triggerByUiComponentAndHighlight<JEditorPane>(false, false) { ui ->
ui.text?.contains(inspectionInfoLabelText) == true
}
restoreIfModifiedOrMoved()
test {
Thread.sleep(500)
invokeActionViaShortcut("CONTROL F1")
invokeActionViaShortcut("CONTROL F1")
}
}
task {
text(LessonsBundle.message("editor.coding.assistance.fix.warning") + " " + getFixWarningText())
triggerByPartOfComponent { ui: HyperlinkLabel ->
if (ui.text == warningIntentionText) {
Rectangle(ui.x - 20, ui.y - 10, ui.width + 125, ui.height + 10)
}
else null
}
stateCheck { editor.document.charsSequence.contains(warningFixedText) }
restoreByUi()
test {
Thread.sleep(500)
invokeActionViaShortcut("ALT SHIFT ENTER")
}
}
caret(variableNameToHighlight)
task("HighlightUsagesInFile") {
text(LessonsBundle.message("editor.coding.assistance.highlight.usages", action(it)))
trigger(it) { checkSymbolAtCaretIsLetter() }
restoreIfModifiedOrMoved()
test { actions(it) }
}
}
protected open fun LearningDslBase.getFixErrorTaskText(): @Nls String {
return LessonsBundle.message("editor.coding.assistance.fix.error", action("ShowIntentionActions"),
strong(errorIntentionText))
}
protected abstract fun getFixWarningText(): @Nls String
private fun TaskTestContext.invokeIntention(intentionText: String) {
actions("ShowIntentionActions")
ideFrame {
jList(intentionText).clickItem(intentionText)
}
}
private fun TaskRuntimeContext.checkSymbolAtCaretIsLetter(): Boolean {
val caretOffset = editor.caretModel.offset
val sequence = editor.document.charsSequence
return caretOffset != sequence.length && sequence[caretOffset].isLetter()
}
} | apache-2.0 | 9bb1fd90cb2a0455cb13f4474543150c | 33.966667 | 140 | 0.720143 | 4.941107 | false | true | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/clean/CoroutineStateElimination.kt | 6 | 3273 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.inline.clean
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.coroutine.finallyPath
import org.jetbrains.kotlin.js.coroutine.targetBlock
import org.jetbrains.kotlin.js.coroutine.targetExceptionBlock
class CoroutineStateElimination(private val body: JsBlock) {
fun apply(): Boolean {
var changed = false
body.accept(object : RecursiveJsVisitor() {
override fun visitBlock(x: JsBlock) {
visitStatements(x.statements)
super.visitBlock(x)
}
override fun visitCase(x: JsCase) {
visitStatements(x.statements)
super.visitCase(x)
}
private fun visitStatements(statements: MutableList<JsStatement>) {
class IndexHolder {
var value: Int? = null
}
val indexesToRemove = mutableSetOf<Int>()
val lastTargetBlockIndex = IndexHolder()
val lastTargetExceptionBlockIndex = IndexHolder()
val lastFinallyPathIndex = IndexHolder()
for ((index, statement) in statements.withIndex()) {
val indexesToUpdate = mutableListOf<IndexHolder>()
if (statement is JsExpressionStatement) {
if (statement.targetBlock) {
indexesToUpdate += lastTargetBlockIndex
}
if (statement.targetExceptionBlock) {
indexesToUpdate += lastTargetExceptionBlockIndex
}
if (statement.finallyPath) {
indexesToUpdate += lastFinallyPathIndex
}
}
if (indexesToUpdate.isNotEmpty()) {
for (indexToUpdate in indexesToUpdate) {
indexToUpdate.value?.let { indexesToRemove += it }
indexToUpdate.value = index
}
}
else {
lastTargetBlockIndex.value = null
lastTargetExceptionBlockIndex.value = null
lastFinallyPathIndex.value = null
}
}
for (index in indexesToRemove.sorted().reversed()) {
statements.removeAt(index)
}
if (indexesToRemove.isNotEmpty()) {
changed = true
}
}
})
return changed
}
} | apache-2.0 | 8abf7c22c63470f5991f0bc948ac45e1 | 36.632184 | 79 | 0.546593 | 5.556876 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/MovableContent.kt | 3 | 10205 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime
/**
* Convert a lambda into one that moves the remembered state and nodes created in a previous call to
* the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun movableContentOf(content: @Composable () -> Unit): @Composable () -> Unit {
val movableContent = MovableContent<Unit>({ content() })
return {
currentComposer.insertMovableContent(movableContent, Unit)
}
}
/**
* Convert a lambda into one that moves the remembered state and nodes created in a previous call to
* the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <P> movableContentOf(content: @Composable (P) -> Unit): @Composable (P) -> Unit {
val movableContent = MovableContent(content)
return {
currentComposer.insertMovableContent(movableContent, it)
}
}
/**
* Convert a lambda into one that moves the remembered state and nodes created in a previous call to
* the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <P1, P2> movableContentOf(content: @Composable (P1, P2) -> Unit): @Composable (P1, P2) -> Unit {
val movableContent = MovableContent<Pair<P1, P2>> { content(it.first, it.second) }
return { p1, p2 ->
currentComposer.insertMovableContent(movableContent, p1 to p2)
}
}
/**
* Convert a lambda into one that moves the remembered state and nodes created in a previous call to
* the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <P1, P2, P3> movableContentOf(
content: @Composable (P1, P2, P3) -> Unit
): @Composable (P1, P2, P3) -> Unit {
val movableContent = MovableContent<Pair<Pair<P1, P2>, P3>> {
content(it.first.first, it.first.second, it.second)
}
return { p1, p2, p3 ->
currentComposer.insertMovableContent(movableContent, (p1 to p2) to p3)
}
}
/**
* Convert a lambda into one that moves the remembered state and nodes created in a previous call to
* the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <P1, P2, P3, P4> movableContentOf(
content: @Composable (P1, P2, P3, P4) -> Unit
): @Composable (P1, P2, P3, P4) -> Unit {
val movableContent = MovableContent<Pair<Pair<P1, P2>, Pair<P3, P4>>> {
content(it.first.first, it.first.second, it.second.first, it.second.second)
}
return { p1, p2, p3, p4 ->
currentComposer.insertMovableContent(movableContent, (p1 to p2) to (p3 to p4))
}
}
/**
* Convert a lambda with a receiver into one that moves the remembered state and nodes created in a
* previous call to the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <R> movableContentWithReceiverOf(content: @Composable R.() -> Unit): @Composable R.() -> Unit {
val movableContent = MovableContent<R>({ it.content() })
return {
currentComposer.insertMovableContent(movableContent, this)
}
}
/**
* Convert a lambda with a receiver into one that moves the remembered state and nodes created in a
* previous call to the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <R, P> movableContentWithReceiverOf(
content: @Composable R.(P) -> Unit
): @Composable R.(P) -> Unit {
val movableContent = MovableContent<Pair<R, P>>({ it.first.content(it.second) })
return {
currentComposer.insertMovableContent(movableContent, this to it)
}
}
/**
* Convert a lambda with a receiver into one that moves the remembered state and nodes created in a
* previous call to the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <R, P1, P2> movableContentWithReceiverOf(
content: @Composable R.(P1, P2) -> Unit
): @Composable R.(P1, P2) -> Unit {
val movableContent = MovableContent<Pair<Pair<R, P1>, P2>> {
it.first.first.content(it.first.second, it.second)
}
return { p1, p2 ->
currentComposer.insertMovableContent(movableContent, (this to p1) to p2)
}
}
/**
* Convert a lambda with a receiver into one that moves the remembered state and nodes created in a
* previous call to the new location it is called.
*
* Tracking compositions can be used to produce a composable that moves its content between a row
* and a column based on a parameter, such as,
*
* @sample androidx.compose.runtime.samples.MovableContentColumnRowSample
*
* Or they can be used to ensure the composition state tracks with a model as moves in the layout,
* such as,
*
* @sample androidx.compose.runtime.samples.MovableContentMultiColumnSample
*
* @param content The composable lambda to convert into a state tracking lambda.
* @return A tracking composable lambda
*/
@OptIn(InternalComposeApi::class)
fun <R, P1, P2, P3> movableContentWithReceiverOf(
content: @Composable R.(P1, P2, P3) -> Unit
): @Composable R.(P1, P2, P3) -> Unit {
val movableContent = MovableContent<Pair<Pair<R, P1>, Pair<P2, P3>>> {
it.first.first.content(it.first.second, it.second.first, it.second.second)
}
return { p1, p2, p3 ->
currentComposer.insertMovableContent(movableContent, (this to p1) to (p2 to p3))
}
}
// An arbitrary key created randomly. This key is used for the group containing the movable content
internal const val movableContentKey = 0x078cc281 | apache-2.0 | 9d339bb1f4d76cda8c5ab0cb49582f97 | 37.806084 | 100 | 0.733268 | 3.905473 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/artifacts/KotlinArtifacts.kt | 7 | 1734 | // 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.artifacts
import com.intellij.openapi.application.PathManager
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import java.io.File
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts as KotlinArtifactsNew
@Suppress("unused")
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts' instead")
class KotlinArtifacts private constructor(val kotlincDirectory: File) {
companion object {
val KOTLIN_DIST_LOCATION_PREFIX: File = File(PathManager.getSystemPath(), "kotlin-dist-for-ide")
@get:JvmStatic
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts' instead")
val instance: KotlinArtifacts by lazy {
KotlinArtifacts(KotlinPluginLayout.kotlinc)
}
}
val kotlinStdlib: File get() = KotlinArtifactsNew.kotlinStdlib
val kotlinStdlibSources: File get() = KotlinArtifactsNew.kotlinStdlibSources
val kotlinStdlibJdk7: File get() = KotlinArtifactsNew.kotlinStdlibJdk7
val kotlinStdlibJdk7Sources: File get() = KotlinArtifactsNew.kotlinStdlibJdk7Sources
val kotlinStdlibJdk8: File get() = KotlinArtifactsNew.kotlinStdlibJdk8
val kotlinStdlibJdk8Sources: File get() = KotlinArtifactsNew.kotlinStdlibJdk8Sources
val kotlinReflect: File get() = KotlinArtifactsNew.kotlinReflect
val kotlinStdlibJs: File get() = KotlinArtifactsNew.kotlinStdlibJs
val kotlinMainKts: File get() = KotlinArtifactsNew.kotlinMainKts
val kotlinScriptRuntime: File get() = KotlinArtifactsNew.kotlinScriptRuntime
}
| apache-2.0 | 1671912363aac1422d47b31775f7791b | 53.1875 | 120 | 0.783737 | 4.575198 | false | false | false | false |
GunoH/intellij-community | platform/testFramework/testSrc/com/intellij/testFramework/TestClassesSortingTest.kt | 2 | 2382 | // 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.testFramework
import com.intellij.TestCaseLoader
import com.intellij.nastradamus.NastradamusTestCaseSorter
import org.junit.Assert.assertEquals
import org.junit.Test
class TestClassesSortingTest {
private class Debug1Test
private class Debug2Test
private class Debug3Test
private class DebugAnother1Test
private class DebugAnother2Test
private class DebugAnother3Test
private class OneMore1Test
private class OneMore2Test
private val rankedClasses = mapOf<Class<*>, Int>(
DebugAnother2Test::class.java to 1,
Debug1Test::class.java to 2,
OneMore1Test::class.java to 3,
DebugAnother1Test::class.java to 4,
OneMore2Test::class.java to 5,
DebugAnother3Test::class.java to 6,
Debug2Test::class.java to 7,
Debug3Test::class.java to 8,
)
@Test
fun checkGeneralSortingLogic() {
val shuffledSourceClasses = rankedClasses
.map { it.key }
.shuffled()
.toMutableList()
val sortedClasses: List<Class<*>> = NastradamusTestCaseSorter { _ -> rankedClasses }
.sorted(unsortedClasses = shuffledSourceClasses, ranker = TestCaseLoader::getRank)
val failureMessage =
"""
Expected order of classes:
${rankedClasses.entries.joinToString(separator = System.lineSeparator()) { it.toString() }}
Sorted order of classes:
${sortedClasses.joinToString(separator = System.lineSeparator()) { it.toString() }}
""".trimMargin().trimIndent()
assertEquals("Size of collection provided ranked classes and sorted classes should be the same",
rankedClasses.size, sortedClasses.size)
sortedClasses.forEachIndexed { index, clazz ->
val expectedSortedRank = rankedClasses.get(clazz)?.minus(1)
assertEquals(
"Sorted $clazz should have position with index $expectedSortedRank in collection, but it's actual position is $index"
.plus(System.lineSeparator())
.plus(failureMessage).trimMargin().trimIndent(),
expectedSortedRank, index
)
}
}
@Test
fun checkSortingWithBucketing() {
// TODO
}
// TODO: test on provided ranked classes list size < found classes list size
// TODO: test on found classes list size < provided ranked classes size
} | apache-2.0 | ba8c33eef501da63ec346acac9b38f2d | 31.643836 | 125 | 0.715365 | 4.268817 | false | true | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/strategy/GrammarCheckingStrategy.kt | 1 | 9308 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("DEPRECATION")
package com.intellij.grazie.grammar.strategy
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.grazie.GraziePlugin
import com.intellij.grazie.grammar.Typo
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.ElementBehavior.*
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.TextDomain.*
import com.intellij.grazie.grammar.strategy.impl.ReplaceCharRule
import com.intellij.grazie.grammar.strategy.impl.RuleGroup
import com.intellij.grazie.utils.LinkedSet
import com.intellij.grazie.utils.orTrue
import com.intellij.lang.Language
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
/**
* Strategy extracting elements for grammar checking used by Grazie plugin
*
* You need to implement [isMyContextRoot] and add com.intellij.grazie.grammar.strategy extension in your .xml config
*/
@Deprecated("Use TextExtractor and ProblemFilter instead")
interface GrammarCheckingStrategy {
/**
* Possible PsiElement behavior during grammar check
*
* [TEXT] - element contains text
* [STEALTH] - element's text is ignored
* [ABSORB] - element's text is ignored, as well as the typos that contain this element
*
* [ABSORB] and [STEALTH] behavior also prevents visiting children of these elements.
*
* Examples:
* Text: This is a <bold>error</bold> sample.
* PsiElements: ["This is a ", "<bold>", "error", "</bold>", " sample"]
*
* If this text pass as is to the grammar checker, then there are no errors.
* The reason are tags framing word 'error', these tags are not part of the sentence and used only for formatting.
* So you can add [STEALTH] behavior to these tags PsiElements, which made text passed to grammar checker 'This is a error sample.'
* and checker will find an error - 'Use "an" instead of 'a' if the following word starts with a vowel sound'
*
*
* Text: There is raining <br> Days passing by
* PsiElements: ["There is raining ", "<br>", "Days passing by"]
*
* There is <br> tag. Like in previous example this tag not used in the result text.
* But if we make tag <br> [STEALTH] there will be an error - 'There *are* raining days'
* By the way, 'Days passing by' is a new sentence that doesn't applies to previous one.
* In that case you can use [ABSORB] behavior, then this kind of errors will be filtered.
*/
enum class ElementBehavior {
TEXT,
STEALTH,
ABSORB
}
/**
* Possible domains for grammar check.
*
* [NON_TEXT] - domain for elements accepted as context root, but not containing reasonable text for check (IDs, file paths, etc.)
* [LITERALS] - domain for string literals of programming language
* [COMMENTS] - domain for general comments of programming languages (excluding doc comments)
* [DOCS] - domain for in-code documentation (JavaDocs, Python DocStrings, etc.)
* [PLAIN_TEXT] - domain for plain text (Markdown, HTML or LaTeX) and UI strings
*/
enum class TextDomain {
NON_TEXT,
LITERALS,
COMMENTS,
DOCS,
PLAIN_TEXT
}
/**
* Visible name of strategy for settings window.
*
* @return name of this strategy
*/
@NlsSafe
fun getName(): String {
val extension = StrategyUtils.getStrategyExtensionPoint(this)
return Language.findLanguageByID(extension.language)?.displayName ?: extension.language
}
/**
* Return unique ID for grammar strategy. Used to distinguish strategies for user settings.
*
* NOTE: you need to override this method if you intend to use several strategies for one language.
*
* @return unique ID
*/
fun getID(): String {
val extension = StrategyUtils.getStrategyExtensionPoint(this)
return "${extension.pluginDescriptor.pluginId}:${extension.language}"
}
/**
* Determine text block root, for example a paragraph of text.
*
* @param element visited element
* @return true if context root
*/
fun isMyContextRoot(element: PsiElement): Boolean
/**
* Determine tokens which should be treated as whitespaces for the current [Language].
* Default implementation considers that these tokens are the same as [ParserDefinition.getWhitespaceTokens].
*
* @return [TokenSet] of whitespace tokens
*/
fun getWhiteSpaceTokens(): TokenSet {
val extension = StrategyUtils.getStrategyExtensionPoint(this)
val language = Language.findLanguageByID(extension.language) ?: return TokenSet.WHITE_SPACE
return LanguageParserDefinitions.INSTANCE.forLanguage(language).whitespaceTokens
}
/**
* Determine PsiElement roots that should be considered as a continuous text including [root].
* [root] element MUST be present in chain.
* Passing any sub-element in chain must return the same list of all the elements in the chain.
* Chain roots must be in the same [TextDomain] and have the same [GrammarCheckingStrategy]
* or be one of [getWhiteSpaceTokens].
* For example, this method can be used to combine single-line comments into
* a single block of text for grammar check.
*
* @param root root element previously selected in [isMyContextRoot]
* @return list of root elements that should be considered as a continuous text with [getWhiteSpaceTokens] elements
*/
fun getRootsChain(root: PsiElement): List<PsiElement> = listOf(root)
/**
* Determine if this strategy enabled by default.
*
* @return true if enabled else false
*/
fun isEnabledByDefault(): Boolean = !GraziePlugin.isBundled || ApplicationManager.getApplication()?.isUnitTestMode.orTrue()
/**
* Determine root PsiElement domain @see [TextDomain].
*
* @param root root element previously selected in [isMyContextRoot]
* @return [TextDomain] for [root] element
*/
fun getContextRootTextDomain(root: PsiElement) = StrategyUtils.getTextDomainOrDefault(this, root, default = PLAIN_TEXT)
/**
* Determine PsiElement behavior @see [ElementBehavior].
*
* @param root root element previously selected in [isMyContextRoot]
* @param child current checking element for which behavior is specified
* @return [ElementBehavior] for [child] element
*/
fun getElementBehavior(root: PsiElement, child: PsiElement) = TEXT
/**
* Specify ranges, which will be removed from text before checking (like STEALTH behavior).
* You can use [StrategyUtils.indentIndexes] to hide the indentation of each line of text.
*
* @param root root element previously selected in [isMyContextRoot]
* @param text extracted text from root element without [ABSORB] and [STEALTH] ones
* in which you need to specify the ranges to remove from the grammar checking
* @return set of ranges in the [text] to be ignored
*/
fun getStealthyRanges(root: PsiElement, text: CharSequence): LinkedSet<IntRange> = StrategyUtils.emptyLinkedSet()
/**
* Determine if typo will be shown to user. The final check before add typo to [ProblemsHolder].
*
* @param root root element previously selected in [isMyContextRoot]
* @param typoRange range of the typo inside [root] element
* @param ruleRange range of elements needed for rule to find typo
* @return true if typo should be accepted
*/
fun isTypoAccepted(root: PsiElement, typoRange: IntRange, ruleRange: IntRange) = true
/**
* Determine if typo will be shown to user. The final check before add typo to [ProblemsHolder].
*
* @param parent common parent of [roots]
* @param roots roots from [getRootsChain] method
* @param typoRange range of the typo inside [parent] element
* @param ruleRange range of elements needed for rule to find typo
* @return true if typo should be accepted
*/
fun isTypoAccepted(parent: PsiElement, roots: List<PsiElement>, typoRange: IntRange, ruleRange: IntRange) = true
/**
* Get ignored typo categories for [child] element @see [Typo.Category].
*
* @param root root element previously selected in [isMyContextRoot]
* @param child current checking element for which ignored categories are specified
* @return set of the ignored categories for [child]
*/
fun getIgnoredTypoCategories(root: PsiElement, child: PsiElement): Set<Typo.Category>? = null
/**
* Get ignored rules for [child] element @see [RuleGroup].
*
* @param root root element previously selected in [isMyContextRoot]
* @param child current checking element for which ignored rules are specified
* @return RuleGroup with ignored rules for [child]
*/
fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement): RuleGroup? = null
/**
* Get rules for char replacement in PSI elements text @see [ReplaceCharRule].
* (In most cases you don't want to change this)
*
* @param root root element previously selected in [isMyContextRoot]
* @return list of char replacement rules for whole root context
*/
fun getReplaceCharRules(root: PsiElement): List<ReplaceCharRule> = emptyList()
}
| apache-2.0 | c7b9caa984582072bdbc8b8cb3c71056 | 41.117647 | 140 | 0.729265 | 4.293358 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesAndInterfacesDependencyMemberInfoModel.kt | 4 | 1853 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.classMembers.ANDCombinedMemberInfoModel
import com.intellij.refactoring.classMembers.DelegatingMemberInfoModel
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.classMembers.MemberInfoModel
import com.intellij.refactoring.util.classMembers.UsesDependencyMemberInfoModel
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
open class KotlinUsesAndInterfacesDependencyMemberInfoModel<T : KtNamedDeclaration, M : MemberInfoBase<T>>(
klass: KtClassOrObject,
superClass: PsiNamedElement?,
recursive: Boolean,
interfaceContainmentVerifier: (T) -> Boolean = { false }
) : DelegatingMemberInfoModel<T, M>(
ANDCombinedMemberInfoModel(
object : KotlinUsesDependencyMemberInfoModel<T, M>(klass, superClass, recursive) {
override fun checkForProblems(memberInfo: M): Int {
val problem = super.checkForProblems(memberInfo)
if (problem == MemberInfoModel.OK) return MemberInfoModel.OK
val member = memberInfo.member
if (interfaceContainmentVerifier(member)) return MemberInfoModel.OK
return problem
}
},
KotlinInterfaceDependencyMemberInfoModel<T, M>(klass)
)
) {
@Suppress("UNCHECKED_CAST")
fun setSuperClass(superClass: PsiNamedElement) {
((delegatingTarget as ANDCombinedMemberInfoModel<T, M>).model1 as UsesDependencyMemberInfoModel<T, PsiNamedElement, M>).setSuperClass(
superClass
)
}
}
| apache-2.0 | e59e508fce7b367373552070be9d7533 | 44.195122 | 158 | 0.745818 | 5.062842 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/ispn/InfinispanJsonExternalizer.kt | 2 | 946 | package com.github.kerubistan.kerub.utils.ispn
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.github.kerubistan.kerub.model.Entity
import com.github.kerubistan.kerub.utils.createObjectMapper
import org.infinispan.commons.marshall.AdvancedExternalizer
import java.io.ObjectInput
import java.io.ObjectOutput
class InfinispanJsonExternalizer : AdvancedExternalizer<Entity<*>> {
companion object {
private val mapper = createObjectMapper(prettyPrint = false)
}
override fun getTypeClasses(): Set<Class<out Entity<*>>> =
(Entity::class.annotations
.single { it is JsonSubTypes } as JsonSubTypes)
.value.map { it.value.java as Class<out Entity<*>> }
.toSet()
override fun writeObject(output: ObjectOutput, entity: Entity<*>?) {
mapper.writeValue(output, entity)
}
override fun readObject(input: ObjectInput): Entity<*> = mapper.readValue(input, Entity::class.java)
override fun getId(): Int = 6666
} | apache-2.0 | a29544b511afa7f7335e7b4be6affaa2 | 31.655172 | 101 | 0.766385 | 3.941667 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/property/varStringAssign.kt | 4 | 164 | <warning descr="SSR">var a = "Hello world"</warning>
<warning descr="SSR">var b = ("Hello world")</warning>
<warning descr="SSR">var c = (("Hello world"))</warning> | apache-2.0 | 4c51d47ed66e5049320c437df0345847 | 54 | 56 | 0.658537 | 3.346939 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KotlinReferenceContributor.kt | 2 | 2974 | // 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.references
import com.intellij.psi.PsiReference
import org.jetbrains.kotlin.idea.kdoc.KDocReferenceDescriptorsImpl
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.psiUtil.parents
class KotlinReferenceContributor : KotlinReferenceProviderContributor {
override fun registerReferenceProviders(registrar: KotlinPsiReferenceRegistrar) {
with(registrar) {
registerProvider(factory = ::KtSimpleNameReferenceDescriptorsImpl)
registerMultiProvider<KtNameReferenceExpression> { nameReferenceExpression ->
if (nameReferenceExpression.getReferencedNameElementType() != KtTokens.IDENTIFIER) {
return@registerMultiProvider PsiReference.EMPTY_ARRAY
}
if (nameReferenceExpression.parents.any { it is KtImportDirective || it is KtPackageDirective || it is KtUserType }) {
return@registerMultiProvider PsiReference.EMPTY_ARRAY
}
when (nameReferenceExpression.readWriteAccess(useResolveForReadWrite = false)) {
ReferenceAccess.READ ->
arrayOf(SyntheticPropertyAccessorReferenceDescriptorImpl(nameReferenceExpression, getter = true))
ReferenceAccess.WRITE ->
arrayOf(SyntheticPropertyAccessorReferenceDescriptorImpl(nameReferenceExpression, getter = false))
ReferenceAccess.READ_WRITE ->
arrayOf(
SyntheticPropertyAccessorReferenceDescriptorImpl(nameReferenceExpression, getter = true),
SyntheticPropertyAccessorReferenceDescriptorImpl(nameReferenceExpression, getter = false)
)
}
}
registerProvider(factory = ::KtConstructorDelegationReferenceDescriptorsImpl)
registerProvider(factory = ::KtInvokeFunctionReferenceDescriptorsImpl)
registerProvider(factory = ::KtArrayAccessReferenceDescriptorsImpl)
registerProvider(factory = ::KtCollectionLiteralReferenceDescriptorsImpl)
registerProvider(factory = ::KtForLoopInReferenceDescriptorsImpl)
registerProvider(factory = ::KtPropertyDelegationMethodsReferenceDescriptorsImpl)
registerProvider(factory = ::KtDestructuringDeclarationReferenceDescriptorsImpl)
registerProvider(factory = ::KDocReferenceDescriptorsImpl)
registerProvider(KotlinDefaultAnnotationMethodImplicitReferenceProvider)
}
}
}
| apache-2.0 | d7cb2de017b517cac8f40e91ac0710fa | 49.40678 | 158 | 0.710827 | 6.49345 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.