repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/loadtest/frontend/ForwardedStorageFrontendSimulatorRunner.kt | 1 | 1504 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.loadtest.frontend
import org.wfanet.measurement.common.commandLineMain
import org.wfanet.measurement.storage.forwarded.ForwardedStorageFromFlags
import picocli.CommandLine
/** Implementation of [FrontendSimulatorRunner] using Fake Storage Service. */
@CommandLine.Command(
name = "ForwardedStorageFrontendSimulatorRunnerDaemon",
description = ["Daemon for ForwardedStorageFrontendSimulatorRunner."],
mixinStandardHelpOptions = true,
showDefaultValues = true
)
class ForwardedStorageFrontendSimulatorRunner : FrontendSimulatorRunner() {
@CommandLine.Mixin private lateinit var forwardedStorageFlags: ForwardedStorageFromFlags.Flags
override fun run() {
run(ForwardedStorageFromFlags(forwardedStorageFlags, flags.tlsFlags).storageClient)
}
}
fun main(args: Array<String>) = commandLineMain(ForwardedStorageFrontendSimulatorRunner(), args)
| apache-2.0 | b47ac2b8ee2d229b41e2fa3bc1bfae8b | 40.777778 | 96 | 0.797207 | 4.714734 | false | false | false | false |
SimonVT/cathode | cathode-provider/src/main/java/net/simonvt/cathode/provider/helper/ShowDatabaseHelper.kt | 1 | 12217 | /*
* Copyright (C) 2017 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.provider.helper
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import net.simonvt.cathode.api.entity.Show
import net.simonvt.cathode.common.database.DatabaseUtils
import net.simonvt.cathode.common.database.getBoolean
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.util.TextUtils
import net.simonvt.cathode.provider.DatabaseContract
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.DatabaseContract.ShowColumns
import net.simonvt.cathode.provider.ProviderSchematic
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.provider.update
import net.simonvt.cathode.settings.FirstAiredOffsetPreference
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ShowDatabaseHelper @Inject constructor(private val context: Context) {
fun getId(traktId: Long): Long {
synchronized(LOCK_ID) {
val c = context.contentResolver.query(
Shows.SHOWS,
arrayOf(ShowColumns.ID),
ShowColumns.TRAKT_ID + "=?",
arrayOf(traktId.toString())
)
val id = if (c.moveToFirst()) c.getLong(ShowColumns.ID) else -1L
c.close()
return id
}
}
fun getIdFromTmdb(tmdbId: Int): Long {
synchronized(LOCK_ID) {
val c = context.contentResolver.query(
Shows.SHOWS,
arrayOf(ShowColumns.ID),
ShowColumns.TMDB_ID + "=?",
arrayOf(tmdbId.toString())
)
val id = if (c.moveToFirst()) c.getLong(ShowColumns.ID) else -1L
c.close()
return id
}
}
fun getTraktId(showId: Long): Long {
val c = context.contentResolver.query(
Shows.withId(showId),
arrayOf(ShowColumns.TRAKT_ID)
)
val traktId = if (c.moveToFirst()) c.getLong(ShowColumns.TRAKT_ID) else -1L
c.close()
return traktId
}
fun getTmdbId(showId: Long): Int {
val c = context.contentResolver.query(
Shows.withId(showId),
arrayOf(ShowColumns.TMDB_ID)
)
val tmdbId = if (c.moveToFirst()) c.getInt(ShowColumns.TMDB_ID) else -1
c.close()
return tmdbId
}
class IdResult(var showId: Long, var didCreate: Boolean)
fun getIdOrCreate(traktId: Long): IdResult {
synchronized(LOCK_ID) {
var id = getId(traktId)
if (id == -1L) {
id = create(traktId)
return IdResult(id, true)
} else {
return IdResult(id, false)
}
}
}
private fun create(traktId: Long): Long {
val values = ContentValues()
values.put(ShowColumns.TRAKT_ID, traktId)
values.put(ShowColumns.NEEDS_SYNC, true)
return Shows.getShowId(context.contentResolver.insert(Shows.SHOWS, values)!!)
}
fun fullUpdate(show: Show): Long {
val result = getIdOrCreate(show.ids.trakt!!)
val id = result.showId
val values = getValues(show)
values.put(ShowColumns.NEEDS_SYNC, false)
values.put(ShowColumns.LAST_SYNC, System.currentTimeMillis())
context.contentResolver.update(Shows.withId(id), values)
if (show.genres != null) {
insertShowGenres(id, show.genres!!)
}
return id
}
/**
* Creates the show if it does not exist.
*/
fun partialUpdate(show: Show): Long {
val result = getIdOrCreate(show.ids.trakt!!)
val id = result.showId
val values = getPartialValues(show)
context.contentResolver.update(Shows.withId(id), values)
if (show.genres != null) {
insertShowGenres(id, show.genres!!)
}
return id
}
fun getNextEpisodeId(showId: Long): Long {
var lastWatchedSeason = -1
var lastWatchedEpisode = -1
val lastWatchedCursor = context.contentResolver.query(
Episodes.fromShow(showId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.SEASON, EpisodeColumns.EPISODE),
EpisodeColumns.WATCHED + "=1",
null,
EpisodeColumns.SEASON + " DESC, " + EpisodeColumns.EPISODE + " DESC LIMIT 1"
)
if (lastWatchedCursor!!.moveToFirst()) {
lastWatchedSeason = lastWatchedCursor.getInt(EpisodeColumns.SEASON)
lastWatchedEpisode = lastWatchedCursor.getInt(EpisodeColumns.EPISODE)
}
lastWatchedCursor.close()
val nextEpisode = context.contentResolver.query(
Episodes.fromShow(showId),
arrayOf(EpisodeColumns.ID),
EpisodeColumns.SEASON + ">0 AND (" +
EpisodeColumns.SEASON + ">? OR (" +
EpisodeColumns.SEASON + "=? AND " +
EpisodeColumns.EPISODE + ">?)) AND " +
EpisodeColumns.FIRST_AIRED + " NOT NULL",
arrayOf(
lastWatchedSeason.toString(),
lastWatchedSeason.toString(),
lastWatchedEpisode.toString()
),
EpisodeColumns.SEASON + " ASC, " + EpisodeColumns.EPISODE + " ASC LIMIT 1"
)
var nextEpisodeId = -1L
if (nextEpisode!!.moveToFirst()) {
nextEpisodeId = nextEpisode.getLong(EpisodeColumns.ID)
}
nextEpisode.close()
return nextEpisodeId
}
fun needsSync(showId: Long): Boolean {
var show: Cursor? = null
try {
show = context.contentResolver.query(
Shows.withId(showId),
arrayOf(ShowColumns.NEEDS_SYNC)
)
return if (show.moveToFirst()) show.getBoolean(ShowColumns.NEEDS_SYNC) else false
} finally {
show?.close()
}
}
fun lastSync(showId: Long): Long {
var show: Cursor? = null
try {
show = context.contentResolver.query(
Shows.withId(showId),
arrayOf(ShowColumns.LAST_SYNC)
)
return if (show.moveToFirst()) show.getLong(ShowColumns.LAST_SYNC) else 0L
} finally {
show?.close()
}
}
fun markPending(showId: Long) {
val values = ContentValues()
values.put(ShowColumns.NEEDS_SYNC, true)
context.contentResolver.update(Shows.withId(showId), values, null, null)
}
fun isUpdated(traktId: Long, lastUpdated: Long): Boolean {
var show: Cursor? = null
try {
show = context.contentResolver.query(
Shows.SHOWS,
arrayOf(ShowColumns.LAST_UPDATED),
ShowColumns.TRAKT_ID + "=?",
arrayOf(traktId.toString())
)
if (show.moveToFirst()) {
val showLastUpdated = show.getLong(ShowColumns.LAST_UPDATED)
return lastUpdated > showLastUpdated
}
return false
} finally {
show?.close()
}
}
private fun insertShowGenres(showId: Long, genres: List<String>) {
context.contentResolver.delete(ProviderSchematic.ShowGenres.fromShow(showId), null, null)
for (genre in genres) {
val values = ContentValues()
values.put(DatabaseContract.ShowGenreColumns.SHOW_ID, showId)
values.put(DatabaseContract.ShowGenreColumns.GENRE, TextUtils.upperCaseFirstLetter(genre))
context.contentResolver.insert(ProviderSchematic.ShowGenres.fromShow(showId), values)
}
}
fun addToHistory(showId: Long, watchedAt: Long) {
val values = ContentValues()
values.put(EpisodeColumns.WATCHED, true)
val firstAiredOffset = FirstAiredOffsetPreference.getInstance().offsetMillis
val millis = System.currentTimeMillis() - firstAiredOffset
context.contentResolver.update(
Episodes.fromShow(showId), values, EpisodeColumns.FIRST_AIRED + "<?",
arrayOf(millis.toString())
)
if (watchedAt == WATCHED_RELEASE) {
values.clear()
val episodes = context.contentResolver.query(
Episodes.fromShow(showId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.FIRST_AIRED),
EpisodeColumns.WATCHED + " AND " + EpisodeColumns.FIRST_AIRED + ">" + EpisodeColumns.LAST_WATCHED_AT
)
while (episodes.moveToNext()) {
val episodeId = episodes.getLong(EpisodeColumns.ID)
val firstAired = episodes.getLong(EpisodeColumns.FIRST_AIRED)
values.put(EpisodeColumns.LAST_WATCHED_AT, firstAired)
context.contentResolver.update(Episodes.withId(episodeId), values, null, null)
}
episodes.close()
} else {
values.clear()
values.put(EpisodeColumns.LAST_WATCHED_AT, watchedAt)
context.contentResolver.update(
Episodes.fromShow(showId),
values,
EpisodeColumns.WATCHED + " AND " + EpisodeColumns.LAST_WATCHED_AT + "<?",
arrayOf(watchedAt.toString())
)
}
}
fun removeFromHistory(showId: Long) {
val values = ContentValues()
values.put(EpisodeColumns.WATCHED, false)
values.put(EpisodeColumns.LAST_WATCHED_AT, 0)
context.contentResolver.update(Episodes.fromShow(showId), null, null, null)
}
@JvmOverloads
fun setIsInWatchlist(showId: Long, inWatchlist: Boolean, listedAt: Long = 0) {
val values = ContentValues()
values.put(ShowColumns.IN_WATCHLIST, inWatchlist)
values.put(ShowColumns.LISTED_AT, listedAt)
context.contentResolver.update(Shows.withId(showId), values, null, null)
}
fun setIsInCollection(traktId: Long, inCollection: Boolean) {
val showId = getId(traktId)
val values = ContentValues()
values.put(EpisodeColumns.IN_COLLECTION, inCollection)
val firstAiredOffset = FirstAiredOffsetPreference.getInstance().offsetMillis
val millis = System.currentTimeMillis() - firstAiredOffset
context.contentResolver.update(
Episodes.fromShow(showId), values, EpisodeColumns.FIRST_AIRED + "<?",
arrayOf(millis.toString())
)
}
private fun getPartialValues(show: Show): ContentValues {
val values = ContentValues()
values.put(ShowColumns.TITLE, show.title)
values.put(ShowColumns.TITLE_NO_ARTICLE, DatabaseUtils.removeLeadingArticle(show.title))
values.put(ShowColumns.TRAKT_ID, show.ids.trakt)
values.put(ShowColumns.SLUG, show.ids.slug)
values.put(ShowColumns.IMDB_ID, show.ids.imdb)
values.put(ShowColumns.TVDB_ID, show.ids.tvdb)
values.put(ShowColumns.TMDB_ID, show.ids.tmdb)
values.put(ShowColumns.TVRAGE_ID, show.ids.tvrage)
return values
}
private fun getValues(show: Show): ContentValues {
val values = ContentValues()
values.put(ShowColumns.TITLE, show.title)
values.put(ShowColumns.TITLE_NO_ARTICLE, DatabaseUtils.removeLeadingArticle(show.title))
values.put(ShowColumns.YEAR, show.year)
values.put(ShowColumns.FIRST_AIRED, show.first_aired?.timeInMillis)
values.put(ShowColumns.COUNTRY, show.country)
values.put(ShowColumns.OVERVIEW, show.overview)
values.put(ShowColumns.RUNTIME, show.runtime)
values.put(ShowColumns.NETWORK, show.network)
values.put(ShowColumns.AIR_DAY, show.airs?.day)
values.put(ShowColumns.AIR_TIME, show.airs?.time)
values.put(ShowColumns.AIR_TIMEZONE, show.airs?.timezone)
values.put(ShowColumns.CERTIFICATION, show.certification)
values.put(ShowColumns.TRAILER, show.trailer)
values.put(ShowColumns.HOMEPAGE, show.homepage)
values.put(ShowColumns.STATUS, show.status?.toString())
values.put(ShowColumns.TRAKT_ID, show.ids.trakt)
values.put(ShowColumns.SLUG, show.ids.slug)
values.put(ShowColumns.IMDB_ID, show.ids.imdb)
values.put(ShowColumns.TVDB_ID, show.ids.tvdb)
values.put(ShowColumns.TMDB_ID, show.ids.tmdb)
values.put(ShowColumns.TVRAGE_ID, show.ids.tvrage)
values.put(ShowColumns.LAST_UPDATED, show.updated_at?.timeInMillis)
values.put(ShowColumns.RATING, show.rating)
values.put(ShowColumns.VOTES, show.votes)
return values
}
companion object {
const val WATCHED_RELEASE = -1L
private val LOCK_ID = Any()
}
}
| apache-2.0 | f96577c15feca73c5e4c8b6e3b1fcac1 | 30.815104 | 108 | 0.693951 | 4.158271 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/structure/latex/LatexPairedDelimiterPresentation.kt | 1 | 1016 | package nl.hannahsten.texifyidea.structure.latex
import com.intellij.navigation.ItemPresentation
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.psi.LatexCommands
class LatexPairedDelimiterPresentation(newCommand: LatexCommands) : ItemPresentation {
private val newCommandName: String
private val locationString: String
init {
// Get command name.
val required = newCommand.requiredParameters
newCommandName = if (required.size > 0) {
required.first()
}
else ""
locationString = if (required.size >= 3) {
when (newCommand.name) {
"\\DeclarePairedDelimiterXPP" -> (1..4).joinToString(" ") { required[it] }
else -> "${required[1]} ${required[2]}"
}
}
else ""
}
override fun getPresentableText() = newCommandName
override fun getLocationString() = locationString
override fun getIcon(b: Boolean) = TexifyIcons.DOT_COMMAND
} | mit | 05396cc29b0f40bbc18c3d6de975b8d4 | 28.911765 | 90 | 0.651575 | 4.908213 | false | false | false | false |
googlecast/CastVideos-android | app-kotlin/src/main/kotlin/com/google/sample/cast/refplayer/VideoBrowserActivity.kt | 1 | 7513 | /*
* Copyright 2022 Google LLC. 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 com.google.sample.cast.refplayer
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.SessionManagerListener
import com.google.android.gms.cast.framework.CastSession
import android.view.MenuItem
import com.google.android.gms.cast.framework.IntroductoryOverlay
import com.google.android.gms.cast.framework.CastStateListener
import android.os.Bundle
import com.google.android.gms.cast.framework.CastState
import android.view.View
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Menu
import com.google.android.gms.cast.framework.CastButtonFactory
import android.view.KeyEvent
import androidx.appcompat.widget.Toolbar
import com.google.sample.cast.refplayer.queue.ui.QueueListViewActivity
import com.google.sample.cast.refplayer.settings.CastPreference
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* The main activity that displays the list of videos.
*/
class VideoBrowserActivity : AppCompatActivity() {
private var mCastContext: CastContext? = null
private val mSessionManagerListener: SessionManagerListener<CastSession> = MySessionManagerListener()
private var mCastSession: CastSession? = null
private var mediaRouteMenuItem: MenuItem? = null
private var mQueueMenuItem: MenuItem? = null
private var mToolbar: Toolbar? = null
private var mIntroductoryOverlay: IntroductoryOverlay? = null
private var mCastStateListener: CastStateListener? = null
private val castExecutor: Executor = Executors.newSingleThreadExecutor();
private inner class MySessionManagerListener : SessionManagerListener<CastSession> {
override fun onSessionEnded(session: CastSession, error: Int) {
if (session === mCastSession) {
mCastSession = null
}
invalidateOptionsMenu()
}
override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) {
mCastSession = session
invalidateOptionsMenu()
}
override fun onSessionStarted(session: CastSession, sessionId: String) {
mCastSession = session
invalidateOptionsMenu()
}
override fun onSessionStarting(session: CastSession) {}
override fun onSessionStartFailed(session: CastSession, error: Int) {}
override fun onSessionEnding(session: CastSession) {}
override fun onSessionResuming(session: CastSession, sessionId: String) {}
override fun onSessionResumeFailed(session: CastSession, error: Int) {}
override fun onSessionSuspended(session: CastSession, reason: Int) {}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.video_browser)
setupActionBar()
mCastStateListener = CastStateListener { newState ->
if (newState != CastState.NO_DEVICES_AVAILABLE) {
showIntroductoryOverlay()
}
}
mCastContext = CastContext.getSharedInstance(this,castExecutor).result
}
private fun setupActionBar() {
mToolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(mToolbar)
}
private fun intentToJoin() {
val intent = intent
val intentToJoinUri = Uri.parse("https://castvideos.com/cast/join")
Log.i(TAG, "URI passed: $intentToJoinUri")
if (intent.data != null && intent.data == intentToJoinUri) {
mCastContext!!.sessionManager.startSession(intent)
Log.i(TAG, "Uri Joined: $intentToJoinUri")
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.browse, menu)
mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton(
applicationContext, menu,
R.id.media_route_menu_item
)
mQueueMenuItem = menu.findItem(R.id.action_show_queue)
showIntroductoryOverlay()
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(R.id.action_show_queue).isVisible =
mCastSession != null && mCastSession!!.isConnected
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val intent: Intent
if (item.itemId == R.id.action_settings) {
intent = Intent(this@VideoBrowserActivity, CastPreference::class.java)
startActivity(intent)
} else if (item.itemId == R.id.action_show_queue) {
intent = Intent(this@VideoBrowserActivity, QueueListViewActivity::class.java)
startActivity(intent)
}
return true
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
return (mCastContext!!.onDispatchVolumeKeyEventBeforeJellyBean(event)
|| super.dispatchKeyEvent(event))
}
override fun onResume() {
mCastContext!!.addCastStateListener(mCastStateListener!!)
mCastContext!!.sessionManager.addSessionManagerListener(
mSessionManagerListener, CastSession::class.java
)
intentToJoin()
if (mCastSession == null) {
mCastSession = CastContext.getSharedInstance(this,castExecutor).result.sessionManager
.currentCastSession
}
if (mQueueMenuItem != null) {
mQueueMenuItem!!.isVisible = mCastSession != null && mCastSession!!.isConnected
}
super.onResume()
}
override fun onPause() {
mCastContext!!.removeCastStateListener(mCastStateListener!!)
mCastContext!!.sessionManager.removeSessionManagerListener(
mSessionManagerListener, CastSession::class.java
)
super.onPause()
}
private fun showIntroductoryOverlay() {
if (mIntroductoryOverlay != null) {
mIntroductoryOverlay!!.remove()
}
if (mediaRouteMenuItem != null && mediaRouteMenuItem!!.isVisible) {
Handler(Looper.getMainLooper()).post {
mIntroductoryOverlay = IntroductoryOverlay.Builder(
this@VideoBrowserActivity, mediaRouteMenuItem!!
)
.setTitleText(getString(R.string.introducing_cast))
.setOverlayColor(R.color.primary)
.setSingleTime()
.setOnOverlayDismissedListener { mIntroductoryOverlay = null }
.build()
mIntroductoryOverlay!!.show()
}
}
}
companion object {
private const val TAG = "VideoBrowserActivity"
}
} | apache-2.0 | 6806f33599ddddf118be331049f31281 | 38.340314 | 105 | 0.684147 | 5.049059 | false | false | false | false |
PaulWoitaschek/Voice | settings/src/main/kotlin/voice/settings/views/Settings.kt | 1 | 6735 | package voice.settings.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.BugReport
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.GridView
import androidx.compose.material.icons.outlined.HelpOutline
import androidx.compose.material.icons.outlined.Language
import androidx.compose.material.icons.outlined.Lightbulb
import androidx.compose.material.icons.outlined.ViewList
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.squareup.anvil.annotations.ContributesTo
import voice.common.AppScope
import voice.common.compose.VoiceTheme
import voice.common.compose.rememberScoped
import voice.common.rootComponentAs
import voice.settings.R
import voice.settings.SettingsListener
import voice.settings.SettingsViewModel
import voice.settings.SettingsViewState
@Composable
@Preview
fun SettingsPreview() {
val viewState = SettingsViewState(
useDarkTheme = false,
showDarkThemePref = true,
resumeOnReplug = true,
seekTimeInSeconds = 42,
autoRewindInSeconds = 12,
dialog = null,
appVersion = "1.2.3",
useGrid = true,
)
VoiceTheme {
Settings(
viewState,
object : SettingsListener {
override fun close() {}
override fun toggleResumeOnReplug() {}
override fun toggleDarkTheme() {}
override fun seekAmountChanged(seconds: Int) {}
override fun onSeekAmountRowClicked() {}
override fun autoRewindAmountChanged(seconds: Int) {}
override fun onAutoRewindRowClicked() {}
override fun dismissDialog() {}
override fun openTranslations() {}
override fun getSupport() {}
override fun suggestIdea() {}
override fun openBugReport() {}
override fun toggleGrid() {}
},
)
}
}
@Composable
private fun Settings(viewState: SettingsViewState, listener: SettingsListener) {
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBar(
scrollBehavior = scrollBehavior,
title = {
Text(stringResource(R.string.action_settings))
},
navigationIcon = {
IconButton(
onClick = {
listener.close()
},
) {
Icon(
imageVector = Icons.Outlined.Close,
contentDescription = stringResource(R.string.close),
)
}
},
)
},
) { contentPadding ->
Box(Modifier.padding(contentPadding)) {
Column(Modifier.padding(vertical = 8.dp)) {
if (viewState.showDarkThemePref) {
DarkThemeRow(viewState.useDarkTheme, listener::toggleDarkTheme)
}
ListItem(
modifier = Modifier.clickable { listener.toggleGrid() },
leadingContent = {
val imageVector = if (viewState.useGrid) {
Icons.Outlined.GridView
} else {
Icons.Outlined.ViewList
}
Icon(imageVector, stringResource(R.string.pref_use_grid))
},
headlineText = { Text(stringResource(R.string.pref_use_grid)) },
trailingContent = {
Switch(
checked = viewState.useGrid,
onCheckedChange = {
listener.toggleGrid()
},
)
},
)
ResumeOnReplugRow(viewState.resumeOnReplug, listener::toggleResumeOnReplug)
SeekTimeRow(viewState.seekTimeInSeconds) {
listener.onSeekAmountRowClicked()
}
AutoRewindRow(viewState.autoRewindInSeconds) {
listener.onAutoRewindRowClicked()
}
ListItem(
modifier = Modifier.clickable { listener.suggestIdea() },
leadingContent = { Icon(Icons.Outlined.Lightbulb, stringResource(R.string.pref_suggest_idea)) },
headlineText = { Text(stringResource(R.string.pref_suggest_idea)) },
)
ListItem(
modifier = Modifier.clickable { listener.getSupport() },
leadingContent = { Icon(Icons.Outlined.HelpOutline, stringResource(R.string.pref_get_support)) },
headlineText = { Text(stringResource(R.string.pref_get_support)) },
)
ListItem(
modifier = Modifier.clickable { listener.openBugReport() },
leadingContent = { Icon(Icons.Outlined.BugReport, stringResource(R.string.pref_report_issue)) },
headlineText = { Text(stringResource(R.string.pref_report_issue)) },
)
ListItem(
modifier = Modifier.clickable { listener.openTranslations() },
leadingContent = { Icon(Icons.Outlined.Language, stringResource(R.string.pref_help_translating)) },
headlineText = { Text(stringResource(R.string.pref_help_translating)) },
)
AppVersion(appVersion = viewState.appVersion)
Dialog(viewState, listener)
}
}
}
}
@ContributesTo(AppScope::class)
interface SettingsComponent {
val settingsViewModel: SettingsViewModel
}
@Composable
fun Settings() {
val viewModel = rememberScoped { rootComponentAs<SettingsComponent>().settingsViewModel }
val viewState = viewModel.viewState()
Settings(viewState, viewModel)
}
@Composable
private fun Dialog(
viewState: SettingsViewState,
listener: SettingsListener,
) {
val dialog = viewState.dialog ?: return
when (dialog) {
SettingsViewState.Dialog.AutoRewindAmount -> {
AutoRewindAmountDialog(
currentSeconds = viewState.autoRewindInSeconds,
onSecondsConfirmed = listener::autoRewindAmountChanged,
onDismiss = listener::dismissDialog,
)
}
SettingsViewState.Dialog.SeekTime -> {
SeekAmountDialog(
currentSeconds = viewState.seekTimeInSeconds,
onSecondsConfirmed = listener::seekAmountChanged,
onDismiss = listener::dismissDialog,
)
}
}
}
| gpl-3.0 | 5bd692fe1f8ce88add6e70d0286a47c8 | 33.896373 | 109 | 0.685523 | 4.732959 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/ui/views/settings/SettingsSwitch.kt | 1 | 2840 | package com.duopoints.android.ui.views.settings
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.CompoundButton
import android.widget.FrameLayout
import com.duopoints.android.R
import com.duopoints.android.logistics.Pers
import com.duopoints.android.utils.logging.LogLevel
import com.duopoints.android.utils.logging.log
import kotlinx.android.synthetic.main.settings_view_checkbox.view.*
import kotlinx.android.synthetic.main.settings_view_text_container.view.*
class SettingsSwitch @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FrameLayout(context, attrs, defStyleAttr), CompoundButton.OnCheckedChangeListener {
private var settingKey: String? = null
init {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
var title: String? = null
var subtitle: String? = null
var hideSubtitle = false
var defaultChecked = false
attrs?.let {
val ta = context.obtainStyledAttributes(attrs, R.styleable.SettingsSwitch, 0, 0)
try {
settingKey = ta.getString(R.styleable.SettingsSwitch_switch_setting_key)
title = ta.getString(R.styleable.SettingsSwitch_switch_title)
subtitle = ta.getString(R.styleable.SettingsSwitch_switch_subtitle)
hideSubtitle = ta.getBoolean(R.styleable.SettingsSwitch_switch_hide_subtitle, false)
defaultChecked = ta.getBoolean(R.styleable.SettingsSwitch_switch_default, false)
} finally {
ta.recycle()
}
}
inflate(context, R.layout.settings_view_checkbox, this)
settingTitle.text = title
settingSubtitle.text = subtitle
if (hideSubtitle) {
settingSubtitle.visibility = View.GONE
}
if (!isInEditMode) {
if (settingKey != null) {
settingCheckbox.isChecked = Pers.get(settingKey!!, defaultChecked)
settingCheckbox.setOnCheckedChangeListener(this)
} else {
settingCheckbox.isChecked = defaultChecked
javaClass.log(LogLevel.WARN, "Setting Key not give! Warning")
}
} else {
settingCheckbox.isChecked = defaultChecked
}
}
fun manualChange(isChecked: Boolean) {
settingCheckbox.isChecked = isChecked
}
fun externalSetting(isChecked: Boolean, onClickListener: OnClickListener) {
manualChange(isChecked)
settingCheckbox.setOnClickListener(onClickListener)
this.setOnClickListener(onClickListener)
}
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
settingKey?.let { Pers.put(it, isChecked) }
}
}
| gpl-3.0 | fd028714aafa270f13530245cd2d2df7 | 34.949367 | 118 | 0.67007 | 4.871355 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher | web/src/main/kotlin/org/metplus/cruncher/web/controller/canned/ResumeCannedController.kt | 1 | 8195 | package org.metplus.cruncher.web.controller.canned
import org.metplus.cruncher.canned.rating.CompareResumeWithJobCanned
import org.metplus.cruncher.canned.resume.MatchWithJobCanned
import org.metplus.cruncher.rating.CompareResumeWithJobObserver
import org.metplus.cruncher.resume.DownloadResume
import org.metplus.cruncher.resume.DownloadResumeObserver
import org.metplus.cruncher.resume.MatchWithJobObserver
import org.metplus.cruncher.resume.ReCrunchAllResumes
import org.metplus.cruncher.resume.ReCrunchAllResumesObserver
import org.metplus.cruncher.resume.Resume
import org.metplus.cruncher.resume.ResumeFile
import org.metplus.cruncher.resume.UploadResume
import org.metplus.cruncher.resume.UploadResumeObserver
import org.metplus.cruncher.web.controller.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.util.FileCopyUtils
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.ByteArrayOutputStream
import javax.servlet.http.HttpServletResponse
@RestController
@RequestMapping(value = [
"/api/v99999/resume"
])
class ResumeCannedController(
@Autowired private val uploadResume: UploadResume,
@Autowired private val downloadResume: DownloadResume,
@Autowired private val matchWithJob: MatchWithJobCanned,
@Autowired private val reCrunchAllResumes: ReCrunchAllResumes,
@Autowired private val compareResumeWithJob: CompareResumeWithJobCanned
) {
@PostMapping("upload")
@ResponseBody
fun uploadResumeEndpoint(@RequestParam("userId") id: String,
@RequestParam("name") name: String,
@RequestParam("file") file: MultipartFile): CruncherResponse {
return uploadResume.process(id, name, file.inputStream, file.size, observer = object : UploadResumeObserver<CruncherResponse> {
override fun onException(exception: Exception, resume: Resume): CruncherResponse {
return CruncherResponse(
resultCode = ResultCodes.FATAL_ERROR,
message = "Exception happened while uploading the resume"
)
}
override fun onSuccess(resume: Resume): CruncherResponse {
return CruncherResponse(
resultCode = ResultCodes.SUCCESS,
message = "Resume upload successful"
)
}
override fun onEmptyFile(resume: Resume): CruncherResponse {
return CruncherResponse(
resultCode = ResultCodes.FATAL_ERROR,
message = "Resume is empty"
)
}
}) as CruncherResponse
}
@GetMapping("{userId}")
@ResponseBody
fun downloadResumeEndpoint(@PathVariable("userId") id: String, response: HttpServletResponse): CruncherResponse? {
return downloadResume.process(id, observer = object : DownloadResumeObserver<CruncherResponse?> {
override fun onError(userId: String, exception: Exception): CruncherResponse {
return CruncherResponse(
resultCode = ResultCodes.FATAL_ERROR,
message = "Exception happened while uploading the resume"
)
}
override fun onSuccess(resume: Resume, resumeFile: ResumeFile): CruncherResponse? {
val outputFile = ByteArrayOutputStream()
var data = resumeFile.fileStream.read()
while (data >= 0) {
outputFile.write(data.toChar().toInt())
data = resumeFile.fileStream.read()
}
outputFile.flush()
response.contentType = "application/octet-stream"
response.setHeader("Content-Disposition", "inline; filename=\"" + resumeFile.filename + "\"")
FileCopyUtils.copy(outputFile.toByteArray(), response.outputStream)
response.setContentLength(outputFile.size())
response.flushBuffer()
return null
}
override fun onResumeNotFound(userId: String): CruncherResponse {
return CruncherResponse(
resultCode = ResultCodes.FATAL_ERROR,
message = "Resume is empty"
)
}
})
}
@GetMapping("/match/{jobId}")
@ResponseBody
fun downloadResumeEndpoint(@PathVariable("jobId") id: String): ResponseEntity<CruncherResponse> {
return matchWithJob.process(jobId = id, observer = object : MatchWithJobObserver<ResponseEntity<CruncherResponse>> {
override fun noMatchFound(jobId: String, matchers: Map<String, List<Resume>>): ResponseEntity<CruncherResponse> {
return ResponseEntity(ResumeMatchedAnswer(
resultCode = ResultCodes.SUCCESS,
message = "Job with id '$jobId' was not matches",
resumes = matchers.toAllCrunchedResumesAnswer()
), HttpStatus.OK)
}
override fun jobNotFound(jobId: String): ResponseEntity<CruncherResponse> {
return ResponseEntity(CruncherResponse(
resultCode = ResultCodes.JOB_NOT_FOUND,
message = "Job with id '$jobId' was not found"
), HttpStatus.NOT_FOUND)
}
override fun success(matchedResumes: Map<String, List<Resume>>): ResponseEntity<CruncherResponse> {
return ResponseEntity(ResumeMatchedAnswer(
resultCode = ResultCodes.SUCCESS,
message = "Job matches ${matchedResumes.size} resumes",
resumes = matchedResumes.toAllCrunchedResumesAnswer()
), HttpStatus.OK)
}
})
}
@GetMapping("{resumeId}/compare/{jobId}")
@ResponseBody
fun compare(@PathVariable("resumeId") resumeId: String, @PathVariable("jobId") jobId: String): ResponseEntity<CruncherResponse> {
return compareResumeWithJob.process(resumeId, jobId, object : CompareResumeWithJobObserver<ResponseEntity<CruncherResponse>> {
override fun onJobNotFound(jobId: String): ResponseEntity<CruncherResponse> {
return ResponseEntity.ok(CruncherResponse(
resultCode = ResultCodes.JOB_NOT_FOUND,
message = "Job $jobId was not found"))
}
override fun onResumeNotFound(resumeId: String): ResponseEntity<CruncherResponse> {
return ResponseEntity(CruncherResponse(
resultCode = ResultCodes.RESUME_NOT_FOUND,
message = "Resume $resumeId was not found"), HttpStatus.NOT_FOUND)
}
override fun onSuccess(starsRating: Double): ResponseEntity<CruncherResponse> {
return ResponseEntity.ok(ComparisonMatchAnswer(
message = "Job and Resume match",
stars = mapOf("naiveBayes" to starsRating)
))
}
})
}
@GetMapping("/reindex")
@ResponseBody
fun reindex(): CruncherResponse {
return reCrunchAllResumes.process(object : ReCrunchAllResumesObserver<CruncherResponse> {
override fun onSuccess(numberScheduled: Int): CruncherResponse {
return CruncherResponse(
resultCode = ResultCodes.SUCCESS,
message = "Going to reindex $numberScheduled resumes"
)
}
})
}
} | gpl-3.0 | 783edafa16501dc5e918174c160832b6 | 45.834286 | 135 | 0.641001 | 5.698887 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-android | app/src/androidTest/java/tv/superawesome/demoapp/util/TestColors.kt | 1 | 811 | package tv.superawesome.demoapp.util
import android.graphics.Color
import kotlin.math.abs
object TestColors {
val bannerYellow = Color.valueOf(0.96862745f, 0.8862745f, 0.41960785f)
val ksfYellow = Color.valueOf(0.8784314f, 0.8784314f, 0.8784314f)
val vastYellow = Color.valueOf(0.9647059f, 0.90588236f, 0.46666667f)
val vpaidYellow = Color.valueOf(0.96862745f, 0.8862745f, 0.4627451f)
fun checkApproximatelyEqual(givenColor: Color?, targetColor: Color?): Boolean {
if (givenColor == null || targetColor == null) return false
val threshold = 0.10
return abs(givenColor.red() - targetColor.red()) <= threshold
&& abs(givenColor.red() - targetColor.red()) <= threshold
&& abs(givenColor.red() - targetColor.red()) <= threshold
}
}
| lgpl-3.0 | 5a450748f3b0b2d831b2fbea17ec4ca5 | 41.684211 | 83 | 0.680641 | 3.49569 | false | true | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/helpers/SwipeDragItemTouchHelperCallback.kt | 1 | 2841 | /*
* *************************************************************************
* SwipeDragItemTouchHelperCallback.java
* **************************************************************************
* Copyright © 2015-2017 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.helpers
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import org.videolan.vlc.interfaces.SwipeDragHelperAdapter
class SwipeDragItemTouchHelperCallback(private val mAdapter: SwipeDragHelperAdapter, private val longPressDragEnable: Boolean = false) : ItemTouchHelper.Callback() {
private var dragFrom = -1
private var dragTo = -1
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END
return makeMovementFlags(dragFlags, swipeFlags)
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
mAdapter.onItemMove(viewHolder.layoutPosition, target.layoutPosition)
val fromPosition = viewHolder.layoutPosition
val toPosition = target.layoutPosition
if (dragFrom == -1) {
dragFrom = fromPosition
}
dragTo = toPosition
return true
}
override fun isLongPressDragEnabled(): Boolean {
return longPressDragEnable
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
if (dragFrom != -1 && dragTo != -1 && dragFrom != dragTo) {
mAdapter.onItemMoved(dragFrom, dragTo)
}
dragTo = -1
dragFrom = dragTo
super.clearView(recyclerView, viewHolder)
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
mAdapter.onItemDismiss(viewHolder.layoutPosition)
}
}
| gpl-2.0 | 1ac379df560f1d5ef37fb70d21650a0b | 38.430556 | 165 | 0.665375 | 5.17122 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/services/ZipService.kt | 1 | 12920 | /*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.asynchronous.services
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.*
import android.net.Uri
import android.os.AsyncTask
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.O
import android.os.IBinder
import android.widget.RemoteViews
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.preference.PreferenceManager
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil
import com.amaze.filemanager.filesystem.FileUtil
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.filesystem.files.FileUtils
import com.amaze.filemanager.filesystem.files.GenericCopyUtil
import com.amaze.filemanager.ui.activities.MainActivity
import com.amaze.filemanager.ui.notifications.NotificationConstants
import com.amaze.filemanager.utils.DatapointParcelable
import com.amaze.filemanager.utils.ObtainableServiceBinder
import com.amaze.filemanager.utils.ProgressHandler
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.*
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipException
import java.util.zip.ZipOutputStream
@Suppress("TooManyFunctions") // Hack.
class ZipService : AbstractProgressiveService() {
private val log: Logger = LoggerFactory.getLogger(ZipService::class.java)
private val mBinder: IBinder = ObtainableServiceBinder(this)
private lateinit var asyncTask: CompressAsyncTask
private lateinit var mNotifyManager: NotificationManagerCompat
private lateinit var mBuilder: NotificationCompat.Builder
private lateinit var progressListener: ProgressListener
private val progressHandler = ProgressHandler()
// list of data packages, to initiate chart in process viewer fragment
private val dataPackages = ArrayList<DatapointParcelable>()
private var accentColor = 0
private var sharedPreferences: SharedPreferences? = null
private var customSmallContentViews: RemoteViews? = null
private var customBigContentViews: RemoteViews? = null
override fun onCreate() {
super.onCreate()
registerReceiver(receiver1, IntentFilter(KEY_COMPRESS_BROADCAST_CANCEL))
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val mZipPath = intent.getStringExtra(KEY_COMPRESS_PATH)
val baseFiles: ArrayList<HybridFileParcelable> =
intent.getParcelableArrayListExtra(KEY_COMPRESS_FILES)!!
val zipFile = File(mZipPath)
mNotifyManager = NotificationManagerCompat.from(applicationContext)
if (!zipFile.exists()) {
try {
zipFile.createNewFile()
} catch (e: IOException) {
log.warn("failed to create zip file", e)
}
}
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
accentColor = (application as AppConfig)
.utilsProvider
.colorPreference
.getCurrentUserColorPreferences(this, sharedPreferences).accent
val notificationIntent = Intent(this, MainActivity::class.java)
.putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true)
val pendingIntent = PendingIntent.getActivity(
this,
0,
notificationIntent,
getPendingIntentFlag(0)
)
customSmallContentViews = RemoteViews(packageName, R.layout.notification_service_small)
customBigContentViews = RemoteViews(packageName, R.layout.notification_service_big)
val stopIntent = Intent(KEY_COMPRESS_BROADCAST_CANCEL)
val stopPendingIntent = PendingIntent.getBroadcast(
applicationContext,
1234,
stopIntent,
getPendingIntentFlag(FLAG_UPDATE_CURRENT)
)
val action = NotificationCompat.Action(
R.drawable.ic_zip_box_grey,
getString(R.string.stop_ftp),
stopPendingIntent
)
mBuilder = NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID)
.setSmallIcon(R.drawable.ic_zip_box_grey)
.setContentIntent(pendingIntent)
.setCustomContentView(customSmallContentViews)
.setCustomBigContentView(customBigContentViews)
.setCustomHeadsUpContentView(customSmallContentViews)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.addAction(action)
.setOngoing(true)
.setColor(accentColor)
NotificationConstants.setMetadata(this, mBuilder, NotificationConstants.TYPE_NORMAL)
startForeground(NotificationConstants.ZIP_ID, mBuilder.build())
initNotificationViews()
super.onStartCommand(intent, flags, startId)
super.progressHalted()
asyncTask = CompressAsyncTask(this, baseFiles, mZipPath!!)
asyncTask.execute()
// If we get killed, after returning from here, restart
return START_NOT_STICKY
}
override fun getNotificationManager(): NotificationManagerCompat = mNotifyManager
override fun getNotificationBuilder(): NotificationCompat.Builder = mBuilder
override fun getNotificationId(): Int = NotificationConstants.ZIP_ID
@StringRes
override fun getTitle(move: Boolean): Int = R.string.compressing
override fun getNotificationCustomViewSmall(): RemoteViews = customSmallContentViews!!
override fun getNotificationCustomViewBig(): RemoteViews = customBigContentViews!!
override fun getProgressListener(): ProgressListener = progressListener
override fun setProgressListener(progressListener: ProgressListener) {
this.progressListener = progressListener
}
override fun getDataPackages(): ArrayList<DatapointParcelable> = dataPackages
override fun getProgressHandler(): ProgressHandler = progressHandler
override fun clearDataPackages() = dataPackages.clear()
inner class CompressAsyncTask(
private val zipService: ZipService,
private val baseFiles: ArrayList<HybridFileParcelable>,
private val zipPath: String
) : AsyncTask<Void, Void?, Void?>() {
private lateinit var zos: ZipOutputStream
private lateinit var watcherUtil: ServiceWatcherUtil
private var totalBytes = 0L
override fun doInBackground(vararg p1: Void): Void? {
// setting up service watchers and initial data packages
// finding total size on background thread (this is necessary condition for SMB!)
totalBytes = FileUtils.getTotalBytes(baseFiles, zipService.applicationContext)
progressHandler.sourceSize = baseFiles.size
progressHandler.totalSize = totalBytes
progressHandler.setProgressListener { speed: Long ->
publishResults(speed, false, false)
}
zipService.addFirstDatapoint(
baseFiles[0].getName(applicationContext),
baseFiles.size,
totalBytes,
false
)
execute(
zipService.applicationContext,
FileUtils.hybridListToFileArrayList(baseFiles),
zipPath
)
return null
}
override fun onCancelled() {
super.onCancelled()
progressHandler.cancelled = true
val zipFile = File(zipPath)
if (zipFile.exists()) zipFile.delete()
}
public override fun onPostExecute(a: Void?) {
watcherUtil.stopWatch()
val intent = Intent(MainActivity.KEY_INTENT_LOAD_LIST)
.putExtra(MainActivity.KEY_INTENT_LOAD_LIST_FILE, zipPath)
zipService.sendBroadcast(intent)
zipService.stopSelf()
}
/**
* Main logic for zipping specified files.
*/
fun execute(context: Context, baseFiles: ArrayList<File>, zipPath: String?) {
val out: OutputStream?
val zipDirectory = File(zipPath)
watcherUtil = ServiceWatcherUtil(progressHandler)
watcherUtil.watch(this@ZipService)
try {
out = FileUtil.getOutputStream(zipDirectory, context)
zos = ZipOutputStream(BufferedOutputStream(out))
for ((fileProgress, file) in baseFiles.withIndex()) {
if (isCancelled) return
progressHandler.fileName = file.name
progressHandler.sourceFilesProcessed = fileProgress + 1
compressFile(file, "")
}
} catch (e: IOException) {
log.warn("failed to zip file", e)
} finally {
try {
zos.flush()
zos.close()
context.sendBroadcast(
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
.setData(Uri.fromFile(zipDirectory))
)
} catch (e: IOException) {
log.warn("failed to close zip streams", e)
}
}
}
@Throws(IOException::class, NullPointerException::class, ZipException::class)
private fun compressFile(file: File, path: String) {
if (progressHandler.cancelled) return
if (!file.isDirectory) {
zos.putNextEntry(createZipEntry(file, path))
val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE)
var len: Int
BufferedInputStream(FileInputStream(file)).use { `in` ->
while (`in`.read(buf).also { len = it } > 0) {
if (!progressHandler.cancelled) {
zos.write(buf, 0, len)
ServiceWatcherUtil.position += len.toLong()
} else break
}
}
return
}
file.listFiles()?.forEach {
compressFile(it, "${createZipEntryPrefixWith(path)}${file.name}")
}
}
}
private fun createZipEntryPrefixWith(path: String): String =
if (path.isEmpty()) {
path
} else {
"$path/"
}
private fun createZipEntry(file: File, path: String): ZipEntry =
ZipEntry("${createZipEntryPrefixWith(path)}${file.name}").apply {
if (SDK_INT >= O) {
val attrs = Files.readAttributes(
Paths.get(file.absolutePath),
BasicFileAttributes::class.java
)
setCreationTime(attrs.creationTime())
.setLastAccessTime(attrs.lastAccessTime())
.lastModifiedTime = attrs.lastModifiedTime()
} else {
time = file.lastModified()
}
}
/*
* Class used for the client Binder. Because we know this service always runs in the same process
* as its clients, we don't need to deal with IPC.
*/
private val receiver1: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
progressHandler.cancelled = true
}
}
override fun onBind(arg0: Intent): IBinder = mBinder
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(receiver1)
}
companion object {
const val KEY_COMPRESS_PATH = "zip_path"
const val KEY_COMPRESS_FILES = "zip_files"
const val KEY_COMPRESS_BROADCAST_CANCEL = "zip_cancel"
}
}
| gpl-3.0 | d1af2964b439ac84d6d3db1f19ddd1db | 39.124224 | 107 | 0.654025 | 5.273469 | false | false | false | false |
michaelgallacher/intellij-community | java/java-impl/src/com/intellij/reporting/ReportMissingOrExcessiveInlineHint.kt | 2 | 4708 | /*
* 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.reporting
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import java.io.File
class ReportMissingOrExcessiveInlineHint : AnAction() {
private val text = "Report Missing or Excessive Inline Hint"
private val description = "Text line at caret will be anonymously reported to our servers"
companion object {
private val LOG = Logger.getInstance(ReportMissingOrExcessiveInlineHint::class.java)
}
init {
val presentation = templatePresentation
presentation.text = text
presentation.description = description
}
private val recorderId = "inline-hints-reports"
private val file = File(PathManager.getTempPath(), recorderId)
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = false
if (!isHintsEnabled()) return
CommonDataKeys.PROJECT.getData(e.dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return
val range = getCurrentLineRange(editor)
if (editor.getInlays(range).isNotEmpty()) {
e.presentation.isEnabledAndVisible = true
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = CommonDataKeys.PROJECT.getData(e.dataContext)!!
val editor = CommonDataKeys.EDITOR.getData(e.dataContext)!!
val document = editor.document
val range = getCurrentLineRange(editor)
val inlays = editor.getInlays(range)
if (inlays.isNotEmpty()) {
val line = document.getText(range)
reportInlays(line.trim(), inlays)
showHint(project)
}
}
private fun reportInlays(text: String, inlays: List<Inlay>) {
val hintManager = ParameterHintsPresentationManager.getInstance()
val hints = inlays.mapNotNull { hintManager.getHintText(it) }
trySend(text, hints)
}
private fun trySend(text: String, inlays: List<String>) {
val report = InlayReport(text, inlays)
writeToFile(createReportLine(recorderId, report))
trySendFileInBackground()
}
private fun trySendFileInBackground() {
LOG.debug("File: ${file.path} Length: ${file.length()}")
if (!file.exists() || file.length() == 0L) return
ApplicationManager.getApplication().executeOnPooledThread {
val text = file.readText()
LOG.debug("File text $text")
if (StatsSender.send(text, compress = false)) {
file.delete()
LOG.debug("File deleted")
}
}
}
private fun showHint(project: Project) {
val notification = Notification(
"Inline Hints",
"Inline Hints Reporting",
"Problematic inline hint was reported",
NotificationType.INFORMATION
)
notification.notify(project)
}
private fun writeToFile(line: String) {
if (!file.exists()) {
file.createNewFile()
}
file.appendText(line)
}
private fun getCurrentLineRange(editor: Editor): TextRange {
val offset = editor.caretModel.currentCaret.offset
val document = editor.document
val line = document.getLineNumber(offset)
return TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line))
}
}
private fun isHintsEnabled() = EditorSettingsExternalizable.getInstance().isShowParameterNameHints
private fun Editor.getInlays(range: TextRange): List<Inlay> {
return inlayModel.getInlineElementsInRange(range.startOffset, range.endOffset)
}
private class InlayReport(@JvmField var text: String, @JvmField var inlays: List<String>) | apache-2.0 | c325edc167dea9c508be66ef2eae2e02 | 33.372263 | 98 | 0.740654 | 4.518234 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/extensions/links/GitHubIngestionLinksByBuildNameInput.kt | 1 | 857 | package net.nemerosa.ontrack.extension.github.ingestion.extensions.links
import net.nemerosa.ontrack.model.annotations.APIDescription
/**
* Input for the links for a build identified by its name
*/
@APIDescription("Input for the links for a build identified by its name")
class GitHubIngestionLinksByBuildNameInput(
owner: String,
repository: String,
buildLinks: List<GitHubIngestionLink>,
addOnly: Boolean,
@APIDescription("Name of the build")
val buildName: String,
) : AbstractGitHubIngestionLinksInput(
owner,
repository,
buildLinks,
addOnly,
) {
override fun toPayload() = GitHubIngestionLinksPayload(
owner = owner,
repository = repository,
buildLinks = buildLinks,
buildName = buildName,
addOnly = addOnly ?: GitHubIngestionLinksPayload.ADD_ONLY_DEFAULT,
)
} | mit | 6ff96320c3cd82502e9f3cc65a02f42c | 28.586207 | 74 | 0.718786 | 4.372449 | false | false | false | false |
liceoArzignano/app_bold | app/src/main/kotlin/it/liceoarzignano/bold/utils/SystemUtils.kt | 1 | 1731 | package it.liceoarzignano.bold.utils
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.os.Build
import android.util.Log
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import it.liceoarzignano.bold.BuildConfig
object SystemUtils {
private const val TAG = "SystemUtils"
val isNotLegacy: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
fun hasGDrive(context: Context): Boolean =
try {
val info = context.packageManager
.getPackageInfo("com.google.android.apps.docs", 0)
info.applicationInfo.enabled
} catch (e: PackageManager.NameNotFoundException) {
// Gotta catch 'em all
false
}
fun hasNoInternetConnection(context: Context): Boolean {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return manager.activeNetworkInfo == null
}
fun hasNoGMS(context: Context): Boolean =
GoogleApiAvailability.getInstance()
.isGooglePlayServicesAvailable(context) != ConnectionResult.SUCCESS
fun getSafetyNetApiKey(context: Context): String = try {
val info = context.packageManager
.getApplicationInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_META_DATA)
val metadata = info.metaData
val apiKey = metadata.getString("com.google.android.safetynet.ATTEST_API_KEY")
apiKey ?: ""
} catch (e: PackageManager.NameNotFoundException) {
Log.e(TAG, e.message)
""
}
} | lgpl-3.0 | 604ec5869ffaf2c05a2218fcd16a670e | 35.851064 | 99 | 0.681687 | 4.917614 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/extension/ExtensionFeatureOptions.kt | 1 | 1115 | package net.nemerosa.ontrack.model.extension;
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Options for a feature
*
* @property isGui Does the extension provides some web components?
* @property dependencies List of extensions IDs this feature depends on.
*/
class ExtensionFeatureOptions(
@JsonProperty("gui")
val isGui: Boolean = false,
val dependencies: Set<String>
) {
companion object {
/**
* Default options
*/
@JvmField
val DEFAULT = ExtensionFeatureOptions(
isGui = false,
dependencies = emptySet()
)
}
/**
* With GUI
*/
fun withGui(isGui: Boolean) = ExtensionFeatureOptions(isGui, dependencies)
/**
* List of extensions IDs this feature depends on.
*/
fun withDependencies(dependencies: Set<String>) = ExtensionFeatureOptions(isGui, dependencies)
/**
* Adds a dependency
*/
fun withDependency(feature: ExtensionFeature) = ExtensionFeatureOptions(
isGui,
dependencies + feature.id
)
}
| mit | 42c54f7e84dd3fcdcc14bd2206fddfbd | 22.723404 | 98 | 0.624215 | 4.911894 | false | false | false | false |
material-components/material-components-android-examples | Reply/app/src/main/java/com/materialstudies/reply/ui/compose/ComposeFragment.kt | 1 | 8091 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.compose
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.transition.Slide
import androidx.transition.TransitionManager
import com.google.android.material.transition.MaterialContainerTransform
import com.materialstudies.reply.R
import com.materialstudies.reply.data.Account
import com.materialstudies.reply.data.AccountStore
import com.materialstudies.reply.data.Email
import com.materialstudies.reply.data.EmailStore
import com.materialstudies.reply.databinding.ComposeRecipientChipBinding
import com.materialstudies.reply.databinding.FragmentComposeBinding
import com.materialstudies.reply.util.themeColor
import kotlin.LazyThreadSafetyMode.NONE
/**
* A [Fragment] which allows for the composition of a new email.
*/
class ComposeFragment : Fragment() {
private lateinit var binding: FragmentComposeBinding
private val args: ComposeFragmentArgs by navArgs()
// The new email being composed.
private val composeEmail: Email by lazy(NONE) {
// Get the id of the email being replied to, if any, and either create an new empty email
// or a new reply email.
val id = args.replyToEmailId
if (id == -1L) EmailStore.create() else EmailStore.createReplyTo(id)
}
// Handle closing an expanded recipient card when on back is pressed.
private val closeRecipientCardOnBackPressed = object : OnBackPressedCallback(false) {
var expandedChip: View? = null
override fun handleOnBackPressed() {
expandedChip?.let { collapseChip(it) }
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(this, closeRecipientCardOnBackPressed)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentComposeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.run {
closeIcon.setOnClickListener { findNavController().navigateUp() }
email = composeEmail
composeEmail.nonUserAccountRecipients.forEach { addRecipientChip(it) }
senderSpinner.adapter = ArrayAdapter(
senderSpinner.context,
R.layout.spinner_item_layout,
AccountStore.getAllUserAccounts().map { it.email }
)
// Set transitions here so we are able to access Fragment's binding views.
enterTransition = MaterialContainerTransform().apply {
// Manually add the Views to be shared since this is not a standard Fragment to
// Fragment shared element transition.
startView = requireActivity().findViewById(R.id.fab)
endView = emailCardView
duration = resources.getInteger(R.integer.reply_motion_duration_large).toLong()
scrimColor = Color.TRANSPARENT
containerColor = requireContext().themeColor(R.attr.colorSurface)
startContainerColor = requireContext().themeColor(R.attr.colorSecondary)
endContainerColor = requireContext().themeColor(R.attr.colorSurface)
}
returnTransition = Slide().apply {
duration = resources.getInteger(R.integer.reply_motion_duration_medium).toLong()
addTarget(R.id.email_card_view)
}
}
}
/**
* Add a chip for the given [Account] to the recipients chip group.
*
* This method also sets up the ability for expanding/collapsing the chip into a recipient
* address selection dialog.
*/
private fun addRecipientChip(acnt: Account) {
binding.recipientChipGroup.run {
val chipBinding = ComposeRecipientChipBinding.inflate(
LayoutInflater.from(context),
this,
false
).apply {
account = acnt
root.setOnClickListener {
// Bind the views in the expanded card view to this account's details when
// clicked and expand.
binding.focusedRecipient = acnt
expandChip(it)
}
}
addView(chipBinding.root)
}
}
/**
* Expand the recipient [chip] into a popup with a list of contact addresses to choose from.
*/
private fun expandChip(chip: View) {
// Configure the analogous collapse transform back to the recipient chip. This should
// happen when the card is clicked, any region outside of the card (the card's transparent
// scrim) is clicked, or when the back button is pressed.
binding.run {
recipientCardView.setOnClickListener { collapseChip(chip) }
recipientCardScrim.visibility = View.VISIBLE
recipientCardScrim.setOnClickListener { collapseChip(chip) }
}
closeRecipientCardOnBackPressed.expandedChip = chip
closeRecipientCardOnBackPressed.isEnabled = true
val transform = MaterialContainerTransform().apply {
startView = chip
endView = binding.recipientCardView
scrimColor = Color.TRANSPARENT
// Have the transform match the endView card's native elevation as closely as possible.
endElevation = requireContext().resources.getDimension(
R.dimen.email_recipient_card_popup_elevation_compat
)
// Avoid having this transform from running on both the start and end views by setting
// its target to the endView.
addTarget(binding.recipientCardView)
}
TransitionManager.beginDelayedTransition(binding.composeConstraintLayout, transform)
binding.recipientCardView.visibility = View.VISIBLE
// Using INVISIBLE instead of GONE ensures the chip's parent layout won't shift during
// the transition due to chips being effectively removed.
chip.visibility = View.INVISIBLE
}
/**
* Collapse the recipient card back into its [chip] form.
*/
private fun collapseChip(chip: View) {
// Remove the scrim view and on back pressed callbacks
binding.recipientCardScrim.visibility = View.GONE
closeRecipientCardOnBackPressed.expandedChip = null
closeRecipientCardOnBackPressed.isEnabled = false
val transform = MaterialContainerTransform().apply {
startView = binding.recipientCardView
endView = chip
scrimColor = Color.TRANSPARENT
startElevation = requireContext().resources.getDimension(
R.dimen.email_recipient_card_popup_elevation_compat
)
addTarget(chip)
}
TransitionManager.beginDelayedTransition(binding.composeConstraintLayout, transform)
chip.visibility = View.VISIBLE
binding.recipientCardView.visibility = View.INVISIBLE
}
} | apache-2.0 | ed0b57a1f2c985108ae3abffbd0dcd18 | 40.285714 | 100 | 0.677543 | 5.302097 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/EclipseAnimView.kt | 1 | 5469 | package com.hewking.custom
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
/**
* Created by test on 2018/1/18.
*/
class EclipseAnimView : View{
constructor(context : Context, attrs : AttributeSet?):super(context,attrs) {
}
constructor(context: Context) : this(context,null) {
}
private val mPaint : Paint by lazy {
Paint().apply {
color = Color.YELLOW
strokeWidth = 2f
isAntiAlias = true
style = Paint.Style.FILL
}
}
private var circleCanvas : Canvas? = null
private var circleBitmap : Bitmap? = null
init{
mPaint
}
private var mWidth = 0
private var mHeight = 0
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w
mHeight = h
circleBitmap?.recycle()
if (measuredWidth != 0 && measuredHeight != 0) {
circleBitmap = Bitmap.createBitmap(measuredWidth,measuredHeight,Bitmap.Config.ARGB_8888)
circleCanvas = Canvas(circleBitmap)
}
Log.d("EclipseAnimView : " ,"onSizeChanged :${measuredWidth}")
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
// 开启动画
startAnimator()
}
private var startAnimator: ValueAnimator? = null
private var fraction : Float = 0f
private var count : Int = 0
private var eclipseEnd = false
private fun startAnimator() {
if (startAnimator == null) {
startAnimator = ValueAnimator.ofFloat(0f,1f).apply {
repeatMode = ValueAnimator.RESTART
repeatCount = 2
duration = 2000
addUpdateListener {
fraction = it.animatedValue as Float
postInvalidateOnAnimation()
}
addListener(object : AnimatorListenerAdapter(){
override fun onAnimationEnd(animation: Animator?) {
eclipseEnd = true
fraction = 0f
ValueAnimator.ofFloat(0f,4f).apply {
duration = 1000
repeatCount = 1
repeatMode = ValueAnimator.RESTART
addUpdateListener({
fraction = it.animatedValue as Float
postInvalidateOnAnimation()
})
start()
}
}
override fun onAnimationRepeat(animation: Animator?) {
super.onAnimationRepeat(animation)
count ++
Log.d("EclipseAnimView : " ,"count :${count}")
}
})
start()
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
startAnimator?.cancel()
circleBitmap?.recycle()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
}
val radius = 100f
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
Log.d("EclipseAnimView : " ,"onDraw :${measuredWidth}")
canvas.drawARGB(255,23,12,53)
if (eclipseEnd) {
canvas.save()
mPaint.color = Color.YELLOW
mPaint.style = Paint.Style.STROKE
canvas.translate(mWidth/2f,mHeight/2f)
val rectf = RectF(-radius,-radius,radius,radius)
canvas.drawArc(rectf,-90 * (1 + fraction),90f ,false,mPaint)
if (fraction >= 4) {
mPaint.style = Paint.Style.FILL
canvas.drawCircle(rectf.centerX(),rectf.centerY(),radius,mPaint)
}
canvas.restore()
} else {
circleCanvas?.let {
it.save()
it.drawARGB(255,23,12,53)
mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
it.drawPaint(mPaint)
mPaint.xfermode = null
it.translate(mWidth / 2f , mHeight / 2f)
mPaint.color = Color.YELLOW
it.drawCircle(0f,0f,radius,mPaint)
mPaint.color = Color.TRANSPARENT
mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)
Log.d("EclipseAnimView : " ,"fraction :${if(count % 2 == 0)fraction else -fraction}")
it.drawCircle((if(count % 2 == 0)fraction else -fraction) * radius * 2,0f,radius,mPaint)
mPaint.xfermode = null
it.restore()
canvas.drawBitmap(circleBitmap,0f,0f,null)
}
}
}
} | mit | 61874a39e60e592af8ae847072ac514f | 32.14375 | 104 | 0.530855 | 5.200952 | false | false | false | false |
soywiz/korge | korge-swf/src/commonMain/kotlin/com/soywiz/korfl/as3swf/as3swf.kt | 1 | 26920 | package com.soywiz.korfl.as3swf
import com.soywiz.kds.*
import com.soywiz.kmem.*
import com.soywiz.korio.lang.*
import com.soywiz.korio.stream.*
import com.soywiz.korio.util.*
import kotlin.collections.set
import kotlin.math.*
@Suppress("unused")
open class SWF : SWFTimelineContainer(), Extra by Extra.Mixin() {
private var bytes: SWFData = SWFData()
var signature: String? = null
var version = 0
var fileLength = 0
var fileLengthCompressed = 0
var frameSize = SWFRectangle()
var frameRate = 0.0
var frameCount = 0
var compressed = false
var compressionMethod = COMPRESSION_METHOD_ZLIB
companion object {
const val COMPRESSION_METHOD_ZLIB = "zlib"
const val COMPRESSION_METHOD_LZMA = "lzma"
const val TOSTRING_FLAG_TIMELINE_STRUCTURE = 0x01
const val TOSTRING_FLAG_AVM1_BYTECODE = 0x02
protected const val FILE_LENGTH_POS = 4
protected const val COMPRESSION_START_POS = 8
}
init {
version = 10
fileLength = 0
fileLengthCompressed = 0
frameSize = SWFRectangle()
frameRate = 50.0
frameCount = 1
compressed = true
compressionMethod = COMPRESSION_METHOD_ZLIB
}
suspend fun loadBytes(bytes: ByteArray): SWF = this.apply {
val ba = bytes.toFlash()
this.bytes.length = 0
ba.position = 0
ba.readBytes(this.bytes)
parse(this.bytes)
}
suspend fun parse(data: SWFData) {
bytes = data
parseHeader()
parseTags(data, version)
}
suspend protected fun parseHeader() {
signature = ""
compressed = false
compressionMethod = COMPRESSION_METHOD_ZLIB
bytes.position = 0
var signatureByte = bytes.readUI8()
when (signatureByte.toChar()) {
'C' -> {
compressed = true
compressionMethod = COMPRESSION_METHOD_ZLIB
}
'Z' -> {
compressed = true
compressionMethod = COMPRESSION_METHOD_LZMA
}
'F' -> {
compressed = false
}
else -> throw Error("Not a SWF. First signature byte is 0x" + signatureByte.toString(16) + " (expected: 0x43 or 0x5A or 0x46)")
}
signature += String_fromIntArray(intArrayOf(signatureByte.toChar().toInt()))
signatureByte = bytes.readUI8()
if (signatureByte != 0x57) throw Error("Not a SWF. Second signature byte is 0x" + signatureByte.toString(16) + " (expected: 0x57)")
signature += String_fromIntArray(intArrayOf(signatureByte.toChar().toInt()))
signatureByte = bytes.readUI8()
if (signatureByte != 0x53) throw Error("Not a SWF. Third signature byte is 0x" + signatureByte.toString(16) + " (expected: 0x53)")
signature += String_fromIntArray(intArrayOf(signatureByte.toChar().toInt()))
version = bytes.readUI8()
fileLength = bytes.readUI32()
fileLengthCompressed = bytes.length
if (fileLength >= fileLengthCompressed * 4) invalidOp("something went wrong! fileLength >= fileLengthCompressed * 4 : $fileLength >= $fileLengthCompressed * 4")
if (compressed) {
// The following data (up to end of file) is compressed, if header has CWS or ZWS signature
bytes.swfUncompress(compressionMethod, fileLength)
}
frameSize = bytes.readRECT()
frameRate = bytes.readFIXED8()
frameCount = bytes.readUI16()
}
override fun toString(indent: Int, flags: Int): String {
val indent0 = " ".repeat(indent)
val indent2 = " ".repeat(indent + 2)
val indent4 = " ".repeat(indent + 4)
var s: String = indent0 + "[SWF]\n" +
indent2 + "Header:\n" +
indent4 + "Version: " + version + "\n" +
indent4 + "Compression: "
s += if (compressed) {
when (compressionMethod) {
COMPRESSION_METHOD_ZLIB -> "ZLIB"
COMPRESSION_METHOD_LZMA -> "LZMA"
else -> "Unknown"
}
} else {
"None"
}
return s + "\n" + indent4 + "FileLength: " + fileLength + "\n" +
indent4 + "FileLengthCompressed: " + fileLengthCompressed + "\n" +
indent4 + "FrameSize: " + frameSize.toStringSize() + "\n" +
indent4 + "FrameRate: " + frameRate + "\n" +
indent4 + "FrameCount: " + frameCount +
super.toString(indent, 0)
}
}
@Suppress("unused")
class SWFData : BitArray() {
companion object {
fun dump(ba: FlashByteArray, length: Int, offset: Int = 0) {
val posOrig = ba.position
val pos = min(max(posOrig + offset, 0), ba.length - length)
ba.position = pos
var str = "[Dump] total length: " + ba.length + ", original position: " + posOrig
for (i in 0 until length) {
var b: String = ba.readUnsignedByte().toString(16)
if (b.length == 1) {
b = "0$b"
}
if (i % 16 == 0) {
var addr: String = (pos + i).toString(16)
addr = "00000000".substr(0, 8 - addr.length) + addr
str += "\r$addr: "
}
b += " "
str += b
}
ba.position = posOrig
println(str)
}
}
init {
endian = Endian.LITTLE_ENDIAN
}
/////////////////////////////////////////////////////////
// Integers
/////////////////////////////////////////////////////////
fun readSI8(): Int = resetBitsPending().readByte()
fun writeSI8(value: Int) = resetBitsPending().writeByte(value)
fun readSI16(): Int = resetBitsPending().readShort()
fun writeSI16(value: Int) = resetBitsPending().writeShort(value)
fun readSI32(): Int = resetBitsPending().readInt()
fun writeSI32(value: Int) = resetBitsPending().writeInt(value)
fun readUI8(): Int = resetBitsPending().readUnsignedByte()
fun writeUI8(value: Int) = resetBitsPending().writeByte(value)
fun writeUI8(value: Boolean) = writeUI8(if (value) 1 else 0)
fun readUI16(): Int = resetBitsPending().readUnsignedShort()
fun writeUI16(value: Int) = resetBitsPending().writeShort(value)
fun readUI24(): Int {
resetBitsPending()
val loWord = readUnsignedShort()
val hiByte = readUnsignedByte()
return (hiByte shl 16) or loWord
}
fun writeUI24(value: Int) {
resetBitsPending()
writeShort(value and 0xffff)
writeByte(value ushr 16)
}
fun readUI32(): Int = resetBitsPending().readUnsignedInt()
fun writeUI32(value: Int) = resetBitsPending().writeUnsignedInt(value)
/////////////////////////////////////////////////////////
// Fixed-point numbers
/////////////////////////////////////////////////////////
fun readFIXED(): Double = resetBitsPending().readInt().toDouble() / 65536
//fun writeFIXED(value: Int) = writeFIXED(value.toDouble())
fun writeFIXED(value: Double) = resetBitsPending().writeInt((value * 65536).toInt())
fun readFIXED8(): Double = resetBitsPending().readShort().toDouble() / 256.0
fun writeFIXED8(value: Double) = resetBitsPending().writeShort((value * 256).toInt())
/////////////////////////////////////////////////////////
// Floating-point numbers
/////////////////////////////////////////////////////////
fun readFLOAT(): Double = resetBitsPending().readFloat()
fun writeFLOAT(value: Double) = resetBitsPending().writeFloat(value)
fun readDOUBLE(): Double = resetBitsPending().readDouble()
fun writeDOUBLE(value: Double) = resetBitsPending().writeDouble(value)
fun readFLOAT16(): Double = Float16.intBitsToDouble(resetBitsPending().readUnsignedShort().toUShort())
fun writeFLOAT16(value: Double) = resetBitsPending().writeShort(Float16.doubleToIntBits(value).toInt())
/////////////////////////////////////////////////////////
// Encoded integer
/////////////////////////////////////////////////////////
fun readEncodedU32(): Int {
resetBitsPending()
var result = readUnsignedByte()
if ((result and 0x80) != 0) {
result = (result and 0x7f) or (readUnsignedByte() shl 7)
if ((result and 0x4000) != 0) {
result = (result and 0x3fff) or (readUnsignedByte() shl 14)
if ((result and 0x200000) != 0) {
result = (result and 0x1fffff) or (readUnsignedByte() shl 21)
if ((result and 0x10000000) != 0) {
result = (result and 0xfffffff) or (readUnsignedByte() shl 28)
}
}
}
}
return result
}
fun writeEncodedU32(_value: Int) {
var value = _value
while (true) {
val v = value and 0x7f
value = value ushr 7
if (value == 0) {
writeUI8(v)
break
}
writeUI8(v or 0x80)
}
}
/////////////////////////////////////////////////////////
// Bit values
/////////////////////////////////////////////////////////
fun readUB(bits: Int): Int = readBits(bits)
fun writeUB(bits: Int, value: Int) = writeBits(bits, value)
fun writeUB(bits: Int, value: Boolean) = writeUB(bits, if (value) 1 else 0)
fun readSB(bits: Int): Int {
val shift = 32 - bits
return (readBits(bits) shl shift) shr shift
}
fun writeSB(bits: Int, value: Int) = writeBits(bits, value)
fun readFB(bits: Int): Double = (readSB(bits)).toDouble() / 65536
fun writeFB(bits: Int, value: Double) = writeSB(bits, (value * 65536).toInt())
/////////////////////////////////////////////////////////
// String
/////////////////////////////////////////////////////////
fun readString(): String {
//var index = position
//while (this[index++] != 0) Unit
resetBitsPending()
return this.data.readStringz()
//return readUTFBytes(index - position)
}
fun writeString(value: String?) {
if (value != null && value.isNotEmpty()) writeUTFBytes(value)
writeByte(0)
}
/////////////////////////////////////////////////////////
// Labguage code
/////////////////////////////////////////////////////////
fun readLANGCODE(): Int {
resetBitsPending()
return readUnsignedByte()
}
fun writeLANGCODE(value: Int) {
resetBitsPending()
writeByte(value)
}
/////////////////////////////////////////////////////////
// Color records
/////////////////////////////////////////////////////////
fun readRGB(): Int {
resetBitsPending()
val r = readUnsignedByte()
val g = readUnsignedByte()
val b = readUnsignedByte()
return 0xff000000.toInt() or (r shl 16) or (g shl 8) or b
}
fun writeRGB(value: Int) {
resetBitsPending()
writeByte((value ushr 16) and 0xff)
writeByte((value ushr 8) and 0xff)
writeByte((value ushr 0) and 0xff)
}
fun readRGBA(): Int {
resetBitsPending()
val rgb = readRGB() and 0x00ffffff
val a = readUnsignedByte()
return (a shl 24) or rgb
}
fun writeRGBA(value: Int) {
resetBitsPending()
writeRGB(value)
writeByte((value ushr 24) and 0xff)
}
fun readARGB(): Int {
resetBitsPending()
val a = readUnsignedByte()
val rgb = readRGB() and 0x00ffffff
return (a shl 24) or rgb
}
fun writeARGB(value: Int) {
resetBitsPending()
writeByte((value ushr 24) and 0xff)
writeRGB(value)
}
fun readRECT(): SWFRectangle = SWFRectangle().apply { parse(this@SWFData) }
fun readMATRIX(): SWFMatrix = SWFMatrix().apply { parse(this@SWFData) }
fun readCXFORM(): SWFColorTransform = SWFColorTransform().apply { parse(this@SWFData) }
fun readCXFORMWITHALPHA(): SWFColorTransformWithAlpha = SWFColorTransformWithAlpha().apply { parse(this@SWFData) }
fun readSHAPE(unitDivisor: Double = 20.0): SWFShape = SWFShape(unitDivisor).apply { parse(this@SWFData) }
fun readSHAPEWITHSTYLE(level: Int = 1, unitDivisor: Double = 20.0): SWFShapeWithStyle =
SWFShapeWithStyle(unitDivisor).apply { parse(this@SWFData, level) }
fun readSTRAIGHTEDGERECORD(numBits: Int) = SWFShapeRecordStraightEdge(numBits).apply { parse(this@SWFData) }
fun readCURVEDEDGERECORD(numBits: Int): SWFShapeRecordCurvedEdge =
SWFShapeRecordCurvedEdge(numBits).apply { parse(this@SWFData) }
fun readSTYLECHANGERECORD(states: Int, fillBits: Int, lineBits: Int, level: Int = 1): SWFShapeRecordStyleChange =
SWFShapeRecordStyleChange(states, fillBits, lineBits).apply { parse(this@SWFData, level) }
fun readFILLSTYLE(level: Int = 1): SWFFillStyle = SWFFillStyle().apply { parse(this@SWFData, level) }
fun readLINESTYLE(level: Int = 1): SWFLineStyle = SWFLineStyle().apply { parse(this@SWFData, level) }
fun readLINESTYLE2(level: Int = 1): SWFLineStyle2 = SWFLineStyle2().apply { parse(this@SWFData, level) }
fun readBUTTONRECORD(level: Int = 1): SWFButtonRecord? {
if (readUI8() == 0) {
return null
} else {
position--
return SWFButtonRecord().apply { parse(this@SWFData, level) }
}
}
fun readBUTTONCONDACTION(): SWFButtonCondAction = SWFButtonCondAction().apply { parse(this@SWFData) }
fun readFILTER(): IFilter {
val filterId = readUI8()
val filter = SWFFilterFactory.create(filterId)
filter.parse(this)
return filter
}
fun readTEXTRECORD(
glyphBits: Int,
advanceBits: Int,
previousRecord: SWFTextRecord? = null,
level: Int = 1
): SWFTextRecord? {
if (readUI8() == 0) {
return null
} else {
position--
return SWFTextRecord().apply { parse(this@SWFData, glyphBits, advanceBits, previousRecord, level) }
}
}
fun readGLYPHENTRY(glyphBits: Int, advanceBits: Int): SWFGlyphEntry =
SWFGlyphEntry().apply { parse(this@SWFData, glyphBits, advanceBits) }
fun readZONERECORD(): SWFZoneRecord = SWFZoneRecord(this@SWFData)
fun readZONEDATA(): SWFZoneData = SWFZoneData(this@SWFData)
fun readKERNINGRECORD(wideCodes: Boolean): SWFKerningRecord =
SWFKerningRecord().apply { parse(this@SWFData, wideCodes) }
fun readGRADIENT(level: Int = 1): SWFGradient = SWFGradient().apply { parse(this@SWFData, level) }
fun readFOCALGRADIENT(level: Int = 1): SWFFocalGradient = SWFFocalGradient().apply { parse(this@SWFData, level) }
fun readGRADIENTRECORD(level: Int = 1): SWFGradientRecord = SWFGradientRecord().apply { parse(this@SWFData, level) }
fun readMORPHFILLSTYLE(level: Int = 1) = SWFMorphFillStyle().apply { parse(this@SWFData, level) }
fun readMORPHLINESTYLE(level: Int = 1) = SWFMorphLineStyle().apply { parse(this@SWFData, level) }
fun readMORPHLINESTYLE2(level: Int = 1): SWFMorphLineStyle2 =
SWFMorphLineStyle2().apply { parse(this@SWFData, level) }
fun readMORPHGRADIENT(level: Int = 1) = SWFMorphGradient().apply { parse(this@SWFData, level) }
fun readMORPHFOCALGRADIENT(level: Int = 1) = SWFMorphFocalGradient().apply { parse(this@SWFData, level) }
fun readMORPHGRADIENTRECORD(): SWFMorphGradientRecord = SWFMorphGradientRecord().apply { parse(this@SWFData) }
fun readACTIONRECORD(): IAction? {
val pos: Int = position
var action: IAction? = null
val actionCode: Int = readUI8()
if (actionCode != 0) {
val actionLength: Int = if (actionCode >= 0x80) readUI16() else 0
action = SWFActionFactory.create(actionCode, actionLength, pos)
action.parse(this)
}
return action
}
fun readACTIONVALUE(): SWFActionValue = SWFActionValue().apply { parse(this@SWFData) }
fun readREGISTERPARAM(): SWFRegisterParam = SWFRegisterParam().apply { parse(this@SWFData) }
fun readSYMBOL(): SWFSymbol = SWFSymbol(this@SWFData)
fun readSOUNDINFO(): SWFSoundInfo = SWFSoundInfo().apply { parse(this@SWFData) }
fun readSOUNDENVELOPE(): SWFSoundEnvelope = SWFSoundEnvelope(this@SWFData)
fun readCLIPACTIONS(version: Int): SWFClipActions = SWFClipActions().apply { parse(this@SWFData, version) }
fun readCLIPACTIONRECORD(version: Int): SWFClipActionRecord? {
val pos = position
val flags = if (version >= 6) readUI32() else readUI16()
if (flags == 0) {
return null
} else {
position = pos
return SWFClipActionRecord().apply { parse(this@SWFData, version) }
}
}
fun readCLIPEVENTFLAGS(version: Int): SWFClipEventFlags = SWFClipEventFlags().apply { parse(this@SWFData, version) }
fun readTagHeader(): SWFRecordHeader {
val pos = position
val tagTypeAndLength = readUI16()
var tagLength = tagTypeAndLength and 0x003f
if (tagLength == 0x3f) {
// The SWF10 spec sez that this is a signed int.
// Shouldn't it be an unsigned int?
tagLength = readSI32()
}
return SWFRecordHeader(tagTypeAndLength ushr 6, tagLength, position - pos)
}
suspend fun swfUncompress(compressionMethod: String, uncompressedLength: Int = 0) {
val pos = position
val ba = FlashByteArray()
when (compressionMethod) {
SWF.COMPRESSION_METHOD_ZLIB -> {
readBytes(ba)
ba.position = 0
ba.uncompressInWorker()
}
SWF.COMPRESSION_METHOD_LZMA -> {
// LZMA compressed SWF:
// 0000 5A 57 53 0F (ZWS, Version 15)
// 0004 DF 52 00 00 (Uncompressed size: 21215)
// 0008 94 3B 00 00 (Compressed size: 15252)
// 000C 5D 00 00 00 01 (LZMA Properties)
// 0011 00 3B FF FC A6 14 16 5A ... (15252 bytes of LZMA Compressed Data, until EOF)
// 7z LZMA format:
// 0000 5D 00 00 00 01 (LZMA Properties)
// 0005 D7 52 00 00 00 00 00 00 (Uncompressed size: 21207, 64 bit)
// 000D 00 3B FF FC A6 14 16 5A ... (15252 bytes of LZMA Compressed Data, until EOF)
// (see also https://github.com/claus/as3swf/pull/23#issuecomment-7203861)
// Write LZMA properties
for (i in 0 until 5) ba.writeByte(this[i + 12])
// Write uncompressed length (64 bit)
ba.endian = Endian.LITTLE_ENDIAN
ba.writeUnsignedInt(uncompressedLength - 8)
ba.writeUnsignedInt(0)
// Write compressed data
position = 17
ba.position = 13
ba.writeBytes(this.readBytes(this.bytesAvailable))
ba.position = 13
// Uncompress
ba.position = 0
ba.uncompressInWorker(compressionMethod)
}
else -> error("Unknown compression method: $compressionMethod")
}
length = pos
position = pos
writeBytes(ba)
position = pos
}
/////////////////////////////////////////////////////////
// etc
/////////////////////////////////////////////////////////
fun readRawTag(): SWFRawTag = SWFRawTag().apply { parse(this@SWFData) }
fun skipBytes(length: Int) = run { position += length }
}
@Suppress("unused", "UNUSED_PARAMETER")
open class SWFTimelineContainer {
// We're just being lazy here.
companion object {
var EXTRACT_SOUND_STREAM: Boolean = true
}
val tags = ArrayList<ITag>()
var tagsRaw = ArrayList<SWFRawTag>()
var dictionary = hashMapOf<Int, Int>()
var scenes = ArrayList<Scene>()
var frames = ArrayList<Frame>()
var layers = ArrayList<Layer>()
var soundStream: SoundStream? = null
lateinit var currentFrame: Frame
protected var frameLabels = hashMapOf<Int, String>()
protected var hasSoundStream: Boolean = false
protected var eof: Boolean = false
protected var _tmpData: SWFData? = null
protected var _tmpVersion: Int = 0
protected var _tmpTagIterator: Int = 0
protected var tagFactory: ISWFTagFactory = SWFTagFactory()
internal var rootTimelineContainer: SWFTimelineContainer = this
var backgroundColor: Int = 0xffffff
var jpegTablesTag: TagJPEGTables? = null
fun getCharacter(characterId: Int): IDefinitionTag? {
val tagIndex = rootTimelineContainer.dictionary[characterId] ?: 0
if (tagIndex >= 0 && tagIndex < rootTimelineContainer.tags.size) {
return rootTimelineContainer.tags[tagIndex] as IDefinitionTag
}
return null
}
suspend fun parseTags(data: SWFData, version: Int) {
parseTagsInit(data, version)
while (data.bytesAvailable > 0) {
dispatchProgress(_tmpData!!.position, _tmpData!!.length)
val tag = parseTag(_tmpData!!, true) ?: break
//println(tag)
if (tag.type == TagEnd.TYPE) break
}
parseTagsFinalize()
}
private fun dispatchProgress(position: Int, length: Int) {
}
private fun dispatchWarning(msg: String) {
}
private fun parseTagsInit(data: SWFData, version: Int) {
tags.clear()
frames.clear()
layers.clear()
dictionary = hashMapOf()
this.currentFrame = Frame()
frameLabels = hashMapOf()
hasSoundStream = false
_tmpData = data
_tmpVersion = version
}
suspend protected fun parseTag(data: SWFData, async: Boolean = false): ITag? {
val pos: Int = data.position
// Bail out if eof
eof = (pos >= data.length)
if (eof) {
println("WARNING: end of file encountered, no end tag.")
return null
}
val tagRaw = data.readRawTag()
val tagHeader = tagRaw.header
val tag: ITag = tagFactory.create(tagHeader.type)
try {
if (tag is SWFTimelineContainer) {
val timelineContainer: SWFTimelineContainer = tag
// Currently, the only SWFTimelineContainer (other than the SWF root
// itself) is TagDefineSprite (MovieClips have their own timeline).
// Inject the current tag factory there.
timelineContainer.tagFactory = tagFactory
timelineContainer.rootTimelineContainer = this
}
// Parse tag
tag.parse(data, tagHeader.contentLength, _tmpVersion, async)
} catch (e: Throwable) {
// If we get here there was a problem parsing this particular tag.
// Corrupted SWF, possible SWF exploit, or obfuscated SWF.
// TODO: register errors and warnings
println("ERROR: parse error: " + e.message + ", Tag: " + tag.name + ", Index: " + tags.size)
e.printStackTrace()
//throw(e)
}
// Register tag
tags.add(tag)
tagsRaw.add(tagRaw)
// Build dictionary and display list etc
processTag(tag)
// Adjust position (just in case the parser under- or overflows)
if (data.position != pos + tagHeader.tagLength) {
val index: Int = tags.size - 1
val excessBytes = data.position - (pos + tagHeader.tagLength)
//var eventType: String = if (excessBytes < 0) SWFWarningEvent.UNDERFLOW else SWFWarningEvent.OVERFLOW;
//var eventDataPos = pos
//var eventDataBytes = if (excessBytes < 0) -excessBytes else excessBytes
if (rootTimelineContainer == this) {
println(
"WARNING: excess bytes: " + excessBytes + ", " +
"Tag: " + tag.name + ", " +
"Index: " + index
)
} else {
//eventData.indexRoot = rootTimelineContainer.tags.length;
println(
"WARNING: excess bytes: " + excessBytes + ", " +
"Tag: " + tag.name + ", " +
"Index: " + index + ", " +
"IndexRoot: " + rootTimelineContainer.tags.size
)
}
data.position = pos + tagHeader.tagLength
}
return tag
}
private fun parseTagsFinalize() {
val soundStream = soundStream
if (soundStream != null && soundStream.data.length == 0) this.soundStream = null
}
private fun processTag(tag: ITag) {
val currentTagIndex: Int = tags.size - 1
if (tag is IDefinitionTag) {
processDefinitionTag(tag, currentTagIndex)
return
} else if (tag is IDisplayListTag) {
processDisplayListTag(tag, currentTagIndex)
return
}
when (tag.type) {
TagFrameLabel.TYPE, TagDefineSceneAndFrameLabelData.TYPE -> {
// Frame labels and scenes
processFrameLabelTag(tag, currentTagIndex)
}
TagSoundStreamHead.TYPE, TagSoundStreamHead2.TYPE, TagSoundStreamBlock.TYPE -> {
// Sound stream
if (EXTRACT_SOUND_STREAM) processSoundStreamTag(tag, currentTagIndex)
}
TagSetBackgroundColor.TYPE -> {
// Background color
processBackgroundColorTag(tag as TagSetBackgroundColor, currentTagIndex)
}
TagJPEGTables.TYPE -> {
// Global JPEG Table
processJPEGTablesTag(tag as TagJPEGTables, currentTagIndex)
}
}
}
private fun processDefinitionTag(tag: IDefinitionTag, currentTagIndex: Int) {
if (tag.characterId > 0) {
// Register definition tag in dictionary
// key: character id
// value: definition tag index
dictionary[tag.characterId] = currentTagIndex
// Register character id in the current frame's character array
currentFrame.characters.add(tag.characterId)
}
}
private fun processDisplayListTag(tag: IDisplayListTag, currentTagIndex: Int) {
when (tag.type) {
TagShowFrame.TYPE -> {
currentFrame.tagIndexEnd = currentTagIndex
if (currentFrame.label == null && currentFrame.frameNumber in frameLabels) {
currentFrame.label = frameLabels[currentFrame.frameNumber]
}
frames.add(currentFrame)
currentFrame = currentFrame.clone()
currentFrame.frameNumber = frames.size
currentFrame.tagIndexStart = currentTagIndex + 1
}
TagPlaceObject.TYPE, TagPlaceObject2.TYPE, TagPlaceObject3.TYPE -> {
currentFrame.placeObject(currentTagIndex, tag as TagPlaceObject)
}
TagRemoveObject.TYPE, TagRemoveObject2.TYPE -> {
currentFrame.removeObject(tag as TagRemoveObject)
}
}
}
private fun processFrameLabelTag(tag: ITag, currentTagIndex: Int) {
when (tag.type) {
TagDefineSceneAndFrameLabelData.TYPE -> {
val tagSceneAndFrameLabelData: TagDefineSceneAndFrameLabelData = tag as TagDefineSceneAndFrameLabelData
for (i in 0 until tagSceneAndFrameLabelData.frameLabels.size) {
val frameLabel = tagSceneAndFrameLabelData.frameLabels[i]
frameLabels[frameLabel.frameNumber] = frameLabel.name
}
for (i in 0 until tagSceneAndFrameLabelData.scenes.size) {
val scene: SWFScene = tagSceneAndFrameLabelData.scenes[i]
scenes.add(Scene(scene.offset, scene.name))
}
}
TagFrameLabel.TYPE -> {
val tagFrameLabel = tag as TagFrameLabel
currentFrame.label = tagFrameLabel.frameName
}
}
}
private fun processSoundStreamTag(tag: ITag, currentTagIndex: Int) {
when (tag.type) {
TagSoundStreamHead.TYPE, TagSoundStreamHead2.TYPE -> {
val tagSoundStreamHead = tag as TagSoundStreamHead
soundStream = SoundStream()
val soundStream = soundStream!!
soundStream.compression = tagSoundStreamHead.streamSoundCompression
soundStream.rate = tagSoundStreamHead.streamSoundRate
soundStream.size = tagSoundStreamHead.streamSoundSize
soundStream.type = tagSoundStreamHead.streamSoundType
soundStream.numFrames = 0
soundStream.numSamples = 0
}
TagSoundStreamBlock.TYPE -> {
if (soundStream != null) {
val soundStream = soundStream!!
if (!hasSoundStream) {
hasSoundStream = true
soundStream.startFrame = currentFrame.frameNumber
}
val tagSoundStreamBlock = tag as TagSoundStreamBlock
val soundData = tagSoundStreamBlock.soundData
soundData.endian = Endian.LITTLE_ENDIAN
soundData.position = 0
when (soundStream.compression) {
SoundCompression.ADPCM -> {
// ADPCM
// TODO
}
SoundCompression.MP3 -> {
// MP3
val numSamples: Int = soundData.readUnsignedShort()
@Suppress("UNUSED_VARIABLE")
var seekSamples: Int = soundData.readShort()
if (numSamples > 0) {
soundStream.numSamples += numSamples
soundStream.data.writeBytes(soundData, 4)
}
}
}
soundStream.numFrames++
}
}
}
}
protected fun processBackgroundColorTag(tag: TagSetBackgroundColor, currentTagIndex: Int) {
backgroundColor = tag.color
}
protected fun processJPEGTablesTag(tag: TagJPEGTables, currentTagIndex: Int) {
jpegTablesTag = tag
}
open fun toString(indent: Int = 0, flags: Int = 0): String {
var str = ""
if (tags.size > 0) {
str += "\n" + " ".repeat(indent + 2) + "Tags:"
for (i in 0 until tags.size) {
str += "\n" + tags[i].toString(indent + 4)
}
}
if ((flags and SWF.TOSTRING_FLAG_TIMELINE_STRUCTURE) != 0) {
if (scenes.size > 0) {
str += "\n" + " ".repeat(indent + 2) + "Scenes:"
for (i in 0 until scenes.size) {
str += "\n" + scenes[i].toString(indent + 4)
}
}
if (frames.size > 0) {
str += "\n" + " ".repeat(indent + 2) + "Frames:"
for (i in 0 until frames.size) {
str += "\n" + frames[i].toString(indent + 4)
}
}
if (layers.size > 0) {
str += "\n" + " ".repeat(indent + 2) + "Layers:"
for (i in 0 until layers.size) {
str += "\n" + " ".repeat(indent + 4) +
"[" + i + "] " + layers[i].toString(indent + 4)
}
}
}
return str
}
override fun toString() = toString(0, 0)
}
| apache-2.0 | 79a8a4e25435f448899ae4735559511c | 31.709599 | 162 | 0.663039 | 3.572661 | false | false | false | false |
npryce/hamkrest | src/main/kotlin/com/natpryce/hamkrest/core_matchers.kt | 1 | 6060 | package com.natpryce.hamkrest
/**
* A [Matcher] that matches anything, always returning [MatchResult.Match].
*/
val anything = object : Matcher<Any?> {
override fun invoke(actual: Any?): MatchResult = MatchResult.Match
override val description: String get() = "anything"
override val negatedDescription: String get() = "nothing"
}
/**
* A [Matcher] that matches nothing, always returning a [MatchResult.Mismatch].
*/
val nothing = !anything
/**
* Returns a matcher that reports if a value is equal to an [expected] value. Handles null comparisons, just as
* the `==` operator does.
*/
fun <T> equalTo(expected: T?): Matcher<T?> =
object : Matcher<T?> {
override fun invoke(actual: T?): MatchResult = match(actual == expected) { "was: ${describe(actual)}" }
override val description: String get() = "is equal to ${describe(expected)}"
override val negatedDescription: String get() = "is not equal to ${describe(expected)}"
}
/**
* Returns a matcher that reports if a value is the same instance as [expected] value.
*/
fun <T> sameInstance(expected: T): Matcher<T> =
object : Matcher<T> {
override fun invoke(actual: T): MatchResult = match(actual === expected) { "was: ${describe(actual)}" }
override val description: String get() = "is same instance as ${describe(expected)}"
override val negatedDescription: String get() = "is not same instance as ${describe(expected)}"
}
/**
* Returns a matcher that reports if a value is null.
*/
fun <T> absent(): Matcher<T?> = object : Matcher<T?> {
override fun invoke(actual: T?): MatchResult = match(actual == null) { "was: ${describe(actual)}" }
override val description: String get() = "null"
}
/**
* Returns a matcher that reports if a value is not null and meets the criteria of the [valueMatcher]
*/
fun <T> present(valueMatcher: Matcher<T>? = null) = object : Matcher<T?> {
override fun invoke(actual: T?) =
if (actual == null) {
MatchResult.Mismatch("was: null")
}
else if (valueMatcher == null) {
MatchResult.Match
}
else {
valueMatcher(actual)
}
override val description: String
get() = "is not null" + (if (valueMatcher == null) "" else " & ${valueMatcher.description}")
}
/**
* Returns a matcher that reports if a value of [Any] type is of a type compatible with [downcastMatcher] and, if so,
* if the value meets its criteria.
*/
inline fun <reified T : Any> isA(downcastMatcher: Matcher<T>? = null) =
object : Matcher<Any> {
override fun invoke(actual: Any) =
if (actual !is T) {
MatchResult.Mismatch("was: a ${actual.javaClass.kotlin.qualifiedName}")
}
else if (downcastMatcher == null) {
MatchResult.Match
}
else {
downcastMatcher(actual)
}
override val description: String
get() = "is a ${T::class.qualifiedName}" + if (downcastMatcher == null) "" else " ${downcastMatcher.description}"
}
/**
* Returns a matcher that reports if a value of [Any] type is of a type compatible with [downcastMatcher] and, if so,
* if the value meets its criteria.
*/
inline fun <reified T : Any> cast(downcastMatcher: Matcher<T>): Matcher<Any> = isA(downcastMatcher)
/**
* Returns a matcher that reports if a [Comparable] value is greater than [n]
*/
fun <N : Comparable<N>> greaterThan(n: N) = _comparesAs("greater than", n) { it > 0 }
/**
* Returns a matcher that reports if a [Comparable] value is greater than or equal to [n]
*/
fun <N : Comparable<N>> greaterThanOrEqualTo(n: N) = _comparesAs("greater than or equal to", n) { it >= 0 }
/**
* Returns a matcher that reports if a [Comparable] value is less than [n]
*/
fun <N : Comparable<N>> lessThan(n: N) = _comparesAs("less than", n) { it < 0 }
/**
* Returns a matcher that reports if a [Comparable] value is less than or equal to [n]
*/
fun <N : Comparable<N>> lessThanOrEqualTo(n: N) = _comparesAs("less than or equal to", n) { it <= 0 }
private fun <N : Comparable<N>> _comparesAs(description: String, n: N, expectedSignum: (Int) -> Boolean): Matcher<N> {
return object : Matcher<N> {
override fun invoke(actual: N): MatchResult =
match(expectedSignum(actual.compareTo(n))) { "was: ${describe(actual)}" }
override val description: String get() {
return "is ${description} ${describe(n)}"
}
}
}
/**
* Returns a matcher that reports if a [kotlin.Comparable] value falls within the given [range].
*
* @param range The range that contains matching values.
*/
fun <T : Comparable<T>> isWithin(range: ClosedRange<T>): Matcher<T> {
fun _isWithin(actual: T, range: ClosedRange<T>): Boolean {
return range.contains(actual)
}
return Matcher.Companion(::_isWithin, range)
}
/**
* Returns a matcher that reports if a block throws an exception of type [T] and, if [exceptionCriteria] is given,
* the exception matches the [exceptionCriteria].
*/
inline fun <reified T : Throwable> throws(exceptionCriteria: Matcher<T>? = null): Matcher<() -> Unit> {
val exceptionName = T::class.qualifiedName
return object : Matcher<() -> Unit> {
override fun invoke(actual: () -> Unit): MatchResult =
try {
actual()
MatchResult.Mismatch("did not throw")
}
catch (e: Throwable) {
if (e is T) {
exceptionCriteria?.invoke(e) ?: MatchResult.Match
}
else {
MatchResult.Mismatch("threw ${e.javaClass.kotlin.qualifiedName}")
}
}
override val description: String get() = "throws ${exceptionName}${exceptionCriteria?.let { " that ${describe(it)}" } ?: ""}"
override val negatedDescription: String get() = "does not throw ${exceptionName}${exceptionCriteria?.let { " that ${describe(it)}" } ?: ""}"
}
}
| apache-2.0 | edc72fcb1076e0d89efd017abe36d376 | 35.727273 | 148 | 0.619472 | 4.086312 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/adapters/TornadoFXTables.kt | 1 | 2316 | package tornadofx.adapters
import javafx.beans.property.ObjectProperty
import javafx.scene.control.*
import javafx.util.Callback
import tornadofx.mapEach
fun TreeTableView<*>.toTornadoFXTable() = TornadoFXTreeTable(this)
fun TableView<*>.toTornadoFXTable() : TornadoFXTable<TableColumn<*,*>, TableView<*>> = TornadoFXNormalTable(this)
interface TornadoFXTable<COLUMN, out TABLE : Any> {
val table: TABLE
val contentWidth: Double
val properties: Properties
val contentColumns: List<TornadoFXColumn<COLUMN>>
var skin: Skin<*>?
val skinProperty: ObjectProperty<Skin<*>>
}
class TornadoFXTreeTable(override val table: TreeTableView<*>) : TornadoFXTable<TreeTableColumn<*, *>, TreeTableView<*>> {
override val skinProperty = table.skinProperty()
override var skin
get() = table.skin
set(value) {
table.skin = value
}
override val contentColumns get() = table.columns.flatMap {
if (it.columns.isEmpty()) listOf(it) else it.columns
}.mapEach { toTornadoFXColumn() }
override val properties = table.properties
private val contentWidthField by lazy {
TreeTableView::class.java.getDeclaredField("contentWidth").also {
it.isAccessible = true
}
}
override val contentWidth get() = contentWidthField.get(table) as Double
var columnResizePolicy: Callback<TreeTableView.ResizeFeatures<Any>, Boolean>
get() = table.columnResizePolicy
set(value) {
table.columnResizePolicy = value
}
}
class TornadoFXNormalTable(override val table: TableView<*>) : TornadoFXTable<TableColumn<*, *>, TableView<*>> {
override val skinProperty: ObjectProperty<Skin<*>> get() = table.skinProperty()
override val contentColumns get() = table.columns.flatMap {
if (it.columns.isEmpty()) listOf(it) else it.columns
}.mapEach { toTornadoFXColumn() }
override var skin
get() = table.skin
set(value) {
table.skin = value
}
private val contentWidthField by lazy {
TableView::class.java.getDeclaredField("contentWidth").also {
it.isAccessible = true
}
}
override val contentWidth get() = contentWidthField.get(table) as Double
override val properties = table.properties
}
| apache-2.0 | a45405560b92986d07b3dbdaaaafc39b | 30.726027 | 122 | 0.680915 | 4.775258 | false | false | false | false |
varpeti/Suli | Android/work/varpe8/homeworks/01/HF01/app/src/main/java/ml/varpeti/hf01/MainActivity.kt | 1 | 3284 | package ml.varpeti.hf01
import android.app.Activity
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.content.Intent
import android.widget.Toast
class MainActivity : AppCompatActivity()
{
val colorOf = arrayOf("#ffffff","#00ff00")
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Mentett szöveg visszaállítása
val fruits = resources.getStringArray(R.array.fruits)
val ll01 = findViewById(R.id.ll01) as LinearLayout
for (i in fruits.indices)
{
val b = Button(this)
b.id = i
b.setText(fruits[i])
b.setBackgroundColor(Color.parseColor(colorOf[0]))
b.tag = 0
b.setOnClickListener {
val btn = it as Button
val name = btn.text as String
var ci = btn.tag as Int
Log.i("\\|/", name+" "+btn.tag)
if (ci==1)
{
ci=0
btn.setBackgroundColor(Color.parseColor(colorOf[ci]))
btn.tag = ci
//Shopping Cart
val tw = findViewById<TextView>(R.id.tw01)
tw.text = ""+((tw.text as String).toInt()-1)
}
else
{
val int = Intent(this, ItemViewActivity::class.java)
int.putExtra("name", name)
int.putExtra("id", i)
startActivityForResult(int,0)
}
}
ll01.addView(b)
}
//Shopping Cart
val tw = findViewById<TextView>(R.id.tw01)
tw.text = "0"
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
if (resultCode == Activity.RESULT_OK && requestCode == 0)
{
if (data!!.hasExtra("id"))
{
val id = data.extras.getInt("id")
val ci = data.extras.getInt("status",0)
val b = findViewById<Button>(resources.getIdentifier(""+id, "id", getPackageName()))
if (ci==1)
{
b.tag = ci
Log.i("\\|/", "res: "+id+" "+ci)
b.setBackgroundColor(Color.parseColor(colorOf[ci]))
val tw = findViewById<TextView>(R.id.tw01)
tw.text = ""+((tw.text as String).toInt()+1)
}
}
}
}
//Lementés TODO
override fun onSaveInstanceState(savedInstanceState: Bundle)
{
super.onSaveInstanceState(savedInstanceState)
val fruits = resources.getStringArray(R.array.fruits)
for (i in fruits.indices)
{
val b = findViewById<Button>(resources.getIdentifier(""+i, "id", getPackageName()))
var ci = b.tag as Int
//Log.i("\\|/", ""+ci)
savedInstanceState.putInt("b"+i+"color",ci)
}
}
}
| unlicense | e051a9eb7e02ab2c68466ff48c4f6533 | 28.540541 | 100 | 0.522415 | 4.473397 | false | false | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/NotificationService.kt | 1 | 6041 | package com.matejdro.wearmusiccenter
import android.annotation.TargetApi
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.media.session.MediaController
import android.os.Build
import android.preference.PreferenceManager
import android.provider.Settings
import android.service.notification.NotificationListenerService
import androidx.lifecycle.Observer
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.NodeClient
import com.google.android.gms.wearable.Wearable
import com.matejdro.wearmusiccenter.common.CommPaths
import com.matejdro.wearmusiccenter.common.MiscPreferences
import com.matejdro.wearmusiccenter.common.model.AutoStartMode
import com.matejdro.wearmusiccenter.music.ActiveMediaSessionProvider
import com.matejdro.wearmusiccenter.music.MusicService
import com.matejdro.wearmusiccenter.music.isPlaying
import com.matejdro.wearutils.lifecycle.Resource
import com.matejdro.wearutils.messages.sendMessageToNearestClient
import com.matejdro.wearutils.preferences.definition.Preferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import timber.log.Timber
class NotificationService : NotificationListenerService() {
private lateinit var preferences: SharedPreferences
private var bound = false
private var activeMediaProvider: ActiveMediaSessionProvider? = null
private val coroutineScope = CoroutineScope(Job())
private lateinit var messageClient: MessageClient
private lateinit var nodeClient: NodeClient
override fun onCreate() {
super.onCreate()
preferences = PreferenceManager.getDefaultSharedPreferences(this)
nodeClient = Wearable.getNodeClient(applicationContext)
messageClient = Wearable.getMessageClient(applicationContext)
Timber.d("Service started")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (ACTION_UNBIND_SERVICE == intent?.action &&
bound &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
requestUnbindSafe()
Timber.d("Unbind on command")
}
return super.onStartCommand(intent, flags, startId)
}
override fun onListenerConnected() {
super.onListenerConnected()
Timber.d("Listener connected")
val musicServiceNotifyIntent = Intent(this, MusicService::class.java)
musicServiceNotifyIntent.action = MusicService.ACTION_NOTIFICATION_SERVICE_ACTIVATED
startService(musicServiceNotifyIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !shouldRun()) {
//Running notification service is not needed for this app to run, it only needs to be enabled.
Timber.d("Unbind on start")
// On N+ we can turn off the service
requestUnbindSafe()
return
}
activeMediaProvider = ActiveMediaSessionProvider(this)
if (MiscPreferences.isAnyKindOfAutoStartEnabled(preferences)) {
activeMediaProvider!!.observeForever(mediaObserver)
}
bound = true
}
override fun onListenerDisconnected() {
Timber.d("Listener disconnected")
activeMediaProvider?.removeObserver(mediaObserver)
super.onListenerDisconnected()
}
override fun onDestroy() {
Timber.d("Service destroyed")
activeMediaProvider?.removeObserver(mediaObserver)
coroutineScope.cancel()
super.onDestroy()
}
private fun shouldRun(): Boolean {
return MiscPreferences.isAnyKindOfAutoStartEnabled(preferences)
}
private fun startAppOnWatch() {
Timber.d("AttemptToStartApp")
coroutineScope.launch {
try {
val legacySetting = Preferences.getBoolean(preferences, MiscPreferences.AUTO_START)
val openType = if (legacySetting) {
AutoStartMode.OPEN_APP
} else {
Preferences.getEnum(preferences, MiscPreferences.AUTO_START_MODE)
}
val message = when (openType) {
AutoStartMode.OFF, null -> return@launch
AutoStartMode.SHOW_ICON -> CommPaths.MESSAGE_START_SERVICE
AutoStartMode.OPEN_APP -> CommPaths.MESSAGE_OPEN_APP
}
messageClient.sendMessageToNearestClient(nodeClient, message)
Timber.d("Start success")
} catch (e: Exception) {
Timber.e(e, "Start Fail")
}
}
}
private val mediaObserver = Observer<Resource<MediaController>> {
Timber.d("Playback update %b %s", MusicService.active, it?.data?.playbackState?.state)
if (!MusicService.active && it?.data?.playbackState?.isPlaying() == true) {
val autoStartBlacklist = Preferences.getStringSet(preferences, MiscPreferences.AUTO_START_APP_BLACKLIST)
if (!autoStartBlacklist.contains(it.data?.packageName)) {
startAppOnWatch()
}
}
}
companion object {
fun isEnabled(context: Context): Boolean {
val component = ComponentName(context, NotificationService::class.java)
val enabledListeners = Settings.Secure.getString(context.contentResolver,
"enabled_notification_listeners")
return enabledListeners != null && enabledListeners.contains(component.flattenToString())
}
const val ACTION_UNBIND_SERVICE = "UNBIND"
}
@TargetApi(Build.VERSION_CODES.N)
private fun requestUnbindSafe() {
try {
requestUnbind()
} catch (e: SecurityException) {
// Sometimes notification service may be unbound before we can unbind safely.
// just stop self.
stopSelf()
}
}
}
| gpl-3.0 | b0079eeaa0224da9602e0778dbdf1f29 | 34.535294 | 116 | 0.683496 | 5.158839 | false | false | false | false |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/McMiningOptimizer.kt | 1 | 3673 | package org.hildan.minecraft.mining.optimizer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.hildan.minecraft.mining.optimizer.blocks.Sample
import org.hildan.minecraft.mining.optimizer.geometry.Dimensions
import org.hildan.minecraft.mining.optimizer.ore.BlockType
import org.hildan.minecraft.mining.optimizer.ore.generateSamples
import org.hildan.minecraft.mining.optimizer.patterns.DiggingPattern
import org.hildan.minecraft.mining.optimizer.patterns.generated.GenerationConstraints
import org.hildan.minecraft.mining.optimizer.patterns.generated.PatternGenerator
import org.hildan.minecraft.mining.optimizer.statistics.EvaluatedPattern
import org.hildan.minecraft.mining.optimizer.statistics.PatternEvaluator
import org.hildan.minecraft.mining.optimizer.statistics.PatternStore
private const val NUM_EVAL_SAMPLES = 50
private const val SAMPLE_WIDTH = 16
private const val SAMPLE_HEIGHT = 5
private const val SAMPLE_LENGTH = 16
private const val SAMPLE_LOW_Y_POSITION = 5
private const val MAX_DUG_BLOCKS = 20
fun main() = runBlocking {
val sampleDimensions = Dimensions(SAMPLE_WIDTH, SAMPLE_HEIGHT, SAMPLE_LENGTH)
val constraints = GenerationConstraints(sampleDimensions, MAX_DUG_BLOCKS)
println("Generating $NUM_EVAL_SAMPLES reference samples with lowest Y=$SAMPLE_LOW_Y_POSITION...")
val referenceSamples = generateSamples(NUM_EVAL_SAMPLES, sampleDimensions, SAMPLE_LOW_Y_POSITION)
println("Starting pattern generation with constraints: $constraints")
val generatedPatterns = generatePatternsAsync(constraints)
println("Starting pattern evaluation on reference samples...")
val evaluatedPatterns = evaluateAsync(referenceSamples, generatedPatterns)
val store = storePatternsAndPrintProgress(evaluatedPatterns)
printBestPatterns(sampleDimensions, store)
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun CoroutineScope.generatePatternsAsync(constraints: GenerationConstraints): ReceiveChannel<DiggingPattern> =
produce(Dispatchers.Default, capacity = 200) {
PatternGenerator(constraints).forEach { send(it) }
close()
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun CoroutineScope.evaluateAsync(
referenceSamples: List<Sample>,
generatedPatterns: ReceiveChannel<DiggingPattern>
) = produce(Dispatchers.Default, capacity = 200) {
repeat(Runtime.getRuntime().availableProcessors() - 1) {
launch {
val patternEvaluator = PatternEvaluator(referenceSamples)
for (p in generatedPatterns) {
send(patternEvaluator.evaluate(p))
}
}
}
}
private suspend fun storePatternsAndPrintProgress(evaluatedPatterns: ReceiveChannel<EvaluatedPattern>): PatternStore {
val store = PatternStore()
var count = 0
for (p in evaluatedPatterns) {
count++
if (count % 10000 == 0) {
println("$count evaluated patterns so far")
}
if (store.add(p)) {
println(store)
}
}
println("Finished with $count total evaluated patterns")
return store
}
fun printBestPatterns(sampleDimensions: Dimensions, store: PatternStore) {
val sample = Sample(sampleDimensions, BlockType.STONE)
for (pattern in store) {
sample.fill(BlockType.STONE)
pattern.pattern.digInto(sample)
println(sample)
println(pattern.statistics.toFullString(NUM_EVAL_SAMPLES))
}
}
| mit | dbd04f00a662ce75884aaf416accbb7b | 37.663158 | 118 | 0.762864 | 4.562733 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/Video.kt | 1 | 6234 | @file:JvmName("VideoUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
import com.vimeo.networking2.common.Entity
import com.vimeo.networking2.enums.LicenseType
import com.vimeo.networking2.enums.VideoStatusType
import com.vimeo.networking2.enums.asEnum
import java.util.Date
/**
* Video data.
*
* @param badge Information for the video's badge.
* @param categories The categories to which this video belongs.
* @param contentRating The content ratings of this video.
* @param context The context of the video's subscription, if this video is part of a subscription.
* @param createdTime The time in ISO 8601 format when the video was created.
* @param description A brief explanation of the video's content.
* @param download A list of downloadable files.
* @param duration The video's duration in seconds.
* @param editSession Information about the Vimeo Create session of a video.
* @param embed Information about embedding this video.
* @param fileTransferPage Information about the file transfer page associated with this video. This data requires a
* bearer token with the private scope.
* @param height The video's height in pixels.
* @param isPlayable Whether the clip is playable.
* @param language The video's primary language.
* @param lastUserActionEventDate The time in ISO 8601 format when the user last modified the video.
* @param license The Creative Commons license used for the video. See [Video.licenseType].
* @param link The link to the video.
* @param live Live playback information.
* @param metadata The video's metadata.
* @param modifiedTime The time in ISO 8601 format when the video metadata was last modified.
* @param name The video's title.
* @param parentFolder Information about the folder that contains the video, or null if it is in the root directory.
* @param password The privacy-enabled password to watch this video. This data requires a bearer token with the private
* scope.
* @param pictures The active picture for this video.
* @param play The Play representation.
* @param privacy The video's privacy setting.
* @param releaseTime The time in ISO 8601 format when the video was released.
* @param resourceKey The resource key string of the video.
* @param reviewPage Information about the review page associated with this video. This data requires a bearer token
* with the private scope.
* @param spatial 360 spatial data.
* @param stats A collection of stats associated with this video.
* @param status The status code for the availability of the video. This field is deprecated in favor of [upload] and
* [transcode]. See [Video.statusType].
* @param tags An array of all tags assigned to this video.
* @param transcode The transcode information for a video upload.
* @param upload The upload information for this video.
* @param uri The video's canonical relative URI.
* @param user The video owner.
* @param width The video's width in pixels.
*/
@JsonClass(generateAdapter = true)
data class Video(
@Json(name = "badge")
val badge: VideoBadge? = null,
@Json(name = "categories")
val categories: List<Category>? = null,
@Json(name = "content_rating")
val contentRating: List<String>? = null,
@Json(name = "context")
val context: VideoContext? = null,
@Json(name = "created_time")
val createdTime: Date? = null,
@Json(name = "description")
val description: String? = null,
@Json(name = "download")
val download: List<DownloadableVideoFile>? = null,
@Json(name = "duration")
val duration: Int? = null,
@Json(name = "edit_session")
val editSession: EditSession? = null,
@Json(name = "embed")
val embed: VideoEmbed? = null,
@Internal
@Json(name = "file_transfer")
val fileTransferPage: FileTransferPage? = null,
@Json(name = "height")
val height: Int? = null,
@Json(name = "is_playable")
val isPlayable: Boolean? = null,
@Json(name = "language")
val language: String? = null,
@Json(name = "last_user_action_event_date")
val lastUserActionEventDate: Date? = null,
@Json(name = "license")
val license: String? = null,
@Json(name = "link")
val link: String? = null,
@Json(name = "live")
val live: Live? = null,
@Json(name = "metadata")
val metadata: Metadata<VideoConnections, VideoInteractions>? = null,
@Json(name = "modified_time")
val modifiedTime: Date? = null,
@Json(name = "name")
val name: String? = null,
@Json(name = "parent_project")
val parentFolder: Folder? = null,
@Internal
@Json(name = "password")
val password: String? = null,
@Json(name = "pictures")
val pictures: PictureCollection? = null,
@Internal
@Json(name = "play")
val play: Play? = null,
@Json(name = "privacy")
val privacy: Privacy? = null,
@Json(name = "release_time")
val releaseTime: Date? = null,
@Json(name = "resource_key")
val resourceKey: String? = null,
@Internal
@Json(name = "review_page")
val reviewPage: ReviewPage? = null,
@Json(name = "spatial")
val spatial: Spatial? = null,
@Json(name = "stats")
val stats: VideoStats? = null,
@Json(name = "status")
@Deprecated("This property is deprecated in favor of upload and transcode.")
val status: String? = null,
@Json(name = "tags")
val tags: List<Tag>? = null,
@Json(name = "transcode")
val transcode: Transcode? = null,
@Json(name = "upload")
val upload: Upload? = null,
@Json(name = "uri")
val uri: String? = null,
@Json(name = "user")
val user: User? = null,
@Json(name = "width")
val width: Int? = null
) : Entity {
override val identifier: String? = resourceKey
}
/**
* @see Video.license
* @see LicenseType
*/
val Video.licenseType: LicenseType
get() = license.asEnum(LicenseType.UNKNOWN)
/**
* @see Video.status
* @see VideoStatusType
*/
@Deprecated(message = "This property is deprecated in favor of upload and transcode.")
val Video.statusType: VideoStatusType
get() = status.asEnum(VideoStatusType.UNKNOWN)
| mit | dec5e34cc616ff1d38b0f42fb166a230 | 30.17 | 119 | 0.69153 | 3.879278 | false | false | false | false |
AndroidX/androidx | work/work-lint/src/test/java/androidx/work/lint/SpecifyForegroundServiceTypeIssueDetectorTest.kt | 3 | 7717 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work.lint
import androidx.work.lint.Stubs.FOREGROUND_INFO
import androidx.work.lint.Stubs.NOTIFICATION
import com.android.tools.lint.checks.infrastructure.LintDetectorTest.kotlin
import com.android.tools.lint.checks.infrastructure.LintDetectorTest.manifest
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.junit.Ignore
import org.junit.Test
class SpecifyForegroundServiceTypeIssueDetectorTest {
@Ignore("b/196831196")
@Test
fun failWhenServiceTypeIsNotSpecified() {
val application = kotlin(
"com/example/App.kt",
"""
package com.example
import android.app.Notification
import androidx.work.ForegroundInfo
class App {
fun onCreate() {
val notification = Notification()
val info = ForegroundInfo(0, notification, 1)
}
}
"""
).indented().within("src")
lint().files(
// Source files
NOTIFICATION,
FOREGROUND_INFO,
application
).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE)
.run()
/* ktlint-disable max-line-length */
.expect(
"""
src/com/example/App.kt:9: Error: Missing dataSync foregroundServiceType in the AndroidManifest.xml [SpecifyForegroundServiceType]
val info = ForegroundInfo(0, notification, 1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
""".trimIndent()
)
/* ktlint-enable max-line-length */
}
@Ignore("b/196831196")
@Test
fun failWhenSpecifiedServiceTypeIsInSufficient() {
val manifest = manifest(
"""
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example">
<application>
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:exported="false"
android:directBootAware="false"
android:enabled="@bool/enable_system_foreground_service_default"
android:foregroundServiceType="location"
tools:targetApi="n"/>
</application>
</manifest>
"""
).indented()
val application = kotlin(
"com/example/App.kt",
"""
package com.example
import android.app.Notification
import androidx.work.ForegroundInfo
class App {
fun onCreate() {
val notification = Notification()
val info = ForegroundInfo(0, notification, 9)
}
}
"""
).indented().within("src")
lint().files(
// Manifest
manifest,
// Sources
NOTIFICATION,
FOREGROUND_INFO,
application
).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE)
.run()
/* ktlint-disable max-line-length */
.expect(
"""
src/com/example/App.kt:9: Error: Missing dataSync foregroundServiceType in the AndroidManifest.xml [SpecifyForegroundServiceType]
val info = ForegroundInfo(0, notification, 9)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
""".trimIndent()
)
/* ktlint-enable max-line-length */
}
@Test
fun passWhenCorrectForegroundServiceTypeSpecified() {
val manifest = manifest(
"""
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example">
<application>
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:exported="false"
android:directBootAware="false"
android:enabled="@bool/enable_system_foreground_service_default"
android:foregroundServiceType="location"
tools:targetApi="n"/>
</application>
</manifest>
"""
).indented()
val application = kotlin(
"com/example/App.kt",
"""
package com.example
import android.app.Notification
import androidx.work.ForegroundInfo
class App {
fun onCreate() {
val notification = Notification()
val info = ForegroundInfo(0, notification, 8)
}
}
"""
).indented().within("src")
lint().files(
// Manifest
manifest,
// Sources
NOTIFICATION,
FOREGROUND_INFO,
application
).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE)
.run()
.expectClean()
}
@Test
fun passWhenMultipleForegroundServiceTypeSpecified() {
val manifest = manifest(
"""
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example">
<application>
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:exported="false"
android:directBootAware="false"
android:enabled="@bool/enable_system_foreground_service_default"
android:foregroundServiceType="dataSync|location"
tools:targetApi="n"/>
</application>
</manifest>
"""
).indented()
val application = kotlin(
"com/example/App.kt",
"""
package com.example
import android.app.Notification
import androidx.work.ForegroundInfo
class App {
fun onCreate() {
val notification = Notification()
val info = ForegroundInfo(0, notification, 9)
}
}
"""
).indented().within("src")
lint().files(
// Manifest
manifest,
// Sources
NOTIFICATION,
FOREGROUND_INFO,
application
).issues(SpecifyForegroundServiceTypeIssueDetector.ISSUE)
.run()
.expectClean()
}
}
| apache-2.0 | 39654bd701cc320361ef3acca39e9e3e | 33.605381 | 145 | 0.522353 | 5.645208 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/execution/model/rules/cleanup/StopContainerStepRuleSpec.kt | 1 | 4422 | /*
Copyright 2017-2020 Charles Korn.
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 batect.execution.model.rules.cleanup
import batect.config.Container
import batect.docker.DockerContainer
import batect.execution.model.events.ContainerStoppedEvent
import batect.execution.model.rules.TaskStepRuleEvaluationResult
import batect.execution.model.steps.StopContainerStep
import batect.os.OperatingSystem
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.imageSourceDoesNotMatter
import batect.testutils.on
import com.natpryce.hamkrest.assertion.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object StopContainerStepRuleSpec : Spek({
describe("a stop container step rule") {
val containerToStop = Container("the-container", imageSourceDoesNotMatter())
val dockerContainerToStop = DockerContainer("some-container-id")
given("there are no containers that must be stopped first") {
val rule = StopContainerStepRule(containerToStop, dockerContainerToStop, emptySet())
on("evaluating the rule") {
val result = rule.evaluate(emptySet())
it("returns a 'stop container' step") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.Ready(StopContainerStep(containerToStop, dockerContainerToStop))))
}
}
on("toString()") {
it("returns a human-readable representation of itself") {
assertThat(rule.toString(), equalTo("StopContainerStepRule(container: 'the-container', Docker container: 'some-container-id', containers that must be stopped first: [])"))
}
}
}
given("there are some containers that must be stopped first") {
val container1 = Container("container-1", imageSourceDoesNotMatter())
val container2 = Container("container-2", imageSourceDoesNotMatter())
val rule = StopContainerStepRule(containerToStop, dockerContainerToStop, setOf(container1, container2))
given("those containers have been stopped") {
val events = setOf(
ContainerStoppedEvent(container1),
ContainerStoppedEvent(container2)
)
on("evaluating the rule") {
val result = rule.evaluate(events)
it("returns a 'stop container' step") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.Ready(StopContainerStep(containerToStop, dockerContainerToStop))))
}
}
}
given("those containers have not been stopped") {
on("evaluating the rule") {
val result = rule.evaluate(emptySet())
it("indicates that the step is not yet ready") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.NotReady))
}
}
}
on("toString()") {
it("returns a human-readable representation of itself") {
assertThat(rule.toString(), equalTo("StopContainerStepRule(container: 'the-container', Docker container: 'some-container-id', containers that must be stopped first: ['container-1', 'container-2'])"))
}
}
}
on("getting the manual cleanup instruction") {
val rule = StopContainerStepRule(containerToStop, dockerContainerToStop, emptySet())
val instruction = rule.getManualCleanupInstructionForOperatingSystem(OperatingSystem.Other)
it("returns no instruction, since it will be covered by the removal rule's instruction") {
assertThat(instruction, equalTo(null))
}
}
}
})
| apache-2.0 | bce1458e19e35d2b0f1dd466bfd17f08 | 42.352941 | 219 | 0.651063 | 5.493168 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/model/Pago.kt | 1 | 863 | package com.quijotelui.model
import org.hibernate.annotations.Immutable
import java.io.Serializable
import java.math.BigDecimal
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Immutable
@Table(name = "v_ele_pagos")
class Pago : Serializable {
@Id
@Column(name = "id")
var id : Long? = null
@Column(name = "codigo")
var codigo : String? = null
@Column(name = "numero")
var numero : String? = null
@Column(name = "forma_pago")
var formaPago : String? = null
@Column(name = "forma_pago_descripcion")
var formaPagoDescripcion : String? = null
@Column(name = "total")
var total : BigDecimal? = null
@Column(name = "plazo")
var plazo : String? = null
@Column(name = "tiempo")
var tiempo : String? = null
}
| gpl-3.0 | 93d0a8f2900cad1ba5a2d5622e808acc | 20.04878 | 45 | 0.669757 | 3.424603 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogContent.kt | 1 | 1739 | package com.habitrpg.android.habitica.ui.views.shops
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import coil.load
import com.habitrpg.android.habitica.extensions.dpToPx
import com.habitrpg.android.habitica.extensions.fromHtml
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.models.shops.ShopItem
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.helpers.loadImage
abstract class PurchaseDialogContent @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
abstract val imageView: ImageView
abstract val titleTextView: TextView
init {
orientation = VERTICAL
gravity = Gravity.CENTER
}
open fun setItem(item: ShopItem) {
if (item.path?.contains("timeTravelBackgrounds") == true) {
imageView.load("${DataBindingUtils.BASE_IMAGE_URL}${item.imageName?.replace("icon_", "")}.gif")
val params = imageView.layoutParams
params.height = 147.dpToPx(context)
params.width = 140.dpToPx(context)
imageView.layoutParams = params
} else {
imageView.loadImage(item.imageName)
}
titleTextView.text = item.text
}
open fun setQuestContentItem(questContent: QuestContent) {
imageView.loadImage("inventory_quest_scroll_" + questContent.key)
titleTextView.setText(questContent.text.fromHtml(), TextView.BufferType.SPANNABLE)
}
}
| gpl-3.0 | 211afd27160425ed55e5f36752297361 | 35.229167 | 107 | 0.73088 | 4.564304 | false | false | false | false |
vdewillem/dynamic-extensions-for-alfresco | alfresco-integration/src/main/kotlin/com/github/dynamicextensionsalfresco/osgi/Configuration.kt | 1 | 595 | package com.github.dynamicextensionsalfresco.osgi
import java.io.File
/**
* Value object representing the OSGi container configuration;
* @author Laurens Fridael
*/
public class Configuration {
var frameworkRestartEnabled = true
var hotDeployEnabled = true
var repositoryBundlesEnabled = true
var storageDirectory: File? = null
get() = $storageDirectory ?: File(System.getProperty("java.io.tmpdir"), "bundles")
var systemPackageCacheMode: PackageCacheMode? = null
val systemPackageCache = File(System.getProperty("java.io.tmpdir"), "system-packages.txt")
}
| apache-2.0 | 2410dd7768c99740c96d2f6d3abf61dc | 23.791667 | 94 | 0.744538 | 4.280576 | false | true | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/GLXTypes.kt | 1 | 1236 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl
import org.lwjgl.generator.*
import org.lwjgl.system.linux.*
val GLXContext = "GLXContext".opaque_p
val GLXFBConfig = "GLXFBConfig".opaque_p
val GLXFBConfig_p = GLXFBConfig.p
val GLXFBConfigSGIX = "GLXFBConfigSGIX".opaque_p
val GLXFBConfigSGIX_p = GLXFBConfigSGIX.p
val GLXWindow = "GLXWindow".opaque_p
val GLXDrawable = "GLXDrawable".opaque_p
val GLXPixmap = "GLXPixmap".opaque_p
val GLXContextID = typedef(XID, "GLXContextID")
val GLXPbuffer = "GLXPbuffer".opaque_p
fun configGLX() {
struct(OPENGL_PACKAGE, "GLXStereoNotifyEventEXT", "glx", mutable = false) {
int.member("type", "GenericEvent")
unsigned_long.member("serial", "\\# of last request server processed")
Bool.member("send_event", "{@code True} if generated by {@code SendEvent} request")
Display_p.member("display", "display the event was read from")
int.member("extension", "GLX major opcode, from {@code XQueryExtension}")
int.member("evtype", "always {@code GLX_STEREO_NOTIFY_EXT}")
GLXDrawable.member("window", "XID of the X window affected")
Bool.member("stereo_tree", "{@code True} if tree contains stereo windows")
}
} | bsd-3-clause | 56aeed7ba15746941e23d325c5cb5e89 | 32.432432 | 85 | 0.73301 | 3.442897 | false | true | false | false |
veyndan/reddit-client | app/src/main/java/com/veyndan/paper/reddit/post/media/mutator/ImgurMutatorFactory.kt | 2 | 4752 | package com.veyndan.paper.reddit.post.media.mutator
import android.support.annotation.StringRes
import android.util.Size
import com.veyndan.paper.reddit.BuildConfig
import com.veyndan.paper.reddit.api.imgur.network.ImgurService
import com.veyndan.paper.reddit.api.reddit.model.PostHint
import com.veyndan.paper.reddit.api.reddit.model.Source
import com.veyndan.paper.reddit.post.media.model.Image
import com.veyndan.paper.reddit.post.model.Post
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
class ImgurMutatorFactory : MutatorFactory {
companion object {
val REGEX = Regex("""^https?://(?:m\.|www\.)?(i\.)?imgur\.com/(a/|gallery/)?(.*)$""")
}
override fun mutate(post: Post): Maybe<Post> {
val matchResult = REGEX.matchEntire(post.linkUrl)
return Single.just(post)
.filter {BuildConfig.HAS_IMGUR_API_CREDENTIALS && matchResult != null}
.map {
val isAlbum = matchResult!!.groupValues[2].isNotEmpty()
val isDirectImage = matchResult.groupValues[1].isNotEmpty()
var linkUrl: String = it.linkUrl
var postHint: PostHint = it.postHint
if (!isAlbum && !isDirectImage) {
// TODO .gifv links are HTML 5 videos so the PostHint should be set accordingly.
if (!linkUrl.endsWith(".gifv")) {
linkUrl = singleImageUrlToDirectImageUrl(linkUrl)
postHint = PostHint.IMAGE
}
}
val images: Observable<Image>
if (isAlbum) {
postHint = PostHint.IMAGE
val client: OkHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
val request: Request = chain.request().newBuilder()
.addHeader("Authorization", "Client-ID ${BuildConfig.IMGUR_API_KEY}")
.build()
chain.proceed(request)
}
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://api.imgur.com/3/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.client(client)
.build()
val imgurService: ImgurService = retrofit.create(ImgurService::class.java)
val id: String = matchResult.groupValues[3]
images = imgurService.album(id)
.flattenAsObservable { basic -> basic.body()!!.data.images }
.map { (width, height, link) -> Image(link, Size(width, height)) }
} else {
val imageDimensAvailable: Boolean = it.preview.images.isNotEmpty()
val url: String = if (linkUrl.endsWith(".gifv") && imageDimensAvailable) it.preview.images[0].source.url else linkUrl
val size = if (imageDimensAvailable) {
val source: Source = it.preview.images[0].source
Size(source.width, source.height)
} else {
Size(0, 0)
}
@StringRes val type: Int = if (linkUrl.endsWith(".gif") || linkUrl.endsWith(".gifv")) Image.IMAGE_TYPE_GIF else Image.IMAGE_TYPE_STANDARD
images = Observable.just(Image(url, size, type))
}
it.copy(it.medias.concatWith(images), linkUrl = linkUrl, postHint = postHint)
}
}
/**
* Returns a direct image url
* (e.g. <a href="http://i.imgur.com/1AGVxLl.png">http://i.imgur.com/1AGVxLl.png</a>) from a
* single image url (e.g. <a href="http://imgur.com/1AGVxLl">http://imgur.com/1AGVxLl</a>)
*
* @param url The single image url.
* @return The direct image url.
*/
private fun singleImageUrlToDirectImageUrl(url: String): String {
return "${HttpUrl.parse(url)!!.newBuilder().host("i.imgur.com").build()}.png"
}
}
| mit | ef98791099685f066a3f885817f1052f | 43 | 161 | 0.5383 | 4.888889 | false | false | false | false |
SimpleMobileTools/Simple-Calculator | app/src/main/kotlin/com/simplemobiletools/calculator/activities/WidgetConfigureActivity.kt | 1 | 6197 | package com.simplemobiletools.calculator.activities
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.RemoteViews
import android.widget.SeekBar
import com.simplemobiletools.calculator.R
import com.simplemobiletools.calculator.extensions.config
import com.simplemobiletools.calculator.helpers.MyWidgetProvider
import com.simplemobiletools.commons.dialogs.ColorPickerDialog
import com.simplemobiletools.commons.dialogs.FeatureLockedDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.IS_CUSTOMIZING_COLORS
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.widget_config.*
class WidgetConfigureActivity : SimpleActivity() {
private var mBgAlpha = 0f
private var mWidgetId = 0
private var mBgColor = 0
private var mTextColor = 0
private var mBgColorWithoutTransparency = 0
private var mFeatureLockedDialog: FeatureLockedDialog? = null
public override fun onCreate(savedInstanceState: Bundle?) {
useDynamicTheme = false
super.onCreate(savedInstanceState)
setResult(Activity.RESULT_CANCELED)
setContentView(R.layout.widget_config)
initVariables()
val isCustomizingColors = intent.extras?.getBoolean(IS_CUSTOMIZING_COLORS) ?: false
mWidgetId = intent.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID
if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID && !isCustomizingColors) {
finish()
}
config_save.setOnClickListener { saveConfig() }
config_bg_color.setOnClickListener { pickBackgroundColor() }
config_text_color.setOnClickListener { pickTextColor() }
val primaryColor = getProperPrimaryColor()
config_bg_seekbar.setColors(mTextColor, primaryColor, primaryColor)
if (!isCustomizingColors && !isOrWasThankYouInstalled()) {
mFeatureLockedDialog = FeatureLockedDialog(this) {
if (!isOrWasThankYouInstalled()) {
finish()
}
}
}
}
override fun onResume() {
super.onResume()
window.decorView.setBackgroundColor(0)
if (mFeatureLockedDialog != null && isOrWasThankYouInstalled()) {
mFeatureLockedDialog?.dismissDialog()
}
setupToolbar(config_toolbar)
}
private fun initVariables() {
mBgColor = config.widgetBgColor
mBgAlpha = Color.alpha(mBgColor) / 255.toFloat()
btn_reset.beVisible()
mBgColorWithoutTransparency = Color.rgb(Color.red(mBgColor), Color.green(mBgColor), Color.blue(mBgColor))
config_bg_seekbar.setOnSeekBarChangeListener(seekbarChangeListener)
config_bg_seekbar.progress = (mBgAlpha * 100).toInt()
updateBackgroundColor()
mTextColor = config.widgetTextColor
updateTextColor()
formula.text = "15,937*5"
result.text = "79,685"
}
private fun saveConfig() {
val appWidgetManager = AppWidgetManager.getInstance(this) ?: return
val views = RemoteViews(packageName, R.layout.widget).apply {
applyColorFilter(R.id.widget_background, mBgColor)
}
appWidgetManager.updateAppWidget(mWidgetId, views)
storeWidgetColors()
requestWidgetUpdate()
Intent().apply {
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId)
setResult(Activity.RESULT_OK, this)
}
finish()
}
private fun storeWidgetColors() {
config.apply {
widgetBgColor = mBgColor
widgetTextColor = mTextColor
}
}
private fun requestWidgetUpdate() {
Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java).apply {
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId))
sendBroadcast(this)
}
}
private fun updateBackgroundColor() {
mBgColor = mBgColorWithoutTransparency.adjustAlpha(mBgAlpha)
widget_background.applyColorFilter(mBgColor)
config_bg_color.setFillWithStroke(mBgColor, mBgColor)
config_save.backgroundTintList = ColorStateList.valueOf(getProperPrimaryColor())
}
private fun updateTextColor() {
config_text_color.setFillWithStroke(mTextColor, mTextColor)
val viewIds = intArrayOf(
R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4, R.id.btn_5, R.id.btn_6, R.id.btn_7, R.id.btn_8,
R.id.btn_9, R.id.btn_percent, R.id.btn_power, R.id.btn_root, R.id.btn_clear, R.id.btn_reset, R.id.btn_divide, R.id.btn_multiply,
R.id.btn_minus, R.id.btn_plus, R.id.btn_decimal, R.id.btn_equals
)
result.setTextColor(mTextColor)
formula.setTextColor(mTextColor)
config_save.setTextColor(getProperPrimaryColor().getContrastColor())
viewIds.forEach {
(findViewById<Button>(it)).setTextColor(mTextColor)
}
}
private fun pickBackgroundColor() {
ColorPickerDialog(this, mBgColorWithoutTransparency) { wasPositivePressed, color ->
if (wasPositivePressed) {
mBgColorWithoutTransparency = color
updateBackgroundColor()
}
}
}
private fun pickTextColor() {
ColorPickerDialog(this, mTextColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
mTextColor = color
updateTextColor()
}
}
}
private val seekbarChangeListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
mBgAlpha = progress.toFloat() / 100.toFloat()
updateBackgroundColor()
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
}
}
| gpl-3.0 | 62787205dfdf83186e6b02c52fb20ebf | 35.239766 | 140 | 0.675811 | 4.807603 | false | true | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/settings/SettingsActivity.kt | 2 | 3139 | package ru.fantlab.android.ui.modules.settings
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_settings.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.SettingsModel
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.ui.adapter.SettingsAdapter
import ru.fantlab.android.ui.base.BaseActivity
import ru.fantlab.android.ui.modules.settings.category.SettingsCategoryActivity
import ru.fantlab.android.ui.modules.theme.ThemeActivity
import ru.fantlab.android.ui.widgets.dialog.FontScaleBottomSheetDialog
import ru.fantlab.android.ui.widgets.dialog.LanguageBottomSheetDialog
import kotlin.reflect.KFunction0
class SettingsActivity : BaseActivity<SettingsMvp.View, SettingsPresenter>(), SettingsMvp.View,
LanguageBottomSheetDialog.LanguageDialogViewActionCallback{
override fun isTransparent(): Boolean = false
override fun providePresenter(): SettingsPresenter = SettingsPresenter()
override fun layout(): Int = R.layout.activity_settings
override fun canBack(): Boolean = true
private val adapter: SettingsAdapter by lazy { SettingsAdapter(arrayListOf()) }
private val THEME_CHANGE = 55
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = getString(R.string.settings)
if (savedInstanceState == null) {
setResult(RESULT_CANCELED)
}
adapter.listener = presenter
recycler.addDivider()
recycler.adapter = adapter
adapter.addItem(SettingsModel(R.drawable.ic_language, getString(R.string.language), "", SettingsModel.LANGUAGE))
adapter.addItem(SettingsModel(R.drawable.ic_theme, getString(R.string.theme_title), "", SettingsModel.THEME))
//adapter.addItem(SettingsModel(R.drawable.ic_forum, getString(R.string.forum), "", SettingsModel.FORUM))
adapter.addItem(SettingsModel(R.drawable.ic_custom, getString(R.string.customization), getString(R.string.customizationHint), SettingsModel.CUSTOMIZATION))
hideShowShadow(true)
}
override fun onItemClicked(item: SettingsModel) {
when (item.settingsType) {
SettingsModel.THEME -> {
startActivityForResult(Intent(this, ThemeActivity::class.java), THEME_CHANGE)
}
SettingsModel.LANGUAGE -> {
showLanguageList()
}
else -> {
val intent = Intent(this, SettingsCategoryActivity::class.java)
intent.putExtras(Bundler.start()
.put(BundleConstant.ITEM, item.settingsType)
.put(BundleConstant.EXTRA, item.title)
.end())
startActivity(intent)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == THEME_CHANGE && resultCode == Activity.RESULT_OK) {
setResult(resultCode)
finish()
}
}
private fun showLanguageList() {
val languageBottomSheetDialog = LanguageBottomSheetDialog()
languageBottomSheetDialog.onAttach(this as Context)
languageBottomSheetDialog.show(supportFragmentManager, "LanguageBottomSheetDialog")
}
override fun onLanguageChanged() {
setResult(Activity.RESULT_OK)
finish()
}
} | gpl-3.0 | c323989885c6f92b1a799195eb676e15 | 36.380952 | 157 | 0.783371 | 4.071336 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/debugger/LuaDebuggerEvaluator.kt | 2 | 3412 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* 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.tang.intellij.lua.debugger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.tang.intellij.lua.psi.*
/**
*
* Created by tangzx on 2017/5/1.
*/
abstract class LuaDebuggerEvaluator : XDebuggerEvaluator() {
override fun getExpressionRangeAtOffset(project: Project, document: Document, offset: Int, sideEffectsAllowed: Boolean): TextRange? {
var currentRange: TextRange? = null
PsiDocumentManager.getInstance(project).commitAndRunReadAction {
try {
val file = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return@commitAndRunReadAction
if (currentRange == null) {
val ele = file.findElementAt(offset)
if (ele != null && ele.node.elementType == LuaTypes.ID) {
val parent = ele.parent
when (parent) {
is LuaFuncDef,
is LuaLocalFuncDef -> currentRange = ele.textRange
is LuaClassMethodName,
is PsiNameIdentifierOwner -> currentRange = parent.textRange
}
}
}
if (currentRange == null) {
val expr = PsiTreeUtil.findElementOfClassAtOffset(file, offset, LuaExpr::class.java, false)
currentRange = when (expr) {
is LuaCallExpr,
is LuaClosureExpr,
is LuaLiteralExpr -> null
else -> expr?.textRange
}
}
} catch (ignored: IndexNotReadyException) {
}
}
return currentRange
}
override fun evaluate(express: String, xEvaluationCallback: XDebuggerEvaluator.XEvaluationCallback, xSourcePosition: XSourcePosition?) {
var expr = express.trim()
if (!expr.endsWith(')')) {
val lastDot = express.lastIndexOf('.')
val lastColon = express.lastIndexOf(':')
if (lastColon > lastDot) // a:xx -> a.xx
expr = expr.replaceRange(lastColon, lastColon + 1, ".")
}
eval(expr, xEvaluationCallback, xSourcePosition)
}
protected abstract fun eval(express: String, xEvaluationCallback: XDebuggerEvaluator.XEvaluationCallback, xSourcePosition: XSourcePosition?)
}
| apache-2.0 | ca938adbec2208208cb6608611b7ac54 | 41.65 | 144 | 0.630715 | 5.18541 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/general/PriorityThreadPoolExecutor.kt | 1 | 1601 | package com.intfocus.template.general
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
/**
* @author liuruilin
* @data 2017/11/30
* @describe 带有开始/暂停功能的线程池
*/
class PriorityThreadPoolExecutor(
corePoolSize: Int,
maximumPoolSize: Int,
keepAliveTime: Long,
unit: TimeUnit,
workQueue: PriorityBlockingQueue<Runnable>,
factory: ThreadFactory
): ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory) {
private var isPause = false
private var pauseLock = ReentrantLock()
private var unPaused = pauseLock.newCondition()
/**
* 线程池任务执行前调用
*/
override fun beforeExecute(t: Thread?, r: Runnable?) {
super.beforeExecute(t, r)
}
/**
* 线程池任务执行完毕后调用
*/
override fun afterExecute(r: Runnable?, t: Throwable?) {
super.afterExecute(r, t)
}
fun pause() {
pauseLock.lock()
try {
isPause = true
}
finally {
pauseLock.unlock()
}
}
fun resume() {
pauseLock.lock()
try {
isPause = false
unPaused.signalAll()
}
finally {
pauseLock.unlock()
}
}
/**
* 线程池终止后调用
*/
override fun terminated() {
super.terminated()
}
}
| gpl-3.0 | 8dc5441cbe87d20d561a607339afa93a | 21.641791 | 95 | 0.60646 | 4.44868 | false | false | false | false |
JavaEden/Orchid | plugins/OrchidKSS/src/main/kotlin/com/eden/orchid/kss/menu/StyleguidePagesMenuItemType.kt | 2 | 1760 | package com.eden.orchid.kss.menu
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.kss.model.KssModel
import com.eden.orchid.kss.pages.KssPage
@Description("All pages in your styleguide, optionally by section.", name = "Styleguide")
class StyleguidePagesMenuItemType : OrchidMenuFactory("styleguide") {
@Option
@Description("The Styleguide section to get pages for.")
lateinit var section: String
override fun getMenuItems(
context: OrchidContext,
page: OrchidPage
): List<MenuItem> {
val model = context.resolve(KssModel::class.java)
val menuItems = ArrayList<MenuItem>()
val pages = model.getSectionRoot(section)
if (pages.isNotEmpty()) {
menuItems.add(getChildMenuItem(context, null, pages))
}
return menuItems
}
private fun getChildMenuItem(context: OrchidContext, parent: KssPage?, childPages: List<KssPage>): MenuItem {
val childMenuItems = ArrayList<MenuItem>()
val title: String?
if (parent != null) {
childMenuItems.add(MenuItem.Builder(context).page(parent).build())
title = parent.title
} else {
title = "Styleguide Pages"
}
childPages.forEach {
childMenuItems.add(getChildMenuItem(context, it, it.children))
}
return MenuItem.Builder(context)
.title(title)
.children(childMenuItems)
.build()
}
}
| lgpl-3.0 | 8adc55c112678c56f15d3260fa10e5ee | 29.344828 | 113 | 0.672159 | 4.313725 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/lib/src/main/kotlin/jupyter/kotlin/context.kt | 1 | 2058 | package jupyter.kotlin
import java.util.HashMap
import kotlin.reflect.KFunction
import kotlin.reflect.KProperty
/**
* Kotlin REPL has built-in context for getting user-declared functions and variables
* and setting invokeWrapper for additional side effects in evaluation.
* It can be accessed inside REPL by name `kc`, e.g. kc.showVars()
*/
class KotlinContext(
val vars: HashMap<String, KotlinVariableInfo> = HashMap(),
val functions: HashMap<String, KotlinFunctionInfo> = HashMap()
)
private fun functionSignature(function: KFunction<*>) =
function.toString().replace("Line_\\d+\\.".toRegex(), "")
private fun shortenType(name: String) =
name.replace("(\\b[_a-zA-Z$][_a-zA-Z0-9$]*\\b\\.)+".toRegex(), "")
class KotlinFunctionInfo(val function: KFunction<*>, val line: Any) : Comparable<KotlinFunctionInfo> {
val name: String
get() = function.name
fun toString(shortenTypes: Boolean): String {
return if (shortenTypes) {
shortenType(toString())
} else toString()
}
override fun toString(): String {
return functionSignature(function)
}
override fun compareTo(other: KotlinFunctionInfo): Int {
return this.toString().compareTo(other.toString())
}
override fun hashCode(): Int {
return this.toString().hashCode()
}
override fun equals(other: Any?): Boolean {
return if (other is KotlinFunctionInfo) {
this.toString() == other.toString()
} else false
}
}
class KotlinVariableInfo(val value: Any?, val descriptor: KProperty<*>, val line: Any) {
val name: String
get() = descriptor.name
@Suppress("MemberVisibilityCanBePrivate")
val type: String
get() = descriptor.returnType.toString()
fun toString(shortenTypes: Boolean): String {
var type: String = type
if (shortenTypes) {
type = shortenType(type)
}
return "$name: $type = $value"
}
override fun toString(): String {
return toString(false)
}
}
| apache-2.0 | ca84c532a74395a30fe07489801bad59 | 27.191781 | 102 | 0.648202 | 4.341772 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz_choice/ui/delegate/ChoiceStepQuizFormDelegate.kt | 2 | 4265 | package org.stepik.android.view.step_quiz_choice.ui.delegate
import android.view.View
import androidx.annotation.StringRes
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_step_quiz.view.*
import kotlinx.android.synthetic.main.layout_step_quiz_choice.view.*
import org.stepic.droid.R
import org.stepik.android.model.Reply
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.model.ReplyResult
import org.stepik.android.view.step_quiz.resolver.StepQuizFormResolver
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate
import org.stepik.android.view.step_quiz_choice.mapper.ChoiceStepQuizOptionsMapper
import org.stepik.android.view.step_quiz_choice.model.Choice
import org.stepik.android.view.step_quiz_choice.ui.adapter.ChoicesAdapterDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.ui.adapters.selection.MultipleChoiceSelectionHelper
import ru.nobird.android.ui.adapters.selection.SelectionHelper
import ru.nobird.android.ui.adapters.selection.SingleChoiceSelectionHelper
class ChoiceStepQuizFormDelegate(
containerView: View,
private val onQuizChanged: (ReplyResult) -> Unit
) : StepQuizFormDelegate {
private val context = containerView.context
private val quizDescription = containerView.stepQuizDescription
private val choiceStepQuizOptionsMapper = ChoiceStepQuizOptionsMapper()
private var choicesAdapter: DefaultDelegateAdapter<Choice> = DefaultDelegateAdapter()
private lateinit var selectionHelper: SelectionHelper
init {
containerView.choicesRecycler.apply {
itemAnimator = null
adapter = choicesAdapter
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
isNestedScrollingEnabled = false
}
}
override fun setState(state: StepQuizFeature.State.AttemptLoaded) {
val dataset = state.attempt.dataset ?: return
@StringRes
val descriptionRes =
if (dataset.isMultipleChoice) {
R.string.step_quiz_choice_description_multiple
} else {
R.string.step_quiz_choice_description_single
}
quizDescription.setText(descriptionRes)
val submission = (state.submissionState as? StepQuizFeature.SubmissionState.Loaded)
?.submission
val reply = submission?.reply
if (!::selectionHelper.isInitialized) {
selectionHelper =
if (dataset.isMultipleChoice) {
MultipleChoiceSelectionHelper(choicesAdapter)
} else {
SingleChoiceSelectionHelper(choicesAdapter)
}
choicesAdapter += ChoicesAdapterDelegate(selectionHelper, onClick = ::handleChoiceClick)
}
choicesAdapter.items = choiceStepQuizOptionsMapper.mapChoices(
dataset.options ?: emptyList(),
reply?.choices,
submission,
StepQuizFormResolver.isQuizEnabled(state)
)
selectionHelper.reset()
reply?.choices?.let {
it.forEachIndexed { index, choice ->
if (choice) {
selectionHelper.select(index)
}
}
}
}
override fun createReply(): ReplyResult {
val choices = (0 until choicesAdapter.itemCount).map { selectionHelper.isSelected(it) }
return if ((true !in choices && selectionHelper is SingleChoiceSelectionHelper)) {
ReplyResult(Reply(choices = choices), ReplyResult.Validation.Error(context.getString(R.string.step_quiz_choice_empty_reply)))
} else {
ReplyResult(Reply(choices = choices), ReplyResult.Validation.Success)
}
}
private fun handleChoiceClick(choice: Choice) {
when (selectionHelper) {
is SingleChoiceSelectionHelper ->
selectionHelper.select(choicesAdapter.items.indexOf(choice))
is MultipleChoiceSelectionHelper ->
selectionHelper.toggle(choicesAdapter.items.indexOf(choice))
}
onQuizChanged(createReply())
}
} | apache-2.0 | 9af1597b48ae4bdb2d974ce4f5257d05 | 39.628571 | 137 | 0.696835 | 5.150966 | false | false | false | false |
Asqatasun/Asqatasun | server/asqatasun-server/src/main/kotlin/org/asqatasun/web/user/UserDetailsService.kt | 1 | 1316 | package org.asqatasun.web.user
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl
import org.springframework.stereotype.Service
import javax.annotation.PostConstruct
import javax.sql.DataSource
@Service
class UserDetailsService(private val asqaDataSource: DataSource) : JdbcDaoImpl() {
@PostConstruct
fun init() {
setDataSource(asqaDataSource)
usersByUsernameQuery = USERS_BY_USERNAME_QUERY
authoritiesByUsernameQuery = AUTHORITIES_BY_USERNAME_QUERY
}
override fun createUserDetails(username: String, userFromUserQuery: UserDetails,
combinedAuthorities: List<GrantedAuthority>): UserDetails {
return User(username, userFromUserQuery.password, combinedAuthorities)
}
companion object {
private const val USERS_BY_USERNAME_QUERY = "SELECT Email1, Password, Activated as enabled FROM USER WHERE Email1=?"
private const val AUTHORITIES_BY_USERNAME_QUERY = ("SELECT USER.Email1, ROLE.Role_Name as authorities FROM USER, ROLE "
+ "WHERE USER.Email1 = ? AND USER.ROLE_Id_Role=ROLE.Id_Role")
}
}
| agpl-3.0 | ab5b91549d813d9478df12df45da81a8 | 41.451613 | 127 | 0.75 | 4.601399 | false | false | false | false |
kittttttan/pe | kt/pe/src/main/kotlin/ktn/pe/Main.kt | 1 | 4473 | package ktn.pe
import java.util.Arrays
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
*
*/
object Main {
private const val PROBLEM_MIN = 1
private const val PROBLEM_MAX = 12
private const val THREAD_COUNT = 4
/**
* @param args
* problemNumber options...
*/
@JvmStatic
fun main(args: Array<String>) {
if (args.isEmpty()) {
help()
} else if ("-h" == args[0] || "--help" == args[0]) {
help()
} else if ("-a" == args[0]) {
solveAll()
} else if ("-A" == args[0]) {
var n = -1
if (args.size > 1) {
n = args[1].toInt()
}
solveAllAsync(n)
} else {
if (!solve(args)) {
help()
}
}
}
/**
* Show help
*/
private fun help() {
println("problemNumber options...")
println("-a all")
println("-A [n] all async with n threads")
println("-h help")
}
/**
*
* @param n
* @return
*/
private fun loadClassName(n: Int): String {
return Main::class.java.`package`.name + ".Pe" + n
}
/**
*
* @param args
* commandline options
* @return true means
*/
internal fun solve(args: Array<String>): Boolean {
var done = false
try {
val n = args[0].toInt()
if (n < PROBLEM_MIN || n > PROBLEM_MAX) {
return done
}
val loader = ClassLoader.getSystemClassLoader()
val clazz = loader.loadClass(loadClassName(n))
val pe = clazz.newInstance() as Pe
val shiftedArgs = Arrays.copyOfRange(args, 1, args.size)
pe.setArgs(shiftedArgs)
val start = System.currentTimeMillis()
pe.solve()
val stop = System.currentTimeMillis()
println((stop - start).toString() + " ms")
done = true
} catch (e: NumberFormatException) {
System.err.println(e.toString())
} catch (e: ClassNotFoundException) {
System.err.println(e.toString())
} catch (e: InstantiationException) {
System.err.println(e.toString())
} catch (e: IllegalAccessException) {
System.err.println(e.toString())
}
return done
}
private fun solveAll() {
val loader = ClassLoader.getSystemClassLoader()
var clazz: Class<*>
var pe: Pe
val start = System.currentTimeMillis()
try {
for (i in PROBLEM_MIN until PROBLEM_MAX + 1) {
clazz = loader.loadClass(loadClassName(i))
pe = clazz.newInstance() as Pe
pe.solve()
}
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: InstantiationException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
val stop = System.currentTimeMillis()
println((stop - start).toString() + " ms")
}
private fun solveAllAsync(n: Int) {
var threadCount = THREAD_COUNT
if (n > 0) {
threadCount = n
}
val executor = Executors.newFixedThreadPool(threadCount)
val loader = ClassLoader.getSystemClassLoader()
val start = System.currentTimeMillis()
try {
(PROBLEM_MIN until PROBLEM_MAX + 1)
.map { loader.loadClass(loadClassName(it)) }
.map { it.getDeclaredConstructor().newInstance() as Pe }
.forEach { executor.execute(it) }
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: InstantiationException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
val awaitTime = (30 * 1000).toLong()
try {
executor.shutdown()
if (!executor.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)) {
executor.shutdownNow()
}
} catch (e: InterruptedException) {
println("awaitTermination interrupted: " + e)
executor.shutdownNow()
}
val stop = System.currentTimeMillis()
println((stop - start).toString() + " ms")
}
}
| mit | 56915a294d8e056620ef71612c7aa3e1 | 26.611111 | 79 | 0.511514 | 4.61134 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/PanelBuilder.kt | 1 | 1372 | package org.hexworks.zircon.api.builder.component
import org.hexworks.zircon.api.component.Panel
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.component.impl.DefaultPanel
import org.hexworks.zircon.internal.component.renderer.DefaultPanelRenderer
import org.hexworks.zircon.internal.dsl.ZirconDsl
import kotlin.jvm.JvmStatic
@Suppress("UNCHECKED_CAST")
@ZirconDsl
class PanelBuilder private constructor() : BaseContainerBuilder<Panel, PanelBuilder>(
initialRenderer = DefaultPanelRenderer()
) {
override fun build(): Panel {
return DefaultPanel(
componentMetadata = createMetadata(),
renderingStrategy = createRenderingStrategy(),
initialTitle = title,
).apply {
addComponents(*childrenToAdd.toTypedArray())
}.attachListeners()
}
override fun createCopy() = newBuilder()
.withProps(props.copy())
.withChildren(*childrenToAdd.toTypedArray())
override fun calculateContentSize(): Size {
// best effort
val result = childrenToAdd.map { it.size }.fold(Size.zero(), Size::plus)
return if (result < Size.one()) Size.one() else result
}
companion object {
@JvmStatic
fun newBuilder() = PanelBuilder()
}
}
| apache-2.0 | ae3f87def4cdb6f6f181f46a4d466a06 | 30.906977 | 85 | 0.703353 | 4.763889 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultParagraph.kt | 1 | 1030 | package org.hexworks.zircon.internal.component.impl
import org.hexworks.zircon.api.behavior.TextOverride
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.Paragraph
import org.hexworks.zircon.api.component.data.ComponentMetadata
import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy
import org.hexworks.zircon.api.uievent.Pass
import org.hexworks.zircon.api.uievent.UIEventResponse
class DefaultParagraph internal constructor(
componentMetadata: ComponentMetadata,
initialText: String,
renderingStrategy: ComponentRenderingStrategy<Paragraph>
) : Paragraph, TextOverride by TextOverride.create(initialText), DefaultComponent(
metadata = componentMetadata,
renderer = renderingStrategy
) {
override fun acceptsFocus() = false
override fun focusGiven(): UIEventResponse = Pass
override fun focusTaken(): UIEventResponse = Pass
override fun convertColorTheme(colorTheme: ColorTheme) = colorTheme.toSecondaryContentStyle()
}
| apache-2.0 | 62980cb3118f1c7232a6f514b573f457 | 35.785714 | 97 | 0.815534 | 4.746544 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-3/app/src/main/java/dev/mfazio/pennydrop/types/Player.kt | 1 | 416 | package dev.mfazio.pennydrop.types
import dev.mfazio.pennydrop.game.AI
data class Player(
var playerName: String = "",
var isHuman: Boolean = true,
var selectedAI: AI? = null
) {
var pennies: Int = defaultPennyCount
fun addPennies(count: Int = 1) {
pennies += count
}
var isRolling: Boolean = false
companion object {
const val defaultPennyCount = 10
}
}
| apache-2.0 | 8b14fb0b65fa9c4646d498d5557bbf79 | 18.809524 | 40 | 0.634615 | 3.816514 | false | false | false | false |
spinnaker/orca | orca-web/src/test/kotlin/com/netflix/spinnaker/orca/controllers/AdminControllerTest.kt | 1 | 2487 | /*
* Copyright 2021 Armory, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.controllers
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.netflix.spinnaker.orca.api.test.OrcaFixture
import com.netflix.spinnaker.orca.api.test.orcaFixture
import com.netflix.spinnaker.q.discovery.DiscoveryActivator
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
import strikt.api.expectThat
import strikt.assertions.isEqualTo
import strikt.assertions.isFalse
import strikt.assertions.isTrue
class AdminControllerTest : JUnit5Minutests {
fun tests() = rootContext<Fixture> {
orcaFixture {
Fixture()
}
test("/admin/instance/enabled endpoint can disable queue Activator") {
// wait up to 5 seconds for discoveryActivator to initialize
for (i in 1..5) {
if (discoveryActivator.enabled){
println("discoveryActivator.enabled = true. Start")
break
}
println("discoveryActivator.enabled = false. Sleep 1sec")
Thread.sleep(1000L)
}
expectThat(discoveryActivator.enabled).isTrue()
val response = mockMvc.post("/admin/instance/enabled") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(mapOf("enabled" to false))
}.andReturn().response
expectThat(response.status).isEqualTo(200)
expectThat(discoveryActivator.enabled).isFalse()
}
}
@AutoConfigureMockMvc
class Fixture : OrcaFixture() {
@Autowired
lateinit var mockMvc: MockMvc
@Autowired
lateinit var discoveryActivator: DiscoveryActivator
}
}
| apache-2.0 | db9baf2b555c4f013de639c3e40952a2 | 32.16 | 85 | 0.745476 | 4.554945 | false | true | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/growth/sideeffect/GrowthSideEffectHandler.kt | 1 | 1467 | package io.ipoli.android.growth.sideeffect
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.growth.GrowthAction
import io.ipoli.android.growth.usecase.CalculateGrowthStatsUseCase
import space.traversal.kapsule.required
object GrowthSideEffectHandler : AppSideEffectHandler() {
private val calculateGrowthStatsUseCase by required { calculateGrowthStatsUseCase }
private val permissionChecker by required { permissionChecker }
override suspend fun doExecute(action: Action, state: AppState) {
when (action) {
is GrowthAction.Load -> {
val canReadAppUsageData = permissionChecker.canReadAppUsageStats()
val result = calculateGrowthStatsUseCase.execute(
CalculateGrowthStatsUseCase.Params(includeAppUsageStats = canReadAppUsageData)
)
dispatch(
DataLoadedAction.GrowthChanged(
dailyGrowth = result.todayGrowth,
weeklyGrowth = result.weeklyGrowth,
monthlyGrowth = result.monthlyGrowth,
includesAppUsageData = canReadAppUsageData
)
)
}
}
}
override fun canHandle(action: Action) = action is GrowthAction.Load
} | gpl-3.0 | abbab9e837377d784a894b1467772092 | 36.641026 | 98 | 0.669393 | 5.453532 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/DefaultScriptingSupport.kt | 2 | 25147 | // 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.core.script.configuration
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.ProjectExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.ui.EditorNotifications
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.core.script.*
import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptConfigurationManagerExtensions.LOADER
import org.jetbrains.kotlin.idea.core.script.configuration.cache.*
import org.jetbrains.kotlin.idea.core.script.configuration.loader.DefaultScriptConfigurationLoader
import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoader
import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoadingContext
import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptOutsiderFileConfigurationLoader
import org.jetbrains.kotlin.idea.core.script.configuration.utils.*
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import org.jetbrains.kotlin.scripting.resolve.ScriptReportSink
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.api.ScriptDiagnostic
/**
* Standard implementation of scripts configuration loading and caching.
*
* ## Loading initiation
*
* [getOrLoadConfiguration] will be called when we need to show or analyze some script file.
*
* As described in [DefaultScriptingSupportBase], configuration may be loaded from [cache]
* or [reloadOutOfDateConfiguration] will be called on [cache] miss.
*
* There are 2 tiers [cache]: memory and FS. For now FS cache implemented by [ScriptConfigurationLoader]
* because we are not storing classpath roots yet. As a workaround cache.all() will return only memory
* cached configurations. So, for now we are indexing roots that loaded from FS with
* default [reloadOutOfDateConfiguration] mechanics.
*
* Also, [ensureLoadedFromCache] may be called from [UnusedSymbolInspection]
* to ensure that configuration of all scripts containing some symbol are up-to-date or try load it in sync.
*
* ## Loading
*
* When requested, configuration will be loaded using first applicable [loaders].
* It can work synchronously or asynchronously.
*
* Synchronous loader will be called just immediately. Despite this, its result may not be applied immediately,
* see next section for details.
*
* Asynchronous loader will be called in background thread (by [BackgroundExecutor]).
*
* ## Applying
*
* By default loaded configuration will *not* be applied immediately. Instead, we show in editor notification
* that suggests user to apply changed configuration. This was done to avoid sporadically starting indexing of new roots,
* which may happens regularly for large Gradle projects.
*
* Notification will be displayed when configuration is going to be updated. First configuration will be loaded
* without notification.
*
* This behavior may be disabled by enabling "auto reload" in project settings.
* When enabled, all loaded configurations will be applied immediately, without any notification.
*
* ## Concurrency
*
* Each files may be in on of this state:
* - scriptDefinition is not ready
* - not loaded
* - up-to-date
* - invalid, in queue (in [BackgroundExecutor] queue)
* - invalid, loading
* - invalid, waiting for apply
*
* [reloadOutOfDateConfiguration] guard this states. See it's docs for more details.
*/
class DefaultScriptingSupport(manager: CompositeScriptConfigurationManager) : DefaultScriptingSupportBase(manager) {
// TODO public for tests
internal val backgroundExecutor: BackgroundExecutor = when {
isUnitTestMode() -> @Suppress("TestOnlyProblems") TestingBackgroundExecutor(manager)
else -> DefaultBackgroundExecutor(project, manager)
}
private val outsiderLoader = ScriptOutsiderFileConfigurationLoader(project)
private val fileAttributeCache = ScriptConfigurationFileAttributeCache(project)
private val defaultLoader = DefaultScriptConfigurationLoader(project)
private val loaders: List<ScriptConfigurationLoader>
get() = mutableListOf<ScriptConfigurationLoader>().apply {
add(outsiderLoader)
add(fileAttributeCache)
addAll(LOADER.getPoint(project).extensionList)
add(defaultLoader)
}
private val saveLock = ReentrantLock()
override fun createCache(): ScriptConfigurationCache = object : ScriptConfigurationMemoryCache(project) {
override fun setLoaded(file: VirtualFile, configurationSnapshot: ScriptConfigurationSnapshot) {
super.setLoaded(file, configurationSnapshot)
fileAttributeCache.save(file, configurationSnapshot)
}
}
/**
* Will be called on [cache] miss to initiate loading of [file]'s script configuration.
*
* ## Concurrency
*
* Each files may be in on of the states described below:
* - scriptDefinition is not ready. `ScriptDefinitionsManager.getInstance(project).isReady() == false`.
* [updateScriptDefinitionsReferences] will be called when [ScriptDefinitionsManager] will be ready
* which will call [reloadOutOfDateConfiguration] for opened editors.
* - unknown. When [isFirstLoad] true (`cache[file] == null`).
* - up-to-date. `cache[file]?.upToDate == true`.
* - invalid, in queue. `cache[file]?.upToDate == false && file in backgroundExecutor`.
* - invalid, loading. `cache[file]?.upToDate == false && file !in backgroundExecutor`.
* - invalid, waiting for apply. `cache[file]?.upToDate == false && file !in backgroundExecutor` and has notification panel?
* - invalid, waiting for update. `cache[file]?.upToDate == false` and has notification panel
*
* Async:
* - up-to-date: [reloadOutOfDateConfiguration] will not be called.
* - `unknown` and `invalid, in queue`:
* Concurrent async loading will be guarded by `backgroundExecutor.ensureScheduled`
* (only one task per file will be scheduled at same time)
* - `invalid, loading`
* Loading should be removed from `backgroundExecutor`, and will be rescheduled on change
* and file will be up-to-date checked again. This will happen after current loading,
* because only `backgroundExecutor` execute tasks in one thread.
* - `invalid, waiting for apply`:
* Loading will not be queued, since we are marking file as up-to-date with
* not yet applied configuration.
* - `invalid, waiting for update`:
* Loading wasn't started, only notification is shown
*
* Sync:
* - up-to-date:
* [reloadOutOfDateConfiguration] will not be called.
* - all other states, i.e: `unknown`, `invalid, in queue`, `invalid, loading` and `invalid, ready for apply`:
* everything will be computed just in place, possible concurrently.
* [suggestOrSaveConfiguration] calls will be serialized by the [saveLock]
*/
override fun reloadOutOfDateConfiguration(
file: KtFile,
isFirstLoad: Boolean,
forceSync: Boolean,
fromCacheOnly: Boolean,
skipNotification: Boolean
): Boolean {
val virtualFile = file.originalFile.virtualFile ?: return false
if (project.isDisposed || !ScriptDefinitionsManager.getInstance(project).isReady()) return false
val scriptDefinition = file.findScriptDefinition() ?: return false
val (async, sync) = loaders.partition { it.shouldRunInBackground(scriptDefinition) }
val syncLoader =
sync.filter { it.loadDependencies(isFirstLoad, file, scriptDefinition, loadingContext) }.firstOrNull()
return if (syncLoader == null) {
if (!fromCacheOnly) {
if (forceSync) {
loaders.firstOrNull { it.loadDependencies(isFirstLoad, file, scriptDefinition, loadingContext) }
} else {
val autoReloadEnabled = KotlinScriptingSettings.getInstance(project).autoReloadConfigurations(scriptDefinition)
val forceSkipNotification = skipNotification || autoReloadEnabled
// sync loaders can do something, let's recheck
val isFirstLoadActual = getCachedConfigurationState(virtualFile)?.applied == null
val intercepted = !forceSkipNotification && async.any {
it.interceptBackgroundLoading(virtualFile, isFirstLoadActual) {
runAsyncLoaders(file, virtualFile, scriptDefinition, listOf(it), true)
}
}
if (!intercepted) {
runAsyncLoaders(file, virtualFile, scriptDefinition, async, forceSkipNotification)
}
}
}
false
} else {
true
}
}
private fun runAsyncLoaders(
file: KtFile,
virtualFile: VirtualFile,
scriptDefinition: ScriptDefinition,
loaders: List<ScriptConfigurationLoader>,
forceSkipNotification: Boolean
) {
backgroundExecutor.ensureScheduled(virtualFile) {
val cached = getCachedConfigurationState(virtualFile)
val applied = cached?.applied
if (applied != null && applied.inputs.isUpToDate(project, virtualFile)) {
// in case user reverted to applied configuration
suggestOrSaveConfiguration(virtualFile, applied, forceSkipNotification)
} else if (cached == null || !cached.isUpToDate(project, virtualFile)) {
// don't start loading if nothing was changed
// (in case we checking for up-to-date and loading concurrently)
val actualIsFirstLoad = cached == null
loaders.firstOrNull { it.loadDependencies(actualIsFirstLoad, file, scriptDefinition, loadingContext) }
}
}
}
@TestOnly
fun runLoader(file: KtFile, loader: ScriptConfigurationLoader): ScriptCompilationConfigurationWrapper? {
val virtualFile = file.originalFile.virtualFile ?: return null
if (!ScriptDefinitionsManager.getInstance(project).isReady()) return null
val scriptDefinition = file.findScriptDefinition() ?: return null
manager.updater.update {
loader.loadDependencies(false, file, scriptDefinition, loadingContext)
}
return getAppliedConfiguration(virtualFile)?.configuration
}
private val loadingContext = object : ScriptConfigurationLoadingContext {
/**
* Used from [ScriptOutsiderFileConfigurationLoader] only.
*/
override fun getCachedConfiguration(file: VirtualFile): ScriptConfigurationSnapshot? =
getAppliedConfiguration(file) ?: getFromGlobalCache(file)
private fun getFromGlobalCache(file: VirtualFile): ScriptConfigurationSnapshot? {
val info = manager.getLightScriptInfo(file.path) ?: return null
return ScriptConfigurationSnapshot(CachedConfigurationInputs.UpToDate, listOf(), info.buildConfiguration())
}
override fun suggestNewConfiguration(file: VirtualFile, newResult: ScriptConfigurationSnapshot) {
suggestOrSaveConfiguration(file, newResult, false)
}
override fun saveNewConfiguration(file: VirtualFile, newResult: ScriptConfigurationSnapshot) {
suggestOrSaveConfiguration(file, newResult, true)
}
}
private fun suggestOrSaveConfiguration(
file: VirtualFile,
newResult: ScriptConfigurationSnapshot,
forceSkipNotification: Boolean
) {
saveLock.withLock {
scriptingDebugLog(file) { "configuration received = $newResult" }
setLoadedConfiguration(file, newResult)
hideInterceptedNotification(file)
val newConfiguration = newResult.configuration
if (newConfiguration == null) {
saveReports(file, newResult.reports)
return
}
val old = getCachedConfigurationState(file)
val oldConfiguration = old?.applied?.configuration
if (oldConfiguration != null && areSimilar(oldConfiguration, newConfiguration)) {
saveReports(file, newResult.reports)
file.removeScriptDependenciesNotificationPanel(project)
return
}
val skipNotification = forceSkipNotification
|| oldConfiguration == null
|| ApplicationManager.getApplication().isUnitTestModeWithoutScriptLoadingNotification
if (skipNotification) {
if (oldConfiguration != null) {
file.removeScriptDependenciesNotificationPanel(project)
}
saveReports(file, newResult.reports)
setAppliedConfiguration(file, newResult, syncUpdate = true)
return
}
scriptingDebugLog(file) {
"configuration changed, notification is shown: old = $oldConfiguration, new = $newConfiguration"
}
// restore reports for applied configuration in case of previous error
old?.applied?.reports?.let {
saveReports(file, it)
}
file.addScriptDependenciesNotificationPanel(
newConfiguration, project,
onClick = {
saveReports(file, newResult.reports)
file.removeScriptDependenciesNotificationPanel(project)
manager.updater.update {
setAppliedConfiguration(file, newResult)
}
}
)
}
}
private fun saveReports(
file: VirtualFile,
newReports: List<ScriptDiagnostic>
) {
val oldReports = IdeScriptReportSink.getReports(file)
if (oldReports != newReports) {
scriptingDebugLog(file) { "new script reports = $newReports" }
project.service<ScriptReportSink>().attachReports(file, newReports)
GlobalScope.launch(EDT(project)) {
if (project.isDisposed) return@launch
val ktFile = PsiManager.getInstance(project).findFile(file)
if (ktFile != null) {
DaemonCodeAnalyzer.getInstance(project).restart(ktFile)
}
EditorNotifications.getInstance(project).updateAllNotifications()
}
}
}
fun ensureNotificationsRemoved(file: VirtualFile) {
if (cache.remove(file)) {
saveReports(file, listOf())
file.removeScriptDependenciesNotificationPanel(project)
}
// this notification can be shown before something will be in cache
hideInterceptedNotification(file)
}
fun updateScriptDefinitionsReferences() {
// remove notification for all files
cache.allApplied().forEach { (file, _) ->
saveReports(file, listOf())
file.removeScriptDependenciesNotificationPanel(project)
hideInterceptedNotification(file)
}
cache.clear()
}
private fun hideInterceptedNotification(file: VirtualFile) {
loaders.forEach {
it.hideInterceptedNotification(file)
}
}
companion object {
fun getInstance(project: Project) =
(ScriptConfigurationManager.getInstance(project) as CompositeScriptConfigurationManager).default
}
}
/**
* Abstraction for [DefaultScriptingSupportBase] based [cache] and [reloadOutOfDateConfiguration].
* Among this two methods concrete implementation should provide script changes listening.
*
* Basically all requests routed to [cache]. If there is no entry in [cache] or it is considered out-of-date,
* then [reloadOutOfDateConfiguration] will be called, which, in turn, should call [setAppliedConfiguration]
* immediately or in some future (e.g. after user will click "apply context" or/and configuration will
* be calculated by some background thread).
*
* [ScriptClassRootsCache] will be calculated based on [cache]d configurations.
* Every change in [cache] will invalidate [ScriptClassRootsCache] cache.
*/
abstract class DefaultScriptingSupportBase(val manager: CompositeScriptConfigurationManager) {
val project: Project
get() = manager.project
@Suppress("LeakingThis")
protected val cache: ScriptConfigurationCache = createCache()
protected abstract fun createCache(): ScriptConfigurationCache
/**
* Will be called on [cache] miss or when [file] is changed.
* Implementation should initiate loading of [file]'s script configuration and call [setAppliedConfiguration]
* immediately or in some future
* (e.g. after user will click "apply context" or/and configuration will be calculated by some background thread).
*
* @param isFirstLoad may be set explicitly for optimization reasons (to avoid expensive fs cache access)
* @param forceSync should be used in tests only
* @param isPostponedLoad is used to postspone loading: show a notification for out of date script and start loading when user request
* @param fromCacheOnly load only when builtin fast synchronous loaders are available
* @return true, if configuration loaded in sync
*/
protected abstract fun reloadOutOfDateConfiguration(
file: KtFile,
isFirstLoad: Boolean = getAppliedConfiguration(file.originalFile.virtualFile) == null,
forceSync: Boolean = false,
fromCacheOnly: Boolean = false,
skipNotification: Boolean = false
): Boolean
internal fun getCachedConfigurationState(file: VirtualFile?): ScriptConfigurationState? {
if (file == null) return null
return cache[file]
}
fun getAppliedConfiguration(file: VirtualFile?): ScriptConfigurationSnapshot? =
getCachedConfigurationState(file)?.applied
private fun hasCachedConfiguration(file: KtFile): Boolean =
getAppliedConfiguration(file.originalFile.virtualFile) != null
fun isConfigurationLoadingInProgress(file: KtFile): Boolean {
return !hasCachedConfiguration(file)
}
fun getOrLoadConfiguration(
virtualFile: VirtualFile,
preloadedKtFile: KtFile?
): ScriptCompilationConfigurationWrapper? {
val cached = getAppliedConfiguration(virtualFile)
if (cached != null) return cached.configuration
val ktFile = project.getKtFile(virtualFile, preloadedKtFile) ?: return null
manager.updater.update {
reloadOutOfDateConfiguration(ktFile, isFirstLoad = true)
}
return getAppliedConfiguration(virtualFile)?.configuration
}
/**
* Load new configuration and suggest applying it (only if it is changed)
*/
fun ensureUpToDatedConfigurationSuggested(file: KtFile, skipNotification: Boolean = false, forceSync: Boolean = false) {
reloadIfOutOfDate(file, skipNotification, forceSync)
}
private fun reloadIfOutOfDate(file: KtFile, skipNotification: Boolean = false, forceSync: Boolean = false) {
if (!forceSync && !ScriptDefinitionsManager.getInstance(project).isReady()) return
manager.updater.update {
file.originalFile.virtualFile?.let { virtualFile ->
val state = cache[virtualFile]
if (state == null || forceSync || !state.isUpToDate(project, virtualFile, file)) {
reloadOutOfDateConfiguration(
file,
forceSync = forceSync,
isFirstLoad = state == null,
skipNotification = skipNotification
)
}
}
}
}
fun isLoadedFromCache(file: KtFile): Boolean {
if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false
return file.originalFile.virtualFile?.let { cache[it] != null } ?: true
}
/**
* Ensure that any configuration for [files] is loaded from cache
*/
fun ensureLoadedFromCache(files: List<KtFile>): Boolean {
if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false
var allLoaded = true
manager.updater.update {
files.forEach { file ->
file.originalFile.virtualFile?.let { virtualFile ->
cache[virtualFile] ?: run {
if (!reloadOutOfDateConfiguration(
file,
isFirstLoad = true,
fromCacheOnly = true
)
) {
allLoaded = false
}
}
}
}
}
return allLoaded
}
protected open fun setAppliedConfiguration(
file: VirtualFile,
newConfigurationSnapshot: ScriptConfigurationSnapshot?,
syncUpdate: Boolean = false
) {
manager.updater.checkInTransaction()
val newConfiguration = newConfigurationSnapshot?.configuration
scriptingDebugLog(file) { "configuration changed = $newConfiguration" }
if (newConfiguration != null) {
cache.setApplied(file, newConfigurationSnapshot)
manager.updater.invalidate(file, synchronous = syncUpdate)
}
}
protected fun setLoadedConfiguration(
file: VirtualFile,
configurationSnapshot: ScriptConfigurationSnapshot
) {
cache.setLoaded(file, configurationSnapshot)
}
@TestOnly
internal fun updateScriptDependenciesSynchronously(file: PsiFile) {
file.findScriptDefinition() ?: return
file as? KtFile ?: error("PsiFile $file should be a KtFile, otherwise script dependencies cannot be loaded")
val virtualFile = file.virtualFile
if (cache[virtualFile]?.isUpToDate(project, virtualFile, file) == true) return
manager.updater.update {
reloadOutOfDateConfiguration(file, forceSync = true)
}
UIUtil.dispatchAllInvocationEvents()
}
private fun collectConfigurationsWithCache(builder: ScriptClassRootsBuilder) {
// own builder for saving to storage
val rootsStorage = ScriptClassRootsStorage.getInstance(project)
val storageBuilder = ScriptClassRootsBuilder.fromStorage(project, rootsStorage)
val ownBuilder = ScriptClassRootsBuilder(storageBuilder)
cache.allApplied().forEach { (vFile, configuration) ->
ownBuilder.add(vFile, configuration)
if (!ScratchUtil.isScratch(vFile)) {
// do not store (to disk) scratch file configurations due to huge dependencies
// (to be indexed next time - even if you don't use scratches at all)
storageBuilder.add(vFile, configuration)
}
}
storageBuilder.toStorage(rootsStorage)
builder.add(ownBuilder)
}
fun collectConfigurations(builder: ScriptClassRootsBuilder) {
if (isFSRootsStorageEnabled()) {
collectConfigurationsWithCache(builder)
} else {
cache.allApplied().forEach { (vFile, configuration) -> builder.add(vFile, configuration) }
}
}
}
internal fun isFSRootsStorageEnabled(): Boolean = Registry.`is`("kotlin.scripting.fs.roots.storage.enabled")
object DefaultScriptConfigurationManagerExtensions {
val LOADER: ProjectExtensionPointName<ScriptConfigurationLoader> =
ProjectExtensionPointName("org.jetbrains.kotlin.scripting.idea.loader")
}
val ScriptConfigurationManager.testingBackgroundExecutor: TestingBackgroundExecutor
get() {
@Suppress("TestOnlyProblems")
return (this as CompositeScriptConfigurationManager).default.backgroundExecutor as TestingBackgroundExecutor
}
| apache-2.0 | 8f9f0e44b17d987fdad65c8e5c11ca5e | 42.356897 | 158 | 0.680479 | 5.502626 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/OverrideIconForOverloadMethodBug.kt | 5 | 1274 | interface <lineMarker descr="Is implemented by SkipSupportImpl SkipSupportWithDefaults Click or press ... to navigate">SkipSupport</lineMarker> {
fun <lineMarker descr="<html><body>Is implemented in <br> SkipSupportImpl<br> SkipSupportWithDefaults</body></html>">skip</lineMarker>(why: String)
fun <lineMarker descr="<html><body>Is implemented in <br> SkipSupportWithDefaults</body></html>">skip</lineMarker>()
}
public interface <lineMarker descr="Is implemented by SkipSupportImpl Click or press ... to navigate">SkipSupportWithDefaults</lineMarker> : SkipSupport {
override fun <lineMarker descr="<html><body>Is overridden in <br> SkipSupportImpl</body></html>"><lineMarker descr="Implements function in 'SkipSupport'">skip</lineMarker></lineMarker>(why: String) {}
override fun <lineMarker descr="Implements function in 'SkipSupport'">skip</lineMarker>() {
skip("not given")
}
}
open class SkipSupportImpl: SkipSupportWithDefaults {
override fun <lineMarker descr="Overrides function in 'SkipSupportWithDefaults'">skip</lineMarker>(why: String) = throw RuntimeException(why)
}
// KT-4428 Incorrect override icon shown for overloaded methods | apache-2.0 | 353084b96d671601ae2e1c86bdc1edfd | 69.833333 | 227 | 0.754317 | 4.533808 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt | 4 | 2078 | // 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.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.psi.*
class FoldIfToReturnAsymmetricallyIntention : SelfTargetingRangeIntention<KtIfExpression>(
KtIfExpression::class.java,
KotlinBundle.lazyMessage("replace.if.expression.with.return")
) {
override fun applicabilityRange(element: KtIfExpression): TextRange? {
if (BranchedFoldingUtils.getFoldableBranchedReturn(element.then) == null || element.`else` != null) {
return null
}
val nextElement = KtPsiUtil.skipTrailingWhitespacesAndComments(element) as? KtReturnExpression
if (nextElement?.returnedExpression == null) return null
return element.ifKeyword.textRange
}
override fun applyTo(element: KtIfExpression, editor: Editor?) {
val condition = element.condition ?: return
val thenBranch = element.then ?: return
val elseBranch = KtPsiUtil.skipTrailingWhitespacesAndComments(element) as? KtReturnExpression ?: return
val psiFactory = KtPsiFactory(element)
val newIfExpression = psiFactory.createIf(condition, thenBranch, elseBranch)
val thenReturn = BranchedFoldingUtils.getFoldableBranchedReturn(newIfExpression.then!!) ?: return
val elseReturn = BranchedFoldingUtils.getFoldableBranchedReturn(newIfExpression.`else`!!) ?: return
thenReturn.replace(thenReturn.returnedExpression!!)
elseReturn.replace(elseReturn.returnedExpression!!)
element.replace(psiFactory.createExpressionByPattern("return $0", newIfExpression))
elseBranch.delete()
}
} | apache-2.0 | d9e5905d876819d15f900bda25c93c98 | 47.348837 | 120 | 0.766603 | 5.425587 | false | false | false | false |
guacamoledragon/twitch-chat | src/test/kotlin/club/guacamoledragon/plugin/driver/kapchat.kt | 1 | 1611 | package club.guacamoledragon.plugin.driver
import club.guacamoledragon.plugin.kapchat.Client
import club.guacamoledragon.plugin.kapchat.Message
import club.guacamoledragon.plugin.ui.ChatRoom
import java.awt.Dimension
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import javax.swing.JFrame
import javax.swing.WindowConstants
fun main(args: Array<String>) {
val frame = JFrame("Twitch Chat")
val chatroom = ChatRoom()
frame.size = Dimension(500, 500)
frame.contentPane.add(chatroom.panel)
frame.setLocationRelativeTo(null)
frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
frame.isVisible = true
var kapchatClient: Client = Client("MrsViolence")
val onMessageHandler = { msg: Message ->
chatroom.appendMessage(msg.nick, msg.message, msg.userData.color)
}
val onDisconnectHandler: () -> Unit = {
kapchatClient = Client(chatroom.channelField.text)
kapchatClient
.onMessage(onMessageHandler)
.connect()
}
kapchatClient
.onMessage(onMessageHandler)
.onDisconnect(onDisconnectHandler)
.connect()
chatroom.goButton.addActionListener { event ->
kapchatClient.disconnect()
}
frame.addWindowListener(object: WindowAdapter() {
override fun windowClosing(e: WindowEvent?) {
kapchatClient.disconnect()
}
})
}
// Part 4: 1080p @ 30fps/3000bps 02/09/2016
// Part 5: 1080p @ 30fps/3000bps 02/11/2016
// Part 6: 1080p @ 30fps/3000bps 02/11/2016
// Part 7: 1080p @ 30fps/3000bps 02/11/2016 | apache-2.0 | e4fec31397adf03d57eb248761e6b817 | 28.309091 | 73 | 0.693358 | 4.057935 | false | false | false | false |
jk1/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/ImplicitSubclassInspection.kt | 2 | 9425 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.inheritance
import com.intellij.CommonBundle
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.JvmNamedElement
import com.intellij.lang.jvm.actions.MemberRequest
import com.intellij.lang.jvm.actions.createModifierActions
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.psi.*
import com.intellij.uast.UastSmartPointer
import com.intellij.uast.createUastSmartPointer
import com.intellij.util.IncorrectOperationException
import com.intellij.util.SmartList
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UDeclaration
import org.jetbrains.uast.toUElementOfType
class ImplicitSubclassInspection : LocalInspectionTool() {
private fun checkClass(aClass: UClass, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
val psiClass = aClass.javaPsi
val classIsFinal = aClass.isFinal || psiClass.hasModifierProperty(PsiModifier.PRIVATE)
val problems = SmartList<ProblemDescriptor>()
val subclassProviders = ImplicitSubclassProvider.EP_NAME.extensions
.asSequence().filter { it.isApplicableTo(psiClass) }
val subclassInfos = subclassProviders.mapNotNull { it.getSubclassingInfo(psiClass) }
val methodsToOverride = aClass.methods.mapNotNull { method ->
subclassInfos
.mapNotNull { it.methodsInfo?.get(method.javaPsi)?.description }
.firstOrNull()?.let { description ->
method to description
}
}
val methodsToAttachToClassFix = if (classIsFinal)
SmartList<UastSmartPointer<UDeclaration>>()
else null
for ((method, description) in methodsToOverride) {
if (method.isFinal || method.isStatic || method.javaPsi.hasModifierProperty(PsiModifier.PRIVATE)) {
methodsToAttachToClassFix?.add(method.createUastSmartPointer())
val methodFixes = createFixesIfApplicable(method, method.name)
problemTargets(method, methodHighlightableModifiersSet).forEach {
problems.add(manager.createProblemDescriptor(
it, description, isOnTheFly,
methodFixes,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING))
}
}
}
if (classIsFinal) {
val classReasonToBeSubclassed = subclassInfos.firstOrNull()?.description
if ((methodsToOverride.isNotEmpty() || classReasonToBeSubclassed != null)) {
problemTargets(aClass, classHighlightableModifiersSet).forEach {
problems.add(manager.createProblemDescriptor(
it, classReasonToBeSubclassed ?: InspectionsBundle.message("inspection.implicit.subclass.display.forClass", psiClass.name),
isOnTheFly,
createFixesIfApplicable(aClass, psiClass.name ?: "class", methodsToAttachToClassFix ?: emptyList()),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
)
}
}
}
return problems.toTypedArray()
}
private fun createFixesIfApplicable(aClass: UDeclaration,
hintTargetName: String,
methodsToAttachToClassFix: List<UastSmartPointer<UDeclaration>> = emptyList()): Array<LocalQuickFix> {
val fix = MakeExtendableFix(aClass, hintTargetName, methodsToAttachToClassFix)
if (!fix.hasActionsToPerform) return emptyArray()
return arrayOf(fix)
}
private fun problemTargets(declaration: UDeclaration, highlightableModifiersSet: Set<String>): List<PsiElement> {
val modifiersElements = getRelatedJavaModifiers(declaration, highlightableModifiersSet)
if (modifiersElements.isNotEmpty()) return modifiersElements
return listOfNotNull(declaration.uastAnchor?.sourcePsi)
}
private fun getRelatedJavaModifiers(declaration: UDeclaration,
highlightableModifiersSet: Set<String>): List<PsiElement> {
val modifierList = (declaration.sourcePsi as? PsiModifierListOwner)?.modifierList ?: return emptyList()
return modifierList.children.filter { it is PsiKeyword && highlightableModifiersSet.contains(it.getText()) }
}
private val methodHighlightableModifiersSet = setOf(PsiModifier.FINAL, PsiModifier.PRIVATE, PsiModifier.STATIC)
private val classHighlightableModifiersSet = setOf(PsiModifier.FINAL, PsiModifier.PRIVATE)
private class MakeExtendableFix(uDeclaration: UDeclaration,
hintTargetName: String,
val siblings: List<UastSmartPointer<UDeclaration>> = emptyList())
: LocalQuickFixOnPsiElement(uDeclaration.sourcePsi!!) {
companion object {
private val LOG = Logger.getInstance("#com.intellij.codeInspection.inheritance.MakeExtendableFix")
}
private val actionsToPerform = SmartList<IntentionAction>()
val hasActionsToPerform: Boolean get() = actionsToPerform.isNotEmpty()
init {
collectMakeExtendable(uDeclaration, actionsToPerform)
for (sibling in siblings) {
sibling.element?.let {
collectMakeExtendable(it, actionsToPerform, checkParent = false)
}
}
}
override fun getFamilyName(): String = QuickFixBundle.message("fix.modifiers.family")
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
try {
for (intentionAction in actionsToPerform) {
if (intentionAction.isAvailable(project, null, file))
intentionAction.invoke(project, null, file)
}
}
catch (e: IncorrectOperationException) {
if (ApplicationManager.getApplication().isUnitTestMode)
throw e
ApplicationManager.getApplication().invokeLater {
Messages.showErrorDialog(project, e.message, CommonBundle.getErrorTitle())
}
LOG.info(e)
}
}
private fun collectMakeExtendable(declaration: UDeclaration,
actionsList: SmartList<IntentionAction>,
checkParent: Boolean = true) {
val isClassMember = declaration !is JvmClass
addIfApplicable(declaration, JvmModifier.FINAL, false, actionsList)
addIfApplicable(declaration, JvmModifier.PRIVATE, false, actionsList)
if (isClassMember) {
addIfApplicable(declaration, JvmModifier.STATIC, false, actionsList)
}
if (checkParent && isClassMember) {
(declaration.uastParent as? UClass)?.apply {
addIfApplicable(this, JvmModifier.FINAL, false, actionsList)
addIfApplicable(this, JvmModifier.PRIVATE, false, actionsList)
}
}
}
private fun addIfApplicable(declaration: JvmModifiersOwner,
modifier: JvmModifier,
shouldPresent: Boolean,
actionsList: SmartList<IntentionAction>) {
if (declaration.hasModifier(modifier) == shouldPresent) return
val request = MemberRequest.Modifier(modifier, shouldPresent)
actionsList += createModifierActions(declaration, request)
}
private val MAX_MESSAGES_TO_COMBINE = 3
private val text = when (uDeclaration) {
is UClass ->
if (actionsToPerform.size <= MAX_MESSAGES_TO_COMBINE)
actionsToPerform.joinToString { it.text }
else InspectionsBundle.message("inspection.implicit.subclass.make.class.extendable",
hintTargetName,
siblings.size,
siblingsDescription())
else ->
if (actionsToPerform.size <= MAX_MESSAGES_TO_COMBINE)
actionsToPerform.joinToString { it.text }
else
InspectionsBundle.message("inspection.implicit.subclass.extendable", hintTargetName)
}
private fun siblingsDescription() =
when (siblings.size) {
1 -> "'${(siblings.firstOrNull()?.element?.javaPsi as? JvmNamedElement)?.name}'"
else -> ""
}
override fun getText(): String = text
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
val uClass = element.toUElementOfType<UClass>() ?: return
val problems = checkClass(uClass, holder.manager, isOnTheFly) ?: return
for (problem in problems) {
holder.registerProblem(problem)
}
}
}
} | apache-2.0 | d39d8695b80d0f93135f6d570e22b538 | 40.524229 | 140 | 0.697188 | 5.291971 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/dialogs/DialogsInternal.kt | 1 | 2446 | package lt.markmerkk.widgets.dialogs
import lt.markmerkk.ResultDispatcher
import lt.markmerkk.Strings
import lt.markmerkk.entities.Log
import lt.markmerkk.ui_2.views.ticket_split.TicketSplitWidget
import org.slf4j.LoggerFactory
import tornadofx.UIComponent
class DialogsInternal(
private val resultDispatcher: ResultDispatcher,
private val strings: Strings,
): Dialogs {
override fun showDialogConfirm(
uiComponent: UIComponent,
header: String,
content: String,
onConfirm: () -> Unit,
) {
resultDispatcher.publish(
DialogConfirmWidget.RESULT_DISPATCH_KEY_BUNDLE,
DialogConfirmWidget.DialogBundle(
header = header,
content = content,
onConfirm = onConfirm,
)
)
uiComponent.openInternalWindow<DialogConfirmWidget>(
escapeClosesWindow = true,
)
}
override fun showDialogInfo(uiComponent: UIComponent, header: String, content: String) {
resultDispatcher.publish(
DialogInfoWidget.RESULT_DISPATCH_KEY_BUNDLE,
DialogInfoWidget.DialogBundle(
header = header,
content = content,
)
)
uiComponent.openInternalWindow<DialogInfoWidget>(
escapeClosesWindow = true,
)
}
override fun showDialogCustomAction(
uiComponent: UIComponent,
header: String,
content: String,
actionTitle: String,
onAction: () -> Unit
) {
resultDispatcher.publish(
DialogCustomActionWidget.RESULT_DISPATCH_KEY_BUNDLE,
DialogCustomActionWidget.DialogBundle(
header = header,
content = content,
actionTitle = actionTitle,
onAction = onAction,
)
)
uiComponent.openInternalWindow<DialogCustomActionWidget>(
escapeClosesWindow = true,
)
}
override fun showDialogSplitTicket(
uiComponent: UIComponent,
worklog: Log,
) {
resultDispatcher.publish(
TicketSplitWidget.RESULT_DISPATCH_KEY_ENTITY,
worklog,
)
uiComponent.openInternalWindow<TicketSplitWidget>(
escapeClosesWindow = true,
)
}
companion object {
private val l = LoggerFactory.getLogger(DialogsInternal::class.java)!!
}
} | apache-2.0 | 9e6e360c49e0df5dae8cb88897d2e00a | 28.130952 | 92 | 0.61202 | 5.411504 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-test-host/jvmAndNix/test/TestApplicationTest.kt | 1 | 10807 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.server.testing
import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.plugins.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.server.testing.client.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.test.*
class TestApplicationTest {
private val TestPlugin = createApplicationPlugin("test_plugin") {
onCall { call ->
if (!call.request.headers.contains("request_header")) {
throw BadRequestException("Error")
}
call.response.header("response_header", call.request.headers["request_header"]!!)
}
}
private val testApplication = TestApplication {
install(TestPlugin)
routing {
get("a") {
call.respond("OK")
}
}
}
private object TestClientPlugin : HttpClientPlugin<Unit, TestClientPlugin> {
override val key: AttributeKey<TestClientPlugin> = AttributeKey("testClientPlugin")
override fun prepare(block: Unit.() -> Unit) = TestClientPlugin
override fun install(plugin: TestClientPlugin, scope: HttpClient) {
scope.sendPipeline.intercept(HttpSendPipeline.State) {
context.headers.append("request_header", "value_1")
}
}
}
private val testClient = testApplication.createClient {
install(TestClientPlugin)
}
@Test
fun testTopLevel() = runBlocking {
val response = testClient.get("a")
assertEquals("OK", response.bodyAsText())
assertEquals("value_1", response.headers["response_header"])
}
@Test
fun testApplicationBlock() = testApplication {
application {
install(TestPlugin)
routing {
get("a") {
call.respond("OK")
}
}
}
val client = createClient { install(TestClientPlugin) }
val response = client.get("a")
assertEquals("OK", response.bodyAsText())
assertEquals("value_1", response.headers["response_header"])
}
@Test
fun testBridge() = testApplication {
install(TestPlugin)
routing {
get("a") {
call.respond("OK")
}
}
val client = createClient { install(TestClientPlugin) }
val response = client.get("a")
assertEquals("OK", response.bodyAsText())
assertEquals("value_1", response.headers["response_header"])
}
@Test
fun testExternalServices() = testApplication {
externalServices {
hosts("http://www.google.com:123", "https://google.com") {
routing {
get { call.respond("EXTERNAL OK") }
}
}
}
routing {
get { call.respond("OK") }
}
val internal = client.get("/")
assertEquals("OK", internal.bodyAsText())
val external1 = client.get("//www.google.com:123")
assertEquals("EXTERNAL OK", external1.bodyAsText())
val external2 = client.get("https://google.com")
assertEquals("EXTERNAL OK", external2.bodyAsText())
assertFailsWith<InvalidTestRequestException> { client.get("//google.com:123") }
assertFailsWith<InvalidTestRequestException> { client.get("//google.com") }
assertFailsWith<InvalidTestRequestException> { client.get("https://www.google.com") }
}
@Test
fun testCanAccessClient() = testApplication {
class TestPluginConfig {
lateinit var pluginClient: HttpClient
}
val TestPlugin = createApplicationPlugin("test", ::TestPluginConfig) {
onCall {
val externalValue = pluginConfig.pluginClient.get("https://test.com").bodyAsText()
it.response.headers.append("test", externalValue)
}
}
install(TestPlugin) {
pluginClient = client
}
externalServices {
hosts("https://test.com") {
routing { get { call.respond("TEST_VALUE") } }
}
}
routing {
get {
call.respond("OK")
}
}
val response = client.get("/")
assertEquals("OK", response.bodyAsText())
assertEquals("TEST_VALUE", response.headers["test"])
}
@Test
fun testingSchema() = testApplication {
routing {
get("/echo") {
call.respondText(call.request.local.scheme)
}
}
assertEquals("http", client.get("/echo").bodyAsText())
assertEquals("https", client.get("https://localhost/echo").bodyAsText())
}
@Test
fun testManualStart() = testApplication {
var externalServicesRoutingCalled = false
var routingCalled = false
var applicationCalled = false
var applicationStarted = false
externalServices {
hosts("https://test.com") {
routing {
externalServicesRoutingCalled = true
}
}
}
routing {
routingCalled = true
}
application {
applicationCalled = true
environment.monitor.subscribe(ApplicationStarted) {
applicationStarted = true
}
}
startApplication()
assertEquals(true, routingCalled)
assertEquals(true, applicationCalled)
assertEquals(true, applicationStarted)
assertEquals(true, externalServicesRoutingCalled)
}
@Test
fun testManualStartAndClientCallAfter() = testApplication {
externalServices {
hosts("https://test.com") {
routing {
get {
call.respond("OK")
}
}
}
}
routing {
get {
call.respond([email protected]("https://test.com").bodyAsText())
}
}
startApplication()
assertEquals("OK", client.get("/").bodyAsText())
}
@Test
fun testClientWithTimeout() = testApplication {
val client = createClient {
install(HttpTimeout)
}
externalServices {
hosts("http://fake.site.io") {
routing {
get("/toto") {
call.respond("OK")
}
}
}
}
routing {
get("/") {
val response = client.get("http://fake.site.io/toto") {
timeout {
requestTimeoutMillis = 100
}
}.bodyAsText()
call.respondText(response)
}
}
assertEquals("OK", client.get("/").bodyAsText())
}
@Test
fun testMultipleParallelRequests() = testApplication {
routing {
get("/") {
call.respondText("OK")
}
}
coroutineScope {
val jobs = (1..100).map {
async {
client.get("/").apply {
assertEquals("OK", bodyAsText())
}
}
}
jobs.awaitAll()
}
}
@Test
fun testRequestRunningInParallel() = testApplication {
routing {
post("/") {
val text = call.receiveText()
call.respondText(text)
}
}
coroutineScope {
val secondRequestStarted = CompletableDeferred<Unit>()
val request1 = async {
client.post("/") {
setBody(object : OutgoingContent.WriteChannelContent() {
override suspend fun writeTo(channel: ByteWriteChannel) {
channel.writeStringUtf8("OK")
secondRequestStarted.await()
channel.flush()
}
})
}.apply {
assertEquals("OK", bodyAsText())
}
}
val request2 = async {
client.preparePost("/") {
setBody("OK")
}.execute {
secondRequestStarted.complete(Unit)
assertEquals("OK", it.bodyAsText())
}
}
request1.await()
request2.await()
}
}
@Test
fun testExceptionThrowsByDefault() = testApplication {
routing {
get("/boom") {
throw IllegalStateException("error")
}
}
val error = assertFailsWith<IllegalStateException> {
client.get("/boom")
}
assertEquals("error", error.message)
}
@Test
fun testExceptionRespondsWith500IfFlagSet() = testApplication {
environment {
config = MapApplicationConfig(CONFIG_KEY_THROW_ON_EXCEPTION to "false")
}
routing {
get("/boom") {
throw IllegalStateException("error")
}
}
val response = client.get("/boom")
assertEquals(HttpStatusCode.InternalServerError, response.status)
}
@Test
fun testConnectors(): Unit = testApplication {
environment {
connector {
port = 8080
}
connector {
port = 8081
}
module {
routing {
port(8080) {
get {
call.respond("8080")
}
}
port(8081) {
get {
call.respond("8081")
}
}
}
}
}
val response8080 = client.get {
host = "0.0.0.0"
port = 8080
}
assertEquals("8080", response8080.bodyAsText())
val response8081 = client.get {
host = "0.0.0.0"
port = 8081
}
assertEquals("8081", response8081.bodyAsText())
}
}
| apache-2.0 | 9512817da6dee148dd946c4ccfb973f6 | 27.818667 | 119 | 0.506709 | 5.284597 | false | true | false | false |
neva-dev/javarel-framework | foundation/src/main/kotlin/com/neva/javarel/foundation/api/osgi/ClassUtils.kt | 1 | 2080 | package com.neva.javarel.foundation.api.osgi
import org.objectweb.asm.AnnotationVisitor
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.Opcodes
import java.net.URL
import java.util.*
object ClassUtils {
fun toClassName(classReader: ClassReader): String {
return classReader.className.replace("/", ".")
}
fun toClassName(url: URL): String {
val file = url.file
val canonicalName = file.substring(1, file.length - ".class".length)
return canonicalName.replace('/', '.')
}
fun isAnnotated(classReader: ClassReader, annotation: Class<out Annotation>): Boolean {
return isAnnotated(classReader, setOf(annotation))
}
fun isAnnotated(classReader: ClassReader, annotations: Set<Class<out Annotation>>): Boolean {
val annotationReader = AnnotationReader();
classReader.accept(annotationReader, ClassReader.SKIP_DEBUG);
return annotationReader.isAnnotationPresent(annotations);
}
class AnnotationReader : ClassVisitor(Opcodes.ASM5) {
private val visited = ArrayList<String>()
override fun visit(paramInt1: Int, paramInt2: Int, paramString1: String?, paramString2: String?,
paramString3: String?, paramArrayOfString: Array<String?>) {
visited.clear()
}
override fun visitAnnotation(paramString: String?, paramBoolean: Boolean): AnnotationVisitor? {
if (paramString != null) {
val annotationClassName = getAnnotationClassName(paramString)
visited.add(annotationClassName)
}
return super.visitAnnotation(paramString, paramBoolean)
}
fun isAnnotationPresent(annotations: Set<Class<out Annotation>>): Boolean {
return annotations.any { annotation -> visited.contains(annotation.name) }
}
private fun getAnnotationClassName(rawName: String): String {
return rawName.substring(1, rawName.length - 1).replace('/', '.')
}
}
} | apache-2.0 | cf9cf71912994ff6e2c6e60c1d5a443a | 33.683333 | 104 | 0.66875 | 4.871194 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/ViewUtil.kt | 1 | 4068 | package org.wikipedia.views
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.text.TextUtils
import android.view.ActionMode
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.databinding.ViewActionModeCloseButtonBinding
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DimenUtil.roundedDpToPx
import org.wikipedia.util.ResourceUtil.getThemedColor
import org.wikipedia.util.WhiteBackgroundTransformation
import java.util.*
object ViewUtil {
private val CENTER_CROP_ROUNDED_CORNERS = MultiTransformation(CenterCrop(),
WhiteBackgroundTransformation(), RoundedCorners(roundedDpToPx(2f)))
val ROUNDED_CORNERS = RoundedCorners(roundedDpToPx(15f))
val CENTER_CROP_LARGE_ROUNDED_CORNERS = MultiTransformation(CenterCrop(),
WhiteBackgroundTransformation(), ROUNDED_CORNERS)
@JvmStatic
fun loadImageWithRoundedCorners(view: ImageView, url: String?) {
loadImage(view, url, true)
}
@JvmStatic
fun loadImageWithRoundedCorners(view: ImageView, url: String?, largeRoundedSize: Boolean) {
loadImage(view, url, true, largeRoundedSize)
}
@JvmStatic
@JvmOverloads
fun loadImage(view: ImageView, url: String?, roundedCorners: Boolean = false, largeRoundedSize: Boolean = false, force: Boolean = false,
listener: RequestListener<Drawable?>? = null) {
val placeholder = getPlaceholderDrawable(view.context)
var builder = Glide.with(view)
.load(if ((Prefs.isImageDownloadEnabled() || force) && !TextUtils.isEmpty(url)) Uri.parse(url) else null)
.placeholder(placeholder)
.downsample(DownsampleStrategy.CENTER_INSIDE)
.error(placeholder)
builder = if (roundedCorners) {
builder.transform(if (largeRoundedSize) CENTER_CROP_LARGE_ROUNDED_CORNERS else CENTER_CROP_ROUNDED_CORNERS)
} else {
builder.transform(WhiteBackgroundTransformation())
}
if (listener != null) {
builder = builder.listener(listener)
}
builder.into(view)
}
fun getPlaceholderDrawable(context: Context): Drawable {
return ColorDrawable(getThemedColor(context, R.attr.material_theme_border_color))
}
@JvmStatic
fun setCloseButtonInActionMode(context: Context, actionMode: ActionMode) {
val binding = ViewActionModeCloseButtonBinding.inflate(LayoutInflater.from(context))
actionMode.customView = binding.root
binding.closeButton.setOnClickListener { actionMode.finish() }
}
@JvmStatic
fun formatLangButton(langButton: TextView, langCode: String,
langButtonTextSizeSmaller: Int, langButtonTextSizeLarger: Int) {
val langCodeStandardLength = 3
val langButtonTextMaxLength = 7
if (langCode.length > langCodeStandardLength) {
langButton.textSize = langButtonTextSizeSmaller.toFloat()
if (langCode.length > langButtonTextMaxLength) {
langButton.text = langCode.substring(0, langButtonTextMaxLength).toUpperCase(Locale.ENGLISH)
}
return
}
langButton.textSize = langButtonTextSizeLarger.toFloat()
}
@JvmStatic
fun adjustImagePlaceholderHeight(containerWidth: Float, thumbWidth: Float, thumbHeight: Float): Int {
return (Constants.PREFERRED_GALLERY_IMAGE_SIZE.toFloat() / thumbWidth * thumbHeight * containerWidth / Constants.PREFERRED_GALLERY_IMAGE_SIZE.toFloat()).toInt()
}
}
| apache-2.0 | 82eccff8510b35d1bf53620c20a22279 | 41.821053 | 168 | 0.725172 | 4.76905 | false | false | false | false |
fwcd/kotlin-language-server | shared/src/main/kotlin/org/javacs/kt/util/DelegatePrintStream.kt | 1 | 1958 | package org.javacs.kt.util
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.util.function.Consumer
class DelegatePrintStream(private val delegate: (String) -> Unit): PrintStream(ByteArrayOutputStream(0)) {
private val newLine = System.lineSeparator()
override fun write(c: Int) = delegate((c.toChar()).toString())
override fun write(buf: ByteArray, off: Int, len: Int) {
if (len > 0 && buf.size > 0) {
delegate(String(buf, off, len))
}
}
override fun append(csq: CharSequence): PrintStream {
delegate(csq.toString())
return this
}
override fun append(csq: CharSequence, start: Int, end: Int): PrintStream {
delegate(csq.subSequence(start, end).toString())
return this
}
override fun append(c:Char): PrintStream {
delegate((c).toString())
return this
}
override fun print(x: Boolean) = delegate(x.toString())
override fun print(x: Char) = delegate(x.toString())
override fun print(x: Int) = delegate(x.toString())
override fun print(x: Long) = delegate(x.toString())
override fun print(x: Float) = delegate(x.toString())
override fun print(x: Double) = delegate(x.toString())
override fun print(s: CharArray) = delegate(String(s))
override fun print(s: String) = delegate(s)
override fun print(obj: Any) = delegate(obj.toString())
override fun println() = delegate(newLine)
override fun println(x: Boolean) = delegate(x.toString() + newLine)
override fun println(x: Char) = delegate(x.toString() + newLine)
override fun println(x: Int) = delegate(x.toString() + newLine)
override fun println(x: Long) = delegate(x.toString() + newLine)
override fun println(x: Float) = delegate(x.toString() + newLine)
override fun println(x: Double) = delegate(x.toString() + newLine)
override fun println(x: CharArray) = delegate(String(x) + newLine)
override fun println(x: String) = delegate(x + newLine)
override fun println(x: Any) = delegate(x.toString() + newLine)
}
| mit | 6beb50f28484fe6b160f191bb81d2843 | 26.971429 | 106 | 0.709908 | 3.417103 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/lang/resolve/ref/refs.kt | 1 | 8103 | package me.serce.solidity.lang.resolve.ref
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import me.serce.solidity.lang.completion.SolCompleter
import me.serce.solidity.lang.psi.*
import me.serce.solidity.lang.psi.impl.SolNewExpressionElement
import me.serce.solidity.lang.resolve.SolResolver
import me.serce.solidity.lang.resolve.canBeApplied
import me.serce.solidity.lang.resolve.function.SolFunctionResolver
import me.serce.solidity.lang.types.*
import me.serce.solidity.wrap
class SolUserDefinedTypeNameReference(element: SolUserDefinedTypeName) : SolReferenceBase<SolUserDefinedTypeName>(element), SolReference {
override fun multiResolve(): Collection<PsiElement> {
val parent = element.parent
if (parent is SolNewExpressionElement) {
return SolResolver.resolveNewExpression(parent)
}
return SolResolver.resolveTypeNameUsingImports(element)
}
override fun getVariants() = SolCompleter.completeTypeName(element)
}
class SolVarLiteralReference(element: SolVarLiteral) : SolReferenceBase<SolVarLiteral>(element), SolReference {
override fun multiResolve() = SolResolver.resolveVarLiteralReference(element)
override fun getVariants() = SolCompleter.completeLiteral(element).toList().toTypedArray()
}
class SolModifierReference(
element: SolReferenceElement,
private val modifierElement: SolModifierInvocationElement
) : SolReferenceBase<SolReferenceElement>(element), SolReference {
override fun calculateDefaultRangeInElement() = modifierElement.parentRelativeRange
override fun multiResolve(): List<SolNamedElement> {
val contract = modifierElement.findContract()!!
val superNames: List<String> = (contract.collectSupers.map { it.name } + contract.name).filterNotNull()
return SolResolver.resolveModifier(modifierElement)
.filter { it.contract.name in superNames }
}
override fun getVariants() = SolCompleter.completeModifier(modifierElement)
}
class SolMemberAccessReference(element: SolMemberAccessExpression) : SolReferenceBase<SolMemberAccessExpression>(element), SolReference {
override fun calculateDefaultRangeInElement(): TextRange {
return element.identifier?.parentRelativeRange ?: super.calculateDefaultRangeInElement()
}
override fun multiResolve() = SolResolver.resolveMemberAccess(element)
.mapNotNull { it.resolveElement() }
override fun getVariants() = SolCompleter.completeMemberAccess(element)
}
class SolNewExpressionReference(val element: SolNewExpression) : SolReferenceBase<SolNewExpression>(element), SolReference {
override fun calculateDefaultRangeInElement(): TextRange {
return element.referenceNameElement.parentRelativeRange
}
override fun multiResolve(): Collection<PsiElement> {
val types = SolResolver.resolveTypeNameUsingImports(element.referenceNameElement)
return types
.filterIsInstance(SolContractDefinition::class.java)
.flatMap {
val constructors = it.findConstructors()
if (constructors.isEmpty()) {
listOf(it)
} else {
constructors
}
}
}
}
fun SolContractDefinition.findConstructors(): List<SolElement> {
return if (this.constructorDefinitionList.isNotEmpty()) {
this.constructorDefinitionList
} else {
this.functionDefinitionList
.filter { it.name == this.name }
}
}
class SolFunctionCallReference(element: SolFunctionCallExpression) : SolReferenceBase<SolFunctionCallExpression>(element), SolReference {
override fun calculateDefaultRangeInElement(): TextRange {
return element.referenceNameElement.parentRelativeRange
}
fun resolveFunctionCall(): Collection<SolCallable> {
if (element.parent is SolRevertStatement) {
return SolResolver.resolveTypeNameUsingImports(element).filterIsInstance<SolErrorDefinition>()
}
if (element.firstChild is SolPrimaryExpression) {
val structs = SolResolver.resolveTypeNameUsingImports(element.firstChild).filterIsInstance<SolStructDefinition>()
if (structs.isNotEmpty()) {
return structs
}
}
val resolved: Collection<SolCallable> = when (val expr = element.expression) {
is SolPrimaryExpression -> {
val regular = expr.varLiteral?.let { SolResolver.resolveVarLiteral(it) }
?.filter { it !is SolStateVariableDeclaration }
?.filterIsInstance<SolCallable>()
?: emptyList()
val casts = resolveElementaryTypeCasts(expr)
regular + casts
}
is SolMemberAccessExpression -> {
resolveMemberFunctions(expr) + resolveFunctionCallUsingLibraries(expr)
}
else ->
emptyList()
}
return removeOverrides(resolved.groupBy { it.callablePriority }.entries.minByOrNull { it.key }?.value ?: emptyList())
}
private fun removeOverrides(callables: Collection<SolCallable>): Collection<SolCallable> {
val test = callables.filterIsInstance<SolFunctionDefinition>()
return callables
.filter {
when (it) {
is SolFunctionDefinition -> SolFunctionResolver.collectOverrides(it).intersect(test).isEmpty()
else -> true
}
}
}
private fun resolveElementaryTypeCasts(expr: SolPrimaryExpression): Collection<SolCallable> {
return expr.elementaryTypeName
?.let {
val type = getSolType(it)
object : SolCallable {
override fun resolveElement(): SolNamedElement? = null
override fun parseParameters(): List<Pair<String?, SolType>> = listOf(null to SolUnknown)
override fun parseType(): SolType = type
override val callablePriority: Int = 1000
override fun getName(): String? = null
}
}
.wrap()
}
private fun resolveMemberFunctions(expression: SolMemberAccessExpression): Collection<SolCallable> {
val name = expression.identifier?.text
return if (name != null) {
expression.expression.getMembers()
.filterIsInstance<SolCallable>()
.filter { it.getName() == name }
} else {
emptyList()
}
}
private fun resolveFunctionCallUsingLibraries(expression: SolMemberAccessExpression): Collection<SolCallable> {
val name = expression.identifier?.text
return if (name != null) {
val type = expression.expression.type
if (type != SolUnknown) {
val contract = expression.findContract()
val superContracts = contract
?.collectSupers
?.flatMap { SolResolver.resolveTypeNameUsingImports(it) }
?.filterIsInstance<SolContractDefinition>()
?: emptyList()
val libraries = (superContracts + contract.wrap())
.flatMap { it.usingForDeclarationList }
.filter {
val usingType = it.type
usingType == null || usingType == type
}
.mapNotNull { it.library }
return libraries
.distinct()
.flatMap { it.functionDefinitionList }
.filter { it.name == name }
.filter {
val firstParam = it.parameters.firstOrNull()
if (firstParam == null) {
false
} else {
getSolType(firstParam.typeName).isAssignableFrom(type)
}
}
.map { it.toLibraryCallable() }
} else {
emptyList()
}
} else {
emptyList()
}
}
private fun SolFunctionDefinition.toLibraryCallable(): SolCallable {
return object : SolCallable {
override fun parseParameters(): List<Pair<String?, SolType>> = [email protected]().drop(1)
override fun parseType(): SolType = [email protected]()
override fun resolveElement() = this@toLibraryCallable
override fun getName() = name
override val callablePriority = 0
}
}
override fun multiResolve(): Collection<PsiElement> {
return resolveFunctionCallAndFilter()
.mapNotNull { it.resolveElement() }
}
fun resolveFunctionCallAndFilter(): List<SolCallable> {
return resolveFunctionCall()
.filter { it.canBeApplied(element.functionCallArguments) }
}
}
| mit | 22bf9ad73e583699b98f6a61eae6b708 | 36.169725 | 138 | 0.707516 | 5.141497 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/url/VirtualFileUrlImpl.kt | 7 | 2230 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.url
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.annotations.TestOnly
import java.io.File
import java.nio.file.Path
/**
* Represent an URL (in VFS format) of a file or directory.
*/
open class VirtualFileUrlImpl(val id: Int, internal val manager: VirtualFileUrlManagerImpl): VirtualFileUrl {
private var cachedUrl: String? = null
override fun getUrl(): String {
if (cachedUrl == null) {
cachedUrl = manager.getUrlById(id)
}
return cachedUrl!!
}
override fun getFileName(): String = url.substringAfterLast('/')
override fun getPresentableUrl(): String {
val calculatedUrl = this.url
if (calculatedUrl.startsWith("file://")) {
return calculatedUrl.substring("file://".length)
}
else if (calculatedUrl.startsWith("jar://")) {
val removedSuffix = calculatedUrl.removeSuffix("!/").removeSuffix("!")
return removedSuffix.substring("jar://".length)
}
return calculatedUrl
}
override fun getSubTreeFileUrls() = manager.getSubtreeVirtualUrlsById(this)
override fun append(relativePath: String): VirtualFileUrl = manager.append(this, relativePath.removePrefix("/"))
override fun toString(): String = this.url
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as VirtualFileUrlImpl
if (id != other.id) return false
return true
}
override fun hashCode(): Int = id
}
// TODO It's possible to write it without additional string allocations besides absolutePath
/**
* Do not use io version in production code as FSD filesystems are incompatible with java.io
*/
@TestOnly
fun File.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = virtualFileManager.fromPath(absolutePath)
fun Path.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = virtualFileManager.fromPath(toAbsolutePath().toString())
| apache-2.0 | 7ba0996eed58d1fb12e5ae02687e1cff | 33.307692 | 143 | 0.743498 | 4.704641 | false | false | false | false |
SerCeMan/jclouds-vsphere | src/main/kotlin/org/jclouds/vsphere/functions/VirtualMachineToNodeMetadata.kt | 1 | 10080 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.jclouds.vsphere.functions
import com.google.common.base.*
import com.google.common.base.Function
import com.google.common.base.Predicates.not
import com.google.common.collect.Iterables.filter
import com.google.common.collect.Lists
import com.google.common.collect.Sets.newHashSet
import com.google.common.net.InetAddresses
import com.google.inject.Inject
import com.google.inject.Singleton
import com.vmware.vim25.VirtualMachinePowerState
import com.vmware.vim25.VirtualMachineToolsStatus
import com.vmware.vim25.mo.InventoryNavigator
import com.vmware.vim25.mo.VirtualMachine
import org.jclouds.compute.domain.NodeMetadata
import org.jclouds.compute.domain.NodeMetadata.Status
import org.jclouds.compute.domain.NodeMetadataBuilder
import org.jclouds.compute.reference.ComputeServiceConstants
import org.jclouds.domain.LocationBuilder
import org.jclouds.domain.LocationScope
import org.jclouds.logging.Logger
import org.jclouds.util.InetAddresses2
import org.jclouds.util.Predicates2
import org.jclouds.vsphere.domain.VSphereServiceInstance
import org.jclouds.vsphere.predicates.VSpherePredicate
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.URI
import java.net.URISyntaxException
import java.util.concurrent.TimeUnit
import javax.annotation.Resource
import javax.inject.Named
import javax.inject.Provider
@Singleton
class VirtualMachineToNodeMetadata
@Inject
constructor(val serviceInstanceSupplier: Supplier<VSphereServiceInstance>,
var toPortableNodeStatus: Provider<Map<VirtualMachinePowerState, Status>>) : Function<VirtualMachine, NodeMetadata> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected var logger = Logger.NULL
override fun apply(vm: VirtualMachine?): NodeMetadata? {
var freshVm: VirtualMachine? = null
var virtualMachineName = ""
val nodeMetadataBuilder = NodeMetadataBuilder()
try {
serviceInstanceSupplier.get().use { instance ->
val vmMORId = vm!!.mor._value
val vms = InventoryNavigator(instance.instance.rootFolder).searchManagedEntities("VirtualMachine")
for (machine in vms) {
if (machine.mor.getVal() == vmMORId) {
freshVm = machine as VirtualMachine
break
}
}
val locationBuilder = LocationBuilder().apply {
description("")
id("")
scope(LocationScope.HOST)
}
if (freshVm == null) {
nodeMetadataBuilder.status(Status.ERROR).id("")
return nodeMetadataBuilder.build()
}
virtualMachineName = freshVm!!.name
logger.trace("<< converting vm ($virtualMachineName) to NodeMetadata")
val vmState = freshVm!!.runtime.getPowerState()
var nodeState: Status? = toPortableNodeStatus.get()[vmState]
if (nodeState == null)
nodeState = Status.UNRECOGNIZED
nodeMetadataBuilder.name(virtualMachineName).ids(virtualMachineName).location(locationBuilder.build()).hostname(virtualMachineName)
val host = freshVm!!.serverConnection.url.host
try {
nodeMetadataBuilder.uri(URI("https://" + host + ":9443/vsphere-client/vmrc/vmrc.jsp?vm=urn:vmomi:VirtualMachine:" + vmMORId + ":" + freshVm!!.summary.getConfig().getUuid()))
} catch (e: URISyntaxException) {
}
val ipv4Addresses = newHashSet<String>()
val ipv6Addresses = newHashSet<String>()
if (nodeState == Status.RUNNING && !freshVm!!.config.isTemplate &&
VSpherePredicate.IsToolsStatusEquals(VirtualMachineToolsStatus.toolsOk).apply(freshVm) &&
VSpherePredicate.isNicConnected(freshVm)) {
Predicates2.retry(Predicate<com.vmware.vim25.mo.VirtualMachine> { vm ->
try {
return@Predicate !Strings.isNullOrEmpty(vm!!.guest.getIpAddress())
} catch (e: Exception) {
return@Predicate false
}
}, 60 * 1000 * 10.toLong(), (10 * 1000).toLong(), TimeUnit.MILLISECONDS).apply(freshVm)
}
if (VSpherePredicate.IsToolsStatusIsIn(Lists.newArrayList(VirtualMachineToolsStatus.toolsNotInstalled, VirtualMachineToolsStatus.toolsNotRunning)).apply(freshVm))
logger.trace("<< No VMware tools installed or not running ( $virtualMachineName )")
else if (nodeState == Status.RUNNING && not(VSpherePredicate.isTemplatePredicate).apply(freshVm)) {
var retries = 0
while (ipv4Addresses.size < 1) {
ipv4Addresses.clear()
ipv6Addresses.clear()
val nics = freshVm!!.guest.getNet()
var nicConnected = false
if (null != nics) {
for (nic in nics) {
nicConnected = nicConnected || nic.connected
val addresses = nic.getIpAddress()
if (null != addresses) {
for (address in addresses) {
if (logger.isTraceEnabled)
logger.trace("<< find IP addresses $address for $virtualMachineName")
if (isInet4Address(address)) {
ipv4Addresses.add(address)
} else if (isInet6Address(address)) {
ipv6Addresses.add(address)
}
}
}
}
}
if (toPortableNodeStatus.get()[freshVm!!.runtime.getPowerState()] != Status.RUNNING) {
logger.trace(">> Node is not running. EXIT IP search.")
break
}
if (freshVm!!.guest.getToolsVersionStatus2() == "guestToolsUnmanaged" && nics == null) {
val ip = freshVm!!.guest.getIpAddress()
if (!Strings.isNullOrEmpty(ip)) {
if (isInet4Address(ip)) {
ipv4Addresses.add(ip)
} else if (isInet6Address(ip)) {
ipv6Addresses.add(ip)
}
}
break
}
if (!nicConnected && retries == 5) {
logger.trace("<< VM does NOT have any NIC connected.")
break
}
if (ipv4Addresses.size < 1 && null != nics) {
logger.warn("<< can't find IPv4 address for vm: " + virtualMachineName)
retries++
Thread.sleep(6000)
}
if (ipv4Addresses.size < 1 && retries == 15) {
logger.error("<< can't find IPv4 address after $retries retries for vm: $virtualMachineName")
break
}
}
nodeMetadataBuilder.publicAddresses(filter(ipv4Addresses, not<String>(isPrivateAddress)))
nodeMetadataBuilder.privateAddresses(filter(ipv4Addresses, isPrivateAddress))
}
nodeMetadataBuilder.status(nodeState)
return nodeMetadataBuilder.build()
}
} catch (t: Throwable) {
logger.error("Got an exception for virtual machine name : " + virtualMachineName)
logger.error("The exception is : " + t.toString())
Throwables.propagate(t)
return nodeMetadataBuilder.build()
}
}
companion object {
private val isPrivateAddress = { addr: String? -> InetAddresses2.IsPrivateIPAddress.INSTANCE.apply(addr) }
private val isInet4Address = { input: String? ->
try {
// Note we can do this, as InetAddress is now on the white list
InetAddresses.forString(input) is Inet4Address
} catch (e: IllegalArgumentException) {
// could be a hostname
false
}
}
private val isInet6Address = { input: String? ->
try {
// Note we can do this, as InetAddress is now on the white list
InetAddresses.forString(input) is Inet6Address
} catch (e: IllegalArgumentException) {
// could be a hostname
false
}
}
}
}
| apache-2.0 | b9d1d5f0e192466e4aef31622597acd9 | 45.027397 | 193 | 0.558036 | 5.487207 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/test/java/co/smartreceipts/android/identity/apis/me/MeResponseTest.kt | 2 | 4840 | package co.smartreceipts.android.identity.apis.me
import co.smartreceipts.android.apis.gson.SmartReceiptsGsonBuilder
import co.smartreceipts.android.date.Iso8601DateFormat
import co.smartreceipts.android.model.ColumnDefinitions
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.core.identity.apis.me.MeResponse
import com.google.gson.Gson
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import java.util.*
@RunWith(RobolectricTestRunner::class)
class MeResponseTest {
companion object {
private const val JSON_EMPTY = "" +
"{\n" +
"}"
private const val OLD_ME_RESPONSE_JSON = "{\n" +
" \"user\":{\n" +
" \"id\":\"1234\",\n" +
" \"email\":\"[email protected]\",\n" +
" \"created_at\":1410400000,\n" +
" \"name\":\"Name\",\n" +
" \"display_name\":\"Display Name\",\n" +
" \"provider\":\"Provider\",\n" +
" \"registration_ids\":[\n" +
" \"REGISTRATION_ID\"\n" +
" ],\n" +
" \"confirmed_at\":\"2014-09-22T11:06:33.556Z\",\n" +
" \"confirmation_sent_at\":null,\n" +
" \"cognito_token\":\"COGNITO_TOKEN\",\n" +
" \"cognito_token_expires_at\":1538076327,\n" +
" \"identity_id\":\"IDENTITY_ID\",\n" +
" \"recognitions_available\":359\n" +
" }\n" +
"}"
private const val NEW_ME_RESPONSE_JSON = "{\n" +
" \"user\":{\n" +
" \"id\":\"1234\",\n" +
" \"email\":\"[email protected]\",\n" +
" \"created_at_iso8601\":\"2014-09-11T03:00:12.368Z\",\n" +
" \"name\":\"Name\",\n" +
" \"display_name\":\"Display Name\",\n" +
" \"provider\":\"Provider\",\n" +
" \"registration_ids\":[\n" +
" \"REGISTRATION_ID\"\n" +
" ],\n" +
" \"confirmed_at_iso8601\":\"2014-09-22T11:06:33.556Z\",\n" +
" \"confirmation_sent_at_iso8601\":null,\n" +
" \"cognito_token\":\"COGNITO_TOKEN\",\n" +
" \"cognito_token_expires_at_iso8601\":\"2015-09-22T11:06:33.556Z\",\n" +
" \"identity_id\":\"IDENTITY_ID\",\n" +
" \"recognitions_available\":359\n" +
" }\n" +
"}"
}
@Mock
lateinit var columnDefinitions: ColumnDefinitions<Receipt>
lateinit var gson: Gson
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
gson = SmartReceiptsGsonBuilder(columnDefinitions).create()
}
@Test
fun deserializeEmptyResponse() {
val response = gson.fromJson<MeResponse>(MeResponseTest.JSON_EMPTY, MeResponse::class.java)
assertNotNull(response)
assertNull(response.user)
}
@Test
fun deserializeOldResponseFormat() {
val response = gson.fromJson<MeResponse>(MeResponseTest.OLD_ME_RESPONSE_JSON, MeResponse::class.java)
assertNotNull(response)
assertNotNull(response.user)
val user = response.user!!
assertEquals("1234", user.id)
assertEquals("[email protected]", user.email)
assertEquals("Name", user.name)
assertEquals("Display Name", user.displayName)
assertEquals("REGISTRATION_ID", user.registrationIds?.get(0))
assertEquals("COGNITO_TOKEN", user.cognitoToken)
assertEquals(Date(1538076327L), user.cognitoTokenExpiresAt)
assertEquals("IDENTITY_ID", user.identityId)
assertEquals(359, user.recognitionsAvailable)
}
@Test
fun deserializeNewResponseFormat() {
val response = gson.fromJson<MeResponse>(MeResponseTest.NEW_ME_RESPONSE_JSON, MeResponse::class.java)
assertNotNull(response)
assertNotNull(response.user)
val user = response.user!!
assertEquals("1234", user.id)
assertEquals("[email protected]", user.email)
assertEquals("Name", user.name)
assertEquals("Display Name", user.displayName)
assertEquals("REGISTRATION_ID", user.registrationIds?.get(0))
assertEquals("COGNITO_TOKEN", user.cognitoToken)
assertEquals(Iso8601DateFormat().parse("2015-09-22T11:06:33.556Z"), user.cognitoTokenExpiresAt)
assertEquals("IDENTITY_ID", user.identityId)
assertEquals(359, user.recognitionsAvailable)
}
} | agpl-3.0 | 611b2522698fd2d4e60c2532c8b37433 | 39.008264 | 109 | 0.552479 | 4.158076 | false | true | false | false |
AlmasB/FXTutorials | src/main/java/com/almasb/fxdocs/Testk.kt | 1 | 1201 | package com.almasb.fxdocs
import java.util.*
typealias D = String
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
fun main(args: Array<String>) {
val D0 = "ab abc cd abd ef e ge bc"
decompose(D0).forEach(::println)
}
private fun decompose(D0: D): List<D> {
println("Decomposing...")
val tokens = D0.split(" +".toRegex()).toMutableList()
println(tokens)
val elements = ArrayDeque<Char>()
val result = arrayListOf<D>()
while (tokens.isNotEmpty()) {
var D1 = ""
elements.add(tokens[0][0])
var usedElements = "" + elements.first
while (elements.isNotEmpty()) {
val e = elements.pop()
val iter = tokens.iterator()
while (iter.hasNext()) {
val token = iter.next()
if (token.contains(e)) {
D1 += token + " "
token.filter { !usedElements.contains(it) }.forEach {
elements.add(it)
usedElements += it
}
iter.remove()
}
}
}
result.add(D1.trim())
}
return result
} | mit | 74e836b7ba981fdbae72f19ae835dc1f | 19.033333 | 73 | 0.492923 | 4.155709 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/test/java/TestManual2.kt | 1 | 11516 | // Copyright 2017-07-21 PlanBase Inc. & Glen Peterson
//
// 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.
import com.planbase.pdf.lm2.PdfLayoutMgr
import com.planbase.pdf.lm2.PdfLayoutMgr.Companion.DEFAULT_MARGIN
import com.planbase.pdf.lm2.attributes.Orientation.*
import com.planbase.pdf.lm2.attributes.*
import com.planbase.pdf.lm2.attributes.Align.*
import com.planbase.pdf.lm2.contents.Cell
import com.planbase.pdf.lm2.contents.ScaledImage
import com.planbase.pdf.lm2.contents.Table
import com.planbase.pdf.lm2.contents.Text
import com.planbase.pdf.lm2.pages.SinglePage
import com.planbase.pdf.lm2.utils.BULLET_CHAR
import com.planbase.pdf.lm2.utils.CMYK_BLACK
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import org.apache.pdfbox.pdmodel.common.PDRectangle
import org.apache.pdfbox.pdmodel.font.PDType1Font
import org.apache.pdfbox.pdmodel.graphics.color.PDColor
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK
import java.io.File
import java.io.FileOutputStream
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Another how-to-use example file
*/
class TestManual2 {
@Test
fun testBody() {
// Nothing happens without a PdfLayoutMgr.
val pageMgr = PdfLayoutMgr(PDDeviceCMYK.INSTANCE, Dim(PDRectangle.A6))
val bodyWidth = PDRectangle.A6.width - 80.0
val f = File("target/test-classes/graph2.png")
// println(f.absolutePath)
val graphPic = ImageIO.read(f)
val lp = pageMgr.startPageGrouping(
PORTRAIT,
a6PortraitBody,
{ pageNum:Int, pb: SinglePage ->
val isLeft = pageNum % 2 == 1
val leftMargin:Double = if (isLeft) 37.0 else 45.0
// System.out.println("pageNum " + pageNum);
pb.drawLine(Coord(leftMargin, 30.0), Coord(leftMargin + bodyWidth, 30.0),
LineStyle(CMYK_THISTLE))
pb.drawStyledText(Coord(leftMargin, 20.0), TextStyle(PDType1Font.HELVETICA, 9.0, CMYK_BLACK),
"Page # " + pageNum, true)
leftMargin })
val bulletTextCellStyle = CellStyle(
Align.TOP_LEFT, BoxStyle(
Padding.NO_PADDING, CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE, LineStyle(CMYK_QUEEN_PINK),
LineStyle.NO_LINE, LineStyle.NO_LINE
)))
// Don't make bullets like this. See WrappedListTest for the right way to do it.
val bulletTable: Table = Table().addCellWidths(30.0, bodyWidth - 30.0)
.startRow()
.cell(BULLET_CELL_STYLE, listOf(Text(BULLET_TEXT_STYLE, BULLET_CHAR)))
.cell(bulletTextCellStyle, listOf(Text(BULLET_TEXT_STYLE, "This is some text that has a bullet")))
.endRow()
.startRow()
.cell(BULLET_CELL_STYLE, listOf(Text(BULLET_TEXT_STYLE, "2.")))
.cell(bulletTextCellStyle, listOf(Text(BULLET_TEXT_STYLE, "Text that has a number")))
.endRow()
val bodyCellStyle = CellStyle(TOP_LEFT_JUSTIFY, BoxStyle(Padding(2.0), CMYK_PALE_PEACH, BorderStyle(CMYK_QUEEN_PINK)))
val bodyCellContinuation = CellStyle(TOP_LEFT_JUSTIFY, BoxStyle(Padding(2.0, 2.0, 8.0, 2.0), CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK),
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK))))
val imageCell = CellStyle(TOP_CENTER, BoxStyle(Padding(0.0, 0.0, 8.0, 0.0), CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK),
LineStyle.NO_LINE,
LineStyle(CMYK_QUEEN_PINK))))
val heading = Cell(CellStyle(BOTTOM_LEFT,
BoxStyle(Padding(10.0, 2.0, 0.0, 2.0), CMYK_PALE_PEACH,
BorderStyle(LineStyle(CMYK_VIOLET, 1.0)))),
bodyWidth,
listOf(Text(HEADING_TEXT_STYLE, "Some Heading")))
var coord = Coord(0.0, pageMgr.pageDim.height - 40.0)
var dap: DimAndPageNums =
lp.add(coord,
Cell(bodyCellStyle,
bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The long "),
Text(TextStyle(PDType1Font.HELVETICA_BOLD, 18.0, CMYK_BLACK),
"families"),
Text(BULLET_TEXT_STYLE,
" needed the national words and women said new."))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, heading.wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height + 0.5)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The new companies told the possible hands that the books" +
" were low."))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, bulletTable.wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The new companies told the possible hands and books was low. " +
"The other questions got the recent children and lots felt" +
" important."))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, Cell(imageCell, bodyWidth, listOf(ScaledImage(graphPic))).wrap())
assertEquals(IntRange(1, 1), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The hard eyes seemed the clear mothers and systems came economic. " +
"The high months showed the possible money and eyes heard certain." +
"People played the different facts and areas showed large. "))).wrap())
assertEquals(IntRange(1, 2), dap.pageNums)
coord = coord.minusY(dap.dim.height)
dap = lp.add(coord, heading.wrap())
assertEquals(IntRange(2, 2), dap.pageNums)
coord = coord.minusY(dap.dim.height + 0.5)
dap = lp.add(coord, Cell(bodyCellContinuation, bodyWidth,
listOf(Text(BULLET_TEXT_STYLE,
"The good ways lived the different countries and stories found good." +
" The certain places found the political months and facts told easy." +
" The long homes ran the good governments and cases lived social."),
ScaledImage(graphPic),
Text(BULLET_TEXT_STYLE,
("The social people ran the local cases and men left local. The " +
"easy areas saw the whole times and systems. The major rights " +
"was the important children and mothers turned unimaginatively.")),
ScaledImage(graphPic),
Text(BULLET_TEXT_STYLE,
("The best points got the economic waters " +
"and problems gave great. The whole " +
"countries went the best children and " +
"eyes became able to see clearly.")))).wrap())
assertEquals(IntRange(2, 3), dap.pageNums)
coord = coord.minusY(dap.dim.height)
lp.drawLine(coord, coord.plusX(bodyWidth), LineStyle(CMYK_QUEEN_PINK))
pageMgr.commit()
// We're just going to write to a file.
val os = FileOutputStream("test2.pdf")
// Commit it to the output stream!
pageMgr.save(os)
}
companion object {
val CMYK_COOL_GRAY = PDColor(floatArrayOf(0.13f, 0.2f, 0f, 0.57f), PDDeviceCMYK.INSTANCE)
val CMYK_LIGHT_GREEN = PDColor(floatArrayOf(0.05f, 0f, 0.1f, 0.01f), PDDeviceCMYK.INSTANCE)
val CMYK_QUEEN_PINK = PDColor(floatArrayOf(0.0f, 0.11f, 0f, 0.09f), PDDeviceCMYK.INSTANCE)
val CMYK_PALE_PEACH = PDColor(floatArrayOf(0.0f, 0.055f, 0.06f, 0f), PDDeviceCMYK.INSTANCE)
val CMYK_THISTLE = PDColor(floatArrayOf(0.05f, 0.19f, 0f, 0.09f), PDDeviceCMYK.INSTANCE)
val CMYK_VIOLET = PDColor(floatArrayOf(0.46f, 0.48f, 0f, 0f), PDDeviceCMYK.INSTANCE)
val a6PortraitBody = PageArea(Coord(DEFAULT_MARGIN, PDRectangle.A6.height - DEFAULT_MARGIN),
Dim(PDRectangle.A6).minus(Dim(DEFAULT_MARGIN * 2, DEFAULT_MARGIN * 2)))
internal val BULLET_CELL_STYLE = CellStyle(TOP_RIGHT,
BoxStyle(Padding(0.0, 4.0, 15.0, 0.0), CMYK_PALE_PEACH,
BorderStyle(
LineStyle.NO_LINE, LineStyle.NO_LINE,
LineStyle.NO_LINE, LineStyle(CMYK_QUEEN_PINK))))
internal val BULLET_TEXT_STYLE = TextStyle(PDType1Font.HELVETICA, 12.0, CMYK_BLACK, "BULLET_TEXT_STYLE")
internal val HEADING_TEXT_STYLE = TextStyle(PDType1Font.TIMES_BOLD, 16.0, CMYK_COOL_GRAY, "HEADING_TEXT_STYLE")
}
} | agpl-3.0 | ba55b9ce0a50f01e2c686f7f741a1092 | 53.582938 | 126 | 0.528048 | 4.690835 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/customize/transferSettings/ui/TransferSettingsLeftPanel.kt | 3 | 1406 | // 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.ide.customize.transferSettings.ui
import com.intellij.ide.customize.transferSettings.models.BaseIdeVersion
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import javax.swing.JList
import javax.swing.ListModel
import javax.swing.ListSelectionModel
import javax.swing.ScrollPaneConstants
import javax.swing.event.ListSelectionEvent
class TransferSettingsLeftPanel(listModel: ListModel<BaseIdeVersion>) : JBScrollPane(JList(listModel)) {
val list get() = (viewport.view as JList<BaseIdeVersion>)
private var previousSelectedIndex = -1
init {
list.apply {
selectionMode = ListSelectionModel.SINGLE_SELECTION
cellRenderer = TransferSettingsLeftPanelItemRenderer()
}
border = JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 1)
background = UIUtil.getListBackground()
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
}
fun addListSelectionListener(action: JList<BaseIdeVersion>.(ListSelectionEvent) -> Unit) {
list.addListSelectionListener s2@{
if (list.selectedIndex == previousSelectedIndex) return@s2
previousSelectedIndex = list.selectedIndex
action(list, it)
}
}
} | apache-2.0 | 9f27fc929af5f1a8f4207f5c2808af5f | 37.027027 | 120 | 0.783073 | 4.625 | false | false | false | false |
google/intellij-community | plugins/ide-features-trainer/src/training/ui/LearningUiHighlightingManager.kt | 5 | 8102 | // 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.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.ui.AbstractPainter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeGlassPane
import com.intellij.ui.ColorUtil
import com.intellij.ui.JBColor
import com.intellij.ui.paint.RectanglePainter
import com.intellij.util.ui.TimerUtil
import java.awt.*
import java.util.*
import javax.swing.*
import javax.swing.tree.TreePath
import kotlin.math.absoluteValue
private const val pulsationSize = 20
object LearningUiHighlightingManager {
data class HighlightingOptions(
val highlightBorder: Boolean = true,
val highlightInside: Boolean = true,
val usePulsation: Boolean = false,
val clearPreviousHighlights: Boolean = true,
)
private val highlights: MutableList<RepaintHighlighting<*>> = ArrayList()
val highlightingComponents: List<Component> get() = highlights.map { it.original }
val highlightingComponentsWithInfo: List<Pair<Component, () -> Any?>> get() = highlights.map { it.original to it.partInfo }
fun highlightComponent(original: Component, options: HighlightingOptions = HighlightingOptions()) {
highlightPartOfComponent(original, options) { Rectangle(Point(0, 0), it.size) }
}
fun highlightJListItem(list: JList<*>,
options: HighlightingOptions = HighlightingOptions(),
index: () -> Int?) {
highlightPartOfComponent(list, options, { index() }) l@{
index()?.let {
if (it in 0 until list.model.size) list.getCellBounds(it, it) else null
}
}
}
fun highlightJTreeItem(tree: JTree,
options: HighlightingOptions = HighlightingOptions(),
path: () -> TreePath?) {
highlightPartOfComponent(tree, options) {
path()?.let { tree.getPathBounds(it) }
}
}
fun <T : Component> highlightPartOfComponent(component: T,
options: HighlightingOptions = HighlightingOptions(),
partInfo: () -> Any? = { null },
rectangle: (T) -> Rectangle?) {
highlightComponent(component, options.clearPreviousHighlights) {
RepaintHighlighting(component, options, partInfo) l@{
val rect = rectangle(component) ?: return@l null
if (component !is JComponent) return@l rect
component.visibleRect.intersection(rect).takeIf { !it.isEmpty }
}
}
}
fun clearHighlights() {
runInEdt {
for (core in highlights) {
removeIt(core)
}
highlights.clear()
}
}
private fun highlightComponent(original: Component,
clearPreviousHighlights: Boolean,
init: () -> RepaintHighlighting<*>) {
runInEdt {
if (clearPreviousHighlights) clearHighlights()
if (!original.isShowing) return@runInEdt // this check is required in rare cases when highlighting called after restore
val repaintByTimer = init()
repaintByTimer.reinitHighlightComponent()
repaintByTimer.initTimer()
highlights.add(repaintByTimer)
}
}
internal fun removeIt(core: RepaintHighlighting<*>) {
core.removed = true
core.cleanup()
}
fun getRectangle(original: Component): Rectangle? =
highlights.find { it.original == original }?.rectangle?.invoke()
}
internal class RepaintHighlighting<T : Component>(val original: T,
val options: LearningUiHighlightingManager.HighlightingOptions,
val partInfo: () -> Any?,
val rectangle: () -> Rectangle?
) {
var removed = false
private val startDate = Date()
private var listLocationOnScreen: Point? = null
private var cellBoundsInList: Rectangle? = null
private var highlightPainter: LearningHighlightPainter? = null
private val pulsationOffset = if (options.usePulsation) pulsationSize else 0
private var disposable: Disposable? = null
fun initTimer() {
val timer = TimerUtil.createNamedTimer("IFT item", 50)
timer.addActionListener {
if (!original.isShowing || original.bounds.isEmpty) {
LearningUiHighlightingManager.removeIt(this)
}
if (this.removed) {
timer.stop()
return@addActionListener
}
if (shouldReinit()) {
cleanup()
reinitHighlightComponent()
}
highlightPainter?.setNeedsRepaint(true)
}
timer.start()
}
fun cleanup() {
disposable?.let {
Disposer.dispose(it)
disposable = null
}
highlightPainter = null
}
private fun shouldReinit(): Boolean {
return highlightPainter == null || original.locationOnScreen != listLocationOnScreen || rectangle() != cellBoundsInList
}
fun reinitHighlightComponent() {
val cellBounds = rectangle() ?: return
cleanup()
val pt = SwingUtilities.convertPoint(original, cellBounds.location, SwingUtilities.getRootPane(original).glassPane)
val bounds = Rectangle(pt.x - pulsationOffset, pt.y - pulsationOffset, cellBounds.width + 2 * pulsationOffset,
cellBounds.height + 2 * pulsationOffset)
val newPainter = LearningHighlightPainter(startDate, options, bounds)
Disposer.newDisposable("RepaintHighlightingDisposable").let {
disposable = it
findIdeGlassPane(original).addPainter(null, newPainter, it)
}
listLocationOnScreen = original.locationOnScreen
cellBoundsInList = cellBounds
highlightPainter = newPainter
}
}
internal class LearningHighlightPainter(
private val startDate: Date,
private val options: LearningUiHighlightingManager.HighlightingOptions,
val bounds: Rectangle
) : AbstractPainter() {
private val pulsationOffset = if (options.usePulsation) pulsationSize else 0
private var previous: Long = 0
override fun executePaint(component: Component?, g: Graphics2D?) {
val g2d = g as Graphics2D
val r: Rectangle = bounds
val oldColor = g2d.color
val time = Date().time
val delta = time - startDate.time
previous = time
val shift = if (pulsationOffset != 0 && (delta / 1000) % 4 == 2.toLong()) {
(((delta / 25 + 20) % 40 - 20).absoluteValue).toInt()
}
else 0
fun cyclicNumber(amplitude: Int, change: Long) = (change % (2 * amplitude) - amplitude).absoluteValue.toInt()
val alphaCycle = cyclicNumber(1000, delta).toDouble() / 1000
val magenta = ColorUtil.withAlpha(Color.magenta, 0.8)
val orange = ColorUtil.withAlpha(Color.orange, 0.8)
val background = ColorUtil.withAlpha(JBColor(Color(0, 0, shift * 10), Color(255 - shift * 10, 255 - shift * 10, 255)),
(0.3 + 0.7 * shift / 20.0) * alphaCycle)
val gradientShift = (delta / 20).toFloat()
val gp = GradientPaint(gradientShift + 0F, gradientShift + 0F, magenta,
gradientShift + r.height.toFloat(), gradientShift + r.height.toFloat(), orange, true)
val x = r.x + pulsationOffset - shift
val y = r.y + pulsationOffset - shift
val width = r.width - (pulsationOffset - shift) * 2
val height = r.height - (pulsationOffset - shift) * 2
RectanglePainter.paint(g2d, x, y, width, height, 2,
if (options.highlightInside) background else null,
if (options.highlightBorder) gp else null)
g2d.color = oldColor
}
override fun needsRepaint(): Boolean = true
}
private fun findIdeGlassPane(component: Component): IdeGlassPane {
val root = when (component) {
is JComponent -> component.rootPane
is RootPaneContainer -> component.rootPane
else -> null
} ?: throw IllegalArgumentException("Component must be visible in order to find glass pane for it")
val gp = root.glassPane
require(gp is IdeGlassPane) { "Glass pane should be " + IdeGlassPane::class.java.name }
return gp
}
| apache-2.0 | b7ce3babae6c59bfc85aa5e9004b9f0a | 35.995434 | 140 | 0.664157 | 4.650976 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt | 1 | 5026 | // 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.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class NullChecksToSafeCallInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
binaryExpressionVisitor { expression ->
if (isNullChecksToSafeCallFixAvailable(expression)) {
holder.registerProblem(
expression,
KotlinBundle.message("null.checks.replaceable.with.safe.calls"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
NullChecksToSafeCallCheckFix()
)
}
}
private class NullChecksToSafeCallCheckFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("null.checks.to.safe.call.check.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
applyFix(descriptor.psiElement as? KtBinaryExpression ?: return)
}
private fun applyFix(expression: KtBinaryExpression) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return
val (lte, rte, isAnd) = collectNullCheckExpressions(expression) ?: return
val parent = expression.parent
expression.replaced(KtPsiFactory(lte.project).buildExpression {
appendExpression(lte)
appendFixedText("?.")
appendExpression(rte.selectorExpression)
appendFixedText(if (isAnd) "!= null" else "== null")
})
if (isNullChecksToSafeCallFixAvailable(parent as? KtBinaryExpression ?: return)) {
applyFix(parent)
}
}
}
companion object {
private fun isNullChecksToSafeCallFixAvailable(expression: KtBinaryExpression): Boolean {
fun String.afterIgnoreCalls() = replace("?.", ".")
val (lte, rte) = collectNullCheckExpressions(expression) ?: return false
val context = expression.analyze()
if (!lte.isChainStable(context)) return false
val resolvedCall = rte.getResolvedCall(context) ?: return false
val extensionReceiver = resolvedCall.extensionReceiver
if (extensionReceiver != null && TypeUtils.isNullableType(extensionReceiver.type)) return false
return rte.receiverExpression.text.afterIgnoreCalls() == lte.text.afterIgnoreCalls()
}
private fun collectNullCheckExpressions(expression: KtBinaryExpression): Triple<KtExpression, KtQualifiedExpression, Boolean>? {
val isAnd = when (expression.operationToken) {
KtTokens.ANDAND -> true
KtTokens.OROR -> false
else -> return null
}
val lhs = expression.left as? KtBinaryExpression ?: return null
val rhs = expression.right as? KtBinaryExpression ?: return null
val expectedOperation = if (isAnd) KtTokens.EXCLEQ else KtTokens.EQEQ
val lte = lhs.getNullTestableExpression(expectedOperation) ?: return null
val rte = rhs.getNullTestableExpression(expectedOperation) as? KtQualifiedExpression ?: return null
return Triple(lte, rte, isAnd)
}
private fun KtBinaryExpression.getNullTestableExpression(expectedOperation: KtToken): KtExpression? {
if (operationToken != expectedOperation) return null
val lhs = left ?: return null
val rhs = right ?: return null
if (KtPsiUtil.isNullConstant(lhs)) return rhs
if (KtPsiUtil.isNullConstant(rhs)) return lhs
return null
}
private fun KtExpression.isChainStable(context: BindingContext): Boolean = when (this) {
is KtReferenceExpression -> isStableSimpleExpression(context)
is KtQualifiedExpression -> selectorExpression?.isStableSimpleExpression(context) == true && receiverExpression.isChainStable(
context
)
else -> false
}
}
}
| apache-2.0 | 0d8bf880c191953638ab5cc4d2bd86ba | 47.326923 | 138 | 0.680462 | 5.763761 | false | false | false | false |
vhromada/Catalog | core/src/test/kotlin/com/github/vhromada/catalog/utils/MediumUtils.kt | 1 | 5885 | package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.domain.io.MediaStatistics
import com.github.vhromada.catalog.entity.Medium
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* A class represents utility class for media.
*
* @author Vladimir Hromada
*/
object MediumUtils {
/**
* Count of media
*/
const val MEDIA_COUNT = 4
/**
* Returns medium for index.
*
* @param index index
* @return medium for index
*/
fun getDomainMedium(index: Int): com.github.vhromada.catalog.domain.Medium {
val lengthMultiplier = 100
return com.github.vhromada.catalog.domain.Medium(
id = index,
number = if (index < 4) 1 else 2,
length = index * lengthMultiplier
).fillAudit(AuditUtils.getAudit())
}
/**
* Returns medium for index.
*
* @param index medium index
* @return medium for index
*/
fun getMedium(index: Int): Medium {
val lengthMultiplier = 100
return Medium(
number = if (index < 4) 1 else 2,
length = index * lengthMultiplier
)
}
/**
* Returns statistics for media.
*
* @return statistics for media
*/
fun getStatistics(): MediaStatistics {
return MediaStatistics(count = MEDIA_COUNT.toLong(), length = 1000L)
}
/**
* Returns count of media.
*
* @param entityManager entity manager
* @return count of media
*/
fun getMediaCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(m.id) FROM Medium m", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns medium.
*
* @param id ID
* @return medium
*/
fun newDomainMedium(id: Int?): com.github.vhromada.catalog.domain.Medium {
return com.github.vhromada.catalog.domain.Medium(
id = id,
number = 1,
length = 10
)
}
/**
* Returns medium.
*
* @return medium
*/
fun newMedium(): Medium {
return Medium(
number = 1,
length = 10
)
}
/**
* Asserts list of medium deep equals.
*
* @param expected expected list of medium
* @param actual actual list of medium
*/
fun assertDomainMediumDeepEquals(expected: List<com.github.vhromada.catalog.domain.Medium>, actual: List<com.github.vhromada.catalog.domain.Medium>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMediumDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts medium deep equals.
*
* @param expected expected medium
* @param actual actual medium
*/
private fun assertMediumDeepEquals(expected: com.github.vhromada.catalog.domain.Medium?, actual: com.github.vhromada.catalog.domain.Medium?) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.length).isEqualTo(expected.length)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
}
}
/**
* Asserts list of medium deep equals.
*
* @param expected expected list of medium
* @param actual actual list of medium
*/
fun assertMediumDeepEquals(expected: List<com.github.vhromada.catalog.domain.Medium>, actual: List<Medium>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMediumDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts medium deep equals.
*
* @param expected expected medium
* @param actual actual medium
*/
private fun assertMediumDeepEquals(expected: com.github.vhromada.catalog.domain.Medium, actual: Medium) {
assertSoftly {
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
/**
* Asserts list of medium deep equals.
*
* @param expected expected list of medium
* @param actual actual list of medium
*/
fun assertMediumListDeepEquals(expected: List<Medium>, actual: List<Medium>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMediumDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts medium deep equals.
*
* @param expected expected medium
* @param actual actual medium
*/
private fun assertMediumDeepEquals(expected: Medium, actual: Medium) {
assertSoftly {
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
/**
* Asserts statistics for media deep equals.
*
* @param expected expected statistics for media
* @param actual actual statistics for media
*/
fun assertStatisticsDeepEquals(expected: MediaStatistics, actual: MediaStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
}
| mit | 817b16c1d72ca05f4fddf8263893987c | 28.278607 | 154 | 0.604928 | 4.583333 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/CustomFrameTitleButtons.kt | 3 | 5102 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.customFrameDecorations
import com.intellij.icons.AllIcons
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.wm.impl.customFrameDecorations.style.ComponentStyle
import com.intellij.openapi.wm.impl.customFrameDecorations.style.ComponentStyleState
import com.intellij.openapi.wm.impl.customFrameDecorations.style.StyleManager
import com.intellij.ui.scale.ScaleType
import com.intellij.util.IconUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Borders
import com.intellij.util.ui.JBUI.CurrentTheme
import net.miginfocom.swing.MigLayout
import java.awt.*
import javax.accessibility.AccessibleContext
import javax.swing.*
import javax.swing.border.Border
import javax.swing.plaf.ButtonUI
import javax.swing.plaf.basic.BasicButtonUI
internal open class CustomFrameTitleButtons constructor(myCloseAction: Action) {
companion object {
private val closeIcon = freezeIconUserSize(AllIcons.Windows.CloseActive)
private val closeHoverIcon = freezeIconUserSize(AllIcons.Windows.CloseHover)
private val closeInactive = freezeIconUserSize(AllIcons.Windows.CloseInactive)
fun create(myCloseAction: Action): CustomFrameTitleButtons {
val darculaTitleButtons = CustomFrameTitleButtons(myCloseAction)
darculaTitleButtons.createChildren()
return darculaTitleButtons
}
fun freezeIconUserSize(icon: Icon): Icon {
return IconUtil.overrideScale(IconUtil.deepCopy(icon, null), ScaleType.USR_SCALE.of(UISettings.defFontScale.toDouble()))
}
}
private val baseStyle = ComponentStyle.ComponentStyleBuilder<JComponent> {
isOpaque = false
border = Borders.empty()
}.apply {
fun paintHover(g: Graphics, width: Int, height: Int, color: Color) {
g.color = color
g.fillRect(0, 0, width, height)
}
class MyBorder(val color: ()-> Color) : Border {
override fun getBorderInsets(c: Component?): Insets = JBUI.emptyInsets()
override fun isBorderOpaque(): Boolean = false
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
paintHover(g, width, height, color())
}
}
val hoverBorder = MyBorder {CurrentTheme.CustomFrameDecorations.titlePaneButtonHoverBackground()}
val pressBorder = MyBorder {CurrentTheme.CustomFrameDecorations.titlePaneButtonPressBackground()}
style(ComponentStyleState.HOVERED) {
this.border = hoverBorder
}
style(ComponentStyleState.PRESSED) {
this.border = pressBorder
}
}
val closeStyleBuilder = ComponentStyle.ComponentStyleBuilder<JButton> {
isOpaque = false
border = Borders.empty()
icon = closeIcon
}.apply {
style(ComponentStyleState.HOVERED) {
isOpaque = true
background = Color(0xe81123)
icon = closeHoverIcon
}
style(ComponentStyleState.PRESSED) {
isOpaque = true
background = Color(0xf1707a)
icon = closeHoverIcon
}
}
private val activeCloseStyle = closeStyleBuilder.build()
private val inactiveCloseStyle = closeStyleBuilder
.updateDefault() {
icon = closeInactive
}.build()
protected val panel = JPanel(MigLayout("top, ins 0 2 0 0, gap 0, hidemode 3, novisualpadding")).apply {
isOpaque = false
}
private val myCloseButton: JButton = createButton("Close", myCloseAction)
var isSelected = false
set(value) {
if(field != value) {
field = value
updateStyles()
}
}
protected open fun updateStyles() {
StyleManager.applyStyle(myCloseButton, if(isSelected) activeCloseStyle else inactiveCloseStyle)
}
protected fun createChildren() {
fillButtonPane()
addCloseButton()
updateVisibility()
updateStyles()
}
fun getView(): JComponent = panel
protected open fun fillButtonPane() {
}
open fun updateVisibility() {
}
private fun addCloseButton() {
addComponent(myCloseButton)
}
protected fun addComponent(component: JComponent) {
component.preferredSize = Dimension((47 * UISettings.defFontScale).toInt(), (28 * UISettings.defFontScale).toInt())
panel.add(component, "top")
}
protected fun getStyle(icon: Icon, hoverIcon : Icon): ComponentStyle<JComponent> {
val clone = baseStyle.clone()
clone.updateDefault {
this.icon = icon
}
clone.updateState(ComponentStyleState.HOVERED) {
this.icon = hoverIcon
}
clone.updateState(ComponentStyleState.PRESSED) {
this.icon = hoverIcon
}
return clone.build()
}
protected fun createButton(accessibleName: String, action: Action): JButton {
val button = object : JButton(){
init {
super.setUI(BasicButtonUI())
}
override fun setUI(ui: ButtonUI?) {
}
}
button.action = action
button.isFocusable = false
button.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, accessibleName)
button.text = null
return button
}
} | apache-2.0 | da99a3f988a5746dac1e3ec57183be05 | 29.740964 | 140 | 0.72109 | 4.432667 | false | false | false | false |
thalescm/kuestioner | sample/src/main/java/br/com/thalesmachado/sample/KuestionerSample.kt | 1 | 1260 | package br.com.thalesmachado.sample
import br.com.thalesmachado.kuestioner.Kuestioner
import br.com.thalesmachado.sample.models.Film
import br.com.thalesmachado.sample.service.StarWarsService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
fun main(args: Array<String>) {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
val retrofit = Retrofit.Builder().baseUrl("http://graphql-swapi.parseapp.com/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val service = retrofit.create(StarWarsService::class.java)
service
.query(Kuestioner.queryOn(Film::class.java, mapOf("id" to "\"ZmlsbXM6MQ==\"")))
.subscribe(
{
println("SUCCESS")
},
{
println("ERROR + $it")
})
} | apache-2.0 | 288a3e191c0a12cefe08f10d77512907 | 35.028571 | 91 | 0.665873 | 4.632353 | false | false | false | false |
cortinico/myo-emg-visualizer | myonnaise/src/main/java/com/ncorti/myonnaise/Myonnaise.kt | 1 | 5170 | package com.ncorti.myonnaise
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.Single
import java.util.concurrent.TimeUnit
/**
* Entry point to the Myonnaise library.
* Use this class to do a Bluetooth scan and search for a new [Myo].
*
* Please note that in order to perform a Bluetooth Scan, the user needs to provide the
* [android.permission.ACCESS_COARSE_LOCATION] permission. You must request this permission to
* the user otherwise your scan will be empty.
*/
class Myonnaise(val context: Context) {
private val blManager = context.getSystemService(Activity.BLUETOOTH_SERVICE) as BluetoothManager
private val blAdapter = blManager.adapter
private val blLowEnergyScanner = blAdapter?.bluetoothLeScanner
private var scanCallback: MyonnaiseScanCallback? = null
/**
* Use this method to perform a scan. This method will return a [Flowable] that will publish
* all the found [BluetoothDevice].
* The scan will be stopped when you cancel the Flowable.
* To set a timeout use the overloaded method
*
* Usage:
* ```
* Myonnaise(context).startScan()
* .subscribeOn(Schedulers.io())
* .observeOn(AndroidSchedulers.mainThread())
* .subscribe({
* // Do something with the found device
* println(it.address)
* })
* ```
* @return A flowable that will publish the found [BluetoothDevice]
*/
fun startScan(): Flowable<BluetoothDevice> {
val scanFlowable: Flowable<BluetoothDevice> = Flowable.create(
{
scanCallback = MyonnaiseScanCallback(it)
blLowEnergyScanner?.startScan(scanCallback)
},
BackpressureStrategy.BUFFER
)
return scanFlowable.doOnCancel {
blLowEnergyScanner?.stopScan(scanCallback)
}
}
/**
* Use this method to perform a scan. This method will return a [Flowable] that will publish
* all the found [BluetoothDevice] and will stop after the timeout.
*
* Usage:
* ```
* Myonnaise(context).startScan(5, TimeUnit.MINUTES)
* .subscribeOn(Schedulers.io())
* .observeOn(AndroidSchedulers.mainThread())
* .subscribe({
* // Do something with the found device.
* println(it.address)
* })
* ```
* @param
* @param interval the timeout value.
* @param timeUnit time units to use for [interval].
*/
fun startScan(interval: Long, timeUnit: TimeUnit): Flowable<BluetoothDevice> =
startScan().takeUntil(Flowable.timer(interval, timeUnit))
/**
* Returns a [Myo] from a [BluetoothDevice]. Use this method after you discovered a device with
* the [startScan] method.
*/
fun getMyo(bluetoothDevice: BluetoothDevice): Myo {
return Myo(bluetoothDevice)
}
/**
* Returns a [Myo] from a Bluetooth address. Please note that this method will perform another
* scan to search for the desired device and return a [Single].
*/
fun getMyo(myoAddress: String): Single<Myo> {
return Single.create {
val filter =
ScanFilter.Builder()
.setDeviceAddress(myoAddress)
.build()
val settings =
ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.build()
blLowEnergyScanner?.startScan(
listOf(filter), settings,
object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.device?.apply {
it.onSuccess(Myo(this))
}
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
it.onError(RuntimeException())
}
}
)
}
}
inner class MyonnaiseScanCallback(private val emitter: FlowableEmitter<BluetoothDevice>) : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.device?.apply { emitter.onNext(this) }
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
emitter.onError(RuntimeException())
}
}
}
| mit | 771f3c7cb4f09621e61839cf568ddc56 | 36.737226 | 111 | 0.595745 | 5.164835 | false | false | false | false |
zdary/intellij-community | plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUi.kt | 1 | 17390 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch.dashboard
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.icons.AllIcons
import com.intellij.ide.CommonActionsManager
import com.intellij.ide.DataManager
import com.intellij.ide.DefaultTreeExpander
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.JBColor
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.speedSearch.SpeedSearch
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.StatusText.getDefaultEmptyText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy
import com.intellij.vcs.log.VcsLogBranchLikeFilter
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.impl.VcsLogManager.BaseVcsLogUiFactory
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties.MAIN_LOG_ID
import com.intellij.vcs.log.ui.VcsLogColorManager
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.ui.VcsLogUiImpl
import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx
import com.intellij.vcs.log.ui.frame.*
import com.intellij.vcs.log.util.VcsLogUiUtil.isDiffPreviewInEditor
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.VisiblePackRefresher
import com.intellij.vcs.log.visible.VisiblePackRefresherImpl
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.with
import com.intellij.vcs.log.visible.filters.without
import git4idea.i18n.GitBundle.message
import git4idea.i18n.GitBundleExtensions.messagePointer
import git4idea.repo.GitRepository
import git4idea.ui.branch.dashboard.BranchesDashboardActions.DeleteBranchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.FetchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.NewBranchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowBranchDiffAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowMyBranchesAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ToggleFavoriteAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.UpdateSelectedBranchAction
import java.awt.Component
import java.awt.datatransfer.DataFlavor
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.TransferHandler
import javax.swing.event.TreeSelectionListener
internal class BranchesDashboardUi(project: Project, private val logUi: BranchesVcsLogUi) : Disposable {
private val uiController = BranchesDashboardController(project, this)
private val tree = FilteringBranchesTree(project, BranchesTreeComponent(project), uiController)
private val branchViewSplitter = BranchViewSplitter()
private val branchesTreePanel = BranchesTreePanel().withBorder(createBorder(JBColor.border(), SideBorder.LEFT))
private val branchesScrollPane = ScrollPaneFactory.createScrollPane(tree.component, true)
private val branchesProgressStripe = ProgressStripe(branchesScrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
private val branchesTreeWithLogPanel = simplePanel()
private val mainPanel = simplePanel().apply { DataManager.registerDataProvider(this, uiController) }
private val branchesSearchFieldPanel = simplePanel()
private val branchesSearchField =
NonOpaquePanel(tree.installSearchField().apply { textEditor.border = JBUI.Borders.emptyLeft(5) }).apply(UIUtil::setNotOpaqueRecursively)
private lateinit var branchesPanelExpandableController: ExpandablePanelController
private val treeSelectionListener = TreeSelectionListener {
if (!branchesPanelExpandableController.isExpanded()) return@TreeSelectionListener
val ui = logUi
val properties = ui.properties
if (properties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) {
updateLogBranchFilter()
}
else if (properties[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY]) {
navigateToSelectedBranch(false)
}
}
internal fun updateLogBranchFilter() {
val ui = logUi
val selectedFilters = tree.getSelectedBranchFilters()
val oldFilters = ui.filterUi.filters
val newFilters = if (selectedFilters.isNotEmpty()) {
oldFilters.without(VcsLogBranchLikeFilter::class.java).with(VcsLogFilterObject.fromBranches(selectedFilters))
} else {
oldFilters.without(VcsLogBranchLikeFilter::class.java)
}
ui.filterUi.filters = newFilters
}
internal fun navigateToSelectedBranch(focus: Boolean) {
val selectedReference = tree.getSelectedBranchFilters().singleOrNull() ?: return
logUi.vcsLog.jumpToReference(selectedReference, focus)
}
internal fun toggleGrouping(key: GroupingKey, state: Boolean) {
tree.toggleGrouping(key, state)
}
internal fun isGroupingEnabled(key: GroupingKey) = tree.isGroupingEnabled(key)
internal fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> {
return tree.getSelectedRepositories(branchInfo)
}
internal fun getSelectedRemotes(): Set<RemoteInfo> {
return tree.getSelectedRemotes()
}
internal fun getRootsToFilter(): Set<VirtualFile> {
val roots = logUi.logData.roots.toSet()
if (roots.size == 1) return roots
return VcsLogUtil.getAllVisibleRoots(roots, logUi.filterUi.filters)
}
private val BRANCHES_UI_FOCUS_TRAVERSAL_POLICY = object : ComponentsListFocusTraversalPolicy() {
override fun getOrderedComponents(): List<Component> = listOf(tree.component, logUi.table,
logUi.changesBrowser.preferredFocusedComponent,
logUi.filterUi.textFilterComponent.textEditor)
}
private val showBranches get() = logUi.properties.get(SHOW_GIT_BRANCHES_LOG_PROPERTY)
init {
initMainUi()
installLogUi()
toggleBranchesPanelVisibility()
}
@RequiresEdt
private fun installLogUi() {
uiController.registerDataPackListener(logUi.logData)
uiController.registerLogUiPropertiesListener(logUi.properties)
uiController.registerLogUiFilterListener(logUi.filterUi)
branchesSearchField.setVerticalSizeReferent(logUi.toolbar)
branchViewSplitter.secondComponent = logUi.mainLogComponent
val isDiffPreviewInEditor = isDiffPreviewInEditor()
val diffPreview = logUi.createDiffPreview(isDiffPreviewInEditor)
if (isDiffPreviewInEditor) {
mainPanel.add(branchesTreeWithLogPanel)
}
else {
mainPanel.add(DiffPreviewSplitter(diffPreview, logUi.properties, branchesTreeWithLogPanel).mainComponent)
}
tree.component.addTreeSelectionListener(treeSelectionListener)
}
@RequiresEdt
private fun disposeBranchesUi() {
branchViewSplitter.secondComponent.removeAll()
uiController.removeDataPackListener(logUi.logData)
uiController.removeLogUiPropertiesListener(logUi.properties)
tree.component.removeTreeSelectionListener(treeSelectionListener)
}
private fun initMainUi() {
val diffAction = ShowBranchDiffAction()
diffAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Diff.ShowDiff"), branchesTreeWithLogPanel)
val deleteAction = DeleteBranchAction()
val shortcuts = KeymapUtil.getActiveKeymapShortcuts("SafeDelete").shortcuts + KeymapUtil.getActiveKeymapShortcuts(
"EditorDeleteToLineStart").shortcuts
deleteAction.registerCustomShortcutSet(CustomShortcutSet(*shortcuts), branchesTreeWithLogPanel)
createFocusFilterFieldAction(branchesSearchField)
installPasteAction(tree)
val toggleFavoriteAction = ToggleFavoriteAction()
val fetchAction = FetchAction(this)
val showMyBranchesAction = ShowMyBranchesAction(uiController)
val newBranchAction = NewBranchAction()
val updateSelectedAction = UpdateSelectedBranchAction()
val defaultTreeExpander = DefaultTreeExpander(tree.component)
val commonActionsManager = CommonActionsManager.getInstance()
val expandAllAction = commonActionsManager.createExpandAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val collapseAllAction = commonActionsManager.createCollapseAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val actionManager = ActionManager.getInstance()
val hideBranchesAction = actionManager.getAction("Git.Log.Hide.Branches")
val settings = actionManager.getAction("Git.Log.Branches.Settings")
val group = DefaultActionGroup()
group.add(hideBranchesAction)
group.add(Separator())
group.add(newBranchAction)
group.add(updateSelectedAction)
group.add(deleteAction)
group.add(diffAction)
group.add(showMyBranchesAction)
group.add(fetchAction)
group.add(toggleFavoriteAction)
group.add(actionManager.getAction("Git.Log.Branches.Navigate.Log.To.Selected.Branch"))
group.add(Separator())
group.add(settings)
group.add(actionManager.getAction("Git.Log.Branches.Grouping.Settings"))
group.add(expandAllAction)
group.add(collapseAllAction)
val toolbar = actionManager.createActionToolbar("Git.Log.Branches", group, false)
toolbar.setTargetComponent(branchesTreePanel)
val branchesButton = ExpandStripeButton(messagePointer("action.Git.Log.Show.Branches.text"), AllIcons.Actions.ArrowExpand)
.apply {
border = createBorder(JBColor.border(), SideBorder.RIGHT)
addActionListener {
if (logUi.properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) {
logUi.properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, true)
}
}
}
branchesSearchFieldPanel.withBackground(UIUtil.getListBackground()).withBorder(createBorder(JBColor.border(), SideBorder.BOTTOM))
branchesSearchFieldPanel.addToCenter(branchesSearchField)
branchesTreePanel.addToTop(branchesSearchFieldPanel).addToCenter(branchesProgressStripe)
branchesPanelExpandableController = ExpandablePanelController(toolbar.component, branchesButton, branchesTreePanel)
branchViewSplitter.firstComponent = branchesTreePanel
branchesTreeWithLogPanel.addToLeft(branchesPanelExpandableController.expandControlPanel).addToCenter(branchViewSplitter)
mainPanel.isFocusCycleRoot = true
mainPanel.focusTraversalPolicy = BRANCHES_UI_FOCUS_TRAVERSAL_POLICY
}
fun toggleBranchesPanelVisibility() {
branchesPanelExpandableController.toggleExpand(showBranches)
updateBranchesTree(true)
}
private fun createFocusFilterFieldAction(searchField: Component) {
DumbAwareAction.create { e ->
val project = e.getRequiredData(CommonDataKeys.PROJECT)
if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(tree.component) != null) {
IdeFocusManager.getInstance(project).requestFocus(searchField, true)
}
else {
IdeFocusManager.getInstance(project).requestFocus(tree.component, true)
}
}.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Find"), branchesTreePanel)
}
private fun installPasteAction(tree: FilteringBranchesTree) {
tree.component.actionMap.put(TransferHandler.getPasteAction().getValue(Action.NAME), object: AbstractAction () {
override fun actionPerformed(e: ActionEvent?) {
val speedSearch = tree.searchModel.speedSearch as? SpeedSearch ?: return
val pasteContent =
CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor)
// the same filtering logic as in javax.swing.text.PlainDocument.insertString (e.g. DnD to search field)
?.let { StringUtil.convertLineSeparators(it, " ") }
speedSearch.type(pasteContent)
speedSearch.update()
}
})
}
inner class BranchesTreePanel : BorderLayoutPanel(), DataProvider {
override fun getData(dataId: String): Any? {
return when {
GIT_BRANCHES.`is`(dataId) -> tree.getSelectedBranches()
GIT_BRANCH_FILTERS.`is`(dataId) -> tree.getSelectedBranchFilters()
BRANCHES_UI_CONTROLLER.`is`(dataId) -> uiController
VcsLogInternalDataKeys.LOG_UI_PROPERTIES.`is`(dataId) -> logUi.properties
else -> null
}
}
}
fun getMainComponent(): JComponent {
return mainPanel
}
fun updateBranchesTree(initial: Boolean) {
if (showBranches) {
tree.update(initial)
}
}
fun refreshTree() {
tree.refreshTree()
}
fun refreshTreeModel() {
tree.refreshNodeDescriptorsModel()
}
fun startLoadingBranches() {
tree.component.emptyText.text = message("action.Git.Loading.Branches.progress")
branchesTreePanel.isEnabled = false
branchesProgressStripe.startLoading()
}
fun stopLoadingBranches() {
tree.component.emptyText.text = getDefaultEmptyText()
branchesTreePanel.isEnabled = true
branchesProgressStripe.stopLoading()
}
override fun dispose() {
disposeBranchesUi()
}
}
internal class BranchesVcsLogUiFactory(logManager: VcsLogManager, logId: String, filters: VcsLogFilterCollection? = null)
: BaseVcsLogUiFactory<BranchesVcsLogUi>(logId, filters, logManager.uiProperties, logManager.colorManager) {
override fun createVcsLogUiImpl(logId: String,
logData: VcsLogData,
properties: MainVcsLogUiProperties,
colorManager: VcsLogColorManager,
refresher: VisiblePackRefresherImpl,
filters: VcsLogFilterCollection?) =
BranchesVcsLogUi(logId, logData, colorManager, properties, refresher, filters)
}
internal class BranchesVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager,
uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher,
initialFilters: VcsLogFilterCollection?) :
VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, initialFilters) {
private val branchesUi =
BranchesDashboardUi(logData.project, this)
.also { branchesUi -> Disposer.register(this, branchesUi) }
internal val mainLogComponent: JComponent
get() = mainFrame
internal val changesBrowser: ChangesBrowserBase
get() = mainFrame.changesBrowser
override fun createMainFrame(logData: VcsLogData, uiProperties: MainVcsLogUiProperties, filterUi: VcsLogFilterUiEx) =
MainFrame(logData, this, uiProperties, filterUi, false, this)
.apply {
isFocusCycleRoot = false
focusTraversalPolicy = null //new focus traversal policy will be configured include branches tree
if (isDiffPreviewInEditor()) {
VcsLogEditorDiffPreview(myProject, uiProperties, this)
}
}
override fun getMainComponent() = branchesUi.getMainComponent()
fun createDiffPreview(isInEditor: Boolean): VcsLogChangeProcessor {
return mainFrame.createDiffPreview(isInEditor, mainFrame.changesBrowser)
}
}
internal val SHOW_GIT_BRANCHES_LOG_PROPERTY =
object : VcsLogProjectTabsProperties.CustomBooleanTabProperty("Show.Git.Branches") {
override fun defaultValue(logId: String) = logId == MAIN_LOG_ID
}
internal val CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Change.Log.Filter.on.Branch.Selection") {
override fun defaultValue() = false
}
internal val NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Navigate.Log.To.Branch.on.Branch.Selection") {
override fun defaultValue() = false
}
private class BranchViewSplitter(first: JComponent? = null, second: JComponent? = null)
: OnePixelSplitter(false, "vcs.branch.view.splitter.proportion", 0.3f) {
init {
firstComponent = first
secondComponent = second
}
}
private class DiffPreviewSplitter(diffPreview: VcsLogChangeProcessor, uiProperties: VcsLogUiProperties, mainComponent: JComponent)
: FrameDiffPreview<VcsLogChangeProcessor>(diffPreview, uiProperties, mainComponent,
"vcs.branch.view.diff.splitter.proportion",
uiProperties[MainVcsLogUiProperties.DIFF_PREVIEW_VERTICAL_SPLIT], 0.3f) {
override fun updatePreview(state: Boolean) {
previewDiff.updatePreview(state)
}
}
| apache-2.0 | bc9688b3260b3c1c900689f7ae717d59 | 42.803526 | 140 | 0.769293 | 5.028918 | false | false | false | false |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt | 1 | 7912 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.google.common.util.concurrent.SettableFuture
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.matches
import com.intellij.vcsUtil.VcsUtil
private const val TAB_NAME = "History"
class VcsLogFileHistoryProviderImpl : VcsLogFileHistoryProvider {
override fun canShowFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!Registry.`is`("vcs.new.history")) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
if (paths.size == 1) {
return canShowSingleFileHistory(project, dataManager, paths.single(), revisionNumber != null)
}
return revisionNumber == null && createPathsFilter(project, dataManager, paths) != null
}
private fun canShowSingleFileHistory(project: Project, dataManager: VcsLogData, path: FilePath, isRevisionHistory: Boolean): Boolean {
val root = VcsLogUtil.getActualRoot(project, path) ?: return false
return dataManager.index.isIndexingEnabled(root) ||
canShowHistoryInLog(dataManager, getCorrectedPath(project, path, root, isRevisionHistory), root)
}
override fun showFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?) {
val hash = revisionNumber?.let { HashImpl.build(it) }
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
triggerFileHistoryUsage(paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
val historyUiConsumer = { ui: VcsLogUiEx, firstTime: Boolean ->
if (hash != null) {
ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true)
}
else if (firstTime) {
ui.jumpToRow(0, true)
}
}
if (paths.size == 1) {
val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (!canShowHistoryInLog(logManager.dataManager, correctedPath, root)) {
findOrOpenHistory(project, logManager, root, correctedPath, hash, historyUiConsumer)
return
}
}
findOrOpenFolderHistory(project, createHashFilter(hash, root), createPathsFilter(project, logManager.dataManager, paths)!!,
historyUiConsumer)
}
private fun canShowHistoryInLog(dataManager: VcsLogData,
correctedPath: FilePath,
root: VirtualFile): Boolean {
if (!correctedPath.isDirectory) {
return false
}
val logProvider = dataManager.logProviders[root] ?: return false
return VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(logProvider)
}
private fun triggerFileHistoryUsage(paths: Collection<FilePath>, hash: Hash?) {
VcsLogUsageTriggerCollector.triggerUsage(VcsLogUsageTriggerCollector.VcsLogEvent.HISTORY_SHOWN) { data ->
val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file"
data.addData("kind", kind).addData("has_revision", hash != null)
}
}
private fun findOrOpenHistory(project: Project, logManager: VcsLogManager,
root: VirtualFile, path: FilePath, hash: Hash?,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var fileHistoryUi = VcsLogContentUtil.findAndSelect(project, FileHistoryUi::class.java) { ui -> ui.matches(path, hash) }
val firstTime = fileHistoryUi == null
if (firstTime) {
val suffix = if (hash != null) " (" + hash.toShortString() + ")" else ""
fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, TAB_NAME, path.name + suffix,
FileHistoryUiFactory(path, root, hash), true)
}
consumer(fileHistoryUi!!, firstTime)
}
private fun findOrOpenFolderHistory(project: Project, hashFilter: VcsLogFilter, pathsFilter: VcsLogFilter,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var ui = VcsLogContentUtil.findAndSelect(project, MainVcsLogUi::class.java) { logUi ->
matches(logUi.filterUi.filters, pathsFilter, hashFilter)
}
val firstTime = ui == null
if (firstTime) {
val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter)
ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return
ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true)
}
consumer(ui!!, firstTime)
}
private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? {
val forRootFilter = mutableSetOf<VirtualFile>()
val forPathsFilter = mutableListOf<FilePath>()
for (path in paths) {
val root = VcsLogUtil.getActualRoot(project, path)
if (root == null) return null
if (!VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null
val correctedPath = getCorrectedPath(project, path, root, false)
if (!correctedPath.isDirectory) return null
if (path.virtualFile == root) {
forRootFilter.add(root)
}
else {
forPathsFilter.add(correctedPath)
}
if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null
}
if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter)
return VcsLogFilterObject.fromRoots(forRootFilter)
}
private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter {
if (hash == null) {
return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.fromCommit(CommitId(hash, root))
}
private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean {
if (!filters.matches(hashFilter.key, pathsFilter.key)) {
return false
}
return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter
}
private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile,
isRevisionHistory: Boolean): FilePath {
var correctedPath = path
if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) {
correctedPath = VcsUtil.getFilePath(correctedPath.path, false)
}
if (!isRevisionHistory) {
return VcsUtil.getLastCommitPath(project, correctedPath)
}
return correctedPath
}
}
private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) {
jumpTo(hash, { model: GraphTableModel, h: Hash? ->
if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo GraphTableModel.COMMIT_NOT_FOUND
val commitIndex: Int = storage.getCommitIndex(h, root)
val visiblePack = model.visiblePack
var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex)
if (rowIndex == null) {
rowIndex = findVisibleAncestorRow(commitIndex, visiblePack)
}
rowIndex ?: GraphTableModel.COMMIT_DOES_NOT_MATCH
}, SettableFuture.create<Boolean>(), silently)
}
| apache-2.0 | 784e9907230031df300c45691d8485e6 | 42.234973 | 140 | 0.710693 | 4.760529 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/signatureAnnotations/defaultBoxTypes.kt | 1 | 1437 | // TARGET_BACKEND: JVM
// FILE: A.java
// ANDROID_ANNOTATIONS
import kotlin.annotations.jvm.internal.*;
public class A {
public Integer a(@DefaultValue("42") Integer arg) {
return arg;
}
public Float b(@DefaultValue("42.5") Float arg) {
return arg;
}
public Boolean c(@DefaultValue("true") Boolean arg) {
return arg;
}
public Byte d(@DefaultValue("42") Byte arg) {
return arg;
}
public Character e(@DefaultValue("o") Character arg) {
return arg;
}
public Double f(@DefaultValue("1e12") Double arg) {
return arg;
}
public Long g(@DefaultValue("42424242424242") Long arg) {
return arg;
}
public Short h(@DefaultValue("123") Short arg) {
return arg;
}
}
// FILE: test.kt
fun box(): String {
val a = A()
if (a.a() != 42) {
return "FAIL Int: ${a.a()}"
}
if (a.b() != 42.5f) {
return "FAIL Float: ${a.b()}"
}
if (!a.c()) {
return "FAIL Boolean: ${a.c()}"
}
if (a.d() != 42.toByte()) {
return "FAIL Byte: ${a.d()}"
}
if (a.e() != 'o') {
return "FAIL Char: ${a.e()}"
}
if (a.f() != 1e12) {
return "FAIl Double: ${a.f()}"
}
if (a.g() != 42424242424242) {
return "FAIL Long: ${a.g()}"
}
if (a.h() != 123.toShort()) {
return "FAIL Short: ${a.h()}"
}
return "OK"
} | apache-2.0 | 7f80d2d8563dcea10127fbff1d23f948 | 16.975 | 61 | 0.492693 | 3.357477 | false | false | false | false |
mpcjanssen/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/FilterActivity.kt | 1 | 15650 | package nl.mpcjanssen.simpletask
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import nl.mpcjanssen.simpletask.remote.FileDialog
import nl.mpcjanssen.simpletask.remote.FileStore
import nl.mpcjanssen.simpletask.task.Priority
import nl.mpcjanssen.simpletask.task.TodoList
import nl.mpcjanssen.simpletask.util.*
import java.io.File
import java.io.IOException
import java.util.*
class FilterActivity : ThemedNoActionBarActivity() {
internal var asWidgetConfigure = false
internal var asWidgetReConfigure = false
internal lateinit var mFilter: Query
internal lateinit var m_app: TodoApplication
val prefs = TodoApplication.config.prefs
private var pager: ViewPager? = null
private var m_menu: Menu? = null
private var pagerAdapter: ScreenSlidePagerAdapter? = null
private var scriptFragment: FilterScriptFragment? = null
private var m_page = 0
override fun onBackPressed() {
if (!asWidgetConfigure && !asWidgetReConfigure) {
applyFilter()
}
super.onBackPressed()
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i(TAG, "Called with intent: " + intent.toString())
m_app = application as TodoApplication
setContentView(R.layout.filter)
val toolbar = findViewById<Toolbar>(R.id.toolbar_edit_filter)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp)
val intent = intent
val environment: String = intent.action?.let {
asWidgetConfigure = it == AppWidgetManager.ACTION_APPWIDGET_CONFIGURE
val id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0)
"widget" + id.toString()
} ?: "mainui"
val context = applicationContext
if (!asWidgetConfigure) {
mFilter = Query(intent, luaModule = environment)
} else if (intent.getBooleanExtra(Constants.EXTRA_WIDGET_RECONFIGURE, false)) {
asWidgetReConfigure = true
asWidgetConfigure = false
setTitle(R.string.config_widget)
val prefsName = intent.getIntExtra(Constants.EXTRA_WIDGET_ID, -1).toString()
val preferences = context.getSharedPreferences(prefsName , Context.MODE_PRIVATE)
mFilter = Query(preferences, luaModule = environment)
} else {
setTitle(R.string.create_widget)
mFilter = Query(prefs, luaModule = environment)
}
pagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager)
val contextTab = FilterListFragment()
contextTab.arguments = Bundle().apply {
val contexts = alfaSort(TodoApplication.todoList.contexts, TodoApplication.config.sortCaseSensitive, "-")
putStringArrayList(FILTER_ITEMS, contexts)
putStringArrayList(INITIAL_SELECTED_ITEMS, mFilter.contexts)
putBoolean(INITIAL_NOT, mFilter.contextsNot)
putString(TAB_TYPE, CONTEXT_TAB)
}
pagerAdapter!!.add(contextTab)
val projectTab = FilterListFragment()
projectTab.arguments = Bundle().apply {
val projects = alfaSort(TodoApplication.todoList.projects, TodoApplication.config.sortCaseSensitive, "-")
putStringArrayList(FILTER_ITEMS, projects)
putStringArrayList(INITIAL_SELECTED_ITEMS, mFilter.projects)
putBoolean(INITIAL_NOT, mFilter.projectsNot)
putString(TAB_TYPE, PROJECT_TAB)
}
pagerAdapter!!.add(projectTab)
val prioTab = FilterListFragment()
prioTab.arguments = Bundle().apply {
putStringArrayList(FILTER_ITEMS, Priority.inCode(TodoApplication.todoList.priorities))
putStringArrayList(INITIAL_SELECTED_ITEMS, Priority.inCode(mFilter.priorities))
putBoolean(INITIAL_NOT, mFilter.prioritiesNot)
putString(TAB_TYPE, PRIO_TAB)
}
pagerAdapter!!.add(prioTab)
val otherTab = FilterOtherFragment()
otherTab.arguments = Bundle().apply {
putBoolean(Query.INTENT_HIDE_COMPLETED_FILTER, mFilter.hideCompleted)
putBoolean(Query.INTENT_HIDE_FUTURE_FILTER, mFilter.hideFuture)
putBoolean(Query.INTENT_HIDE_LISTS_FILTER, mFilter.hideLists)
putBoolean(Query.INTENT_HIDE_TAGS_FILTER, mFilter.hideTags)
putBoolean(Query.INTENT_HIDE_CREATE_DATE_FILTER, mFilter.hideCreateDate)
putBoolean(Query.INTENT_HIDE_HIDDEN_FILTER, mFilter.hideHidden)
putBoolean(Query.INTENT_CREATE_AS_THRESHOLD, mFilter.createIsThreshold)
putString(TAB_TYPE, OTHER_TAB)
}
pagerAdapter!!.add(otherTab)
// Fill arguments for fragment
val sortTab = FilterSortFragment()
sortTab.arguments = Bundle().apply {
putStringArrayList(FILTER_ITEMS, mFilter.getSort(TodoApplication.config.defaultSorts))
putString(TAB_TYPE, SORT_TAB)
}
pagerAdapter!!.add(sortTab)
val scriptTab = FilterScriptFragment()
scriptFragment = scriptTab
scriptTab.arguments = Bundle().apply {
putString(Query.INTENT_LUA_MODULE, environment)
putBoolean(Query.INTENT_USE_SCRIPT_FILTER, mFilter.useScript)
putString(Query.INTENT_SCRIPT_FILTER, mFilter.script)
putString(Query.INTENT_SCRIPT_TEST_TASK_FILTER, mFilter.scriptTestTask)
putString(TAB_TYPE, SCRIPT_TAB)
}
pagerAdapter!!.add(scriptTab)
pager = findViewById<ViewPager>(R.id.pager)
pager!!.adapter = pagerAdapter
// Give the TabLayout the ViewPager
val tabLayout = findViewById<TabLayout>(R.id.sliding_tabs)
tabLayout.setupWithViewPager(pager as ViewPager)
tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
pager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
return
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
return
}
override fun onPageSelected(position: Int) {
Log.i(TAG, "Page $position selected")
m_page = position
}
})
val activePage = prefs.getInt(getString(R.string.last_open_filter_tab), 0)
if (activePage < pagerAdapter?.count ?: 0) {
pager?.setCurrentItem(activePage, false)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
val inflater = menuInflater
inflater.inflate(R.menu.filter, menu)
m_menu = menu
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.menu_filter_action -> {
when {
asWidgetConfigure -> askWidgetName()
asWidgetReConfigure -> {
updateWidget()
finish()
}
else -> applyFilter()
}
}
R.id.menu_filter_load_script -> openScript { contents ->
runOnMainThread(
Runnable { setScript(contents) })
}
}
return true
}
private fun openScript(file_read: (String) -> Unit) {
val dialog = FileDialog()
dialog.addFileListener(object : FileDialog.FileSelectedListener {
override fun fileSelected(file: File) {
Thread(Runnable {
try {
FileStore.readFile(file, file_read)
} catch (e: IOException) {
showToastShort(this@FilterActivity, "Failed to load script.")
e.printStackTrace()
}
}).start()
}
})
dialog.createFileDialog(this@FilterActivity, FileStore, TodoApplication.config.todoFile.parentFile, txtOnly = false)
}
private fun createFilterIntent(): Intent {
val target = Intent(this, Simpletask::class.java)
target.action = Constants.INTENT_START_FILTER
updateFilterFromFragments()
mFilter.saveInIntent(target)
target.putExtra("name", mFilter.proposedName)
return target
}
private fun updateFilterFromFragments() {
for (f in pagerAdapter!!.fragments) {
when (f.arguments?.getString(TAB_TYPE, "")?: "") {
"" -> {
}
OTHER_TAB -> {
val of = f as FilterOtherFragment
mFilter.hideCompleted = of.hideCompleted
mFilter.hideFuture = of.hideFuture
mFilter.hideLists = of.hideLists
mFilter.hideTags = of.hideTags
mFilter.hideCreateDate = of.hideCreateDate
mFilter.hideHidden = of.hideHidden
mFilter.createIsThreshold = of.createAsThreshold
}
CONTEXT_TAB -> {
val lf = f as FilterListFragment
mFilter.contexts = lf.getSelectedItems()
mFilter.contextsNot = lf.getNot()
}
PROJECT_TAB -> {
val pf = f as FilterListFragment
mFilter.projects = pf.getSelectedItems()
mFilter.projectsNot = pf.getNot()
}
PRIO_TAB -> {
val prf = f as FilterListFragment
mFilter.priorities = Priority.toPriority(prf.getSelectedItems())
mFilter.prioritiesNot = prf.getNot()
}
SORT_TAB -> {
val sf = f as FilterSortFragment
mFilter.setSort(sf.selectedItem)
}
SCRIPT_TAB -> {
val scrf = f as FilterScriptFragment
mFilter.useScript = scrf.useScript
mFilter.script = scrf.script
mFilter.scriptTestTask = scrf.testTask
}
}
}
}
private fun setScript(script: String?) {
if (scriptFragment == null) {
// fragment was never intialized
showToastShort(this, "Script tab not visible??")
} else {
script?.let { scriptFragment!!.script = script }
}
}
private fun updateWidget() {
updateFilterFromFragments()
val widgetId = intent.getIntExtra(Constants.EXTRA_WIDGET_ID, 0)
Log.i(TAG, "Saving settings for widget $widgetId")
val preferences = applicationContext.getSharedPreferences("" + widgetId, Context.MODE_PRIVATE)
mFilter.saveInPrefs(preferences)
broadcastRefreshWidgets(m_app.localBroadCastManager)
}
private fun createWidget(name: String) {
val mAppWidgetId: Int
val intent = intent
val extras = intent.extras
updateFilterFromFragments()
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID)
val context = applicationContext
// Store widget applyFilter
val preferences = context.getSharedPreferences("" + mAppWidgetId, Context.MODE_PRIVATE)
val namedFilter = NamedQuery(name, mFilter)
namedFilter.saveInPrefs(preferences)
val appWidgetManager = AppWidgetManager.getInstance(context)
MyAppWidgetProvider.updateAppWidget(context, appWidgetManager,
mAppWidgetId, name)
val resultValue = Intent(applicationContext, AppWidgetService::class.java)
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId)
setResult(Activity.RESULT_OK, resultValue)
finish()
}
}
private fun applyFilter() {
val data = createFilterIntent()
startActivity(data)
finish()
}
private fun askWidgetName() {
val name: String
val alert = AlertDialog.Builder(this)
alert.setTitle("Create widget")
alert.setMessage("Widget title")
updateFilterFromFragments()
name = mFilter.proposedName
// Set an EditText view to get user input
val input = EditText(this)
alert.setView(input)
input.setText(name)
alert.setPositiveButton("Ok") { _, _ ->
val value = input.text.toString()
if (value == "") {
showToastShort(applicationContext, R.string.widget_name_empty)
} else {
createWidget(value)
}
}
alert.setNegativeButton("Cancel") { _, _ -> }
alert.show()
}
override fun onDestroy() {
super.onDestroy()
prefs.edit().putInt(getString(R.string.last_open_filter_tab), m_page).apply()
pager?.clearOnPageChangeListeners()
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private inner class ScreenSlidePagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
val fragments: ArrayList<Fragment>
init {
fragments = ArrayList<Fragment>()
}
fun add(frag: Fragment) {
fragments.add(frag)
}
override fun getPageTitle(position: Int): CharSequence {
val f = fragments[position]
val type = f.arguments?.getString(TAB_TYPE, "unknown") ?:"unknown"
when (type) {
PROJECT_TAB -> return TodoApplication.config.tagTerm
CONTEXT_TAB -> return TodoApplication.config.listTerm
else -> return type
}
}
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
}
companion object {
val TAG = "FilterActivity"
val TAB_TYPE = "type"
val CONTEXT_TAB = "context"
val PROJECT_TAB = "project"
val PRIO_TAB = getString(R.string.filter_tab_header_prio)
val OTHER_TAB = getString(R.string.filter_tab_header_other)
val SORT_TAB = getString(R.string.filter_tab_header_sort)
val SCRIPT_TAB = getString(R.string.filter_tab_header_script)
// Constants for saving state
val FILTER_ITEMS = "items"
val INITIAL_SELECTED_ITEMS = "initialSelectedItems"
val INITIAL_NOT = "initialNot"
}
}
| gpl-3.0 | 924aa420af5504a813b445c0be0b0921 | 36.440191 | 128 | 0.606965 | 5.094401 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/DefaultConnection.kt | 1 | 459 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Connection
/**
* The default implementation of a connection that does not add any other properties.
*/
@JsonClass(generateAdapter = true)
data class DefaultConnection(
@Json(name = "options")
override val options: List<String>? = null,
@Json(name = "uri")
override val uri: String? = null
) : Connection
| mit | 45fa25673c7d6afbea5bbb0877de6f7a | 24.5 | 85 | 0.738562 | 3.923077 | false | false | false | false |
smmribeiro/intellij-community | platform/statistics/src/com/intellij/internal/statistic/collectors/fus/MethodNameRuleValidator.kt | 4 | 1374 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.collectors.fus
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.utils.PluginType
import com.intellij.internal.statistic.utils.getPluginInfo
internal class MethodNameRuleValidator : CustomValidationRule() {
override fun acceptRuleId(ruleId: String?): Boolean = "method_name" == ruleId
override fun doValidate(data: String, context: EventContext): ValidationResultType {
if (isThirdPartyValue(data)) {
return ValidationResultType.ACCEPTED
}
val lastDotIndex = data.lastIndexOf(".")
if (lastDotIndex == -1) {
return ValidationResultType.REJECTED
}
val className = data.substring(0, lastDotIndex)
val info = getPluginInfo(className)
if (info.type === PluginType.UNKNOWN) {
// if we can't detect a plugin then probably it's not a class name
return ValidationResultType.REJECTED
}
return if (info.isSafeToReport()) ValidationResultType.ACCEPTED else ValidationResultType.THIRD_PARTY
}
} | apache-2.0 | c7bb49171504f544006050236f694393 | 40.666667 | 140 | 0.772198 | 4.737931 | false | false | false | false |
mglukhikh/intellij-community | plugins/devkit/src/actions/MigrateModuleNamesInSourcesAction.kt | 1 | 13926 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.idea.devkit.actions
import com.intellij.icons.AllIcons
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleRenamingHistoryState
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Factory
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiPlainText
import com.intellij.psi.search.*
import com.intellij.usageView.UsageInfo
import com.intellij.usages.*
import com.intellij.util.Processor
import com.intellij.util.loadElement
import com.intellij.util.xmlb.XmlSerializationException
import com.intellij.util.xmlb.XmlSerializer
import org.jetbrains.idea.devkit.util.PsiUtil
import java.io.File
import kotlin.experimental.or
private val LOG = Logger.getInstance(MigrateModuleNamesInSourcesAction::class.java)
/**
* This is a temporary action to be used for migrating occurrences of module names in IntelliJ IDEA sources after massive module renaming.
*/
class MigrateModuleNamesInSourcesAction : AnAction("Find/Update Module Names in Sources...", "Find and migrate to the new scheme occurrences of module names in IntelliJ IDEA project sources", null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val viewPresentation = UsageViewPresentation().apply {
tabText = "Occurrences of Module Names"
toolwindowTitle = "Occurrences of Module Names"
usagesString = "occurrences of module names"
usagesWord = "occurrence"
codeUsagesString = "Found Occurrences"
isOpenInNewTab = true
isCodeUsages = false
isUsageTypeFilteringAvailable = true
}
val processPresentation = FindUsagesProcessPresentation(viewPresentation).apply {
isShowNotFoundMessage = true
isShowPanelIfOnlyOneUsage = true
}
val renamingScheme = try {
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(
File(VfsUtil.virtualToIoFile(project.baseDir), "module-renaming-scheme.xml"))?.let {
XmlSerializer.deserialize(loadElement(it.inputStream), ModuleRenamingHistoryState::class.java).oldToNewName
}
}
catch (e: XmlSerializationException) {
LOG.error(e)
return
}
val moduleNames = renamingScheme?.keys?.toList() ?: ModuleManager.getInstance(project).modules.map { it.name }
val targets = moduleNames.map(::ModuleNameUsageTarget).toTypedArray()
val searcherFactory = Factory<UsageSearcher> {
val processed = HashSet<Pair<VirtualFile, Int>>()
UsageSearcher { consumer ->
val usageInfoConsumer = Processor<UsageInfo> {
if (processed.add(Pair(it.virtualFile!!, it.navigationRange!!.startOffset))) {
consumer.process(UsageInfo2UsageAdapter(it))
}
else true
}
processOccurrences(project, moduleNames, usageInfoConsumer)
}
}
val listener = object : UsageViewManager.UsageViewStateListener {
override fun usageViewCreated(usageView: UsageView) {
if (renamingScheme == null) return
val migrateOccurrences = Runnable {
@Suppress("UNCHECKED_CAST")
val usages = (usageView.usages - usageView.excludedUsages) as Set<UsageInfo2UsageAdapter>
val usagesByFile = usages.groupBy { it.file }
val progressIndicator = ProgressManager.getInstance().progressIndicator
var i = 0
usagesByFile.forEach { (file, usages) ->
progressIndicator?.fraction = (i++).toDouble() / usagesByFile.size
try {
usages.sortedByDescending { it.usageInfo.navigationRange!!.startOffset }.forEach {
var range = it.usageInfo.navigationRange!!
if (it.document.charsSequence[range.startOffset] in listOf('"', '\'')) range = TextRange(range.startOffset + 1, range.endOffset - 1)
val oldName = it.document.charsSequence.subSequence(range.startOffset, range.endOffset).toString()
if (oldName !in renamingScheme) throw RuntimeException("Unknown module $oldName")
val newName = renamingScheme[oldName]!!
runWriteAction {
it.document.replaceString(range.startOffset, range.endOffset, newName)
}
}
}
catch (e: Exception) {
throw RuntimeException("Cannot replace usage in ${file.presentableUrl}: ${e.message}", e)
}
}
}
usageView.addPerformOperationAction(migrateOccurrences, "Migrate Module Name Occurrences", "Cannot migrate occurrences", "Migrate Module Name Occurrences")
}
override fun findingUsagesFinished(usageView: UsageView?) {
}
}
UsageViewManager.getInstance(project).searchAndShowUsages(targets, searcherFactory, processPresentation, viewPresentation, listener)
}
private fun processOccurrences(project: Project,
moduleNames: List<String>,
consumer: Processor<UsageInfo>) {
val progress = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator()
progress.text = "Searching for module names..."
val scope = GlobalSearchScope.projectScope(project)
val searchHelper = PsiSearchHelper.SERVICE.getInstance(project)
fun Char.isModuleNamePart() = this.isJavaIdentifierPart() || this == '-'
fun GlobalSearchScope.filter(filter: (VirtualFile) -> Boolean) = object: DelegatingGlobalSearchScope(this) {
override fun contains(file: VirtualFile): Boolean {
return filter(file) && super.contains(file)
}
}
fun mayMentionModuleNames(text: String) = (text.contains("JpsProject") || text.contains("package com.intellij.testGuiFramework")
|| text.contains("getJarPathForClass")) && !text.contains("StandardLicenseUrls")
fun VirtualFile.isBuildScript() = when (extension) {
"gant" -> true
"groovy" -> VfsUtil.loadText(this).contains("package org.jetbrains.intellij.build")
"java" -> mayMentionModuleNames(VfsUtil.loadText(this))
"kt" -> mayMentionModuleNames(VfsUtil.loadText(this))
else -> false
}
fun processCodeUsages(moduleName: String, quotedString: String, groovyOnly: Boolean) {
val ignoredMethods = listOf("getPluginHomePath(", "getPluginHome(", "getPluginHomePathRelative(")
val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
if (element.text != quotedString) return@TextOccurenceProcessor true
if (ignoredMethods.any {
element.textRange.startOffset > it.length && element.containingFile.text.startsWith(it, element.textRange.startOffset - it.length)
}) {
return@TextOccurenceProcessor true
}
consumer.process(UsageInfo(element, offset, offset + quotedString.length))
}
val literalsScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter { it.isBuildScript() &&
!groovyOnly || it.extension in listOf("groovy", "gant") }
else scope
searchHelper.processElementsWithWord(quotedOccurrencesProcessor, literalsScope, quotedString,
UsageSearchContext.IN_CODE or UsageSearchContext.IN_STRINGS, true)
}
fun processUsagesInStrings(moduleName: String, substring: String) {
val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
val text = element.text
if (text[0] == '"' && text.lastOrNull() == '"' || text[0] == '\'' && text.lastOrNull() == '\'') {
consumer.process(UsageInfo(element, offset + substring.indexOf(moduleName), offset + substring.length))
}
else {
true
}
}
searchHelper.processElementsWithWord(quotedOccurrencesProcessor, scope, substring, UsageSearchContext.IN_STRINGS, true)
}
for ((i, moduleName) in moduleNames.withIndex()) {
progress.fraction = i.toDouble() / moduleNames.size
progress.text2 = "Searching for \"$moduleName\""
processCodeUsages(moduleName, "\"$moduleName\"", groovyOnly = false)
processCodeUsages(moduleName, "'$moduleName'", groovyOnly = true)
processUsagesInStrings(moduleName, "production/$moduleName")
processUsagesInStrings(moduleName, "test/$moduleName")
val plainOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
val endOffset = offset + moduleName.length
if ((offset == 0 || element.text[offset - 1].isWhitespace()) && (endOffset == element.textLength || element.text[endOffset].isWhitespace())
&& element is PsiPlainText) {
consumer.process(UsageInfo(element, offset, endOffset))
}
else true
}
val plainTextScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter {it.name == "plugin-list.txt"} else scope
searchHelper.processElementsWithWord(plainOccurrencesProcessor, plainTextScope, moduleName, UsageSearchContext.IN_PLAIN_TEXT, true)
if (moduleName !in regularWordsUsedAsModuleNames) {
val commentsOccurrencesProcessor = TextOccurenceProcessor { element, offset ->
val endOffset = offset + moduleName.length
if ((offset == 0 || !element.text[offset - 1].isModuleNamePart() && element.text[offset-1] != '.')
&& (endOffset == element.textLength || !element.text[endOffset].isModuleNamePart() && element.text[endOffset] != '/'
&& !(endOffset < element.textLength - 2 && element.text[endOffset] == '.' && element.text[endOffset+1].isLetter()))
&& element is PsiComment) {
consumer.process(UsageInfo(element, offset, endOffset))
}
else true
}
searchHelper.processElementsWithWord(commentsOccurrencesProcessor, scope, moduleName, UsageSearchContext.IN_COMMENTS, true)
}
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = PsiUtil.isIdeaProject(e.project)
}
}
private class ModuleNameUsageTarget(val moduleName: String) : UsageTarget, ItemPresentation {
override fun getFiles() = null
override fun getPresentation() = this
override fun canNavigate() = false
override fun getName() = "\"$moduleName\""
override fun findUsages() {
throw UnsupportedOperationException()
}
override fun canNavigateToSource() = false
override fun isReadOnly() = true
override fun navigate(requestFocus: Boolean) {
throw UnsupportedOperationException()
}
override fun findUsagesInEditor(editor: FileEditor) {
}
override fun highlightUsages(file: PsiFile, editor: Editor, clearHighlights: Boolean) {
}
override fun isValid() = true
override fun update() {
}
override fun getPresentableText() = "Occurrences of \"$moduleName\""
override fun getLocationString() = null
override fun getIcon(unused: Boolean) = AllIcons.Nodes.Module!!
}
private val regularWordsUsedAsModuleNames = setOf(
"CloudBees", "AngularJS", "CloudFoundry", "CSS", "CFML", "Docker", "Dart", "EJS", "Guice", "Heroku", "Jade", "Kubernetes", "LiveEdit",
"OpenShift", "Meteor", "NodeJS", "Perforce", "TFS", "WSL", "analyzer", "android", "ant", "annotations", "appcode", "artwork", "asp", "aspectj", "behat", "boot", "bootstrap", "build", "blade",
"commandLineTool", "chronon", "codeception", "common", "commander", "copyright", "coverage", "dependencies", "designer", "ddmlib", "doxygen", "draw9patch", "drupal", "duplicates", "drools", "eclipse", "el", "emma", "editorconfig",
"extensions", "flex", "gherkin", "flags", "freemarker", "github", "gradle", "haml", "graph", "icons", "idea", "images", "ipnb", "jira", "joomla", "jbpm",
"json", "junit", "layoutlib", "less", "localization", "manifest", "main", "markdown", "maven", "ognl", "openapi", "ninepatch", "perflib", "observable", "phing", "php", "phpspec",
"pixelprobe", "play", "profilers", "properties", "puppet", "postcss", "python", "quirksmode", "repository", "resources", "rs", "relaxng", "restClient", "rest", "ruby", "sass", "sdklib", "seam", "ssh",
"spellchecker", "stylus", "swift", "terminal", "tomcat", "textmate", "testData", "testFramework", "testng", "testRunner", "twig", "util", "updater", "vaadin", "vagrant", "vuejs", "velocity", "weblogic",
"websocket", "wizard", "ws", "wordPress", "xml", "xpath", "yaml", "usageView", "error-prone", "spy-js", "WebStorm", "javac2", "dsm", "clion",
"phpstorm", "WebComponents"
)
private val moduleNamesUsedAsIDs = setOf("spring-integration", "spring-aop", "spring-mvc", "spring-security", "spring-webflow", "git4idea", "dvlib", "hg4idea",
"JsTestDriver", "ByteCodeViewer", "appcode-designer", "dsm", "flex",
"google-app-engine", "phpstorm-workshop", "ruby-core", "ruby-slim", "spring-ws", "svn4idea", "Yeoman",
"spring-batch", "spring-data", "sdk-common", "ui-designer") | apache-2.0 | d794ff4315b6c7681f1fc60af8128084 | 50.014652 | 232 | 0.6811 | 4.850575 | false | false | false | false |
smmribeiro/intellij-community | platform/util/concurrency/org/jetbrains/concurrency/promise.kt | 1 | 12093 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmMultifileClass
@file:JvmName("Promises")
package org.jetbrains.concurrency
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.ActionCallback
import com.intellij.util.Function
import com.intellij.util.ThreeState
import com.intellij.util.concurrency.AppExecutorUtil
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.function.Consumer
private val obsoleteError: RuntimeException by lazy { MessageError("Obsolete", false) }
val Promise<*>.isRejected: Boolean
get() = state == Promise.State.REJECTED
val Promise<*>.isPending: Boolean
get() = state == Promise.State.PENDING
private val REJECTED: Promise<*> by lazy {
DonePromise<Any?>(PromiseValue.createRejected(createError("rejected")))
}
@Suppress("RemoveExplicitTypeArguments")
private val fulfilledPromise: CancellablePromise<Any?> by lazy {
DonePromise<Any?>(PromiseValue.createFulfilled(null))
}
@Suppress("UNCHECKED_CAST")
fun <T> resolvedPromise(): Promise<T> = fulfilledPromise as Promise<T>
fun nullPromise(): Promise<*> = fulfilledPromise
/**
* Creates a promise that is resolved with the given value.
*/
fun <T> resolvedPromise(result: T): Promise<T> = resolvedCancellablePromise(result)
/**
* Create a promise that is resolved with the given value.
*/
fun <T> resolvedCancellablePromise(result: T): CancellablePromise<T> {
@Suppress("UNCHECKED_CAST")
return when (result) {
null -> fulfilledPromise as CancellablePromise<T>
else -> DonePromise(PromiseValue.createFulfilled(result))
}
}
@Suppress("UNCHECKED_CAST")
/**
* Consider passing error.
*/
fun <T> rejectedPromise(): Promise<T> = REJECTED as Promise<T>
fun <T> rejectedPromise(error: String): Promise<T> = rejectedCancellablePromise(error)
fun <T> rejectedPromise(error: Throwable?): Promise<T> {
@Suppress("UNCHECKED_CAST")
return when (error) {
null -> REJECTED as Promise<T>
else -> DonePromise(PromiseValue.createRejected(error))
}
}
fun <T> rejectedCancellablePromise(error: String): CancellablePromise<T> =
DonePromise(PromiseValue.createRejected(createError(error, true)))
@Suppress("RemoveExplicitTypeArguments")
private val CANCELLED_PROMISE: Promise<Any?> by lazy {
DonePromise(PromiseValue.createRejected<Any?>(obsoleteError))
}
@Suppress("UNCHECKED_CAST")
fun <T> cancelledPromise(): Promise<T> = CANCELLED_PROMISE as Promise<T>
// only internal usage
interface ObsolescentFunction<Param, Result> : Function<Param, Result>, Obsolescent
abstract class ValueNodeAsyncFunction<PARAM, RESULT>(private val node: Obsolescent) : Function<PARAM, Promise<RESULT>>, Obsolescent {
override fun isObsolete(): Boolean = node.isObsolete
}
abstract class ObsolescentConsumer<T>(private val obsolescent: Obsolescent) : Obsolescent, Consumer<T> {
override fun isObsolete(): Boolean = obsolescent.isObsolete
}
inline fun <T, SUB_RESULT> Promise<T>.then(obsolescent: Obsolescent, crossinline handler: (T) -> SUB_RESULT): Promise<SUB_RESULT> = then(object : ObsolescentFunction<T, SUB_RESULT> {
override fun `fun`(param: T) = handler(param)
override fun isObsolete() = obsolescent.isObsolete
})
inline fun <T> Promise<T>.onSuccess(node: Obsolescent, crossinline handler: (T) -> Unit): Promise<T> = onSuccess(object : ObsolescentConsumer<T>(node) {
override fun accept(param: T) = handler(param)
})
inline fun Promise<*>.processed(node: Obsolescent, crossinline handler: () -> Unit): Promise<Any?>? {
@Suppress("UNCHECKED_CAST")
return (this as Promise<Any?>)
.onProcessed(object : ObsolescentConsumer<Any?>(node) {
override fun accept(param: Any?) = handler()
})
}
@Suppress("UNCHECKED_CAST")
inline fun <T> Promise<*>.thenRun(crossinline handler: () -> T): Promise<T> = (this as Promise<Any?>).then { handler() }
@Suppress("UNCHECKED_CAST")
inline fun Promise<*>.processedRun(crossinline handler: () -> Unit): Promise<*> {
return (this as Promise<Any?>).onProcessed { handler() }
}
inline fun <T, SUB_RESULT> Promise<T>.thenAsync(node: Obsolescent, crossinline handler: (T) -> Promise<SUB_RESULT>): Promise<SUB_RESULT> = thenAsync(object : ValueNodeAsyncFunction<T, SUB_RESULT>(node) {
override fun `fun`(param: T) = handler(param)
})
@Suppress("UNCHECKED_CAST")
inline fun <T> Promise<T>.thenAsyncAccept(node: Obsolescent, crossinline handler: (T) -> Promise<*>): Promise<Any?> {
return thenAsync(object : ValueNodeAsyncFunction<T, Any?>(node) {
override fun `fun`(param: T) = handler(param) as Promise<Any?>
})
}
inline fun <T> Promise<T>.thenAsyncAccept(crossinline handler: (T) -> Promise<*>): Promise<Any?> = thenAsync(Function { param ->
@Suppress("UNCHECKED_CAST")
(return@Function handler(param) as Promise<Any?>)
})
inline fun Promise<*>.onError(node: Obsolescent, crossinline handler: (Throwable) -> Unit): Promise<out Any> = onError(object : ObsolescentConsumer<Throwable>(node) {
override fun accept(param: Throwable) = handler(param)
})
/**
* Merge results into one list. Results are ordered as in the promises list.
*
* `T` here is a not nullable type, if you use this method from Java, take care that all promises are not resolved to `null`.
*
* If `ignoreErrors = false`, list of the same size is returned.
* If `ignoreErrors = true`, list of different size is returned if some promise failed with error.
*/
@JvmOverloads
fun <T : Any> Collection<Promise<T>>.collectResults(ignoreErrors: Boolean = false): Promise<List<T>> {
if (isEmpty()) {
return resolvedPromise(emptyList())
}
val result = AsyncPromise<List<T>>()
val latch = AtomicInteger(size)
val list = Collections.synchronizedList(Collections.nCopies<T?>(size, null).toMutableList())
fun arrive() {
if (latch.decrementAndGet() == 0) {
if (ignoreErrors) {
list.removeIf { it == null }
}
@Suppress("UNCHECKED_CAST")
result.setResult(list as List<T>)
}
}
for ((i, promise) in this.withIndex()) {
promise.onSuccess {
list.set(i, it)
arrive()
}
promise.onError {
if (ignoreErrors) {
arrive()
}
else {
result.setError(it)
}
}
}
return result
}
@JvmOverloads
fun createError(error: String, log: Boolean = false): RuntimeException = MessageError(error, log)
inline fun <T> AsyncPromise<T>.compute(runnable: () -> T) {
val result = try {
runnable()
}
catch (e: Throwable) {
setError(e)
return
}
setResult(result)
}
inline fun <T> runAsync(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
}
/**
* Log error if not a message error
*/
fun Logger.errorIfNotMessage(e: Throwable): Boolean {
if (e is MessageError) {
val log = e.log
if (log == ThreeState.YES || (log == ThreeState.UNSURE && ApplicationManager.getApplication()?.isUnitTestMode == true)) {
error(e)
return true
}
}
else if (e !is ControlFlowException && e !is CancellationException) {
error(e)
return true
}
return false
}
fun ActionCallback.toPromise(): Promise<Any?> {
val promise = AsyncPromise<Any?>()
doWhenDone { promise.setResult(null) }
.doWhenRejected { error -> promise.setError(createError(error ?: "Internal error")) }
return promise
}
fun Promise<*>.toActionCallback(): ActionCallback {
val result = ActionCallback()
onSuccess { result.setDone() }
onError { result.setRejected() }
return result
}
fun Collection<Promise<*>>.all(): Promise<*> = if (size == 1) first() else all(null)
/**
* @see collectResults
*/
@JvmOverloads
fun <T: Any?> Collection<Promise<*>>.all(totalResult: T, ignoreErrors: Boolean = false): Promise<T> {
if (isEmpty()) {
return resolvedPromise()
}
val totalPromise = AsyncPromise<T>()
val done = CountDownConsumer(size, totalPromise, totalResult)
val rejected = if (ignoreErrors) {
Consumer { done.accept(null) }
}
else {
Consumer<Throwable> { totalPromise.setError(it) }
}
for (promise in this) {
promise.onSuccess(done)
promise.onError(rejected)
}
return totalPromise
}
private class CountDownConsumer<T : Any?>(countDown: Int, private val promise: AsyncPromise<T>, private val totalResult: T) : Consumer<Any?> {
private val countDown = AtomicInteger(countDown)
override fun accept(t: Any?) {
if (countDown.decrementAndGet() == 0) {
promise.setResult(totalResult)
}
}
}
fun <T> any(promises: Collection<Promise<T>>, totalError: String): Promise<T> {
if (promises.isEmpty()) {
return resolvedPromise()
}
else if (promises.size == 1) {
return promises.first()
}
val totalPromise = AsyncPromise<T>()
val done = Consumer<T> { result -> totalPromise.setResult(result) }
val rejected = object : Consumer<Throwable> {
private val toConsume = AtomicInteger(promises.size)
override fun accept(throwable: Throwable) {
if (toConsume.decrementAndGet() <= 0) {
totalPromise.setError(totalError)
}
}
}
for (promise in promises) {
promise.onSuccess(done)
promise.onError(rejected)
}
return totalPromise
}
private class DonePromise<T>(private val value: PromiseValue<T>) : Promise<T>, Future<T>, CancellablePromise<T> {
/**
* The same as @{link Future[Future.isDone]}.
* Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
*/
override fun isDone() = true
override fun getState() = value.state
override fun isCancelled() = this.value.isCancelled
override fun get() = blockingGet(-1)
override fun get(timeout: Long, unit: TimeUnit) = blockingGet(timeout.toInt(), unit)
override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
if (state == Promise.State.PENDING) {
cancel()
return true
}
else {
return false
}
}
override fun onSuccess(handler: Consumer<in T?>): CancellablePromise<T> {
if (value.error != null) {
return this
}
if (!isHandlerObsolete(handler)) {
handler.accept(value.result)
}
return this
}
@Suppress("UNCHECKED_CAST")
override fun processed(child: Promise<in T?>): Promise<T> {
if (child is CompletablePromise<*>) {
(child as CompletablePromise<T>).setResult(value.result)
}
return this
}
override fun onProcessed(handler: Consumer<in T?>): CancellablePromise<T> {
if (value.error == null) {
onSuccess(handler)
}
else if (!isHandlerObsolete(handler)) {
handler.accept(null)
}
return this
}
override fun onError(handler: Consumer<in Throwable?>): CancellablePromise<T> {
if (value.error != null && !isHandlerObsolete(handler)) {
handler.accept(value.error)
}
return this
}
override fun <SUB_RESULT : Any?> then(done: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> {
@Suppress("UNCHECKED_CAST")
return when {
value.error != null -> this as Promise<SUB_RESULT>
isHandlerObsolete(done) -> cancelledPromise()
else -> DonePromise(PromiseValue.createFulfilled(done.`fun`(value.result)))
}
}
override fun <SUB_RESULT : Any?> thenAsync(done: Function<in T, out Promise<SUB_RESULT>>): Promise<SUB_RESULT> {
if (value.error == null) {
return done.`fun`(value.result)
}
else {
@Suppress("UNCHECKED_CAST")
return this as Promise<SUB_RESULT>
}
}
override fun blockingGet(timeout: Int, timeUnit: TimeUnit) = value.getResultOrThrowError()
override fun cancel() {}
} | apache-2.0 | 46d768311aa6dd3f540fad83d4e1a0f9 | 29.159601 | 203 | 0.69503 | 4.012276 | false | false | false | false |
FTL-Lang/FTL-Compiler | src/main/kotlin/com/thomas/needham/ftl/frontend/symbols/InterfaceSymbol.kt | 1 | 4319 | /*
The MIT License (MIT)
FTL-Lang Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.frontend.symbols
import java.util.*
/**
* This class represents a defined interface within the compiler
* @author Thomas Needham
*/
class InterfaceSymbol<Type> : Symbol<Type> {
/**
* Unique identifier to represent this symbol
*/
override var id: UUID
/**
* The name of this symbol
*/
override val name: String
/**
* the value of this symbol
*/
override var value: Type?
/**
* The scope in which this symbol is defined
*/
override val scope: Scope
/**
* Whether this symbol is read only
*/
override val readOnly : Boolean
/**
* Whether this symbol is initialised
*/
override var initialised: Boolean
/**
* MutableList of functions defined within this interface
*/
val functions : MutableList<FunctionSymbol<*>>
/**
* Constructor for variable symbol
* @param id the unique identifier of the symbol
* @param name the name of this symbol
* @param value the value of this symbol
* @param readOnly whether this symbol is read only
* @param scope the scope tthat this symbol is defined in
* @param initialised whether this symbol has been initialised defaults to false
* @param functions MutableList of functions defined in this interface
*/
constructor(id: UUID, name: String, value: Type?, readOnly: Boolean, scope: Scope, initialised: Boolean = false,
functions: MutableList<FunctionSymbol<*>> = mutableListOf()){
this.id = id
this.name = name
this.value = value
this.readOnly = readOnly
this.scope = scope
this.initialised = initialised
this.functions = functions
}
/**
* Function to generate unique symbol id
* @param table the symbol table that this symbol is in
* @return A unique ID to represent a symbol
*/
override fun generateID(table: SymbolTable): UUID {
val symbols : MutableList<Symbol<*>> = table.symbols.filter { e -> e is InterfaceSymbol<*> }.toMutableList()
var found : Boolean = false
var id : UUID = UUID.fromString("0".repeat(128))
while (!found){
id = UUID.randomUUID()
for(sym: Symbol<*> in symbols){
if(sym.id == id)
found = true
}
}
return id
}
/**
* Function to compare if two symbols are equal
* @param other the symbol to compare this symbol with
* @return Whether both symbols are equal
*/
override fun equals(other: Any?): Boolean {
if(other !is InterfaceSymbol<*>?)
return false
if (other === null)
return true
return this.id == other.id && this.name == other.name &&
this.value == other.value && this.scope == other.scope &&
this.readOnly == other.readOnly && this.initialised == other.initialised &&
this.functions.containsAll(other.functions)
}
/**
* Generates a hashCode for this symbol
* @return the generated hash code
*/
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + id.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + (value?.hashCode() ?: 0)
result = 31 * result + scope.hashCode()
result = 31 * result + readOnly.hashCode()
result = 31 * result + initialised.hashCode()
result = 31 * result + functions.hashCode()
return result
}
} | mit | ab48c9db61d26c8a01488448165442fb | 30.079137 | 113 | 0.699931 | 4.136973 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/IAM.kt | 1 | 6464 | package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.identitymanagement.model.*
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.IAM
import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy
class IAMManagedPolicyResourcePropertiesBuilder : ResourcePropertiesBuilder<CreatePolicyRequest> {
override val requestClazz = CreatePolicyRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreatePolicyRequest).let {
IAM.ManagedPolicy(
Description = it.description,
PolicyDocument = it.policyDocument.let { IAMGroupResourcePropertiesBuilder.JSON.readValue<Map<String, Any>>(it) },
Path = it.path
)
}
}
class IAMAccessKeyResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateAccessKeyRequest> {
override val requestClazz = CreateAccessKeyRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateAccessKeyRequest).let {
IAM.AccessKey(
UserName = request.userName,
Status = relatedObjects.filterIsInstance<UpdateAccessKeyRequest>().lastOrNull()?.status ?: "Active"
)
}
}
class IAMGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateGroupRequest> {
companion object {
val JSON = jacksonObjectMapper()
.setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
override val requestClazz = CreateGroupRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateGroupRequest).let {
IAM.Group(
GroupName = request.groupName,
Path = request.path,
ManagedPolicyArns = relatedObjects.filterIsInstance<AttachGroupPolicyRequest>().map { it.policyArn },
Policies = relatedObjects.filterIsInstance<PutGroupPolicyRequest>().map {
IAM.Role.PolicyProperty(
PolicyName = it.policyName,
PolicyDocument = it.policyDocument.let { JSON.readValue<Map<String, Any>>(it) }
)
}
)
}
}
class IAMUserResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateUserRequest> {
override val requestClazz = CreateUserRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateUserRequest).let {
IAM.User(
Path = request.path,
UserName = request.userName,
Groups = relatedObjects.filterIsInstance<AddUserToGroupRequest>().map {
it.groupName
},
LoginProfile = relatedObjects.filterIsInstance<CreateLoginProfileRequest>().lastOrNull()?.let {
IAM.User.LoginProfileProperty(
Password = it.password,
PasswordResetRequired = it.passwordResetRequired?.toString()
)
},
ManagedPolicyArns = relatedObjects.filterIsInstance<AttachUserPolicyRequest>().map { it.policyArn },
Policies = relatedObjects.filterIsInstance<PutUserPolicyRequest>().map {
IAM.Role.PolicyProperty(
PolicyName = it.policyName,
PolicyDocument = it.policyDocument.let { IAMGroupResourcePropertiesBuilder.JSON.readValue<Map<String, Any>>(it) }
)
}
)
}
}
class IamInstanceProfilePropertiesBuilder : ResourcePropertiesBuilder<CreateInstanceProfileRequest> {
override val requestClazz = CreateInstanceProfileRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateInstanceProfileRequest).let {
IAM.InstanceProfile(
Path = request.path ?: "/",
Roles = relatedObjects.filterIsInstance(AddRoleToInstanceProfileRequest::class.java).map {
it.roleName
}
)
}
}
class IamPolicyResourcePropertiesBuilder : ResourcePropertiesBuilder<CreatePolicyRequest> {
override val requestClazz = CreatePolicyRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreatePolicyRequest).let {
IAM.Policy(
PolicyName = request.policyName,
PolicyDocument = jacksonObjectMapper().readTree(request.policyDocument),
Roles = relatedObjects.filterIsInstance(AttachRolePolicyRequest::class.java).map {
it.roleName
}
)
}
}
class IamRoleResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateRoleRequest> {
override val requestClazz = CreateRoleRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateRoleRequest).let {
IAM.Role(
AssumeRolePolicyDocument = jacksonObjectMapper().readTree(request.assumeRolePolicyDocument),
Path = request.path,
ManagedPolicyArns = relatedObjects.filterIsInstance<AttachRolePolicyRequest>().map { it.policyArn },
Policies = relatedObjects.filterIsInstance<PutRolePolicyRequest>().map {
IAM.Role.PolicyProperty(
PolicyName = it.policyName,
PolicyDocument = it.policyDocument.let { IAMGroupResourcePropertiesBuilder.JSON.readValue<Map<String, Any>>(it) }
)
},
RoleName = it.roleName
)
}
} | mit | 2c5f075000fa5ad0bfbed020195a07e7 | 43.586207 | 137 | 0.641399 | 5.968606 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryEntityImpl.kt | 1 | 20928 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.io.Serializable
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class LibraryEntityImpl : LibraryEntity, WorkspaceEntityBase() {
companion object {
internal val SDK_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, SdkEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val LIBRARYPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java,
LibraryPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java,
LibraryFilesPackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE,
false)
val connections = listOf<ConnectionId>(
SDK_CONNECTION_ID,
LIBRARYPROPERTIES_CONNECTION_ID,
LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID,
)
}
@JvmField
var _name: String? = null
override val name: String
get() = _name!!
@JvmField
var _tableId: LibraryTableId? = null
override val tableId: LibraryTableId
get() = _tableId!!
@JvmField
var _roots: List<LibraryRoot>? = null
override val roots: List<LibraryRoot>
get() = _roots!!
@JvmField
var _excludedRoots: List<VirtualFileUrl>? = null
override val excludedRoots: List<VirtualFileUrl>
get() = _excludedRoots!!
override val sdk: SdkEntity?
get() = snapshot.extractOneToOneChild(SDK_CONNECTION_ID, this)
override val libraryProperties: LibraryPropertiesEntity?
get() = snapshot.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this)
override val libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
get() = snapshot.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: LibraryEntityData?) : ModifiableWorkspaceEntityBase<LibraryEntity>(), LibraryEntity.Builder {
constructor() : this(LibraryEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity LibraryEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "excludedRoots", this.excludedRoots.toHashSet())
indexLibraryRoots(roots)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field LibraryEntity#name should be initialized")
}
if (!getEntityData().isTableIdInitialized()) {
error("Field LibraryEntity#tableId should be initialized")
}
if (!getEntityData().isRootsInitialized()) {
error("Field LibraryEntity#roots should be initialized")
}
if (!getEntityData().isExcludedRootsInitialized()) {
error("Field LibraryEntity#excludedRoots should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as LibraryEntity
this.entitySource = dataSource.entitySource
this.name = dataSource.name
this.tableId = dataSource.tableId
this.roots = dataSource.roots.toMutableList()
this.excludedRoots = dataSource.excludedRoots.toMutableList()
if (parents != null) {
}
}
private fun indexLibraryRoots(libraryRoots: List<LibraryRoot>) {
val jarDirectories = mutableSetOf<VirtualFileUrl>()
val libraryRootList = libraryRoots.map {
if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) {
jarDirectories.add(it.url)
}
it.url
}.toHashSet()
index(this, "roots", libraryRootList)
indexJarDirectories(this, jarDirectories)
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var tableId: LibraryTableId
get() = getEntityData().tableId
set(value) {
checkModificationAllowed()
getEntityData().tableId = value
changedProperty.add("tableId")
}
private val rootsUpdater: (value: List<LibraryRoot>) -> Unit = { value ->
val _diff = diff
if (_diff != null) {
indexLibraryRoots(value)
}
changedProperty.add("roots")
}
override var roots: MutableList<LibraryRoot>
get() {
val collection_roots = getEntityData().roots
if (collection_roots !is MutableWorkspaceList) return collection_roots
collection_roots.setModificationUpdateAction(rootsUpdater)
return collection_roots
}
set(value) {
checkModificationAllowed()
getEntityData().roots = value
rootsUpdater.invoke(value)
}
private val excludedRootsUpdater: (value: List<VirtualFileUrl>) -> Unit = { value ->
val _diff = diff
if (_diff != null) index(this, "excludedRoots", value.toHashSet())
changedProperty.add("excludedRoots")
}
override var excludedRoots: MutableList<VirtualFileUrl>
get() {
val collection_excludedRoots = getEntityData().excludedRoots
if (collection_excludedRoots !is MutableWorkspaceList) return collection_excludedRoots
collection_excludedRoots.setModificationUpdateAction(excludedRootsUpdater)
return collection_excludedRoots
}
set(value) {
checkModificationAllowed()
getEntityData().excludedRoots = value
excludedRootsUpdater.invoke(value)
}
override var sdk: SdkEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(SDK_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity
}
else {
this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(SDK_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] = value
}
changedProperty.add("sdk")
}
override var libraryProperties: LibraryPropertiesEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity
}
else {
this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(LIBRARYPROPERTIES_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("libraryProperties")
}
override var libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("libraryFilesPackagingElement")
}
override fun getEntityData(): LibraryEntityData = result ?: super.getEntityData() as LibraryEntityData
override fun getEntityClass(): Class<LibraryEntity> = LibraryEntity::class.java
}
}
class LibraryEntityData : WorkspaceEntityData.WithCalculablePersistentId<LibraryEntity>(), SoftLinkable {
lateinit var name: String
lateinit var tableId: LibraryTableId
lateinit var roots: MutableList<LibraryRoot>
lateinit var excludedRoots: MutableList<VirtualFileUrl>
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isTableIdInitialized(): Boolean = ::tableId.isInitialized
fun isRootsInitialized(): Boolean = ::roots.isInitialized
fun isExcludedRootsInitialized(): Boolean = ::excludedRoots.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
result.add(_tableId.moduleId)
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
index.index(this, _tableId.moduleId)
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
val removedItem__tableId_moduleId = mutablePreviousSet.remove(_tableId.moduleId)
if (!removedItem__tableId_moduleId) {
index.index(this, _tableId.moduleId)
}
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val _tableId = tableId
val res_tableId = when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
_tableId
}
is LibraryTableId.ModuleLibraryTableId -> {
val _tableId_moduleId_data = if (_tableId.moduleId == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
var _tableId_data = _tableId
if (_tableId_moduleId_data != null) {
_tableId_data = _tableId_data.copy(moduleId = _tableId_moduleId_data)
}
_tableId_data
}
is LibraryTableId.ProjectLibraryTableId -> {
_tableId
}
}
if (res_tableId != null) {
tableId = res_tableId
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryEntity> {
val modifiable = LibraryEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): LibraryEntity {
val entity = LibraryEntityImpl()
entity._name = name
entity._tableId = tableId
entity._roots = roots.toList()
entity._excludedRoots = excludedRoots.toList()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun clone(): LibraryEntityData {
val clonedEntity = super.clone()
clonedEntity as LibraryEntityData
clonedEntity.roots = clonedEntity.roots.toMutableWorkspaceList()
clonedEntity.excludedRoots = clonedEntity.excludedRoots.toMutableWorkspaceList()
return clonedEntity
}
override fun persistentId(): PersistentEntityId<*> {
return LibraryId(name, tableId)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return LibraryEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return LibraryEntity(name, tableId, roots, excludedRoots, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.tableId != other.tableId) return false
if (this.roots != other.roots) return false
if (this.excludedRoots != other.excludedRoots) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryEntityData
if (this.name != other.name) return false
if (this.tableId != other.tableId) return false
if (this.roots != other.roots) return false
if (this.excludedRoots != other.excludedRoots) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + tableId.hashCode()
result = 31 * result + roots.hashCode()
result = 31 * result + excludedRoots.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + tableId.hashCode()
result = 31 * result + roots.hashCode()
result = 31 * result + excludedRoots.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(LibraryRootTypeId::class.java)
collector.add(LibraryRoot.InclusionOptions::class.java)
collector.add(LibraryRoot::class.java)
collector.add(LibraryTableId::class.java)
collector.add(LibraryTableId.ModuleLibraryTableId::class.java)
collector.add(LibraryTableId.GlobalLibraryTableId::class.java)
collector.add(ModuleId::class.java)
collector.addObject(LibraryTableId.ProjectLibraryTableId::class.java)
this.roots?.let { collector.add(it::class.java) }
this.excludedRoots?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | b7b2a2346dcd6f2318f4432c583cfd92 | 36.776173 | 201 | 0.668578 | 5.36753 | false | false | false | false |
plusCubed/velociraptor | app/src/main/java/com/pluscubed/velociraptor/api/raptor/RaptorLimitProvider.kt | 1 | 5587 | package com.pluscubed.velociraptor.api.raptor
import android.content.Context
import android.location.Location
import androidx.annotation.WorkerThread
import com.android.billingclient.api.Purchase
import com.google.maps.android.PolyUtil
import com.pluscubed.velociraptor.BuildConfig
import com.pluscubed.velociraptor.api.*
import com.pluscubed.velociraptor.api.cache.CacheLimitProvider
import com.pluscubed.velociraptor.billing.BillingConstants
import com.pluscubed.velociraptor.utils.PrefUtils
import com.pluscubed.velociraptor.utils.Utils
import okhttp3.OkHttpClient
import java.util.*
class RaptorLimitProvider(
private val context: Context,
client: OkHttpClient,
private val cacheLimitProvider: CacheLimitProvider
) : LimitProvider {
private val SERVER_URL = "http://overpass.pluscubed.com:4000/"
private val raptorService: RaptorService
private var id: String
private var hereToken: String
private var tomtomToken: String
companion object {
const val USE_DEBUG_ID = BuildConfig.BUILD_TYPE == "debug"
}
init {
val interceptor = LimitInterceptor(LimitInterceptor.Callback())
val raptorClient = client.newBuilder()
.addInterceptor(interceptor)
.build()
val raptorRest = LimitFetcher.buildRetrofit(raptorClient, SERVER_URL)
raptorService = raptorRest.create(RaptorService::class.java)
id = UUID.randomUUID().toString()
if (USE_DEBUG_ID) {
val resId =
context.resources.getIdentifier("debug_id", "string", context.getPackageName())
if (resId != 0) {
id = context.getString(resId);
}
}
hereToken = ""
tomtomToken = ""
}
/**
* Returns whether updated token
*/
@WorkerThread
fun verify(purchase: Purchase): Boolean {
var updated = false
val verificationNetworkResponse = raptorService.verify(id, purchase.originalJson).execute()
val verificationResponse = Utils.getResponseBody(verificationNetworkResponse)
val token = verificationResponse.token
if (purchase.sku == BillingConstants.SKU_HERE || USE_DEBUG_ID) {
if (hereToken.isEmpty())
updated = true
hereToken = token
}
if (purchase.sku == BillingConstants.SKU_TOMTOM || USE_DEBUG_ID) {
if (tomtomToken.isEmpty())
updated = true
tomtomToken = token
}
return updated
}
override fun getSpeedLimit(
location: Location,
lastResponse: LimitResponse?,
origin: Int
): List<LimitResponse> {
val latitude = String.format(Locale.ROOT, "%.5f", location.latitude)
val longitude = String.format(Locale.ROOT, "%.5f", location.longitude)
when (origin) {
LimitResponse.ORIGIN_HERE ->
if (!hereToken.isEmpty()) {
val hereResponse = queryRaptorApi(true, latitude, longitude, location)
return listOf(hereResponse)
}
LimitResponse.ORIGIN_TOMTOM ->
if (!tomtomToken.isEmpty()) {
val tomtomResponse = queryRaptorApi(false, latitude, longitude, location)
return listOf(tomtomResponse)
}
}
return emptyList()
}
private fun queryRaptorApi(
isHere: Boolean,
latitude: String,
longitude: String,
location: Location
): LimitResponse {
val raptorQuery = if (isHere) {
raptorService.getHere(
"Bearer $hereToken",
id,
latitude,
longitude,
location.bearing.toInt(),
"Metric"
)
} else {
raptorService.getTomtom(
"Bearer $tomtomToken",
id,
latitude,
longitude,
location.bearing.toInt(),
"Metric"
)
}
val debuggingEnabled = PrefUtils.isDebuggingEnabled(context)
try {
val raptorNetworkResponse = raptorQuery.execute();
val raptorResponse = Utils.getResponseBody(raptorNetworkResponse)
val coords = PolyUtil.decode(raptorResponse.polyline).map { latLng ->
Coord(latLng.latitude, latLng.longitude)
}
val speedLimit = if (raptorResponse.generalSpeedLimit == 0) {
-1
} else {
raptorResponse.generalSpeedLimit!!
}
val response = LimitResponse(
roadName = if (raptorResponse.name.isEmpty()) "null" else raptorResponse.name,
speedLimit = speedLimit,
timestamp = System.currentTimeMillis(),
coords = coords,
origin = getOriginInt(isHere)
).initDebugInfo(debuggingEnabled)
cacheLimitProvider.put(response)
return response
} catch (e: Exception) {
return LimitResponse(
error = e,
timestamp = System.currentTimeMillis(),
origin = getOriginInt(isHere)
).initDebugInfo(debuggingEnabled)
}
}
private fun getOriginInt(here: Boolean) =
if (here) LimitResponse.ORIGIN_HERE else LimitResponse.ORIGIN_TOMTOM
}
| gpl-3.0 | 735fb844e7b7cc925840a212036eaa09 | 32.860606 | 99 | 0.580992 | 5.197209 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/pager2/KViewPager2.kt | 1 | 5201 | @file:Suppress("unused")
package com.agoda.kakao.pager2
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.DataInteraction
import androidx.test.espresso.Root
import androidx.test.espresso.matcher.RootMatchers
import com.agoda.kakao.common.KakaoDslMarker
import com.agoda.kakao.common.actions.SwipeableActions
import com.agoda.kakao.common.assertions.BaseAssertions
import com.agoda.kakao.common.builders.ViewBuilder
import com.agoda.kakao.common.matchers.PositionMatcher
import com.agoda.kakao.delegate.ViewInteractionDelegate
import org.hamcrest.Matcher
import kotlin.reflect.KClass
/**
* View with SwipeableActions and ViewPager2Assertions
*
* @see SwipeableActions
*/
@KakaoDslMarker
class KViewPager2 : ViewPager2Actions, ViewPager2AdapterAssertions, SwipeableActions, BaseAssertions {
val matcher: Matcher<View>
val itemTypes: Map<KClass<out KViewPagerItem<*>>, KViewPagerItemType<KViewPagerItem<*>>>
override val view: ViewInteractionDelegate
override var root: Matcher<Root> = RootMatchers.DEFAULT
/**
* Constructs view class with view interaction from given ViewBuilder
*
* @param builder ViewBuilder which will result in view's interaction
* @param itemTypeBuilder Lambda with receiver where you pass your item providers
*
* @see ViewBuilder
*/
constructor(builder: ViewBuilder.() -> Unit, itemTypeBuilder: KViewPagerItemTypeBuilder.() -> Unit) {
val vb = ViewBuilder().apply(builder)
matcher = vb.getViewMatcher()
view = vb.getViewInteractionDelegate()
itemTypes = KViewPagerItemTypeBuilder().apply(itemTypeBuilder).itemTypes
}
/**
* Constructs view class with parent and view interaction from given ViewBuilder
*
* @param parent Matcher that will be used as parent in isDescendantOfA() matcher
* @param builder ViewBuilder which will result in view's interaction
* @param itemTypeBuilder Lambda with receiver where you pass your item providers
*
* @see ViewBuilder
*/
constructor(
parent: Matcher<View>, builder: ViewBuilder.() -> Unit,
itemTypeBuilder: KViewPagerItemTypeBuilder.() -> Unit
) : this({
isDescendantOfA { withMatcher(parent) }
builder(this)
}, itemTypeBuilder)
/**
* Constructs view class with parent and view interaction from given ViewBuilder
*
* @param parent DataInteraction that will be used as parent to ViewBuilder
* @param builder ViewBuilder which will result in view's interaction
* @param itemTypeBuilder Lambda with receiver where you pass your item providers
*
* @see ViewBuilder
*/
@Suppress("UNCHECKED_CAST")
constructor(
parent: DataInteraction, builder: ViewBuilder.() -> Unit,
itemTypeBuilder: KViewPagerItemTypeBuilder.() -> Unit
) {
val makeTargetMatcher = DataInteraction::class.java.getDeclaredMethod("makeTargetMatcher")
val parentMatcher = makeTargetMatcher.invoke(parent)
val vb = ViewBuilder().apply {
isDescendantOfA { withMatcher(parentMatcher as Matcher<View>) }
builder(this)
}
matcher = vb.getViewMatcher()
view = vb.getViewInteractionDelegate()
itemTypes = KViewPagerItemTypeBuilder().apply(itemTypeBuilder).itemTypes
}
/**
* Performs given actions/assertion on child at given position
*
* @param T Type of item at given position. Must be registered via constructor.
* @param position Position of item in adapter
* @param function Tail lambda which receiver will be matched item with given type T
*/
inline fun <reified T : KViewPagerItem<*>> childAt(position: Int, function: T.() -> Unit) {
val provideItem = itemTypes.getOrElse(T::class) {
throw IllegalStateException("${T::class.java.simpleName} did not register to KViewPager2")
}.provideItem
try {
scrollTo(position)
} catch (error: Throwable) {
}
val vb = ViewBuilder().apply {
isDescendantOfA { withMatcher([email protected]) }
isInstanceOf(RecyclerView::class.java)
}
function(provideItem(PositionMatcher(vb.getViewMatcher(), position)) as T)
.also { inRoot { withMatcher([email protected]) } }
}
/**
* Operator that allows usage of DSL style
*
* @param function Tail lambda with receiver which is your view
*/
operator fun invoke(function: KViewPager2.() -> Unit) {
function(this)
}
/**
* Infix function for invoking lambda on your view
*
* Sometimes instance of view is a result of a function or constructor.
* In this specific case you can't call invoke() since it will be considered as
* tail lambda of your fun/constructor. In such cases please use this function.
*
* @param function Tail lambda with receiver which is your view
* @return This object
*/
infix fun perform(function: KViewPager2.() -> Unit): KViewPager2 {
function(this)
return this
}
}
| apache-2.0 | aea6650974e5537ac5a346d2d3f6beb7 | 36.15 | 105 | 0.687752 | 4.915879 | false | false | false | false |
cypressious/injekt | api/src/main/kotlin/uy/kohesive/injekt/api/Factory.kt | 1 | 3686 | @file:Suppress("NOTHING_TO_INLINE")
package uy.kohesive.injekt.api
import java.lang.reflect.Type
import kotlin.reflect.KClass
public interface InjektFactory {
public fun <R: Any> getInstance(forType: Type): R
public fun <R: Any> getInstanceOrElse(forType: Type, default: R): R
public fun <R: Any> getInstanceOrElse(forType: Type, default: ()->R): R
public fun <R: Any, K: Any> getKeyedInstance(forType: Type, key: K): R
public fun <R: Any, K: Any> getKeyedInstanceOrElse(forType: Type, key: K, default: R): R
public fun <R: Any, K: Any> getKeyedInstanceOrElse(forType: Type, key: K, default: ()->R): R
public fun <R: Any> getLogger(expectedLoggerType: Type, byName: String): R
public fun <R: Any, T: Any> getLogger(expectedLoggerType: Type, forClass: Class<T>): R
}
public inline fun <R: Any> InjektFactory.get(forType: TypeReference<R>): R = getInstance(forType.type)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, default: R): R = getInstanceOrElse(forType.type, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, noinline default: ()->R): R = getInstanceOrElse(forType.type, default)
public inline fun <reified R: Any> InjektFactory.invoke(): R = getInstance(fullType<R>().type)
public inline fun <reified R: Any> InjektFactory.get(): R = getInstance(fullType<R>().type)
public inline fun <reified R: Any> InjektFactory.getOrElse(default: R): R = getInstanceOrElse(fullType<R>().type, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(noinline default: ()->R): R = getInstanceOrElse(fullType<R>().type, default)
public inline fun <R: Any> InjektFactory.get(forType: TypeReference<R>, key: Any): R = getKeyedInstance(forType.type, key)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, key: Any, default: R): R = getKeyedInstanceOrElse(forType.type, key, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(forType: TypeReference<R>, key: Any, noinline default: ()->R): R = getKeyedInstanceOrElse(forType.type, key, default)
public inline fun <reified R: Any> InjektFactory.get(key: Any): R = getKeyedInstance(fullType<R>().type, key)
public inline fun <reified R: Any> InjektFactory.getOrElse(key: Any, default: R): R = getKeyedInstanceOrElse(fullType<R>().type, key, default)
public inline fun <reified R: Any> InjektFactory.getOrElse(key: Any, noinline default: ()->R): R = getKeyedInstanceOrElse(fullType<R>().type, key, default)
public inline fun <R: Any, T: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, forClass: Class<T>): R = getLogger(expectedLoggerType.type, forClass)
public inline fun <reified R: Any, T: Any> InjektFactory.logger(forClass: Class<T>): R = getLogger(fullType<R>().type, forClass)
public inline fun <R: Any, T: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, forClass: KClass<T>): R = getLogger(expectedLoggerType.type, forClass.java)
public inline fun <reified R: Any, T: Any> InjektFactory.logger(forClass: KClass<T>): R = getLogger(fullType<R>().type, forClass.java)
public inline fun <R: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, byName: String): R = getLogger(expectedLoggerType.type, byName)
public inline fun <reified R: Any> InjektFactory.logger(byName: String): R = getLogger(fullType<R>().type, byName)
public inline fun <R: Any> InjektFactory.logger(expectedLoggerType: TypeReference<R>, byObject: Any): R = getLogger(expectedLoggerType.type, byObject.javaClass)
public inline fun <reified R: Any> InjektFactory.logger(byObject: Any): R = getLogger(fullType<R>().type, byObject.javaClass)
| mit | bb1e866be39b10f0a6eb0d5b3e2104d0 | 72.72 | 176 | 0.747151 | 3.900529 | false | false | false | false |
JetBrains/xodus | openAPI/src/main/kotlin/jetbrains/exodus/crypto/Krypt.kt | 1 | 1653 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.crypto
import jetbrains.exodus.InvalidSettingException
import jetbrains.exodus.util.HexUtil
import java.io.InputStream
import java.io.OutputStream
fun newCipherProvider(cipherId: String) = StreamCipherProvider.getProvider(cipherId) ?:
throw ExodusCryptoException("Failed to load StreamCipherProvider with id = $cipherId")
fun newCipher(cipherId: String): StreamCipher = newCipherProvider(cipherId).newCipher()
fun StreamCipher.with(key: ByteArray, iv: Long) = this.apply { init(key, iv) }
fun toBinaryKey(cipherKey: String): ByteArray {
if (cipherKey.length and 1 == 1) {
throw InvalidSettingException("Odd length of hex representation of cipher key")
}
return HexUtil.stringToByteArray(cipherKey)
}
infix fun OutputStream.encryptBy(cipher: StreamCipher) = StreamCipherOutputStream(this, cipher)
infix fun InputStream.decryptBy(cipherGetter: () -> StreamCipher) = StreamCipherInputStream(this, cipherGetter)
internal fun StreamCipher.cryptAsInt(b: Byte) = this.crypt(b).toInt() and 0xff
| apache-2.0 | 5265e4215e618f5e9e97e001b7f5a482 | 39.317073 | 111 | 0.766485 | 4.206107 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/statistics/KotlinCreateFileFUSCollector.kt | 4 | 1532 | // 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.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
class KotlinCreateFileFUSCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP = EventLogGroup("kotlin.ide.new.file", 2)
private val pluginInfo = getPluginInfoById(KotlinIdePlugin.id)
private val allowedTemplates = listOf(
"Kotlin_Class",
"Kotlin_File",
"Kotlin_Interface",
"Kotlin_Data_Class",
"Kotlin_Enum",
"Kotlin_Sealed_Class",
"Kotlin_Annotation",
"Kotlin_Object",
"Kotlin_Scratch",
"Kotlin_Script",
"Kotlin_Worksheet"
)
private val newFileEvent = GROUP.registerEvent(
"Created",
EventFields.String("file_template", allowedTemplates),
EventFields.PluginInfo
)
fun logFileTemplate(template: String) = newFileEvent.log(template.replace(' ', '_'), pluginInfo)
}
}
| apache-2.0 | 7513619216390a3c6eef93fa5e3ed659 | 37.3 | 158 | 0.679504 | 4.848101 | false | false | false | false |
jwren/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/PluginLayout.kt | 1 | 16574 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.openapi.util.Pair
import com.intellij.util.containers.MultiMap
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.JvmArchitecture
import org.jetbrains.intellij.build.OsFamily
import org.jetbrains.intellij.build.PluginBundlingRestrictions
import java.nio.file.Files
import java.nio.file.Path
import java.util.function.*
/**
* Describes layout of a plugin in the product distribution
*/
class PluginLayout(val mainModule: String): BaseLayout() {
private var mainJarName = "${convertModuleNameToFileName(mainModule)}.jar"
lateinit var directoryName: String
var versionEvaluator: VersionEvaluator = object : VersionEvaluator {
override fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String {
return ideBuildVersion
}
}
var pluginXmlPatcher: UnaryOperator<String> = UnaryOperator.identity()
var directoryNameSetExplicitly: Boolean = false
lateinit var bundlingRestrictions: PluginBundlingRestrictions
val pathsToScramble: MutableList<String> = mutableListOf()
val scrambleClasspathPlugins: MutableList<Pair<String /*plugin name*/, String /*relative path*/>> = mutableListOf()
var scrambleClasspathFilter: BiPredicate<BuildContext, Path> = BiPredicate { _, _ -> true }
/**
* See {@link org.jetbrains.intellij.build.impl.PluginLayout.PluginLayoutSpec#zkmScriptStub}
*/
var zkmScriptStub: String? = null
var pluginCompatibilityExactVersion = false
var retainProductDescriptorForBundledPlugin = false
val resourceGenerators: MutableList<Pair<BiFunction<Path, BuildContext, Path>, String>> = mutableListOf()
val patchers: MutableList<BiConsumer<ModuleOutputPatcher, BuildContext>> = mutableListOf()
fun getMainJarName() = mainJarName
companion object {
/**
* Creates the plugin layout description. The default plugin layout is composed of a jar with name {@code mainModuleName}.jar containing
* production output of {@code mainModuleName} module, and the module libraries of {@code mainModuleName} with scopes 'Compile' and 'Runtime'
* placed under 'lib' directory in a directory with name {@code mainModuleName}.
* If you need to include additional resources or modules into the plugin layout specify them in
* {@code body} parameter. If you don't need to change the default layout there is no need to call this method at all, it's enough to
* specify the plugin module in {@link org.jetbrains.intellij.build.ProductModulesLayout#bundledPluginModules bundledPluginModules/pluginModulesToPublish} list.
*
* <p>Note that project-level libraries on which the plugin modules depend, are automatically put to 'IDE_HOME/lib' directory for all IDEs
* which are compatible with the plugin. If this isn't desired (e.g. a library is used in a single plugin only, or if plugins where
* a library is used aren't bundled with IDEs so we don't want to increase size of the distribution, you may invoke {@link PluginLayoutSpec#withProjectLibrary}
* to include such a library to the plugin distribution.</p>
* @param mainModuleName name of the module containing META-INF/plugin.xml file of the plugin
*/
@JvmStatic
fun plugin(mainModuleName: String, body: Consumer<PluginLayoutSpec>): PluginLayout {
if (mainModuleName.isEmpty()) {
error("mainModuleName must be not empty")
}
val layout = PluginLayout(mainModuleName)
val spec = PluginLayoutSpec(layout)
body.accept(spec)
layout.directoryName = spec.directoryName
if (!layout.getIncludedModuleNames().contains(mainModuleName)) {
layout.withModule(mainModuleName, layout.mainJarName)
}
if (spec.mainJarNameSetExplicitly) {
layout.explicitlySetJarPaths.add(layout.mainJarName)
}
else {
layout.explicitlySetJarPaths.remove(layout.mainJarName)
}
layout.directoryNameSetExplicitly = spec.directoryNameSetExplicitly
layout.bundlingRestrictions = spec.bundlingRestrictions.build()
return layout
}
@JvmStatic
fun simplePlugin(mainModuleName: String): PluginLayout {
if (mainModuleName.isEmpty()) {
error("mainModuleName must be not empty")
}
val layout = PluginLayout(mainModuleName)
layout.directoryName = convertModuleNameToFileName(layout.mainModule)
layout.withModuleImpl(mainModuleName, layout.mainJarName)
layout.bundlingRestrictions = PluginBundlingRestrictions.NONE
return layout
}
}
override fun toString(): String {
return "Plugin '$mainModule'"
}
override fun withModule(moduleName: String) {
if (moduleName.endsWith(".jps") || moduleName.endsWith(".rt")) {
// must be in a separate JAR
super.withModule(moduleName)
}
else {
withModuleImpl(moduleName, mainJarName)
}
}
fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) {
resourceGenerators.add(Pair(BiFunction<Path, BuildContext, Path>{ targetDir, context ->
generator.accept(targetDir, context)
null
}, ""))
}
fun mergeServiceFiles() {
patchers.add(BiConsumer { patcher, context ->
val discoveredServiceFiles: MultiMap<String, Pair<String, Path>> = MultiMap.createLinkedSet()
moduleJars.get(mainJarName).forEach { moduleName: String ->
val path = context.findFileInModuleSources(moduleName, "META-INF/services")
if (path == null) return@forEach
Files.list(path).use { stream ->
stream
.filter { Files.isRegularFile(it) }
.forEach { serviceFile: Path ->
discoveredServiceFiles.putValue(serviceFile.fileName.toString(), Pair.create(moduleName, serviceFile))
}
}
}
discoveredServiceFiles.entrySet().forEach { entry: Map.Entry<String, Collection<Pair<String, Path>>> ->
val serviceFileName = entry.key
val serviceFiles: Collection<Pair<String, Path>> = entry.value
if (serviceFiles.size <= 1) return@forEach
val content = serviceFiles.joinToString("\n") { Files.readString(it.second) }
context.messages.info("Merging service file " + serviceFileName + " (" + serviceFiles.joinToString(", ") { it.first } + ")")
patcher.patchModuleOutput(serviceFiles.first().first, // first one wins
"META-INF/services/$serviceFileName",
content)
}
})
}
class PluginLayoutSpec(private val layout: PluginLayout): BaseLayoutSpec(layout) {
var directoryName: String = convertModuleNameToFileName(layout.mainModule)
/**
* Custom name of the directory (under 'plugins' directory) where the plugin should be placed. By default the main module name is used
* (with stripped {@code intellij} prefix and dots replaced by dashes).
* <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged.
*/
set(value) {
field = value
directoryNameSetExplicitly = true
}
var mainJarNameSetExplicitly: Boolean = false
private set
var directoryNameSetExplicitly: Boolean = false
private set
val mainModule
get() = layout.mainModule
/**
* Returns {@link PluginBundlingRestrictions} instance which can be used to exclude the plugin from some distributions.
*/
val bundlingRestrictions: PluginBundlingRestrictionBuilder = PluginBundlingRestrictionBuilder()
class PluginBundlingRestrictionBuilder {
/**
* Change this value if the plugin works in some OS only and therefore don't need to be bundled with distributions for other OS.
*/
var supportedOs: List<OsFamily> = OsFamily.ALL
/**
* Change this value if the plugin works on some architectures only and
* therefore don't need to be bundled with distributions for other architectures.
*/
var supportedArch: List<JvmArchitecture> = JvmArchitecture.ALL
/**
* Set to {@code true} if the plugin should be included in distribution for EAP builds only.
*/
var includeInEapOnly: Boolean = false
fun build(): PluginBundlingRestrictions =
PluginBundlingRestrictions(supportedOs, supportedArch, includeInEapOnly)
}
var mainJarName: String
get() = layout.mainJarName
/**
* Custom name of the main plugin JAR file. By default the main module name with 'jar' extension is used (with stripped {@code intellij}
* prefix and dots replaced by dashes).
* <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged.
*/
set(value) {
layout.mainJarName = value
mainJarNameSetExplicitly = true
}
/**
* @param binPathRelativeToCommunity path to resource file or directory relative to the intellij-community repo root
* @param outputPath target path relative to the plugin root directory
*/
@JvmOverloads
fun withBin(binPathRelativeToCommunity: String, outputPath: String, skipIfDoesntExist: Boolean = false) {
withGeneratedResources(BiConsumer { targetDir, context ->
val source = context.paths.communityHomeDir.resolve(binPathRelativeToCommunity).normalize()
if (Files.notExists(source)) {
if (skipIfDoesntExist) {
return@BiConsumer
}
error("'$source' doesn't exist")
}
if (Files.isRegularFile(source)) {
BuildHelper.copyFileToDir(source, targetDir.resolve(outputPath))
}
else {
BuildHelper.copyDir(source, targetDir.resolve(outputPath))
}
})
}
/**
* @param resourcePath path to resource file or directory relative to the plugin's main module content root
* @param relativeOutputPath target path relative to the plugin root directory
*/
fun withResource(resourcePath: String, relativeOutputPath: String) {
withResourceFromModule(layout.mainModule, resourcePath, relativeOutputPath)
}
/**
* @param resourcePath path to resource file or directory relative to {@code moduleName} module content root
* @param relativeOutputPath target path relative to the plugin root directory
*/
fun withResourceFromModule(moduleName: String, resourcePath: String, relativeOutputPath: String) {
layout.resourcePaths.add(ModuleResourceData(moduleName, resourcePath, relativeOutputPath, false))
}
/**
* @param resourcePath path to resource file or directory relative to the plugin's main module content root
* @param relativeOutputFile target path relative to the plugin root directory
*/
fun withResourceArchive(resourcePath: String, relativeOutputFile: String) {
withResourceArchiveFromModule(layout.mainModule, resourcePath, relativeOutputFile)
}
/**
* @param resourcePath path to resource file or directory relative to {@code moduleName} module content root
* @param relativeOutputFile target path relative to the plugin root directory
*/
fun withResourceArchiveFromModule(moduleName: String, resourcePath: String, relativeOutputFile: String) {
layout.resourcePaths.add(ModuleResourceData(moduleName, resourcePath, relativeOutputFile, true))
}
/**
* Copy output produced by {@code generator} to the directory specified by {@code relativeOutputPath} under the plugin directory.
*/
fun withGeneratedResources(generator: org.jetbrains.intellij.build.ResourcesGenerator, relativeOutputPath: String) {
layout.resourceGenerators.add(Pair(BiFunction<Path, BuildContext, Path> { _, context ->
generator.generateResources(context)?.toPath()
}, relativeOutputPath))
}
fun withPatch(patcher: BiConsumer<ModuleOutputPatcher, BuildContext> ) {
layout.patchers.add(patcher)
}
fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) {
layout.withGeneratedResources(generator)
}
/**
* By default, version of a plugin is equal to the build number of the IDE it's built with. This method allows to specify custom version evaluator.
*/
fun withCustomVersion(versionEvaluator: VersionEvaluator) {
layout.versionEvaluator = versionEvaluator
}
fun withPluginXmlPatcher(pluginXmlPatcher: UnaryOperator<String>) {
layout.pluginXmlPatcher = pluginXmlPatcher
}
@Deprecated(message = "localizable resources are always put to the module JAR, so there is no need to call this method anymore")
fun doNotCreateSeparateJarForLocalizableResources() {
}
/**
* This plugin will be compatible only with exactly the same IDE version.
* See {@link org.jetbrains.intellij.build.CompatibleBuildRange#EXACT}
*/
fun pluginCompatibilityExactVersion() {
layout.pluginCompatibilityExactVersion = true
}
/**
* <product-description> is usually removed for bundled plugins.
* Call this method to retain it in plugin.xml
*/
fun retainProductDescriptorForBundledPlugin() {
layout.retainProductDescriptorForBundledPlugin = true
}
/**
* Do not automatically include module libraries from {@code moduleNames}
* <strong>Do not use this for new plugins, this method is temporary added to keep layout of old plugins</strong>.
*/
fun doNotCopyModuleLibrariesAutomatically(moduleNames: List<String>) {
layout.modulesWithExcludedModuleLibraries.addAll(moduleNames)
}
/**
* Specifies a relative path to a plugin jar that should be scrambled.
* Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool}
* If scramble tool is not defined, scrambling will not be performed
* Multiple invocations of this method will add corresponding paths to a list of paths to be scrambled
*
* @param relativePath - a path to a jar file relative to plugin root directory
*/
fun scramble(relativePath: String) {
layout.pathsToScramble.add(relativePath)
}
/**
* Specifies a relative to {@link org.jetbrains.intellij.build.BuildPaths#communityHome} path to a zkm script stub file.
* If scramble tool is not defined, scramble toot will expect to find the script stub file at "{@link org.jetbrains.intellij.build.BuildPaths#projectHome}/plugins/{@code pluginName}/build/script.zkm.stub".
* Project home cannot be used since it is not constant (for example for Rider).
*
* @param communityRelativePath - a path to a jar file relative to community project home directory
*/
fun zkmScriptStub(communityRelativePath: String) {
layout.zkmScriptStub = communityRelativePath
}
/**
* Specifies a dependent plugin name to be added to scrambled classpath
* Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool}
* If scramble tool is not defined, scrambling will not be performed
* Multiple invocations of this method will add corresponding plugin names to a list of name to be added to scramble classpath
*
* @param pluginName - a name of dependent plugin, whose jars should be added to scramble classpath
* @param relativePath - a directory where jars should be searched (relative to plugin home directory, "lib" by default)
*/
@JvmOverloads
fun scrambleClasspathPlugin(pluginName: String, relativePath: String = "lib") {
layout.scrambleClasspathPlugins.add(Pair(pluginName, relativePath))
}
/**
* Allows control over classpath entries that will be used by the scrambler to resolve references from jars being scrambled.
* By default all platform jars are added to the 'scramble classpath'
*/
fun filterScrambleClasspath(filter: BiPredicate<BuildContext, Path>) {
layout.scrambleClasspathFilter = filter
}
/**
* Concatenates `META-INF/services` files with the same name from different modules together.
* By default the first service file silently wins.
*/
fun mergeServiceFiles() {
layout.mergeServiceFiles()
}
}
interface VersionEvaluator {
fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String
}
} | apache-2.0 | ce7aab6264f384b1db86c409a7bdccf3 | 42.733509 | 209 | 0.711355 | 5.101262 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt | 4 | 6570 | // 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.uast.kotlin.psi
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightTypeElement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.elements.LightVariableBuilder
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.*
@ApiStatus.Internal
class UastKotlinPsiVariable private constructor(
manager: PsiManager,
name: String,
typeProducer: () -> PsiType,
val ktInitializer: KtExpression?,
psiParentProducer: () -> PsiElement?,
val containingElement: UElement,
val ktElement: KtElement
) : LightVariableBuilder(
manager,
name,
UastErrorType, // Type is calculated lazily
KotlinLanguage.INSTANCE
), PsiLocalVariable {
val psiParent by lz(psiParentProducer)
private val psiType: PsiType by lz(typeProducer)
private val psiTypeElement: PsiTypeElement by lz {
LightTypeElement(manager, psiType)
}
private val psiInitializer: PsiExpression? by lz {
ktInitializer?.let { KotlinUastPsiExpression(it, containingElement) }
}
override fun getType(): PsiType = psiType
override fun getText(): String = ktElement.text
override fun getParent() = psiParent
override fun hasInitializer() = ktInitializer != null
override fun getInitializer(): PsiExpression? = psiInitializer
override fun getTypeElement() = psiTypeElement
override fun setInitializer(initializer: PsiExpression?) = throw NotImplementedError()
override fun getContainingFile(): PsiFile? = ktElement.containingFile
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other::class.java != this::class.java) return false
return ktElement == (other as? UastKotlinPsiVariable)?.ktElement
}
override fun isEquivalentTo(another: PsiElement?): Boolean = this == another || ktElement.isEquivalentTo(another)
override fun hashCode() = ktElement.hashCode()
companion object {
fun create(
declaration: KtVariableDeclaration,
parent: PsiElement?,
containingElement: KotlinUDeclarationsExpression,
initializer: KtExpression? = null
): PsiLocalVariable {
val psi = containingElement.psiAnchor ?: containingElement.sourcePsi
val psiParent = psi?.getNonStrictParentOfType<KtDeclaration>() ?: parent
val initializerExpression = initializer ?: declaration.initializer
return UastKotlinPsiVariable(
manager = declaration.manager,
name = declaration.name.orAnonymous("<unnamed>"),
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getType(declaration, containingElement) ?: UastErrorType
},
ktInitializer = initializerExpression,
psiParentProducer = { psiParent },
containingElement = containingElement,
ktElement = declaration)
}
fun create(
declaration: KtDestructuringDeclaration,
containingElement: UElement
): PsiLocalVariable =
UastKotlinPsiVariable(
manager = declaration.manager,
name = "var" + Integer.toHexString(declaration.getHashCode()),
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getType(declaration, containingElement) ?: UastErrorType
},
ktInitializer = declaration.initializer,
psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: declaration.parent },
containingElement = containingElement,
ktElement = declaration
)
fun create(
initializer: KtExpression,
containingElement: UElement,
parent: PsiElement
): PsiLocalVariable =
UastKotlinPsiVariable(
manager = initializer.manager,
name = "var" + Integer.toHexString(initializer.getHashCode()),
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getType(initializer, containingElement) ?: UastErrorType
},
ktInitializer = initializer,
psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: parent },
containingElement = containingElement,
ktElement = initializer
)
fun create(
name: String,
localFunction: KtFunction,
containingElement: UElement
): PsiLocalVariable =
UastKotlinPsiVariable(
manager = localFunction.manager,
name = name,
typeProducer = {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
service.getFunctionType(localFunction, containingElement) ?: UastErrorType
},
ktInitializer = localFunction,
psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: localFunction.parent },
containingElement = containingElement,
ktElement = localFunction
)
}
}
private class KotlinUastPsiExpression(
val ktExpression: KtExpression,
val parent: UElement
) : PsiElement by ktExpression, PsiExpression {
override fun getType(): PsiType? {
val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java)
return service.getType(ktExpression, parent)
}
}
private fun PsiElement.getHashCode(): Int {
var result = 42
result = 41 * result + (containingFile?.name?.hashCode() ?: 0)
result = 41 * result + startOffset
result = 41 * result + text.hashCode()
return result
}
| apache-2.0 | 6097099b1349d456a1205ca675074d66 | 39.060976 | 158 | 0.65586 | 6.100279 | false | false | false | false |
androidx/androidx | camera/integration-tests/uiwidgetstestapp/src/main/java/androidx/camera/integration/uiwidgets/rotations/ImageCaptureResult.kt | 3 | 2201 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.uiwidgets.rotations
import android.content.ContentResolver
import android.net.Uri
import android.util.Size
import androidx.camera.core.ImageProxy
import androidx.camera.core.impl.utils.Exif
import java.io.File
/** A wrapper around an ImageCapture result, used for testing. */
sealed class ImageCaptureResult {
abstract fun getResolution(): Size
abstract fun getRotation(): Int
abstract fun delete()
class InMemory(private val imageProxy: ImageProxy) : ImageCaptureResult() {
override fun getResolution() = Size(imageProxy.width, imageProxy.height)
override fun getRotation() = imageProxy.imageInfo.rotationDegrees
override fun delete() {}
}
class FileOrOutputStream(private val file: File) : ImageCaptureResult() {
private val exif = Exif.createFromFile(file)
override fun getResolution() = Size(exif.width, exif.height)
override fun getRotation() = exif.rotation
override fun delete() {
file.delete()
}
}
class MediaStore(private val contentResolver: ContentResolver, private val uri: Uri) :
ImageCaptureResult() {
private val exif: Exif
init {
val inputStream = contentResolver.openInputStream(uri)
exif = Exif.createFromInputStream(inputStream!!)
}
override fun getResolution() = Size(exif.width, exif.height)
override fun getRotation() = exif.rotation
override fun delete() {
contentResolver.delete(uri, null, null)
}
}
} | apache-2.0 | b8d7b9e75a675f588a0a7583bb049352 | 32.363636 | 90 | 0.699228 | 4.723176 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/manage/ManageDonationsState.kt | 1 | 1794 | package org.thoughtcrime.securesms.components.settings.app.subscription.manage
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.subscription.Subscription
import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription
data class ManageDonationsState(
val hasOneTimeBadge: Boolean = false,
val hasReceipts: Boolean = false,
val featuredBadge: Badge? = null,
val transactionState: TransactionState = TransactionState.Init,
val availableSubscriptions: List<Subscription> = emptyList(),
private val subscriptionRedemptionState: SubscriptionRedemptionState = SubscriptionRedemptionState.NONE
) {
fun getMonthlyDonorRedemptionState(): SubscriptionRedemptionState {
return when (transactionState) {
TransactionState.Init -> subscriptionRedemptionState
TransactionState.NetworkFailure -> subscriptionRedemptionState
TransactionState.InTransaction -> SubscriptionRedemptionState.IN_PROGRESS
is TransactionState.NotInTransaction -> getStateFromActiveSubscription(transactionState.activeSubscription) ?: subscriptionRedemptionState
}
}
fun getStateFromActiveSubscription(activeSubscription: ActiveSubscription): SubscriptionRedemptionState? {
return when {
activeSubscription.isFailedPayment -> SubscriptionRedemptionState.FAILED
activeSubscription.isInProgress -> SubscriptionRedemptionState.IN_PROGRESS
else -> null
}
}
sealed class TransactionState {
object Init : TransactionState()
object NetworkFailure : TransactionState()
object InTransaction : TransactionState()
class NotInTransaction(val activeSubscription: ActiveSubscription) : TransactionState()
}
enum class SubscriptionRedemptionState {
NONE,
IN_PROGRESS,
FAILED
}
}
| gpl-3.0 | f8e33f6412739d9611429536c2be5975 | 38.866667 | 144 | 0.799889 | 6.164948 | false | false | false | false |
Yusspy/Jolt-Sphere | core/src/org/joltsphere/scenes/Scene3.kt | 1 | 2145 | package org.joltsphere.scenes
import org.joltsphere.main.JoltSphereMain
import org.joltsphere.mountain.MountainSpace
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer
import com.badlogic.gdx.physics.box2d.World
class Scene3(internal val game: JoltSphereMain) : Screen {
internal var world: World
internal var debugRender: Box2DDebugRenderer
internal var mountainSpace: MountainSpace
internal var ppm = JoltSphereMain.ppm
init {
world = World(Vector2(0f, -9.8f), false) //ignore inactive objects false
debugRender = Box2DDebugRenderer()
mountainSpace = MountainSpace(world)
}
private fun update(dt: Float) {
mountainSpace.update(dt, game.cam.viewportWidth / 2f, game.cam.viewportHeight / 2f)
world.step(dt, 6, 2)
}
override fun render(dt: Float) {
update(dt)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
game.shapeRender.begin(ShapeType.Filled)
mountainSpace.shapeRender(game.shapeRender)
game.shapeRender.end()
debugRender.render(world, game.phys2DCam.combined)
game.batch.begin()
//game.font.draw(game.batch, mountainSpace.points + "boombooms FPS: " + Gdx.graphics.getFramesPerSecond(), game.width*0.27f, game.height * 0.85f);
game.batch.end()
val zoom = mountainSpace.getZoom(game.cam.viewportHeight)
game.cam.zoom = zoom
game.phys2DCam.zoom = zoom
game.cam.position.set(mountainSpace.cameraPostion, 0f)
game.phys2DCam.position.set(mountainSpace.debugCameraPostion, 0f)
game.cam.update()
game.phys2DCam.update()
}
override fun dispose() {
}
override fun resize(width: Int, height: Int) {
game.resize(width, height)
}
override fun show() {}
override fun pause() {}
override fun resume() {}
override fun hide() {}
} | agpl-3.0 | 2457f444208c4715fc15d423f90d80ac | 24.547619 | 159 | 0.68345 | 3.623311 | false | false | false | false |
androidx/androidx | camera/integration-tests/uiwidgetstestapp/src/main/java/androidx/camera/integration/uiwidgets/compose/ui/screen/components/CameraControlButton.kt | 3 | 2033 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.uiwidgets.compose.ui.screen.components
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
private val CAMERA_CONTROL_BUTTON_SIZE = 64.dp
@Composable
fun CameraControlButton(
imageVector: ImageVector,
contentDescription: String,
modifier: Modifier = Modifier,
tint: Color = Color.Unspecified,
onClick: () -> Unit
) {
IconButton(
onClick = onClick,
modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE)
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription,
modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE),
tint = tint
)
}
}
@Composable
fun CameraControlText(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE)
)
}
@Composable
fun CameraControlButtonPlaceholder(modifier: Modifier = Modifier) {
Spacer(modifier = modifier.size(CAMERA_CONTROL_BUTTON_SIZE))
} | apache-2.0 | 0d5dcc1fb9cfa8c2c510fa8b4c6970ab | 29.358209 | 75 | 0.729464 | 4.262055 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/MakeAlCtlLinux.kt | 1 | 5076 | package alraune
import alraune.operations.*
import vgrechka.*
import java.io.File
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission
import java.util.*
object MakeAlCtlLinux {
@JvmStatic fun main(args: Array<String>) {
val cp = System.getProperty("java.class.path")
fun fart(filePrefix: String, cmdPrefix: String) {
val file = File("${System.getProperty("user.home")}/bin/${filePrefix}al-ctl")
file.writeText("""
#!/bin/bash
# Generated on ${Date()}
SWT_GTK3=0 ${cmdPrefix}java -D${AlopsConst.JavaSystemProperty.AlCtlCommand}=$1 \
-cp $cp ${AlExecuteCtlCommand::class.qualifiedName} \
"$@"
""".trimIndent())
Files.setPosixFilePermissions(file.toPath(), setOf(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE))
}
fart(filePrefix = "", cmdPrefix = "")
fart(filePrefix = "su-", cmdPrefix = "sudo ")
}
}
//object MakeAlCtl {
// var binDir by notNullOnce<File>()
//
// @JvmStatic
// fun main(args: Array<String>) {
// AlGlobal_MergeMeToKotlinVersion.commandLineArgs = args
// binDir = File(FEProps.shitDir + "/bin")
// if (binDir.exists() && !binDir.isDirectory)
// bitch("I want this to be a directory: ${binDir.path}")
// if (!binDir.exists())
// binDir.mkdir()
//
// forUnix()
// }
//
// private fun forUnix() {
// val buf = StringBuilder()
// fun line(x: String) = buf.append(x + "\n")
//
// line("#!/bin/bash")
// line("CP=${AlConst.cpFirstDir(FEProps.shitDir)}")
// for (entry in System.getProperty("java.class.path").split(File.pathSeparator)) {
// line("CP=\$CP${File.pathSeparator}$entry")
// }
// line("")
// line("java -cp \$CP ${AlExecuteCtlCommand::class.qualifiedName} \"$@\"")
//
// fun writeOut(scriptName: String, content: String) {
// val file = File("${binDir.path}/$scriptName")
// file.writeText(content)
// file.setExecutable(true)
// }
//
// exhaustive=when (AlConfig.envKind) {
// AlConfig.EnvKind.Staging -> {
// writeOut("al-ctl", buf.toString())
// }
// AlConfig.EnvKind.WSLLocalDev -> {
// writeOut("al-ctl--staging", buf.toString())
//
// val p = Alk.Projects
// writeOut("al-ctl", buf.toString()
// .replace("/mnt/e/fegh/fe-private/alraune-private/build/classes/java/main", "boobs")
// .replace("/mnt/e/fegh/fe-private/alraune-private/build/classes/kotlin/main", p.alraunePrivate.ideaOutputClasses)
// .replace("/mnt/e/fegh/fe-private/alraune-private/build/resources/main", p.alraunePrivate.ideaOutputResources)
// .replace(Regex("""/mnt/e/fegh/alraune/alraune/build/libs/alraune-\d+.\d+.\d+.*?\.jar"""), "${p.alraune.ideaOutputClasses}${File.pathSeparator}${p.alraune.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/alraune/alraune-ap/build/libs/alraune-ap-\d+.\d+.\d+.*?\.jar"""), "${p.alrauneAp.ideaOutputClasses}${File.pathSeparator}${p.alrauneAp.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/alraune/alraune-ap-light/build/libs/alraune-ap-light-\d+.\d+.\d+.*?\.jar"""), "${p.alrauneApLight.ideaOutputClasses}${File.pathSeparator}${p.alrauneApLight.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/fe-private/alraune-private/build/libs/alraune-private-\d+.\d+.\d+.*?\.jar"""), "${p.alraunePrivate.ideaOutputClasses}${File.pathSeparator}${p.alraunePrivate.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/hot-reloadable-idea-piece-of-shit/build/libs/hot-reloadable-idea-piece-of-shit-\d+.\d+.\d+.*?\.jar"""), "${p.hotReloadableIdeaPieceOfShit.ideaOutputClasses}${File.pathSeparator}${p.hotReloadableIdeaPieceOfShit.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/idea-backdoor-client/build/libs/idea-backdoor-client-\d+.\d+.\d+.*?\.jar"""), "${p.ideaBackdoorClient.ideaOutputClasses}${File.pathSeparator}${p.ideaBackdoorClient.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/jaco-0/build/libs/jaco-0-\d+.\d+.\d+.*?\.jar"""), "${p.jaco0.ideaOutputClasses}${File.pathSeparator}${p.jaco0.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/shared-idea/build/libs/shared-idea-\d+.\d+.\d+.*?\.jar"""), "${p.sharedIdea.ideaOutputClasses}${File.pathSeparator}${p.sharedIdea.ideaOutputResources}")
// .replace(Regex("""/mnt/e/fegh/1/shared-jvm/build/libs/shared-jvm-\d+.\d+.\d+.*?\.jar"""), "${p.sharedJvm.ideaOutputClasses}${File.pathSeparator}${p.sharedJvm.ideaOutputResources}")
// )
// }
// }
// }
//
//}
| apache-2.0 | c30c9dad436bf0ae538ce4902a972c3f | 50.272727 | 284 | 0.588258 | 3.865956 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/application/options/CodeCompletionConfigurable.kt | 1 | 8612 | // 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.application.options
import com.intellij.application.options.editor.EditorOptionsProvider
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.ide.PowerSaveMode
import com.intellij.ide.ui.UISettings
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.options.BoundCompositeConfigurable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.Configurable.WithEpDependencies
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.options.ex.ConfigurableWrapper
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.IdeUICustomization
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
class CodeCompletionConfigurable : BoundCompositeConfigurable<UnnamedConfigurable>(
ApplicationBundle.message("title.code.completion"), "reference.settingsdialog.IDE.editor.code.completion"),
EditorOptionsProvider, WithEpDependencies {
companion object {
const val ID = "editor.preferences.completion"
private val LOG = Logger.getInstance(CodeCompletionConfigurable::class.java)
}
private lateinit var cbMatchCase: JBCheckBox
private lateinit var rbLettersOnly: JBRadioButton
private lateinit var rbAllOnly: JBRadioButton
override fun createConfigurables(): List<UnnamedConfigurable> =
ConfigurableWrapper.createConfigurables(CodeCompletionConfigurableEP.EP_NAME)
override fun getId() = ID
override fun getDependencies(): Collection<BaseExtensionPointName<*>> =
listOf(CodeCompletionConfigurableEP.EP_NAME)
var caseSensitive: Int
get() =
if (cbMatchCase.isSelected) {
if (rbAllOnly.isSelected) CodeInsightSettings.ALL else CodeInsightSettings.FIRST_LETTER
}
else {
CodeInsightSettings.NONE
}
set(value) =
when (value) {
CodeInsightSettings.ALL -> {
cbMatchCase.isSelected = true
rbAllOnly.setSelected(true)
}
CodeInsightSettings.NONE -> {
cbMatchCase.isSelected = false
}
CodeInsightSettings.FIRST_LETTER -> {
cbMatchCase.isSelected = true
rbLettersOnly.setSelected(true)
}
else -> LOG.warn("Unsupported caseSensitive: $value")
}
override fun reset() {
super<BoundCompositeConfigurable>.reset()
val codeInsightSettings = CodeInsightSettings.getInstance()
caseSensitive = codeInsightSettings.completionCaseSensitive
}
override fun apply() {
super.apply()
val codeInsightSettings = CodeInsightSettings.getInstance()
codeInsightSettings.completionCaseSensitive = caseSensitive
for (project in ProjectManager.getInstance().openProjects) {
DaemonCodeAnalyzer.getInstance(project).settingsChanged()
}
}
override fun isModified(): Boolean {
val result = super<BoundCompositeConfigurable>.isModified()
val codeInsightSettings = CodeInsightSettings.getInstance()
return result || caseSensitive != codeInsightSettings.completionCaseSensitive
}
override fun createPanel(): DialogPanel {
val actionManager = ActionManager.getInstance()
val settings = CodeInsightSettings.getInstance()
return panel {
buttonsGroup {
row {
cbMatchCase = checkBox(ApplicationBundle.message("completion.option.match.case"))
.component
rbLettersOnly = radioButton(ApplicationBundle.message("completion.option.first.letter.only"))
.enabledIf(cbMatchCase.selected)
.component.apply { isSelected = true }
rbAllOnly = radioButton(ApplicationBundle.message("completion.option.all.letters"))
.enabledIf(cbMatchCase.selected)
.component
}
}
val codeCompletion = OptionsApplicabilityFilter.isApplicable(OptionId.AUTOCOMPLETE_ON_BASIC_CODE_COMPLETION)
val smartTypeCompletion = OptionsApplicabilityFilter.isApplicable(OptionId.COMPLETION_SMART_TYPE)
if (codeCompletion || smartTypeCompletion) {
buttonsGroup(ApplicationBundle.message("label.autocomplete.when.only.one.choice")) {
if (codeCompletion) {
row {
checkBox(ApplicationBundle.message("checkbox.autocomplete.basic"))
.bindSelected(settings::AUTOCOMPLETE_ON_CODE_COMPLETION)
.gap(RightGap.SMALL)
comment(KeymapUtil.getFirstKeyboardShortcutText(actionManager.getAction(IdeActions.ACTION_CODE_COMPLETION)))
}
}
if (smartTypeCompletion) {
row {
checkBox(ApplicationBundle.message("checkbox.autocomplete.smart.type"))
.bindSelected(settings::AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION)
.gap(RightGap.SMALL)
comment(KeymapUtil.getFirstKeyboardShortcutText(actionManager.getAction(IdeActions.ACTION_SMART_TYPE_COMPLETION)))
}
}
}
}
row {
checkBox(ApplicationBundle.message("completion.option.sort.suggestions.alphabetically"))
.bindSelected(UISettings.getInstance()::sortLookupElementsLexicographically)
}
lateinit var cbAutocompletion: Cell<JBCheckBox>
row {
cbAutocompletion = checkBox(ApplicationBundle.message("editbox.auto.complete") +
if (PowerSaveMode.isEnabled()) LangBundle.message("label.not.available.in.power.save.mode") else "")
.bindSelected(settings::AUTO_POPUP_COMPLETION_LOOKUP)
}
indent {
row {
checkBox(IdeUICustomization.getInstance().selectAutopopupByCharsText)
.bindSelected(settings::isSelectAutopopupSuggestionsByChars, settings::setSelectAutopopupSuggestionsByChars)
.enabledIf(cbAutocompletion.selected)
}
}
row {
val cbAutopopupJavaDoc = checkBox(ApplicationBundle.message("editbox.autopopup.javadoc.in"))
.bindSelected(settings::AUTO_POPUP_JAVADOC_INFO)
.gap(RightGap.SMALL)
intTextField(CodeInsightSettings.JAVADOC_INFO_DELAY_RANGE.asRange(), 100)
.bindIntText(settings::JAVADOC_INFO_DELAY)
.columns(4)
.enabledIf(cbAutopopupJavaDoc.selected)
.gap(RightGap.SMALL)
label(ApplicationBundle.message("editbox.ms"))
}
addOptions()
group(ApplicationBundle.message("title.parameter.info")) {
if (OptionsApplicabilityFilter.isApplicable(OptionId.SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION)) {
row {
checkBox(ApplicationBundle.message("editbox.complete.with.parameters"))
.bindSelected(settings::SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION)
}
}
row {
val cbParameterInfoPopup = checkBox(ApplicationBundle.message("editbox.autopopup.in"))
.bindSelected(settings::AUTO_POPUP_PARAMETER_INFO)
.gap(RightGap.SMALL)
intTextField(CodeInsightSettings.PARAMETER_INFO_DELAY_RANGE.asRange(), 100)
.bindIntText(settings::PARAMETER_INFO_DELAY)
.columns(4)
.enabledIf(cbParameterInfoPopup.selected)
.gap(RightGap.SMALL)
label(ApplicationBundle.message("editbox.ms"))
}
row {
checkBox(ApplicationBundle.message("checkbox.show.full.signatures"))
.bindSelected(settings::SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO)
}
}
addSections()
}
}
private fun Panel.addOptions() {
configurables.filter { it !is CodeCompletionOptionsCustomSection }
.forEach { appendDslConfigurable(it) }
}
private fun Panel.addSections() {
configurables.filterIsInstance<CodeCompletionOptionsCustomSection>()
.sortedWith(Comparator.comparing { c ->
(c as? Configurable)?.displayName ?: ""
})
.forEach { appendDslConfigurable(it) }
}
} | apache-2.0 | b04945e86895af7d6ef88836521a6580 | 37.450893 | 136 | 0.707733 | 5.065882 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CommentHolder.kt | 6 | 5714 | // 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.codeInliner
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.util.containers.stopAfter
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.children
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
class CommentHolder(val leadingComments: List<CommentNode>, val trailingComments: List<CommentNode>) {
fun restoreComments(element: PsiElement) {
val factory = KtPsiFactory(element)
for (leadingComment in leadingComments) {
addComment(factory, leadingComment, element, true)
}
for (trailingComment in trailingComments.asReversed()) {
addComment(factory, trailingComment, element, false)
}
}
fun merge(other: CommentHolder): CommentHolder = CommentHolder(
other.leadingComments + this.leadingComments,
this.trailingComments + other.trailingComments
)
val isEmpty: Boolean get() = leadingComments.isEmpty() && trailingComments.isEmpty()
class CommentNode(val indentBefore: String, val comment: String, val indentAfter: String) {
companion object {
fun create(comment: PsiComment): CommentNode = CommentNode(indentBefore(comment), comment.text, indentAfter(comment))
fun PsiElement.mergeComments(commentHolder: CommentHolder) {
val oldHolder = getCopyableUserData(COMMENTS_TO_RESTORE_KEY)
val newCommentHolder = oldHolder?.merge(commentHolder) ?: commentHolder
putCopyableUserData(COMMENTS_TO_RESTORE_KEY, newCommentHolder)
}
}
}
companion object {
val COMMENTS_TO_RESTORE_KEY: Key<CommentHolder> = Key("COMMENTS_TO_RESTORE")
fun extract(blockExpression: KtBlockExpression): Sequence<CommentHolder> = sequence {
val children = blockExpression.children().mapNotNull { it.psi }.iterator()
while (children.hasNext()) {
val before = children.stopAfter { it is KtExpression }.asSequence().collectComments()
val after = children.stopAfter { it.isLineBreak() || it is KtExpression }.asSequence().collectComments()
yield(CommentHolder(before, after))
}
}
fun Sequence<PsiElement>.collectComments(): List<CommentNode> = this.filterIsInstance<PsiComment>()
.map { CommentNode.create(it) }
.toList()
}
}
private fun indentBefore(comment: PsiComment): String {
val prevWhiteSpace = comment.prevLeaf() as? PsiWhiteSpace ?: return ""
val whiteSpaceText = prevWhiteSpace.text
if (prevWhiteSpace.prevSibling is PsiComment) return whiteSpaceText
val indexOfLineBreak = whiteSpaceText.indexOfLast { StringUtil.isLineBreak(it) }
if (indexOfLineBreak == -1) return whiteSpaceText
val startIndex = indexOfLineBreak + 1
if (startIndex >= whiteSpaceText.length) return ""
return whiteSpaceText.substring(startIndex)
}
private fun indentAfter(comment: PsiComment): String {
val nextWhiteSpace = comment.nextLeaf() as? PsiWhiteSpace ?: return ""
if (nextWhiteSpace.nextSibling is PsiComment) return ""
val whiteSpaceText = nextWhiteSpace.text
val indexOfLineBreak = whiteSpaceText.indexOfFirst { StringUtil.isLineBreak(it) }
if (indexOfLineBreak == -1) return whiteSpaceText
val endIndex = indexOfLineBreak + 1
if (endIndex > whiteSpaceText.length) return whiteSpaceText
return whiteSpaceText.substring(0, endIndex)
}
private fun addSiblingFunction(before: Boolean): (PsiElement, PsiElement, PsiElement) -> PsiElement = if (before)
PsiElement::addBefore
else
PsiElement::addAfter
private fun PsiElement.addWhiteSpace(factory: KtPsiFactory, whiteSpaceText: String, before: Boolean) {
if (whiteSpaceText.isEmpty()) return
val siblingWhiteSpace = (if (before) prevLeaf() else nextLeaf()) as? PsiWhiteSpace
if (siblingWhiteSpace == null) {
addSiblingFunction(before)(parent, factory.createWhiteSpace(whiteSpaceText), this)
} else {
val siblingText = siblingWhiteSpace.text
val containsLineBreak = StringUtil.containsLineBreak(siblingText) && StringUtil.containsLineBreak(whiteSpaceText)
val newWhiteSpaceText = if (before) {
if (containsLineBreak) whiteSpaceText
else siblingText + whiteSpaceText
} else {
if (containsLineBreak) return
whiteSpaceText + siblingText
}
siblingWhiteSpace.replace(factory.createWhiteSpace(newWhiteSpaceText))
}
}
private fun addComment(factory: KtPsiFactory, commentNode: CommentHolder.CommentNode, target: PsiElement, before: Boolean) {
val parent = target.parent
val comment = factory.createComment(commentNode.comment)
addSiblingFunction(before && parent !is KtReturnExpression)(parent, comment, target).updateWhiteSpaces(factory, commentNode)
}
private fun PsiElement.updateWhiteSpaces(factory: KtPsiFactory, commentNode: CommentHolder.CommentNode) {
addWhiteSpace(factory, commentNode.indentBefore, before = true)
addWhiteSpace(factory, commentNode.indentAfter, before = false)
} | apache-2.0 | 295911d706ed69600a69464146c7747f | 41.333333 | 158 | 0.726111 | 4.93437 | false | false | false | false |
ravidsrk/kotlinextensions.com | Extensions.kt | 1 | 5392 | /**
* Extension method to remove the required boilerplate for running code after a view has been
* inflated and measured.
*
* @author Antonio Leiva
* @see <a href="https://antonioleiva.com/kotlin-ongloballayoutlistener/>Kotlin recipes: OnGlobalLayoutListener</a>
*/
inline fun <T : View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
/**
* Extension method to simplify the code needed to apply spans on a specific sub string.
*/
inline fun SpannableStringBuilder.withSpan(vararg spans: Any, action: SpannableStringBuilder.() -> Unit):
SpannableStringBuilder {
val from = length
action()
for (span in spans) {
setSpan(span, from, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
return this
}
/**
* Extension method to provide simpler access to {@link ContextCompat#getColor(int)}.
*/
fun Context.getColorCompat(color: Int) = ContextCompat.getColor(this, color)
/**
* Extension method to provide simpler access to {@link View#getResources()#getString(int)}.
*/
fun View.getString(stringResId: Int): String = resources.getString(stringResId)
/**
* Extension method to provide show keyboard for View.
*/
fun View.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
this.requestFocus()
imm.showSoftInput(this, 0)
}
/**
* Extension method to provide hide keyboard for [Activity].
*/
fun Activity.hideSoftKeyboard() {
if (currentFocus != null) {
val inputMethodManager = getSystemService(Context
.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
}
}
/**
* Extension method to provide hide keyboard for [Fragment].
*/
fun Fragment.hideSoftKeyboard() {
activity?.hideSoftKeyboard()
}
/**
* Extension method to provide hide keyboard for [View].
*/
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
/**
* Extension method to int time to 2 digit String
*/
fun Int.twoDigitTime() = if (this < 10) "0" + toString() else toString()
/**
* Extension method to provide quicker access to the [LayoutInflater] from [Context].
*/
fun Context.getLayoutInflater() = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
/**
* Extension method to provide quicker access to the [LayoutInflater] from a [View].
*/
fun View.getLayoutInflater() = context.getLayoutInflater()
/**
* Extension method to replace all text inside an [Editable] with the specified [newValue].
*/
fun Editable.replaceAll(newValue: String) {
replace(0, length, newValue)
}
/**
* Extension method to replace all text inside an [Editable] with the specified [newValue] while
* ignoring any [android.text.InputFilter] set on the [Editable].
*/
fun Editable.replaceAllIgnoreFilters(newValue: String) {
val currentFilters = filters
filters = emptyArray()
replaceAll(newValue)
filters = currentFilters
}
/**
* Extension method to cast a char with a decimal value to an [Int].
*/
fun Char.decimalValue(): Int {
if (!isDigit())
throw IllegalArgumentException("Out of range")
return this.toInt() - '0'.toInt()
}
/**
* Extension method to simplify view binding.
*/
fun <T : ViewDataBinding> View.bind() = DataBindingUtil.bind<T>(this) as T
/**
* Extension method to simplify view inflating and binding inside a [ViewGroup].
*
* e.g.
* This:
*<code>
* binding = bind(R.layout.widget_card)
*</code>
*
* Will replace this:
*<code>
* binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.widget_card, this, true)
*</code>
*/
fun <T : ViewDataBinding> ViewGroup.bind(layoutId: Int): T {
return DataBindingUtil.inflate(getLayoutInflater(), layoutId, this, true)
}
/**
* Extension method to get Date for String with specified format.
*/
fun String.dateInFormat(format: String): Date? {
val dateFormat = SimpleDateFormat(format, Locale.US)
var parsedDate: Date? = null
try {
parsedDate = dateFormat.parse(this)
} catch (ignored: ParseException) {
ignored.printStackTrace()
}
return parsedDate
}
/**
* Convert a given date to milliseconds
*/
fun Date.toMillis() : Long {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar.timeInMillis
}
/**
* Checks if dates are same
*/
fun Date.isSame(to : Date) : Boolean {
val sdf = SimpleDateFormat("yyyMMdd", Locale.getDefault())
return sdf.format(this) == sdf.format(to)
}
/**
* Extension method to get ClickableSpan.
* e.g.
* val loginLink = getClickableSpan(context.getColorCompat(R.color.colorAccent), { })
*/
fun getClickableSpan(color: Int, action: (view: View) -> Unit): ClickableSpan {
return object : ClickableSpan() {
override fun onClick(view: View) {
action
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = color
}
}
}
| mit | 5427ab61f7b5173f92fa4257ac601871 | 27.083333 | 115 | 0.6875 | 4.245669 | false | false | false | false |
JiangKlijna/framework-learning | springmvc/spring-springmvc-springdatajpa-kotlin/src/main/java/com/jiangKlijna/web/control/BaseControl.kt | 3 | 1393 | package com.jiangKlijna.web.control
import com.jiangKlijna.web.app.ContextWrapper
import com.jiangKlijna.web.bean.Result
import org.springframework.web.bind.annotation.ModelAttribute
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession
import java.io.IOException
open class BaseControl : ContextWrapper() {
protected var request: HttpServletRequest? = null
protected var response: HttpServletResponse? = null
protected var session: HttpSession? = null
@ModelAttribute
fun setReqAndRes(request: HttpServletRequest, response: HttpServletResponse) {
this.request = request
this.response = response
this.session = request.session
}
protected fun response(contentType: String, content: String) {
try {
response!!.contentType = contentType
val w = response!!.writer
w.print(content)
w.flush()
w.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
companion object {
@JvmStatic protected val errorParameterResult = Result(1, "invalid parameter", "")
@JvmStatic protected fun testParameter(vararg strs: String?): Boolean {
for (s in strs) if (s == null || s.isEmpty()) return false
return true
}
}
}
| apache-2.0 | 13c336572a0ef38dd91958cdb3e46818 | 28.638298 | 90 | 0.669777 | 4.836806 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/usecases/AddTemplatesUseCase.kt | 1 | 6107 | package com.ivanovsky.passnotes.domain.usecases
import com.ivanovsky.passnotes.data.ObserverBus
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.entity.Template
import com.ivanovsky.passnotes.data.entity.TemplateField
import com.ivanovsky.passnotes.data.entity.TemplateFieldType
import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository
import com.ivanovsky.passnotes.domain.DispatcherProvider
import kotlinx.coroutines.withContext
import java.util.UUID
class AddTemplatesUseCase(
private val dbRepo: EncryptedDatabaseRepository,
private val dispatchers: DispatcherProvider,
private val observerBus: ObserverBus
) {
suspend fun addTemplates(): OperationResult<Boolean> {
return withContext(dispatchers.IO) {
val isAdd = dbRepo.templateRepository.addTemplates(createDefaultTemplates())
if (isAdd.isSucceededOrDeferred) {
observerBus.notifyGroupDataSetChanged()
val templateGroupUid = dbRepo.templateRepository.templateGroupUid
if (templateGroupUid != null) {
observerBus.notifyNoteDataSetChanged(templateGroupUid)
}
}
isAdd
}
}
private fun createDefaultTemplates(): List<Template> {
return listOf(
Template(
uid = UUID.randomUUID(),
title = "ID card",
fields = listOf(
TemplateField(
title = "Number",
position = 0,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "Name",
position = 1,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "Place of issue",
position = 2,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "Date of issue",
position = 3,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "@exp_date",
position = 4,
type = TemplateFieldType.DATE_TIME
)
)
),
Template(
uid = UUID.randomUUID(),
title = "E-Mail",
fields = listOf(
TemplateField(
title = "E-Mail",
position = 0,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "URL",
position = 1,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "Password",
position = 2,
type = TemplateFieldType.PROTECTED_INLINE
)
)
),
Template(
uid = UUID.randomUUID(),
title = "Wireless LAN",
fields = listOf(
TemplateField(
title = "SSID",
position = 0,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "Password",
position = 1,
type = TemplateFieldType.PROTECTED_INLINE
)
)
),
Template(
uid = UUID.randomUUID(),
title = "Secure note",
fields = listOf(
TemplateField(
title = "Notes",
position = 0,
type = TemplateFieldType.INLINE
)
)
),
Template(
uid = UUID.randomUUID(),
title = "Credit card",
fields = listOf(
TemplateField(
title = "Number",
position = 0,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "CVV",
position = 1,
type = TemplateFieldType.PROTECTED_INLINE
),
TemplateField(
title = "PIN",
position = 2,
type = TemplateFieldType.PROTECTED_INLINE
),
TemplateField(
title = "Card holder",
position = 3,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "@exp_date",
position = 4,
type = TemplateFieldType.DATE_TIME
)
)
),
Template(
uid = UUID.randomUUID(),
title = "Membership",
fields = listOf(
TemplateField(
title = "Number",
position = 0,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "URL",
position = 1,
type = TemplateFieldType.INLINE
),
TemplateField(
title = "@exp_date",
position = 2,
type = TemplateFieldType.DATE_TIME
)
)
)
)
}
} | gpl-2.0 | 27e8701023af23fd6f9ffd20dfd4af23 | 34.719298 | 88 | 0.406255 | 6.987414 | false | false | false | false |
EvgenyNerush/performance | Kotlin/generation.kt | 1 | 1994 | import kotlin.math.PI
import kotlin.math.asin
import kotlin.math.sqrt
import kotlin.random.Random
import kotlin.system.measureTimeMillis
fun main() {
val n = 2_000_000
val rands = DoubleArray(n)
val gen = Random(321)
// 1st variant
val duration1 = measureTimeMillis {
var i = 0
while (i < n) {
val r1 = gen.nextDouble()
val r2 = gen.nextDouble()
if (r2 < asin(sqrt(r1)) / (PI / 2)) {
rands.set(i, r1)
i++
}
}
}
var sum = 0.0
for (r in rands) {
sum += r
}
println("1st variant:")
println("average = ${sum / n}")
println("generation takes ${1e-3 * duration1} s")
// 2nd variant
// Park-Miller RNG
val a: Long = 48_271
val m: Long = 2_147_483_647
fun pm(state: Long): Long {
return state * a % m
}
fun toD(state: Long): Double {
return state.toDouble() / m.toDouble()
}
val duration2 = measureTimeMillis {
var i = 0
var s: Long = 42
while (i < n) {
s = pm(s)
val r1 = toD(s)
s = pm(s)
val r2 = toD(s)
if (r2 < asin(sqrt(r1)) / (PI / 2)) {
rands.set(i, r1)
i++
}
}
}
sum = 0.0
for (r in rands) {
sum += r
}
println("2nd variant:")
println("average = ${sum / n}")
println("generation takes ${1e-3 * duration2} s")
// 3rd variant
val duration3 = measureTimeMillis {
var i = 0
var s: Long = 142
sum = 0.0
while (i < n) {
s = pm(s)
val r1 = toD(s)
s = pm(s)
val r2 = toD(s)
if (r2 < asin(sqrt(r1)) / (PI / 2)) {
sum += r1
i++
}
}
}
println("3nd variant:")
println("average = ${sum / n}")
println("generation takes ${1e-3 * duration3} s")
}
| bsd-3-clause | 78b92be7827c9185f3076ec37d6ba052 | 21.404494 | 53 | 0.448847 | 3.498246 | false | false | false | false |
JetBrains/teamcity-azure-plugin | plugin-azure-server/src/test/kotlin/jetbrains/buildServer/clouds/azure/arm/AzureCloudImageTest.kt | 1 | 10373 | /*
* Copyright 2000-2022 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.
*/
import io.mockk.*
import jetbrains.buildServer.clouds.CloudInstanceUserData
import jetbrains.buildServer.clouds.InstanceStatus
import jetbrains.buildServer.clouds.azure.arm.*
import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector
import jetbrains.buildServer.clouds.azure.arm.connector.AzureInstance
import kotlinx.coroutines.*
import org.jmock.MockObjectTestCase
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
import java.util.concurrent.CyclicBarrier
import kotlin.concurrent.thread
class AzureCloudImageTest : MockObjectTestCase() {
private lateinit var myJob: CompletableJob
private lateinit var myImageDetails: AzureCloudImageDetails
private lateinit var myApiConnector: AzureApiConnector
private lateinit var myScope: CoroutineScope
@BeforeMethod
fun beforeMethod() {
MockKAnnotations.init(this)
myApiConnector = mockk();
coEvery { myApiConnector.createInstance(any(), any()) } answers {
Unit
}
every { myApiConnector.fetchInstances<AzureInstance>(any<AzureCloudImage>()) } returns emptyMap()
myImageDetails = AzureCloudImageDetails(
mySourceId = null,
deployTarget = AzureCloudDeployTarget.SpecificGroup,
regionId = "regionId",
groupId = "groupId",
imageType = AzureCloudImageType.Image,
imageUrl = null,
imageId = "imageId",
instanceId = null,
osType = null,
networkId = null,
subnetId = null,
vmNamePrefix = "vm",
vmSize = null,
vmPublicIp = null,
myMaxInstances = 2,
username = null,
storageAccountType = null,
template = null,
numberCores = null,
memory = null,
storageAccount = null,
registryUsername = null,
agentPoolId = null,
profileId = null,
myReuseVm = false,
customEnvironmentVariables = null,
spotVm = null,
enableSpotPrice = null,
spotPrice = null,
enableAcceleratedNetworking = null
)
myJob = SupervisorJob()
myScope = CoroutineScope(myJob + Dispatchers.IO)
}
@Test
fun shouldCreateNewInstance() {
// Given
myScope = CoroutineScope(Dispatchers.Unconfined)
val instance = createInstance()
val userData = CloudInstanceUserData(
"agentName",
"authToken",
"",
0,
"profileId",
"profileDescr",
emptyMap()
)
// When
instance.startNewInstance(userData)
// Then
coVerify { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
}
@Test
fun shouldCreateSecondInstance() {
// Given
myScope = CoroutineScope(Dispatchers.Unconfined)
val instance = createInstance()
val userData = CloudInstanceUserData(
"agentName",
"authToken",
"",
0,
"profileId",
"profileDescr",
emptyMap()
)
instance.startNewInstance(userData)
// When
instance.startNewInstance(userData)
// Then
coVerify { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
}
@Test(invocationCount = 30)
fun shouldCreateSecondInstanceInParallel() {
// Given
val instance = createInstance()
val userData = CloudInstanceUserData(
"agentName",
"authToken",
"",
0,
"profileId",
"profileDescr",
emptyMap()
)
val barrier = CyclicBarrier(3)
// When
val thread1 = thread(start = true) { barrier.await(); instance.startNewInstance(userData) }
val thread2 = thread(start = true) { barrier.await(); instance.startNewInstance(userData) }
barrier.await()
thread1.join()
thread2.join()
myJob.complete()
runBlocking { myJob.join() }
// Then
coVerify { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
coVerify { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
}
@Test(invocationCount = 30)
fun shouldCheckInstanceLimitWhenCreateInstanceInParallel() {
// Given
val instance = createInstance()
val userData = CloudInstanceUserData(
"agentName",
"authToken",
"",
0,
"profileId",
"profileDescr",
emptyMap()
)
val barrier = CyclicBarrier(4)
// When
val thread1 = thread(start = true) { barrier.await(); runBlocking { instance.startNewInstance(userData) } }
val thread2 = thread(start = true) { barrier.await(); runBlocking { instance.startNewInstance(userData) } }
val thread3 = thread(start = true) { barrier.await(); runBlocking { instance.startNewInstance(userData) } }
barrier.await()
thread1.join()
thread2.join()
thread3.join()
myJob.complete()
runBlocking { myJob.join() }
// Then
coVerify { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "1" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
coVerify { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "2" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
coVerify(exactly = 0) { myApiConnector.createInstance(
match { i ->
i.imageId == instance.id &&
i.name == myImageDetails.vmNamePrefix!!.toLowerCase() + "3" &&
i.image == instance &&
i.status == InstanceStatus.STARTING
},
match { userData ->
userData.agentName == myImageDetails.vmNamePrefix!!.toLowerCase() + "3" &&
userData.profileId == "profileId" &&
userData.profileDescription == "profileDescr"
})
}
}
private fun createInstance() : AzureCloudImage {
return AzureCloudImage(myImageDetails, myApiConnector, myScope)
}
}
| apache-2.0 | c600a0e6a2720d4cca6fb4d6763c0a34 | 35.269231 | 115 | 0.521064 | 5.811204 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/character/CharacterClass.kt | 1 | 3682 | package com.almasb.zeph.character
import java.util.*
/**
* Character classes with base hp/sp.
*
* @author Almas Baimagambetov ([email protected])
*/
enum class CharacterClass(val hp: Int, val sp: Int, val description: String) {
MONSTER (50, 50, ""),
NOVICE (10, 10, "You've only started your adventure! You have many great opportunities before you!"),
// Warrior tree
WARRIOR (40, 20, "Warriors are strong, tough and fearless. They will fight until their last breath and against all odds, will often emerge victorious."),
CRUSADER (60, 35, "Crusaders are guardians of light. By using divine armor and weapons, they become virtually indestructible."),
PALADIN (90, 50, "TODO"),
GLADIATOR(65, 30, "Gladiators train their whole life to be the unstoppable force they are. Their raw strength can turn the tides of any battle."),
KNIGHT (100, 35, "TODO"),
// Scout tree
SCOUT (30, 35, "Scouts are nimble experts with a bow. They often use unconventional tactics to surprise and, ultimately, defeat their opponents."),
ROGUE (50, 40, "Rogues are shameless combatants who prefer daggers to execute their swift and deadly attacks. No matter who their enemies are, a rogue will always find a chink in their armor."),
ASSASSIN (75, 45, "Assassins have mastered the art of killing. Always walking in the shadows, their enemies will never know what hit them."),
RANGER (40, 40, "TODO"),
HUNTER (50, 55, "TODO"),
// Mage tree
MAGE (25, 45, "Mages are adepts at manipulating the elements themselves. By tapping into the nature's powers, they can defeat their enemies with a single thought."),
WIZARD (35, 60, "Wizards have gained the knowledge to blend elements together, multiplying their skill power. They are able to penetrate even most powerful magic barriers."),
ARCHMAGE (45, 75, "Archmages' arcane powers are second to none. Only few exist who can withstand their full destructive power."),
ENCHANTER(30, 65, "TODO"),
SAGE (40, 90, "TODO");
}
/**
* Enemies can be one of 3 types.
*/
enum class CharacterType {
NORMAL, MINIBOSS, BOSS
}
object CharacterClassChanger {
private val reqList = HashMap<CharacterClass, Ascension>()
init {
reqList[CharacterClass.NOVICE] = Ascension(2, 2, CharacterClass.WARRIOR, CharacterClass.SCOUT, CharacterClass.MAGE)
reqList[CharacterClass.WARRIOR] = Ascension(3, 3, CharacterClass.CRUSADER, CharacterClass.GLADIATOR)
reqList[CharacterClass.SCOUT] = Ascension(3, 3, CharacterClass.ROGUE, CharacterClass.RANGER)
reqList[CharacterClass.MAGE] = Ascension(3, 3, CharacterClass.WIZARD, CharacterClass.ENCHANTER)
reqList[CharacterClass.CRUSADER] = Ascension(5, 5, CharacterClass.PALADIN)
reqList[CharacterClass.GLADIATOR] = Ascension(5, 5, CharacterClass.KNIGHT)
reqList[CharacterClass.ROGUE] = Ascension(5, 5, CharacterClass.ASSASSIN)
reqList[CharacterClass.RANGER] = Ascension(5, 5, CharacterClass.HUNTER)
reqList[CharacterClass.WIZARD] = Ascension(5, 5, CharacterClass.ARCHMAGE)
reqList[CharacterClass.ENCHANTER] = Ascension(5, 5, CharacterClass.SAGE)
}
// fun canChangeClass(player: Entity): Boolean {
// val r = reqList[player.charClass.value]
// return r != null && player.baseLevel.value >= r.baseLevel && player.jobLevel.value >= r.jobLevel
// }
//
// fun getAscensionClasses(player: Entity) = reqList[player.charClass.value]!!.classesTo
private class Ascension(val baseLevel: Int, val jobLevel: Int, vararg classes: CharacterClass) {
val classesTo = classes as Array<CharacterClass>
}
} | gpl-2.0 | d26f68c08c22d0226931c97f45815070 | 45.0375 | 201 | 0.708311 | 3.803719 | false | false | false | false |
hazuki0x0/YuzuBrowser | browser/src/main/java/jp/hazuki/yuzubrowser/browser/behavior/WebViewBehavior.kt | 1 | 3993 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.browser.behavior
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.google.android.material.appbar.AppBarLayout
import jp.hazuki.yuzubrowser.browser.R
import jp.hazuki.yuzubrowser.legacy.browser.BrowserController
import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData
import jp.hazuki.yuzubrowser.ui.widget.PaddingFrameLayout
import jp.hazuki.yuzubrowser.webview.CustomWebView
class WebViewBehavior(context: Context, attrs: AttributeSet) : AppBarLayout.ScrollingViewBehavior(context, attrs) {
private var isInitialized = false
private lateinit var topToolBar: View
private lateinit var bottomBar: View
private lateinit var paddingFrame: View
private lateinit var overlayPaddingFrame: PaddingFrameLayout
private lateinit var controller: BrowserController
private var webView: CustomWebView? = null
private var prevY: Int = 0
private var paddingHeight = 0
var isImeShown = false
override fun layoutDependsOn(parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View): Boolean {
if (dependency is AppBarLayout) {
topToolBar = parent.findViewById(R.id.topToolbar)
bottomBar = parent.findViewById(R.id.bottomOverlayLayout)
paddingFrame = child.findViewById(R.id.toolbarPadding)
overlayPaddingFrame = child.findViewById(R.id.bottomAlwaysOverlayToolbarPadding)
isInitialized = true
return true
}
return false
}
override fun onDependentViewChanged(parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View): Boolean {
val bottom = dependency.bottom
val webView = webView
if (webView != null) {
webView.isToolbarShowing = dependency.top == 0
if (!webView.isTouching && webView.webScrollY != 0) {
webView.scrollBy(0, bottom - prevY)
}
val data = controller.getTabOrNull(webView)
if (data != null) {
adjustWebView(data, topToolBar.height + bottomBar.height)
}
}
prevY = bottom
return super.onDependentViewChanged(parent, child, dependency)
}
fun adjustWebView(data: MainTabData, height: Int) {
if (!isInitialized) return
if (paddingHeight != height) {
paddingHeight = height
val params = paddingFrame.layoutParams
params.height = height
paddingFrame.layoutParams = params
data.mWebView.computeVerticalScrollRangeMethod()
}
if (data.isFinished && !data.mWebView.isScrollable && !isImeShown) {
controller.expandToolbar()
data.mWebView.isNestedScrollingEnabledMethod = false
paddingFrame.visibility = View.VISIBLE
overlayPaddingFrame.forceHide = true
data.mWebView.computeVerticalScrollRangeMethod()
} else {
paddingFrame.visibility = View.GONE
overlayPaddingFrame.forceHide = false
data.mWebView.computeVerticalScrollRangeMethod()
}
}
fun setWebView(webView: CustomWebView?) {
this.webView = webView
}
fun setController(browserController: BrowserController) {
controller = browserController
}
}
| apache-2.0 | 69723051f19f212e5f6cac39bd69c155 | 37.028571 | 142 | 0.692712 | 4.92963 | false | false | false | false |
commonsguy/cwac-saferoom | demo/src/main/java/com/commonsware/android/auth/note/NoteRepository.kt | 1 | 4003 | /***
* Copyright (c) 2018 CommonsWare, 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.
*
* Covered in detail in the book _The Busy Coder's Guide to Android Development_
* https://commonsware.com/Android
*/
package com.commonsware.android.auth.note
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteOpenHelper
import com.commonsware.cwac.saferoom.SafeHelperFactory
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import java.util.*
private const val SCHEMA = 1
private const val DATABASE_NAME = "note.db"
val EMPTY = Note(-1, null)
class NoteRepository private constructor(ctxt: Context, passphrase: CharArray) {
private val db: SupportSQLiteDatabase
init {
val factory = SafeHelperFactory(passphrase)
val cfgBuilder = SupportSQLiteOpenHelper.Configuration.builder(ctxt)
cfgBuilder
.name(DATABASE_NAME)
.callback(object : SupportSQLiteOpenHelper.Callback(SCHEMA) {
override fun onCreate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE note (_id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);")
}
override fun onUpgrade(
db: SupportSQLiteDatabase, oldVersion: Int,
newVersion: Int
) {
throw RuntimeException("How did we get here?")
}
})
db = factory.create(cfgBuilder.build()).writableDatabase
}
private class LoadObservable(ctxt: Context, private val passphrase: CharArray) : ObservableOnSubscribe<Note> {
private val app: Context = ctxt.applicationContext
@Throws(Exception::class)
override fun subscribe(e: ObservableEmitter<Note>) {
val c = NoteRepository.init(app, passphrase).db.query("SELECT _id, content FROM note")
if (c.isAfterLast) {
e.onNext(EMPTY)
} else {
c.moveToFirst()
e.onNext(Note(c.getLong(0), c.getString(1)))
Arrays.fill(passphrase, '\u0000')
}
c.close()
}
}
companion object {
@Volatile
private var INSTANCE: NoteRepository? = null
@Synchronized
private fun init(ctxt: Context, passphrase: CharArray): NoteRepository {
return INSTANCE ?: NoteRepository(ctxt.applicationContext, passphrase).apply { INSTANCE = this }
}
@Synchronized
private fun get(): NoteRepository {
return INSTANCE!!
}
fun load(ctxt: Context, passphrase: CharArray): Observable<Note> {
return Observable.create(LoadObservable(ctxt, passphrase))
}
fun save(note: Note, content: String): Note {
val cv = ContentValues(1)
cv.put("content", content)
return if (note === EMPTY) {
val id = NoteRepository.get().db.insert("note", SQLiteDatabase.CONFLICT_ABORT, cv)
Note(id, content)
} else {
NoteRepository.get().db.update(
"note", SQLiteDatabase.CONFLICT_REPLACE, cv, "_id=?",
arrayOf(note.id.toString())
)
Note(note.id, content)
}
}
}
}
| apache-2.0 | 444b272e3b8962a4232893ab78cff293 | 34.424779 | 114 | 0.629528 | 4.86983 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.