repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Constantinuous/Angus
|
infrastructure/src/main/kotlin/de/constantinuous/angus/parsing/impl/JerichoHtmlParser.kt
|
1
|
1939
|
package de.constantinuous.angus.parsing.impl
import de.constantinuous.angus.parsing.HtmlParser
import de.constantinuous.angus.parsing.ServerBlock
import net.htmlparser.jericho.*
import java.util.*
/**
* Created by RichardG on 25.09.2016.
*/
class JerichoHtmlParser : HtmlParser {
private fun isCommented(serverText: Element, comments: List<Element>): Boolean{
var isCommented = false
for(comment in comments){
isCommented = comment.encloses(serverText)
if(isCommented){ break }
}
return isCommented
}
override fun extractServerBlocks(htmlText: String): List<ServerBlock> {
val serverBlocks = LinkedList<ServerBlock>()
val source = Source(htmlText)
val serverText = source.getAllElements(StartTagType.SERVER_COMMON)
val comments = source.getAllElements(StartTagType.COMMENT)
for(text in serverText){
val content = text.toString().replace("<%", "").replace("%>", "")
val isCommented = isCommented(text, comments)
val row = text.rowColumnVector.row
val column = text.rowColumnVector.column
val serverBlock = ServerBlock(content, isCommented, row, column)
serverBlocks.add(serverBlock)
}
return serverBlocks
}
override fun findAttributes(htmlText: String){
val source = Source(htmlText)
val attributes = source.parseAttributes()
val uriAttributes = source.uriAttributes
val allTags = source.allStartTags
val depth2 = allTags[2].element.depth
val depth3 = allTags[3].element.depth
val foo = ""
}
private fun extractLinks(htmlText: String){
val source = Source(htmlText)
val allTags = source.allStartTags
for(tag in allTags){
if(tag.startTagType == StartTagType.COMMENT){
continue
}
}
}
}
|
mit
|
1bbd471c56248d04aa600f900f7f80e5
| 30.290323 | 83 | 0.642084 | 4.357303 | false | false | false | false |
FountainMC/FountainCommon
|
src/main/java/org/fountainmc/common/mixins/MixinMinecraftServer.kt
|
1
|
5441
|
package org.fountainmc.common.mixins
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import net.minecraft.block.Block
import net.minecraft.item.Item
import net.minecraft.item.ItemBlock
import net.minecraft.server.MinecraftServer
import net.minecraft.server.management.PlayerList
import org.fountainmc.api.BlockType
import org.fountainmc.api.Fountain
import org.fountainmc.api.Material
import org.fountainmc.api.Server
import org.fountainmc.api.enchantments.EnchantmentType
import org.fountainmc.api.entity.EntityType
import org.fountainmc.api.entity.Player
import org.fountainmc.api.inventory.item.ItemFactory
import org.fountainmc.common.AsyncCatcher.verifyNotAsync
import org.fountainmc.common.FountainImplementation
import org.fountainmc.common.Metrics
import org.spongepowered.asm.mixin.Mixin
import org.spongepowered.asm.mixin.Overwrite
import org.spongepowered.asm.mixin.Shadow
import org.spongepowered.asm.mixin.injection.At
import org.spongepowered.asm.mixin.injection.Inject
import java.net.InetSocketAddress
import java.util.Collections.unmodifiableList
@Mixin(MinecraftServer::class)
abstract class MixinMinecraftServer(internal val launchArguments: ImmutableList<String>, val fountainImplementation: FountainImplementation) : Server {
internal val pluginManager = fountainImplementation.createPluginManager()
internal val eventManager = fountainImplementation.createEventManager()
internal val commandManager = fountainImplementation.createCommandManager()
override fun getPluginManager() = pluginManager
override fun getEventManager() = eventManager
override fun getCommandManager() = commandManager
override fun getLaunchArguments() = launchArguments
@Volatile var materialsByName: Map<String, Material> = ImmutableMap.of(); // COW
@Volatile var materialsById: Array<Material?> = arrayOf();
override fun getMaterial(name: String): Material {
return materialsByName[name] ?: throw IllegalArgumentException("The material named '$name' doesn't exist!")
}
override fun getMaterial(id: Int): Material {
val materialsById: Array<Material?> = this.materialsById;
if (id < 0) {
throw IllegalArgumentException("Negative id: $id")
} else if (id < materialsById.size) {
val material: Material? = materialsById[id];
if (material != null) return material;
}
throw IllegalArgumentException("Material with id $id is unknown")
}
@Inject(method = "main", at = arrayOf(At("HEAD")))
fun checkServerInitialized() {
if (Fountain.getServer() == null) {
System.err.println("Fountain.getServer() isn't initialized!")
System.exit(1)
} else if (Fountain.getServer() !is FountainImplementation) {
System.err.println("Fountain.getServer() is a ${Fountain.getServer().javaClass.typeName}, not a FountainImplementation")
System.exit(1)
}
}
val metrics = Metrics(fountainImplementation.implementationName, fountainImplementation.implementationVersion, fountainImplementation);
@Inject(method = "main", at = arrayOf(At("INVOKE", target = "net.minecraft.server.MinecraftServer.startServerThread()")))
fun startFountain() {
fountainImplementation.onServerStart()
metrics.start()
}
@Overwrite
fun getServerModName() = fountainImplementation.implementationName
fun registerItem(item: Item) {
verifyNotAsync()
val material = if (item is ItemBlock) {
item.block as BlockType;
} else {
item as Material;
}
val newArray: Array<Material?> = materialsById.copyOf(materialsById.size + 1);
newArray[item.getId()] = material;
materialsById = newArray;
}
override fun getEntityType(s: String): EntityType<*> {
TODO("Implement EntityType")
}
override fun getExpAtLevel(level: Int): Long {
return when {
level > 29 -> 62 + (level - 30L) * 7;
level > 15 -> 17 + (level - 15L) * 3;
else -> 17;
}
}
override fun getEnchantmentTypeByName(s: String): EnchantmentType {
TODO("Implement EnchantmentType")
}
override fun getItemFactory(): ItemFactory {
TODO("Implement ItemFactory")
}
@Shadow
override abstract fun getName(): String
@Shadow
abstract fun getMinecraftVersion(): String;
override fun getVersion(): String = getMinecraftVersion()
@Shadow
override abstract fun getMotd(): String
@Shadow
override abstract fun getMaxPlayers(): Int
@Shadow
abstract fun getServerOwner(): String
override fun getOwner() = getServerOwner()
@Shadow
abstract fun getHostname(): String
@Shadow
abstract fun getPort(): Int
override fun getAddress(): InetSocketAddress? {
return InetSocketAddress(getHostname(), getPort());
}
abstract val playerList: PlayerList
@Shadow // This shadows getPlayerList()
get
override fun getOnlinePlayers(): List<Player> {
return unmodifiableList(playerList.playerList as List<Player>)
}
override fun getOnlinePlayerCount(): Int {
return playerList.maxPlayers
}
}
fun Block.getId(): Int {
return Block.getIdFromBlock(this);
}
fun Item.getId(): Int {
return Item.REGISTRY.getIDForObject(this);
}
|
mit
|
7a63f4e42d8ead9f5121b936eb59d446
| 32.801242 | 151 | 0.706304 | 4.526622 | false | false | false | false |
google/ksp
|
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/PlatformDeclarationProcessor.kt
|
1
|
2731
|
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.devtools.ksp.processor
import com.google.devtools.ksp.containingFile
import com.google.devtools.ksp.isConstructor
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.visitor.KSTopDownVisitor
open class PlatformDeclarationProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
val collector = EverythingVisitor()
val declarations = mutableListOf<KSDeclaration>()
override fun process(resolver: Resolver): List<KSAnnotated> {
val files = resolver.getNewFiles()
files.forEach {
it.accept(collector, declarations)
}
declarations
.filterNot {
// TODO we should figure out how constructors work in expect-actual world
// expand this test to include constructors
it is KSFunctionDeclaration && it.isConstructor()
}
.sortedBy { "${it.containingFile?.fileName} : ${it.qualifiedName?.asString()}" }.forEach {
val r = mutableListOf<Any?>()
r.add(it.containingFile?.fileName)
r.add(it.qualifiedName?.asString())
r.add(it.isActual)
r.add(it.isExpect)
r.add(it.findActuals().joinToString(", ", "[", "]") { it.containingFile?.fileName.toString() })
r.add(it.findExpects().joinToString(", ", "[", "]") { it.containingFile?.fileName.toString() })
results.add(r.map { it.toString() }.joinToString(" : "))
}
return emptyList()
}
override fun toResult(): List<String> {
return results
}
}
class EverythingVisitor : KSTopDownVisitor<MutableList<KSDeclaration>, Unit>() {
override fun defaultHandler(node: KSNode, data: MutableList<KSDeclaration>) = Unit
override fun visitDeclaration(declaration: KSDeclaration, data: MutableList<KSDeclaration>) {
super.visitDeclaration(declaration, data)
data.add(declaration)
}
}
|
apache-2.0
|
cb31d497a88a865893de98c77e2f7859
| 38.57971 | 111 | 0.667155 | 4.644558 | false | false | false | false |
fnberta/PopularMovies
|
app/src/main/java/ch/berta/fabio/popularmovies/features/grid/component/Model.kt
|
1
|
7092
|
/*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.grid.component
import ch.berta.fabio.popularmovies.R
import ch.berta.fabio.popularmovies.data.GetMoviesResult
import ch.berta.fabio.popularmovies.data.LocalDbWriteResult
import ch.berta.fabio.popularmovies.data.MovieStorage
import ch.berta.fabio.popularmovies.data.SharedPrefs
import ch.berta.fabio.popularmovies.features.common.SnackbarMessage
import ch.berta.fabio.popularmovies.features.grid.Sort
import ch.berta.fabio.popularmovies.features.grid.SortOption
import ch.berta.fabio.popularmovies.features.grid.vdos.rows.GridRowLoadMoreViewData
import ch.berta.fabio.popularmovies.features.grid.vdos.rows.GridRowMovieViewData
import ch.berta.fabio.popularmovies.features.grid.vdos.rows.GridRowViewData
import ch.berta.fabio.popularmovies.formatLong
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
data class GridState(
val sort: Sort,
val movies: List<GridRowViewData> = emptyList(),
val empty: Boolean = false,
val loading: Boolean = false,
val loadingMore: Boolean = false,
val refreshing: Boolean = false,
val snackbar: SnackbarMessage = SnackbarMessage(false)
)
typealias GridStateReducer = (GridState) -> GridState
data class PageWithSort(val page: Int, val sort: Sort)
fun model(
sortOptions: List<Sort>,
initialState: GridState,
actions: Observable<GridAction>,
movieStorage: MovieStorage,
sharedPrefs: SharedPrefs
): Observable<GridState> {
val snackbars = actions
.ofType(GridAction.SnackbarShown::class.java)
.map { snackbarReducer() }
val sortSelectionActions = actions
.ofType(GridAction.SortSelection::class.java)
val sortSelections = sortSelectionActions
.switchMap {
if (it.sort.option == SortOption.SORT_FAVORITE) {
movieStorage.getFavMovies()
.map(::moviesReducer)
} else {
movieStorage.getOnlMovies(1, it.sort.option, false)
.map(::moviesReducer)
}.startWith(sortSelectionsReducer(it))
}
val sortSelectionSave = sortSelectionActions
.map { sortOptions.indexOf(it.sort) }
.flatMap { sharedPrefs.writeSortPos(it) }
.map { sortSelectionSaveReducer() }
val pageWithSort = actions
.ofType(GridAction.LoadMore::class.java)
.withLatestFrom(sortSelectionActions,
BiFunction<GridAction.LoadMore, GridAction.SortSelection, PageWithSort>
{ (page), (sort) -> PageWithSort(page, sort) })
val loadMore = pageWithSort
.switchMap {
movieStorage.getOnlMovies(it.page, it.sort.option, false)
.map(::moviesOnlMoreReducer)
.startWith(loadMoreReducer(GridRowLoadMoreViewData()))
}
val refreshSwipes = actions
.ofType(GridAction.RefreshSwipe::class.java)
.withLatestFrom(pageWithSort, BiFunction<GridAction, PageWithSort, PageWithSort>
{ _, pageWithSort -> pageWithSort })
.switchMap {
movieStorage.getOnlMovies(it.page, it.sort.option, true)
.map(::moviesReducer)
.startWith(refreshingReducer())
}
val favDelete = actions
.ofType(GridAction.FavDelete::class.java)
.flatMap { movieStorage.deleteMovieFromFav(it.movieId) }
.map(::favDeleteReducer)
val reducers = listOf(snackbars, sortSelections, sortSelectionSave, loadMore, refreshSwipes, favDelete)
return Observable.merge(reducers)
.scan(initialState, { state, reducer -> reducer(state) })
.skip(1) // skip initial scan emission
.distinctUntilChanged()
}
private fun snackbarReducer(): GridStateReducer = {
it.copy(snackbar = it.snackbar.copy(show = false))
}
private fun sortSelectionsReducer(sortSelection: GridAction.SortSelection): GridStateReducer = {
it.copy(sort = sortSelection.sort, loading = true)
}
private fun sortSelectionSaveReducer(): GridStateReducer = { it }
private fun refreshingReducer(): GridStateReducer = { it.copy(refreshing = true) }
private fun loadMoreReducer(loadMoreViewData: GridRowLoadMoreViewData): GridStateReducer = {
it.copy(loadingMore = true, movies = it.movies.plus(loadMoreViewData))
}
private fun moviesReducer(result: GetMoviesResult): GridStateReducer = { state ->
when (result) {
is GetMoviesResult.Failure -> state.copy(
loading = false,
refreshing = false,
movies = emptyList(),
empty = true,
snackbar = SnackbarMessage(true, R.string.snackbar_movies_load_failed))
is GetMoviesResult.Success -> {
val movies = result.movies
.map {
GridRowMovieViewData(it.id, it.title, it.overview, it.releaseDate.formatLong(), it.voteAverage,
it.poster, it.backdrop)
}
state.copy(
movies = movies,
empty = movies.isEmpty(),
loading = false,
loadingMore = false,
refreshing = false
)
}
}
}
private fun moviesOnlMoreReducer(result: GetMoviesResult): GridStateReducer = { state ->
when (result) {
is GetMoviesResult.Failure -> state.copy(
loadingMore = false,
movies = state.movies.minus(state.movies.last()),
snackbar = SnackbarMessage(true, R.string.snackbar_movies_load_failed))
is GetMoviesResult.Success -> {
val movies = result.movies
.map {
GridRowMovieViewData(it.id, it.title, it.overview, it.releaseDate.formatLong(), it.voteAverage,
it.poster, it.backdrop)
}
state.copy(movies = state.movies.minus(state.movies.last()).plus(movies), loadingMore = false)
}
}
}
private fun favDeleteReducer(result: LocalDbWriteResult.DeleteFromFav): GridStateReducer = {
it.copy(snackbar = SnackbarMessage(true,
if (result.successful) R.string.snackbar_movie_removed_from_favorites
else R.string.snackbar_movie_delete_failed))
}
|
apache-2.0
|
2af4763b0210813c76f30ba327682421
| 39.525714 | 119 | 0.641709 | 4.463184 | false | false | false | false |
Fitbit/MvRx
|
mvrx-mocking/src/test/kotlin/com/airbnb/mvrx/mocking/AutoValueTypePrinterTest.kt
|
1
|
1520
|
package com.airbnb.mvrx.mocking
import com.airbnb.mvrx.mocking.printer.AutoValueTypePrinter
import com.airbnb.mvrx.mocking.printer.ConstructorCodeGenerator
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class AutoValueTypePrinterTest : BaseTest() {
@Test
fun typePrinterAcceptsAutoValueType() {
val obj = AutoValueClass.builder().setName("foo").setNumberOfLegs(1).build()
assertTrue(AutoValueTypePrinter().acceptsObject(obj))
}
@Test
fun typePrinterGeneratesCode() {
val obj = AutoValueClass.builder().setName("foo").setNumberOfLegs(1).build()
val constructorCode = ConstructorCodeGenerator(
obj,
customTypePrinters = listOf(AutoValueTypePrinter())
)
assertEquals(
"val mockAutoValue_AutoValueClass by lazy { AutoValueClass.builder()\n" +
".setName(\"foo\")\n" +
".setNumberOfLegs(1)\n" +
".build() }", constructorCode.lazyPropertyToCreateObject
)
}
@Test
fun typePrinterUsesCorrectImport() {
val obj = AutoValueClass.builder().setName("foo").setNumberOfLegs(1).build()
val constructorCode = ConstructorCodeGenerator(
obj,
customTypePrinters = listOf(AutoValueTypePrinter())
)
assertEquals(
listOf("com.airbnb.mvrx.mocking.AutoValueClass", "kotlin.Int", "kotlin.String"),
constructorCode.imports
)
}
}
|
apache-2.0
|
5dc0f693869679e4b7271c403ed73db6
| 32.043478 | 92 | 0.654605 | 4.550898 | false | true | false | false |
MyDogTom/detekt
|
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/OptionalAbstractKeywordTest.kt
|
1
|
1200
|
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.test.RuleTest
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
class OptionalAbstractKeywordTest : RuleTest {
override val rule = OptionalAbstractKeyword()
@Test
fun noAbstractKeywordOnInterface() {
val code = "interface A {}"
Assertions.assertThat(lint(code)).isEqualTo(0)
}
@Test
fun abstractInterfaceProperty() {
val code = "abstract interface A { abstract var x: Int }"
Assertions.assertThat(lint(code)).isEqualTo(2)
}
@Test
fun abstractInterfaceFunction() {
val code = "abstract interface A { abstract fun x() }"
Assertions.assertThat(lint(code)).isEqualTo(2)
}
@Test
fun loneAbstractMember() {
val code = "abstract var x: Int"
Assertions.assertThat(lint(code)).isEqualTo(0)
}
@Test
fun innerInterface() {
val code = "class A { abstract interface B {} }"
Assertions.assertThat(lint(code)).isEqualTo(1)
}
@Test
fun abstractClass() {
val code = "abstract class A { abstract fun x() }"
Assertions.assertThat(lint(code)).isEqualTo(0)
}
private fun lint(code: String) = rule.lint(code).size
}
|
apache-2.0
|
8d1c56db8ddcc8ccc6afceb535d70e4d
| 23 | 59 | 0.7275 | 3.389831 | false | true | false | false |
JimSeker/ui
|
RecyclerViews/RecyclerViewDemo3_kt/app/src/main/java/edu/cs4730/recyclerviewdemo3_kt/Phonebook_myAdapter.kt
|
1
|
2895
|
package edu.cs4730.recyclerviewdemo3_kt
import android.content.Context
import edu.cs4730.recyclerviewdemo3_kt.Phonebook_DataModel
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.TextView
import edu.cs4730.recyclerviewdemo3_kt.R
/**
* needs a comment here.
*/
class Phonebook_myAdapter(
private val listPhonebook: MutableList<Phonebook_DataModel>?,
private val rowLayout: Int,
private val context: Context
) : RecyclerView.Adapter<Phonebook_myAdapter.ViewHolder>(), View.OnClickListener {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(rowLayout, viewGroup, false)
return ViewHolder(v)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
//find our place in the datamodel and recycler view.
val entry = listPhonebook!![position]
//setup the view with data.
viewHolder.tvContact.text = entry.name
viewHolder.tvPhone.text = entry.phone
viewHolder.tvMail.text = entry.mail
// Set the onClick Listener on this button
viewHolder.btnRemove.setOnClickListener(this)
// Set the entry, so that you can capture which item was clicked and
// then remove it
// As an alternative, you can use the id/position of the item to capture
// the item that was clicked.
// btnRemove.setId(position);
viewHolder.btnRemove.tag = entry
}
override fun getItemCount(): Int {
return listPhonebook?.size ?: 0
}
/*
* setup the ViewHolder class with the widget variables, to be used in onBindViewholder
*/
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvContact: TextView
var tvPhone: TextView
var tvMail: TextView
var btnRemove: Button
init {
tvContact = itemView.findViewById<View>(R.id.tvContact) as TextView
tvPhone = itemView.findViewById<View>(R.id.tvMobile) as TextView
tvMail = itemView.findViewById<View>(R.id.tvMail) as TextView
btnRemove = itemView.findViewById<View>(R.id.btnRemove) as Button
btnRemove.isFocusableInTouchMode = false
btnRemove.isFocusable = false
}
}
override fun onClick(view: View) {
val entry = view.tag as Phonebook_DataModel
//We could call a dialog showDialog(entry), if we wanted to change it instead of deleting it.
listPhonebook!!.remove(entry)
notifyDataSetChanged()
}
private fun showDialog(entry: Phonebook_DataModel) {
// Create and show your dialog
// Depending on the Dialogs button clicks delete it or do nothing
}
}
|
apache-2.0
|
b2ea2c5d7e2bb797edbe5651aa0daa44
| 36.128205 | 101 | 0.689465 | 4.523438 | false | false | false | false |
yamamotoj/workshop-jb
|
src/iv_builders/_22_ExtensionFunctionLiterals.kt
|
1
|
1127
|
package iv_builders
import java.util.HashMap
import util.TODO
fun functions() {
// function
fun getLastChar(s: String) = s.charAt(s.length() - 1)
getLastChar("abc")
// extension function
fun String.lastChar() = this.charAt(this.length() - 1)
// 'this' can be omitted
fun String.lastChar2() = charAt(length() - 1)
"abc".lastChar()
}
fun functionLiterals() {
// function literal
val getLastChar: (String) -> Char = { s -> s.charAt(s.length() - 1) }
getLastChar("abc")
// extension function literal
val lastChar: String.() -> Char = { this.charAt(this.length() - 1) }
// 'this' can be omitted
val lastChar2: String.() -> Char = { charAt(length() - 1) }
"abc".lastChar()
}
fun todoTask22() = TODO(
"""
Task 22.
Replace 'todoTask22()' so that 'x.isEven()' checks that x is even
and 'x.isOdd()' checks that x is odd.
"""
)
fun task22(): List<Boolean> {
val isEven: Int.() -> Boolean = { this % 2 == 0 }
val isOdd: Int.() -> Boolean = { this % 2 == 1 }
return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}
|
mit
|
f3b5d0209965f154e18fe1ebc43a6a38
| 22.978723 | 73 | 0.582964 | 3.457055 | false | false | false | false |
LordAkkarin/Beacon
|
core/src/main/kotlin/tv/dotstart/beacon/core/gateway/InternetGatewayDeviceLocator.kt
|
1
|
5994
|
/*
* Copyright 2020 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.dotstart.beacon.core.gateway
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.time.withTimeoutOrNull
import net.mm2d.upnp.ControlPoint
import net.mm2d.upnp.ControlPointFactory
import tv.dotstart.beacon.core.delegate.logManager
import tv.dotstart.beacon.core.upnp.DeviceDiscoveryEvent
import tv.dotstart.beacon.core.upnp.FlowDiscoveryListener
import java.net.NetworkInterface
import java.time.Duration
/**
* Provides an interface for the purposes of locating standard compliant internet gateway devices
* within the local network.
*
* When no network interface is explicitly specified, devices are queried via all available network
* interfaces on the system. This behavior is typically desirable as systems may be connected to
* multiple networks (such as VPNs) while only a single gateway will typically answer queries.
*
* @author [Johannes Donath](mailto:[email protected])
* @date 01/12/2020
*/
class InternetGatewayDeviceLocator(
/**
* Provides a listing of network interfaces on which device queries are published.
*/
val networkInterfaces: List<NetworkInterface> = emptyList(),
/**
* Identifies the maximum amount the locator will wait before assuming no compatible device to
* be present within the network.
*/
private val timeout: Duration = Duration.ofSeconds(5)) {
companion object {
private val logger by logManager()
internal const val deviceType = "urn:schemas-upnp-org:device:WANConnectionDevice"
/**
* Defines the specification revisions which are to be queried by the locator.
*/
internal val deviceVersions = listOf(
1,
2
)
}
/**
* Attempts to locate a compatible internet gateway device within the local network.
*
* This method will return the first gateway device which manages to respond to the query as the
* network is expected to only ever contain a single gateway device (or is capable of configuring
* the actual gateway if acting as a repeater of sorts).
*
* TODO: These assumptions may not necessarily hold true - We should select the most compatible
* device based on its responses
*/
suspend fun locate(): InternetGatewayDevice? {
val cp = ControlPointFactory.builder()
.also {
if (this.networkInterfaces.isNotEmpty()) {
it.setInterfaces(this.networkInterfaces)
}
}
.build()
cp.start()
val device = deviceVersions
.mapNotNull { this.locate(cp, it) }
.firstOrNull()
if (device == null) {
logger.debug("locate() found no compatible device - Terminating control point prematurely")
cp.terminate()
return null
}
logger.debug("locate() returned compatible device \"${device.friendlyName}\"")
return device
}
/**
* Attempts to locate an internet gateway device using a given control point.
*
* This method is cancellation compliant and will exit early when its surrounding coroutine scope
* has been cancelled thus permitting timeout behaviors if desired.
*
* By default, this method will never timeout. Only a single query will be dispatched, however.
*/
internal suspend fun locate(cp: ControlPoint, version: Int): InternetGatewayDevice? {
FlowDiscoveryListener().use { listener ->
logger.debug("Registering discovery listener with control point")
cp.addDiscoveryListener(listener)
val queryString = "$deviceType:$version"
logger.debug("Broadcasting search request for device $queryString")
cp.search(queryString)
@Suppress("ConvertLambdaToReference") // ugly
val device = withTimeoutOrNull(this.timeout) {
listener.events
// TODO: Handle loss of devices within the network gracefully
.filter { it.type == DeviceDiscoveryEvent.Type.DISCOVERED }
.mapNotNull { (_, device) ->
logger.info(
"Received announcement for device \"${device.friendlyName}\" (${device.modelName}) of type ${device.deviceType} by ${device.manufacture} <${device.manufactureUrl}>")
logger.debug("Sub-Devices:")
device.deviceList.forEach {
logger.debug(
" * \"${device.friendlyName}\" (${device.modelName}) of type ${device.deviceType}")
}
if (device.deviceType == queryString) {
device
} else {
device.findDeviceByTypeRecursively(queryString)
}
}
.map { device -> InternetGatewayDevice(cp, device) }
.filter {
if (!it.portMappingAvailable) {
logger.warn(
"Device \"${it.friendlyName}\" does not support port mapping and will not be considered")
} else {
logger.info("Device \"${it.friendlyName}\" is compatible")
}
it.portMappingAvailable
}
.firstOrNull()
}
logger.debug("Removing discovery listener from ControlPoint")
cp.removeDiscoveryListener(listener)
return device
}
}
}
|
apache-2.0
|
5361fe9e0b27f12841b00d4f40c6ef5f
| 35.54878 | 183 | 0.67701 | 4.84168 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/utils/JSONObject.kt
|
1
|
4081
|
/*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This file is free software: you may copy, redistribute 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 file 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/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (c) 2002 JSON.org
*
* 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 shall be used for Good, not Evil.
*
* 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.ichi2.utils
import androidx.annotation.CheckResult
import androidx.annotation.VisibleForTesting
import org.json.JSONArray
import org.json.JSONObject
/*
Each method similar to the methods in JSONObjects. Name changed to add a ,
and it throws JSONException instead of JSONException.
Furthermore, it returns JSONObject and JSONArray
*/
@CheckResult
fun JSONObject.deepClone(): JSONObject = deepClonedInto(JSONObject())
/** deep clone this into clone.
*
* Given a subtype [T] of JSONObject, and a JSONObject [clone], we could do
* ```
* T t = new T();
* clone.deepClonedInto(t);
* ```
* in order to obtain a deep clone of [clone] of type [T]. */
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
fun <T : JSONObject> JSONObject.deepClonedInto(clone: T): T {
for (key in this.keys()) {
val value = when (get(key)) {
is JSONObject -> getJSONObject(key).deepClone()
is JSONArray -> getJSONArray(key).deepClone()
else -> get(key)
}
clone.put(key, value)
}
return clone
}
/**
* Change type from JSONObject to JSONObject.
*
* Assuming the whole code use only JSONObject, JSONArray and JSONTokener,
* there should be no instance of JSONObject or JSONArray which is not a JSONObject or JSONArray.
*
* In theory, it would be easy to create a JSONObject similar to a JSONObject. It would suffices to iterate over key and add them here. But this would create two distinct objects, and update here would not be reflected in the initial object. So we must avoid this method.
* Since the actual map in JSONObject is private, the child class can't edit it directly and can't access it. Which means that there is no easy way to create a JSONObject with the same underlying map. Unless the JSONObject was saved in a variable here. Which would entirely defeat the purpose of inheritance.
*
* @param obj A json object
* @return Exactly the same object, with a different type.
*/
fun fromMap(map: Map<String, Any>): JSONObject = JSONObject().apply {
map.forEach { (k, v) -> put(k, v) }
}
|
gpl-3.0
|
13edb88431b136869707bc010982ac12
| 41.957895 | 308 | 0.730703 | 4.155804 | false | false | false | false |
mixitconf/mixit
|
src/main/kotlin/mixit/user/model/UserService.kt
|
1
|
2682
|
package mixit.user.model
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import mixit.security.model.Cryptographer
import mixit.user.repository.UserRepository
import mixit.util.cache.CacheTemplate
import mixit.util.cache.CacheZone
import org.springframework.context.ApplicationEvent
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
data class UserUpdateEvent(val user: User) : ApplicationEvent(user)
@Service
class UserService(
private val userRepository: UserRepository,
private val eventPublisher: ApplicationEventPublisher,
private val cryptographer: Cryptographer
) : CacheTemplate<CachedUser>() {
override val cacheZone: CacheZone = CacheZone.USER
override fun findAll(): Mono<List<CachedUser>> =
findAll { userRepository.findAll().map { user -> CachedUser(user) }.collectList() }
fun findOneByEncryptedEmail(email: String): Mono<CachedUser> =
findAll().flatMap { elements -> Mono.justOrEmpty(elements.firstOrNull { it.email == email }) }
suspend fun coFindOneByEncryptedEmail(email: String): CachedUser? =
findOneByEncryptedEmail(email).awaitSingleOrNull()
fun findOneByNonEncryptedEmail(email: String): Mono<CachedUser> =
cryptographer.encrypt(email)!!.let { encryptedEmail ->
findAll().flatMap { elements -> Mono.justOrEmpty(elements.firstOrNull { it.email == encryptedEmail }) }
}
fun findByRoles(vararg roles: Role): Mono<List<CachedUser>> =
findAll().map { elements -> elements.filter { roles.contains(it.role) } }
suspend fun coFindByRoles(staff: Role, staffInPause: Role) =
findByRoles(staff, staffInPause).awaitSingle()
fun findAllByIds(userIds: List<String>): Mono<List<CachedUser>> =
findAll().map { elements -> elements.filter { userIds.contains(it.login) } }
fun save(user: User): Mono<User> =
userRepository.save(user).doOnSuccess {
cache.invalidateAll()
eventPublisher.publishEvent(UserUpdateEvent(user))
}
fun deleteOne(id: String) =
userRepository.findOne(id).flatMap { user ->
userRepository.deleteOne(id).map {
cache.invalidateAll()
eventPublisher.publishEvent(UserUpdateEvent(user))
user
}
}
fun updateReference(user: User): Mono<User> =
findOne(user.login)
.map {
it.email = it.email ?: user.email
it.newsletterSubscriber = user.newsletterSubscriber
user
}
}
|
apache-2.0
|
71fd076b250a780e9b17a0e3e28d653b
| 37.314286 | 115 | 0.693139 | 4.632124 | false | false | false | false |
infinum/android_dbinspector
|
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/pragma/usecases/GetTablePragmaUseCaseTest.kt
|
1
|
1543
|
package com.infinum.dbinspector.domain.pragma.usecases
import com.infinum.dbinspector.domain.Repositories
import com.infinum.dbinspector.domain.shared.models.parameters.PragmaParameters
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
@DisplayName("GetTablePragmaUseCase tests")
internal class GetTablePragmaUseCaseTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Repositories.Connection>() }
factory { mockk<Repositories.Pragma>() }
}
)
@Test
fun `Invoking use case invokes connection open and pragma table info`() {
val given = PragmaParameters.Pragma(
databasePath = "test.db",
statement = "my_statement"
)
val connectionRepository: Repositories.Connection = get()
val pragmaRepository: Repositories.Pragma = get()
val useCase = GetTablePragmaUseCase(connectionRepository, pragmaRepository)
coEvery { connectionRepository.open(any()) } returns mockk()
coEvery { pragmaRepository.getTableInfo(any()) } returns mockk()
test {
useCase.invoke(given)
}
coVerify(exactly = 1) { connectionRepository.open(any()) }
coVerify(exactly = 1) { pragmaRepository.getTableInfo(any()) }
}
}
|
apache-2.0
|
38aa9ce3230c7faac4f79b8d7b526b53
| 32.543478 | 83 | 0.697991 | 4.421203 | false | true | false | false |
wordpress-mobile/WordPress-Stores-Android
|
example/src/androidTest/java/org/wordpress/android/fluxc/release/ReleaseStack_ManageInsightsTestJetpack.kt
|
2
|
7037
|
package org.wordpress.android.fluxc.release
import kotlinx.coroutines.runBlocking
import org.greenrobot.eventbus.Subscribe
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.wordpress.android.fluxc.TestUtils
import org.wordpress.android.fluxc.action.ActivityLogAction
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.example.BuildConfig
import org.wordpress.android.fluxc.generated.AccountActionBuilder
import org.wordpress.android.fluxc.generated.AuthenticationActionBuilder
import org.wordpress.android.fluxc.generated.SiteActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.fluxc.store.AccountStore.AuthenticatePayload
import org.wordpress.android.fluxc.store.AccountStore.OnAccountChanged
import org.wordpress.android.fluxc.store.AccountStore.OnAuthenticationChanged
import org.wordpress.android.fluxc.store.DEFAULT_INSIGHTS
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.fluxc.store.SiteStore.FetchSitesPayload
import org.wordpress.android.fluxc.store.SiteStore.OnSiteChanged
import org.wordpress.android.fluxc.store.SiteStore.SiteErrorType
import org.wordpress.android.fluxc.store.StatsStore
import org.wordpress.android.fluxc.store.StatsStore.InsightType.FOLLOWER_TOTALS
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.inject.Inject
/**
* Tests with real credentials on real servers using the full release stack (no mock)
*/
class ReleaseStack_ManageInsightsTestJetpack : ReleaseStack_Base() {
private val incomingActions: MutableList<Action<*>> = mutableListOf()
@Inject lateinit var statsStore: StatsStore
@Inject internal lateinit var siteStore: SiteStore
@Inject internal lateinit var accountStore: AccountStore
private var nextEvent: TestEvents? = null
internal enum class TestEvents {
NONE,
SITE_CHANGED,
SITE_REMOVED,
ERROR_DUPLICATE_SITE
}
@Throws(Exception::class)
override fun setUp() {
super.setUp()
mReleaseStackAppComponent.inject(this)
// Register
init()
// Reset expected test event
nextEvent = TestEvents.NONE
this.incomingActions.clear()
}
@Test
fun testAddAndRemoveInsights() {
val site = authenticate()
val emptyStats = runBlocking { statsStore.getAddedInsights(site) }
// Starts with default blocks (those in DEFAULT_INSIGHTS)
assertEquals(emptyStats.size, DEFAULT_INSIGHTS.size)
if (!emptyStats.contains(FOLLOWER_TOTALS)) {
runBlocking { statsStore.addType(site, FOLLOWER_TOTALS) }
}
val statsWithFollowers = runBlocking { statsStore.getAddedInsights(site) }
assertEquals(statsWithFollowers.size, DEFAULT_INSIGHTS.size + 1)
runBlocking { statsStore.removeType(site, FOLLOWER_TOTALS) }
val statsWithoutFollowers = runBlocking { statsStore.getAddedInsights(site) }
assertEquals(statsWithoutFollowers.size, DEFAULT_INSIGHTS.size)
}
@Test
fun testMoveInsightsUp() {
val site = authenticate()
val stats = runBlocking { statsStore.getAddedInsights(site) }
val secondItem = stats[1]
runBlocking { statsStore.moveTypeUp(site, secondItem) }
val updatedStats = runBlocking { statsStore.getAddedInsights(site) }
assertEquals(updatedStats[0], secondItem)
}
@Test
fun testMoveInsightsDown() {
val site = authenticate()
val stats = runBlocking { statsStore.getAddedInsights(site) }
val firstItem = stats[0]
runBlocking { statsStore.moveTypeDown(site, firstItem) }
val updatedStats = runBlocking { statsStore.getAddedInsights(site) }
assertEquals(updatedStats[1], firstItem)
}
private fun authenticate(): SiteModel {
authenticateWPComAndFetchSites(
BuildConfig.TEST_WPCOM_USERNAME_SINGLE_JETPACK_ONLY,
BuildConfig.TEST_WPCOM_PASSWORD_SINGLE_JETPACK_ONLY
)
return siteStore.sites[0]
}
@Subscribe
fun onAuthenticationChanged(event: OnAuthenticationChanged) {
if (event.isError) {
throw AssertionError("Unexpected error occurred with type: " + event.error.type)
}
mCountDownLatch.countDown()
}
@Subscribe
fun onAccountChanged(event: OnAccountChanged) {
AppLog.d(T.TESTS, "Received OnAccountChanged event")
if (event.isError) {
throw AssertionError("Unexpected error occurred with type: " + event.error.type)
}
mCountDownLatch.countDown()
}
@Subscribe
fun onSiteChanged(event: OnSiteChanged) {
AppLog.i(T.TESTS, "site count " + siteStore.sitesCount)
if (event.isError) {
if (nextEvent == TestEvents.ERROR_DUPLICATE_SITE) {
assertEquals(SiteErrorType.DUPLICATE_SITE, event.error.type)
mCountDownLatch.countDown()
return
}
throw AssertionError("Unexpected error occurred with type: " + event.error.type)
}
assertTrue(siteStore.hasSite())
assertEquals(TestEvents.SITE_CHANGED, nextEvent)
mCountDownLatch.countDown()
}
@Subscribe
fun onAction(action: Action<*>) {
if (action.type is ActivityLogAction) {
incomingActions.add(action)
mCountDownLatch?.countDown()
}
}
@Throws(InterruptedException::class)
private fun authenticateWPComAndFetchSites(username: String, password: String) {
// Authenticate a test user (actual credentials declared in gradle.properties)
val payload = AuthenticatePayload(username, password)
mCountDownLatch = CountDownLatch(1)
// Correct user we should get an OnAuthenticationChanged message
mDispatcher.dispatch(AuthenticationActionBuilder.newAuthenticateAction(payload))
// Wait for a network response / onChanged event
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
// Fetch account from REST API, and wait for OnAccountChanged event
mCountDownLatch = CountDownLatch(1)
mDispatcher.dispatch(AccountActionBuilder.newFetchAccountAction())
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
// Fetch sites from REST API, and wait for onSiteChanged event
mCountDownLatch = CountDownLatch(1)
nextEvent = TestEvents.SITE_CHANGED
mDispatcher.dispatch(SiteActionBuilder.newFetchSitesAction(FetchSitesPayload()))
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
assertTrue(siteStore.sitesCount > 0)
}
}
|
gpl-2.0
|
5137f632d8303485dd5d6d5e90874aca
| 36.232804 | 103 | 0.717493 | 4.651024 | false | true | false | false |
mercadopago/px-android
|
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/express/slider/PaymentMethodFragmentAdapter.kt
|
1
|
1829
|
package com.mercadopago.android.px.internal.features.express.slider
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import android.view.ViewGroup
import com.mercadopago.android.px.internal.viewmodel.drawables.DrawableFragmentItem
import com.mercadopago.android.px.internal.viewmodel.drawables.PaymentMethodFragmentDrawer
class PaymentMethodFragmentAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
private var items: List<DrawableFragmentItem> = emptyList()
private var drawer: PaymentMethodFragmentDrawer = PaymentMethodHighResDrawer()
private var renderMode = RenderMode.HIGH_RES
private var currentInstallment = 0
fun setItems(items: List<DrawableFragmentItem>) {
this.items = items
notifyDataSetChanged()
}
override fun getItem(position: Int): Fragment = items[position].draw(drawer)
override fun getItemPosition(item: Any) = PagerAdapter.POSITION_NONE
override fun setPrimaryItem(container: ViewGroup, position: Int, item: Any) {
if (item is ConsumerCreditsFragment) {
item.updateInstallment(currentInstallment)
}
super.setPrimaryItem(container, position, item)
}
fun updateInstallment(installmentSelected: Int) {
currentInstallment = installmentSelected
}
override fun getCount(): Int {
return items.size
}
fun setRenderMode(renderMode: RenderMode) {
if (this.renderMode != renderMode && renderMode == RenderMode.LOW_RES) {
this.renderMode = renderMode
drawer = PaymentMethodLowResDrawer()
notifyDataSetChanged()
}
}
enum class RenderMode {
HIGH_RES, LOW_RES
}
}
|
mit
|
600164d8435721c429627c819eaffd2a
| 33.528302 | 90 | 0.730454 | 4.665816 | false | false | false | false |
debop/debop4k
|
debop4k-data-mongodb/src/main/kotlin/debop4k/mongodb/logback/MongodbLogAppender.kt
|
1
|
3715
|
/*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.mongodb.logback
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.classic.spi.LoggingEvent
import ch.qos.logback.classic.spi.ThrowableProxyUtil
import ch.qos.logback.core.CoreConstants
import ch.qos.logback.core.UnsynchronizedAppenderBase
import com.mongodb.MongoClient
import com.mongodb.ServerAddress
import debop4k.core.asyncs.future
import org.joda.time.DateTime
import org.springframework.data.authentication.UserCredentials
import org.springframework.data.mongodb.core.MongoTemplate
/**
* logback 에서 생성되는 로그를 MongoDB 에 저장하는 Log Appender 입니다
* @author [email protected]
*/
class MongodbLogAppender : UnsynchronizedAppenderBase<LoggingEvent>() {
companion object {
@JvmField val DEFAULT_DB_NAME = "logDB"
@JvmField val DEFAULT_COLLECTION_NAME = "logs"
}
private var template: MongoTemplate? = null
private var client: MongoClient? = null
private val serverName: String? = null
private val applicationName: String? = null
private val host = ServerAddress.defaultHost()
private val port = ServerAddress.defaultPort()
private val dbName = DEFAULT_DB_NAME
private var collectionName = DEFAULT_COLLECTION_NAME
private val username: String? = null
private val password: String? = null
override fun start() {
try {
connect()
super.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun append(eventObject: LoggingEvent?) {
if (eventObject == null)
return
future {
val doc = newLogDocument(eventObject)
template?.save(doc, collectionName)
}
}
private fun connect() {
client = MongoClient(host, port)
val credentials = if (username != null && password != null)
UserCredentials(username, password)
else
UserCredentials.NO_CREDENTIALS
template = MongoTemplate(client!!, dbName, credentials)
if (collectionName.isNullOrBlank())
collectionName = DEFAULT_COLLECTION_NAME
if (!template!!.collectionExists(collectionName))
template!!.createCollection(collectionName)
}
private fun newLogDocument(event: ILoggingEvent): MongodbLogDocument {
val doc = MongodbLogDocument().apply {
serverName = [email protected] ?: ""
applicationName = [email protected] ?: ""
logger = event.loggerName
levelInt = event.level.levelInt
levelStr = event.level.levelStr
threadName = event.threadName
timestamp = DateTime(event.timeStamp)
message = event.formattedMessage
}
if (event.marker != null) {
doc.marker = event.marker.name
}
event.throwableProxy?.let { tp ->
val str = ThrowableProxyUtil.asString(tp)
val stacktrace = str.replace("\t", "")
.split(CoreConstants.LINE_SEPARATOR)
.toMutableList()
if (stacktrace.size > 0)
doc.exception = stacktrace[0]
if (stacktrace.size > 1) {
stacktrace.removeAt(1)
doc.stackTrace = stacktrace
}
}
return doc
}
}
|
apache-2.0
|
7376295c10a9e897ac9e78eb83fc85ce
| 28.934959 | 75 | 0.708231 | 4.164027 | false | false | false | false |
ykrank/S1-Next
|
app/src/main/java/me/ykrank/s1next/view/fragment/ThreadListFragment.kt
|
1
|
4181
|
package me.ykrank.s1next.view.fragment
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import com.github.ykrank.androidtools.ui.LibBaseViewPagerFragment
import com.github.ykrank.androidtools.util.MathUtil
import com.github.ykrank.androidtools.widget.RxBus
import me.ykrank.s1next.App
import me.ykrank.s1next.R
import me.ykrank.s1next.data.api.Api
import me.ykrank.s1next.data.api.model.Forum
import me.ykrank.s1next.data.pref.GeneralPreferencesManager
import me.ykrank.s1next.util.IntentUtil
import me.ykrank.s1next.view.event.PostDisableStickyChangeEvent
import me.ykrank.s1next.view.event.QuickSidebarEnableChangeEvent
import javax.inject.Inject
/**
* A Fragment includes [android.support.v4.view.ViewPager]
* to represent each page of thread lists.
*/
class ThreadListFragment : BaseViewPagerFragment(), ThreadListPagerFragment.PagerCallback {
private var mForumName: String? = null
private var mTypeId: String = "0"
private lateinit var mForumId: String
@Inject
internal lateinit var mRxBus: RxBus
@Inject
internal lateinit var mGeneralPreferencesManager: GeneralPreferencesManager
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
App.appComponent.inject(this)
val forum:Forum = arguments!!.getParcelable(ARG_FORUM)!!
mForumName = forum.name
mForumId = forum.id!!
leavePageMsg("ThreadListFragment##ForumName:$mForumName,ForumId:$mForumId")
if (savedInstanceState == null) {
setTotalPageByThreads(forum.threads)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_thread, menu)
menu.findItem(R.id.menu_page_jump)?.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
val mMenuPostDisableSticky = menu.findItem(R.id.menu_post_disable_sticky)
mMenuPostDisableSticky?.isChecked = mGeneralPreferencesManager.isPostDisableSticky
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_browser -> {
IntentUtil.startViewIntentExcludeOurApp(context, Uri.parse(
Api.getThreadListUrlForBrowser(mForumId, currentPage + 1)))
return true
}
R.id.menu_post_disable_sticky -> {
item.isChecked = !item.isChecked
mGeneralPreferencesManager.isPostDisableSticky = item.isChecked
mRxBus.post(PostDisableStickyChangeEvent())
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun getPagerAdapter(fragmentManager: androidx.fragment.app.FragmentManager)
: FragmentStatePagerAdapter<*> {
return ThreadListPagerAdapter(childFragmentManager)
}
override fun getTitleWithoutPosition(): CharSequence? {
return mForumName
}
override fun setTotalPageByThreads(threads: Int) {
setTotalPages(MathUtil.divide(threads, Api.THREADS_PER_PAGE))
}
fun changeTypeId(typeId: String?) {
mTypeId = typeId ?: "0"
}
/**
* Returns a Fragment corresponding to one of the pages of threads.
*/
private inner class ThreadListPagerAdapter(fm: androidx.fragment.app.FragmentManager)
: FragmentStatePagerAdapter<ThreadListPagerFragment>(fm) {
override fun getItem(i: Int): ThreadListPagerFragment {
return ThreadListPagerFragment.newInstance(mForumId, mTypeId, i + 1)
}
}
companion object {
val TAG = ThreadListFragment::class.java.name
private const val ARG_FORUM = "forum"
fun newInstance(forum: Forum): ThreadListFragment {
val fragment = ThreadListFragment()
val bundle = Bundle()
bundle.putParcelable(ARG_FORUM, forum)
fragment.arguments = bundle
return fragment
}
}
}
|
apache-2.0
|
67d60c511b3a7cd03fa056f805447709
| 33.553719 | 91 | 0.696006 | 4.471658 | false | false | false | false |
timusus/Shuttle
|
app/src/main/java/com/simplecity/amp_library/ui/screens/suggested/SuggestedFragment.kt
|
1
|
14775
|
package com.simplecity.amp_library.ui.screens.suggested
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.bumptech.glide.RequestManager
import com.simplecity.amp_library.R
import com.simplecity.amp_library.R.string
import com.simplecity.amp_library.data.Repository
import com.simplecity.amp_library.model.Album
import com.simplecity.amp_library.model.AlbumArtist
import com.simplecity.amp_library.model.Playlist
import com.simplecity.amp_library.model.Song
import com.simplecity.amp_library.model.SuggestedHeader
import com.simplecity.amp_library.ui.screens.tagger.TaggerDialog
import com.simplecity.amp_library.ui.adapters.ViewType
import com.simplecity.amp_library.ui.common.BaseFragment
import com.simplecity.amp_library.ui.dialog.AlbumBiographyDialog
import com.simplecity.amp_library.ui.dialog.DeleteDialog
import com.simplecity.amp_library.ui.dialog.SongInfoDialog
import com.simplecity.amp_library.ui.modelviews.AlbumView
import com.simplecity.amp_library.ui.modelviews.EmptyView
import com.simplecity.amp_library.ui.modelviews.HorizontalRecyclerView
import com.simplecity.amp_library.ui.modelviews.SuggestedHeaderView
import com.simplecity.amp_library.ui.modelviews.SuggestedSongView
import com.simplecity.amp_library.ui.screens.playlist.detail.PlaylistDetailFragment
import com.simplecity.amp_library.ui.screens.playlist.dialog.CreatePlaylistDialog
import com.simplecity.amp_library.ui.screens.suggested.SuggestedPresenter.SuggestedData
import com.simplecity.amp_library.ui.views.SuggestedDividerDecoration
import com.simplecity.amp_library.utils.ArtworkDialog
import com.simplecity.amp_library.utils.RingtoneManager
import com.simplecity.amp_library.utils.SettingsManager
import com.simplecity.amp_library.utils.ShuttleUtils
import com.simplecity.amp_library.utils.extensions.share
import com.simplecity.amp_library.utils.menu.album.AlbumMenuUtils
import com.simplecity.amp_library.utils.menu.song.SongMenuUtils
import com.simplecity.amp_library.utils.playlists.FavoritesPlaylistManager
import com.simplecity.amp_library.utils.playlists.PlaylistMenuHelper
import com.simplecity.amp_library.utils.sorting.SortManager
import com.simplecity.amp_library.utils.withArgs
import com.simplecityapps.recycler_adapter.adapter.ViewModelAdapter
import com.simplecityapps.recycler_adapter.model.ViewModel
import com.simplecityapps.recycler_adapter.recyclerview.RecyclerListener
import dagger.android.support.AndroidSupportInjection
import io.reactivex.disposables.CompositeDisposable
import java.util.ArrayList
import javax.inject.Inject
class SuggestedFragment :
BaseFragment(),
SuggestedHeaderView.ClickListener,
AlbumView.ClickListener,
SuggestedContract.View {
@Inject lateinit var presenter: SuggestedPresenter
@Inject lateinit var songsRepository: Repository.SongsRepository
@Inject lateinit var sortManager: SortManager
@Inject lateinit var settingsManager: SettingsManager
@Inject lateinit var favoritesPlaylistManager: FavoritesPlaylistManager
@Inject lateinit var playlistMenuHelper: PlaylistMenuHelper
@Inject lateinit var requestManager: RequestManager
private lateinit var adapter: ViewModelAdapter
private lateinit var favoriteRecyclerView: HorizontalRecyclerView
private lateinit var mostPlayedRecyclerView: HorizontalRecyclerView
private val disposables = CompositeDisposable()
private val refreshDisposables = CompositeDisposable()
private var suggestedClickListener: SuggestedClickListener? = null
interface SuggestedClickListener {
fun onAlbumArtistClicked(albumArtist: AlbumArtist, transitionView: View)
fun onAlbumClicked(album: Album, transitionView: View)
}
// Lifecycle
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
if (parentFragment is SuggestedClickListener) {
suggestedClickListener = parentFragment as SuggestedClickListener?
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter = ViewModelAdapter()
mostPlayedRecyclerView = HorizontalRecyclerView("SuggestedFragment - mostPlayed")
favoriteRecyclerView = HorizontalRecyclerView("SuggestedFragment - favorite")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_suggested, container, false) as RecyclerView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view as RecyclerView
val spanCount = if (ShuttleUtils.isTablet(context!!)) 12 else 6
val gridLayoutManager = GridLayoutManager(context, spanCount)
gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
if (!adapter.items.isEmpty() && position >= 0) {
val item = adapter.items[position]
if (item is HorizontalRecyclerView
|| item is SuggestedHeaderView
|| item is AlbumView && item.getViewType() == ViewType.ALBUM_LIST
|| item is AlbumView && item.getViewType() == ViewType.ALBUM_LIST_SMALL
|| item is EmptyView
) {
return spanCount
}
if (item is AlbumView && item.getViewType() == ViewType.ALBUM_CARD_LARGE) {
return 3
}
}
return 2
}
}
view.addItemDecoration(SuggestedDividerDecoration(resources))
view.setRecyclerListener(RecyclerListener())
view.layoutManager = gridLayoutManager
view.adapter = adapter
presenter.bindView(this)
}
override fun onResume() {
super.onResume()
presenter.loadData()
}
override fun onPause() {
disposables.clear()
refreshDisposables.clear()
super.onPause()
}
override fun onDestroyView() {
super.onDestroyView()
presenter.unbindView(this)
}
override fun onDetach() {
super.onDetach()
suggestedClickListener = null
}
inner class SongClickListener(val songs: List<Song>) : SuggestedSongView.ClickListener {
override fun onSongClick(song: Song, holder: SuggestedSongView.ViewHolder) {
mediaManager.playAll(songs, songs.indexOf(song), true) {
onPlaybackFailed()
}
}
override fun onSongOverflowClicked(v: View, position: Int, song: Song) {
val popupMenu = PopupMenu(context!!, v)
SongMenuUtils.setupSongMenu(popupMenu, false, true, playlistMenuHelper)
popupMenu.setOnMenuItemClickListener(SongMenuUtils.getSongMenuClickListener(song, presenter))
popupMenu.show()
}
}
// AlbumView.ClickListener implementation
override fun onAlbumClick(position: Int, albumView: AlbumView, viewHolder: AlbumView.ViewHolder) {
suggestedClickListener?.onAlbumClicked(albumView.album, viewHolder.imageOne)
}
override fun onAlbumLongClick(position: Int, albumView: AlbumView): Boolean {
return false
}
override fun onAlbumOverflowClicked(v: View, album: Album) {
val menu = PopupMenu(context!!, v)
AlbumMenuUtils.setupAlbumMenu(menu, playlistMenuHelper, true)
menu.setOnMenuItemClickListener(AlbumMenuUtils.getAlbumMenuClickListener(album, presenter))
menu.show()
}
override fun onSuggestedHeaderClick(suggestedHeader: SuggestedHeader) {
navigationController.pushViewController(PlaylistDetailFragment.newInstance(suggestedHeader.playlist), "PlaylistListFragment")
}
// SuggestedContract.View implementation
override fun setData(suggestedData: SuggestedData) {
val viewModels = ArrayList<ViewModel<*>>()
if (suggestedData.mostPlayedSongs.isNotEmpty()) {
val mostPlayedHeader = SuggestedHeader(getString(string.mostplayed), getString(string.suggested_most_played_songs_subtitle), suggestedData.mostPlayedPlaylist)
val mostPlayedHeaderView = SuggestedHeaderView(mostPlayedHeader)
mostPlayedHeaderView.setClickListener(this)
viewModels.add(mostPlayedHeaderView)
viewModels.add(mostPlayedRecyclerView)
val songClickListener = SongClickListener(suggestedData.mostPlayedSongs)
mostPlayedRecyclerView.setItems(suggestedData.mostPlayedSongs
.map { song ->
val suggestedSongView = SuggestedSongView(song, requestManager, settingsManager)
suggestedSongView.setClickListener(songClickListener)
suggestedSongView
})
}
if (suggestedData.recentlyPlayedAlbums.isNotEmpty()) {
val recentlyPlayedHeader = SuggestedHeader(getString(string.suggested_recent_title), getString(string.suggested_recent_subtitle), suggestedData.recentlyPlayedPlaylist)
val recentlyPlayedHeaderView = SuggestedHeaderView(recentlyPlayedHeader)
recentlyPlayedHeaderView.setClickListener(this)
viewModels.add(recentlyPlayedHeaderView)
viewModels.addAll(
suggestedData.recentlyPlayedAlbums
.map { album ->
val albumView = AlbumView(album, ViewType.ALBUM_LIST_SMALL, requestManager, sortManager, settingsManager)
albumView.setClickListener(this)
albumView
}.toList()
)
}
if (suggestedData.favoriteSongs.isNotEmpty()) {
val favoriteSongsHeader = SuggestedHeader(getString(string.fav_title), getString(string.suggested_favorite_subtitle), suggestedData.favoriteSongsPlaylist)
val favoriteHeaderView = SuggestedHeaderView(favoriteSongsHeader)
favoriteHeaderView.setClickListener(this)
viewModels.add(favoriteHeaderView)
viewModels.add(favoriteRecyclerView)
val songClickListener = SongClickListener(suggestedData.favoriteSongs)
analyticsManager.dropBreadcrumb(TAG, "favoriteRecyclerView.setItems()")
favoriteRecyclerView.setItems(
suggestedData.favoriteSongs
.map { song ->
val suggestedSongView = SuggestedSongView(song, requestManager, settingsManager)
suggestedSongView.setClickListener(songClickListener)
suggestedSongView
}.toList()
)
}
if (suggestedData.recentlyAddedAlbums.isNotEmpty()) {
val recentlyAddedHeader = SuggestedHeader(getString(string.recentlyadded), getString(string.suggested_recently_added_subtitle), suggestedData.recentlyAddedAlbumsPlaylist)
val recentlyAddedHeaderView = SuggestedHeaderView(recentlyAddedHeader)
recentlyAddedHeaderView.setClickListener(this)
viewModels.add(recentlyAddedHeaderView)
viewModels.addAll(
suggestedData.recentlyAddedAlbums
.map { album ->
val albumView = AlbumView(album, ViewType.ALBUM_CARD, requestManager, sortManager, settingsManager)
albumView.setClickListener(this)
albumView
}.toList()
)
}
if (viewModels.isEmpty()) {
refreshDisposables.add(adapter.setItems(listOf<ViewModel<*>>(EmptyView(R.string.empty_suggested))))
} else {
refreshDisposables.add(adapter.setItems(viewModels))
}
}
// SongMenuContract.View Implementation
override fun presentCreatePlaylistDialog(songs: List<Song>) {
CreatePlaylistDialog.newInstance(songs).show(childFragmentManager, "CreatePlaylistDialog")
}
override fun presentSongInfoDialog(song: Song) {
SongInfoDialog.newInstance(song).show(childFragmentManager)
}
override fun onSongsAddedToPlaylist(playlist: Playlist, numSongs: Int) {
Toast.makeText(context, context!!.resources.getQuantityString(R.plurals.NNNtrackstoplaylist, numSongs, numSongs), Toast.LENGTH_SHORT).show()
}
override fun onSongsAddedToQueue(numSongs: Int) {
Toast.makeText(context, context!!.resources.getQuantityString(R.plurals.NNNtrackstoqueue, numSongs, numSongs), Toast.LENGTH_SHORT).show()
}
override fun presentTagEditorDialog(song: Song) {
TaggerDialog.newInstance(song).show(childFragmentManager)
}
override fun presentDeleteDialog(songs: List<Song>) {
DeleteDialog.newInstance(DeleteDialog.ListSongsRef { songs }).show(childFragmentManager)
}
override fun shareSong(song: Song) {
song.share(context!!)
}
override fun presentRingtonePermissionDialog() {
RingtoneManager.getDialog(context!!).show()
}
override fun showRingtoneSetMessage() {
Toast.makeText(context, R.string.ringtone_set_new, Toast.LENGTH_SHORT).show()
}
// AlbumMenuContract.View Implementation
override fun onPlaybackFailed() {
// Todo: Improve error message
Toast.makeText(context, R.string.emptyplaylist, Toast.LENGTH_SHORT).show()
}
override fun presentTagEditorDialog(album: Album) {
TaggerDialog.newInstance(album).show(childFragmentManager)
}
override fun presentDeleteAlbumsDialog(albums: List<Album>) {
DeleteDialog.newInstance(DeleteDialog.ListAlbumsRef { albums }).show(childFragmentManager)
}
override fun presentAlbumInfoDialog(album: Album) {
AlbumBiographyDialog.newInstance(album).show(childFragmentManager)
}
override fun presentArtworkEditorDialog(album: Album) {
ArtworkDialog.build(context, album).show()
}
// BaseFragment implementation
override fun screenName(): String {
return TAG
}
// Static
companion object {
private const val ARG_TITLE = "title"
private const val TAG = "SuggestedFragment"
fun newInstance(title: String) = SuggestedFragment().withArgs {
putString(ARG_TITLE, title)
}
}
}
|
gpl-3.0
|
50a81aa84b8ce6a81a360fb203d4b8c0
| 37.277202 | 182 | 0.706802 | 5.056468 | false | false | false | false |
FHannes/intellij-community
|
platform/platform-impl/src/com/intellij/util/io/netty.kt
|
3
|
9884
|
/*
* 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.util.io
import com.google.common.net.InetAddresses
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Conditions
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.net.NetUtils
import io.netty.bootstrap.Bootstrap
import io.netty.bootstrap.BootstrapUtil
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel.*
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.oio.OioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.channel.socket.oio.OioServerSocketChannel
import io.netty.channel.socket.oio.OioSocketChannel
import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.handler.codec.http.HttpMethod
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.ssl.SslHandler
import io.netty.resolver.ResolvedAddressTypes
import io.netty.util.concurrent.GenericFutureListener
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.ide.PooledThreadExecutor
import org.jetbrains.io.NettyUtil
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.net.Socket
import java.util.concurrent.TimeUnit
// used in Go
fun oioClientBootstrap(): Bootstrap {
val bootstrap = Bootstrap().group(OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel::class.java)
bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
return bootstrap
}
inline fun Bootstrap.handler(crossinline task: (Channel) -> Unit): Bootstrap {
handler(object : ChannelInitializer<Channel>() {
override fun initChannel(channel: Channel) {
task(channel)
}
})
return this
}
fun serverBootstrap(group: EventLoopGroup): ServerBootstrap {
val bootstrap = ServerBootstrap()
.group(group)
.channel(if (group is NioEventLoopGroup) NioServerSocketChannel::class.java else OioServerSocketChannel::class.java)
bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
return bootstrap
}
inline fun ChannelFuture.addChannelListener(crossinline listener: (future: ChannelFuture) -> Unit) {
addListener(GenericFutureListener<ChannelFuture> { listener(it) })
}
// if NIO, so, it is shared and we must not shutdown it
fun EventLoop.shutdownIfOio() {
if (this is OioEventLoopGroup) {
@Suppress("USELESS_CAST")
(this as OioEventLoopGroup).shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS)
}
}
// Event loop will be shut downed only if OIO
fun Channel.closeAndShutdownEventLoop() {
val eventLoop = eventLoop()
try {
close().awaitUninterruptibly()
}
finally {
eventLoop.shutdownIfOio()
}
}
@JvmOverloads
fun Bootstrap.connect(remoteAddress: InetSocketAddress, promise: AsyncPromise<*>? = null, maxAttemptCount: Int = NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT, stopCondition: Condition<Void>? = null): Channel? {
try {
return doConnect(this, remoteAddress, promise, maxAttemptCount, stopCondition ?: Conditions.alwaysFalse<Void>())
}
catch (e: Throwable) {
promise?.setError(e)
return null
}
}
private fun doConnect(bootstrap: Bootstrap,
remoteAddress: InetSocketAddress,
promise: AsyncPromise<*>?,
maxAttemptCount: Int,
stopCondition: Condition<Void>): Channel? {
var attemptCount = 0
if (bootstrap.config().group() is NioEventLoopGroup) {
return connectNio(bootstrap, remoteAddress, promise, maxAttemptCount, stopCondition, attemptCount)
}
bootstrap.validate()
while (true) {
try {
val channel = OioSocketChannel(Socket(remoteAddress.address, remoteAddress.port))
BootstrapUtil.initAndRegister(channel, bootstrap).sync()
return channel
}
catch (e: IOException) {
if (stopCondition.value(null) || promise != null && promise.state != Promise.State.PENDING) {
return null
}
else if (maxAttemptCount == -1) {
if (sleep(promise, 300)) {
return null
}
attemptCount++
}
else if (++attemptCount < maxAttemptCount) {
if (sleep(promise, attemptCount * NettyUtil.MIN_START_TIME)) {
return null
}
}
else {
promise?.setError(e)
return null
}
}
}
}
private fun connectNio(bootstrap: Bootstrap,
remoteAddress: InetSocketAddress,
promise: AsyncPromise<*>?,
maxAttemptCount: Int,
stopCondition: Condition<Void>,
_attemptCount: Int): Channel? {
var attemptCount = _attemptCount
while (true) {
val future = bootstrap.connect(remoteAddress).awaitUninterruptibly()
if (future.isSuccess) {
if (!future.channel().isOpen) {
continue
}
return future.channel()
}
else if (stopCondition.value(null) || promise != null && promise.state == Promise.State.REJECTED) {
return null
}
else if (maxAttemptCount == -1) {
if (sleep(promise, 300)) {
return null
}
attemptCount++
}
else if (++attemptCount < maxAttemptCount) {
if (sleep(promise, attemptCount * NettyUtil.MIN_START_TIME)) {
return null
}
}
else {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
val cause = future.cause()
if (promise != null) {
if (cause == null) {
promise.setError("Cannot connect: unknown error")
}
else {
promise.setError(cause)
}
}
return null
}
}
}
fun sleep(promise: AsyncPromise<*>?, time: Int): Boolean {
try {
//noinspection BusyWait
Thread.sleep(time.toLong())
}
catch (ignored: InterruptedException) {
promise?.setError("Interrupted")
return true
}
return false
}
val Channel.uriScheme: String
get() = if (pipeline().get(SslHandler::class.java) == null) "http" else "https"
val HttpRequest.host: String?
get() = headers().getAsString(HttpHeaderNames.HOST)
val HttpRequest.origin: String?
get() = headers().getAsString(HttpHeaderNames.ORIGIN)
val HttpRequest.referrer: String?
get() = headers().getAsString(HttpHeaderNames.REFERER)
val HttpRequest.userAgent: String?
get() = headers().getAsString(HttpHeaderNames.USER_AGENT)
inline fun <T> ByteBuf.releaseIfError(task: () -> T): T {
try {
return task()
}
catch (e: Exception) {
try {
release()
}
finally {
throw e
}
}
}
fun isLocalHost(host: String, onlyAnyOrLoopback: Boolean, hostsOnly: Boolean = false): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
// if IP address, it is safe to use getByName (not affected by DNS rebinding)
if (onlyAnyOrLoopback && !InetAddresses.isInetAddress(host)) {
return false
}
fun InetAddress.isLocal() = isAnyLocalAddress || isLoopbackAddress || NetworkInterface.getByInetAddress(this) != null
try {
val address = InetAddress.getByName(host)
if (!address.isLocal()) {
return false
}
// be aware - on windows hosts file doesn't contain localhost
// hosts can contain remote addresses, so, we check it
if (hostsOnly && !InetAddresses.isInetAddress(host)) {
return io.netty.resolver.HostsFileEntriesResolver.DEFAULT.address(host, ResolvedAddressTypes.IPV4_PREFERRED).let { it != null && it.isLocal() }
}
else {
return true
}
}
catch (ignored: IOException) {
return false
}
}
@JvmOverloads
fun HttpRequest.isLocalOrigin(onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false) = parseAndCheckIsLocalHost(origin, onlyAnyOrLoopback, hostsOnly) && parseAndCheckIsLocalHost(referrer, onlyAnyOrLoopback, hostsOnly)
private fun isTrustedChromeExtension(url: Url): Boolean {
return url.scheme == "chrome-extension" && (url.authority == "hmhgeddbohgjknpmjagkdomcpobmllji" || url.authority == "offnedcbhjldheanlbojaefbfbllddna")
}
private val Url.host: String?
get() = authority?.let {
val portIndex = it.indexOf(':')
if (portIndex > 0) it.substring(0, portIndex) else it
}
@JvmOverloads
fun parseAndCheckIsLocalHost(uri: String?, onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean {
if (uri == null || uri == "about:blank") {
return true
}
try {
val parsedUri = Urls.parse(uri, false) ?: return false
val host = parsedUri.host
return host != null && (isTrustedChromeExtension(parsedUri) || isLocalHost(host, onlyAnyOrLoopback, hostsOnly))
}
catch (ignored: Exception) {
}
return false
}
fun HttpRequest.isRegularBrowser() = userAgent?.startsWith("Mozilla/5.0") ?: false
// forbid POST requests from browser without Origin
fun HttpRequest.isWriteFromBrowserWithoutOrigin(): Boolean {
val method = method()
return origin.isNullOrEmpty() && isRegularBrowser() && (method == HttpMethod.POST || method == HttpMethod.PATCH || method == HttpMethod.PUT || method == HttpMethod.DELETE)
}
fun ByteBuf.readUtf8() = toString(Charsets.UTF_8)
fun ByteBuf.writeUtf8(data: CharSequence) = writeCharSequence(data, Charsets.UTF_8)
|
apache-2.0
|
f3ac7d93313fb9a6f6ff823012d75429
| 31.198697 | 225 | 0.70083 | 4.352268 | false | false | false | false |
timusus/Shuttle
|
app/src/main/java/com/simplecity/amp_library/ui/dialog/ShareDialog.kt
|
1
|
4456
|
package com.simplecity.amp_library.ui.dialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.support.v4.content.FileProvider
import com.afollestad.materialdialogs.MaterialDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.simplecity.amp_library.R
import com.simplecity.amp_library.model.Song
import com.simplecity.amp_library.utils.extensions.share
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
class ShareDialog : DialogFragment() {
private lateinit var song: Song
override fun onAttach(context: Context?) {
super.onAttach(context)
song = arguments!!.getSerializable(ARG_SONG) as Song
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return MaterialDialog.Builder(context!!)
.title(R.string.share_dialog_title)
.items(context!!.getString(R.string.share_option_song_info), context!!.getString(R.string.share_option_audio_file))
.itemsCallback { _, _, i, _ ->
when (i) {
0 -> {
val context = context
// Use the compress method on the Bitmap object to write image to the OutputStream
Glide.with(context)
.load(song)
.asBitmap()
.priority(Priority.IMMEDIATE)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>) {
val sendIntent = Intent()
sendIntent.type = "text/plain"
var fileOutputStream: FileOutputStream? = null
try {
val file = File(context!!.filesDir.toString() + "/share_image.jpg")
fileOutputStream = FileOutputStream(file)
if (resource != null) {
resource.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream)
sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, context.applicationContext.packageName + ".provider", file))
sendIntent.type = "image/jpeg"
}
} catch (ignored: FileNotFoundException) {
} finally {
try {
fileOutputStream?.close()
} catch (ignored: IOException) {
}
}
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_TEXT, "#NowPlaying " + song.artistName + " - " + song.name + "\n\n" + "#Shuttle")
context!!.startActivity(Intent.createChooser(sendIntent, "Share current song via: "))
}
})
}
1 -> song.share(context!!)
}
}
.negativeText(R.string.close)
.build()
}
fun show(fragmentManager: FragmentManager) {
show(fragmentManager, TAG)
}
companion object {
private const val TAG = "ShareDialog"
private const val ARG_SONG = "song"
fun newInstance(song: Song): ShareDialog {
val args = Bundle()
args.putSerializable(ARG_SONG, song)
val fragment = ShareDialog()
fragment.arguments = args
return fragment
}
}
}
|
gpl-3.0
|
da3791d5fdeb041aa632a9ae5b53f3fb
| 42.262136 | 181 | 0.529174 | 5.662008 | false | false | false | false |
zyallday/kotlin-koans
|
src/i_introduction/_4_Lambdas/n04Lambdas.kt
|
1
|
801
|
package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas:
return true if the collection contains an even number.
You can find the appropriate function to call on 'Collection' by using code completion.
Don't use the class 'Iterables'.
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean = task4Impl(collection)
fun task4Impl(collection: Collection<Int>) = collection.any { it % 2 == 0 }
|
mit
|
4ca35ee982787f78440590119d09d470
| 28.703704 | 95 | 0.629213 | 3.778302 | false | false | false | false |
natanieljr/droidmate
|
project/pcComponents/core/src/main/kotlin/org/droidmate/configuration/ConfigurationBuilder.kt
|
1
|
26494
|
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.configuration
import com.natpryce.konfig.CommandLineOption
import com.natpryce.konfig.Configuration
import com.natpryce.konfig.ConfigurationProperties
import com.natpryce.konfig.overriding
import com.natpryce.konfig.parseArgs
import org.apache.commons.lang3.builder.ReflectionToStringBuilder
import org.apache.commons.lang3.builder.StandardToStringStyle
import org.droidmate.configuration.ConfigProperties.ApiMonitorServer.monitorSocketTimeout
import org.droidmate.configuration.ConfigProperties.ApiMonitorServer.monitorUseLogcat
import org.droidmate.configuration.ConfigProperties.Core.configPath
import org.droidmate.configuration.ConfigProperties.Core.hostIp
import org.droidmate.configuration.ConfigProperties.Core.logLevel
import org.droidmate.configuration.ConfigProperties.Deploy.deployRawApks
import org.droidmate.configuration.ConfigProperties.Deploy.installApk
import org.droidmate.configuration.ConfigProperties.Deploy.installAux
import org.droidmate.configuration.ConfigProperties.Deploy.installMonitor
import org.droidmate.configuration.ConfigProperties.Deploy.replaceResources
import org.droidmate.configuration.ConfigProperties.Deploy.shuffleApks
import org.droidmate.configuration.ConfigProperties.Deploy.uninstallApk
import org.droidmate.configuration.ConfigProperties.Deploy.uninstallAux
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.checkAppIsRunningRetryAttempts
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.checkAppIsRunningRetryDelay
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.checkDeviceAvailableAfterRebootAttempts
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.checkDeviceAvailableAfterRebootFirstDelay
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.checkDeviceAvailableAfterRebootLaterDelays
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.stopAppRetryAttempts
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.stopAppSuccessCheckDelay
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.waitForCanRebootDelay
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.deviceOperationAttempts
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.deviceOperationDelay
import org.droidmate.configuration.ConfigProperties.DeviceCommunication.waitForDevice
import org.droidmate.configuration.ConfigProperties.ExecutionMode.coverage
import org.droidmate.configuration.ConfigProperties.ExecutionMode.explore
import org.droidmate.configuration.ConfigProperties.ExecutionMode.inline
import org.droidmate.configuration.ConfigProperties.Exploration.apiVersion
import org.droidmate.configuration.ConfigProperties.Exploration.apkNames
import org.droidmate.configuration.ConfigProperties.Exploration.apksDir
import org.droidmate.configuration.ConfigProperties.Exploration.apksLimit
import org.droidmate.configuration.ConfigProperties.Exploration.widgetActionDelay
import org.droidmate.configuration.ConfigProperties.Exploration.deviceIndex
import org.droidmate.configuration.ConfigProperties.Exploration.deviceSerialNumber
import org.droidmate.configuration.ConfigProperties.Exploration.launchActivityDelay
import org.droidmate.configuration.ConfigProperties.Exploration.launchActivityTimeout
import org.droidmate.configuration.ConfigProperties.Exploration.runOnNotInlined
import org.droidmate.configuration.ConfigProperties.Output.outputDir
import org.droidmate.configuration.ConfigProperties.Output.reportDir
import org.droidmate.configuration.ConfigProperties.Output.screenshotDir
import org.droidmate.configuration.ConfigProperties.Report.includePlots
import org.droidmate.configuration.ConfigProperties.Report.inputDir
import org.droidmate.configuration.ConfigProperties.Selectors.actionLimit
import org.droidmate.configuration.ConfigProperties.Selectors.playbackModelDir
import org.droidmate.configuration.ConfigProperties.Selectors.pressBackProbability
import org.droidmate.configuration.ConfigProperties.Selectors.randomSeed
import org.droidmate.configuration.ConfigProperties.Selectors.resetEvery
import org.droidmate.configuration.ConfigProperties.Selectors.stopOnExhaustion
import org.droidmate.configuration.ConfigProperties.Selectors.timeLimit
import org.droidmate.configuration.ConfigProperties.Strategies.Parameters.uiRotation
import org.droidmate.configuration.ConfigProperties.Strategies.allowRuntimeDialog
import org.droidmate.configuration.ConfigProperties.Strategies.back
import org.droidmate.configuration.ConfigProperties.Strategies.denyRuntimeDialog
import org.droidmate.configuration.ConfigProperties.Strategies.minimizeMaximize
import org.droidmate.configuration.ConfigProperties.Strategies.playback
import org.droidmate.configuration.ConfigProperties.Strategies.reset
import org.droidmate.configuration.ConfigProperties.Strategies.rotateUI
import org.droidmate.configuration.ConfigProperties.Strategies.terminate
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.basePort
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.delayedImgFetch
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.enablePrintOuts
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.imgQuality
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.socketTimeout
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.startTimeout
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.waitForInteractableTimeout
import org.droidmate.configuration.ConfigProperties.UiAutomatorServer.waitForIdleTimeout
import org.droidmate.exploration.modelFeatures.reporter.StatementCoverageMF.Companion.StatementCoverage.coverageDir
import org.droidmate.exploration.modelFeatures.reporter.StatementCoverageMF.Companion.StatementCoverage.enableCoverage
import org.droidmate.exploration.modelFeatures.reporter.StatementCoverageMF.Companion.StatementCoverage.onlyCoverAppPackageName
import org.droidmate.legacy.Resource
import org.droidmate.logging.Markers.Companion.runData
import org.droidmate.misc.EnvironmentConstants
import org.slf4j.LoggerFactory
import java.io.File
import java.lang.StringBuilder
import java.lang.management.ManagementFactory
import java.nio.file.*
/**
* @see IConfigurationBuilder#build(java.lang.String [ ], java.nio.file.FileSystem)
*/
class ConfigurationBuilder : IConfigurationBuilder {
@Throws(ConfigurationException::class)
override fun build(args: Array<String>, vararg options: CommandLineOption): ConfigurationWrapper = build(args, FileSystems.getDefault(),*options)
/**
* there may be occassions when an (extended) project only wants to allow for a subset of the commandline arguments to be available,
* e.g. to make the --help more comprehensive.
* Then this function can be used to create a configuration which will only show/allow the commandline options from [options].
*/
fun buildRestrictedOptions(args: Array<String>, fs: FileSystem, vararg options: CommandLineOption): ConfigurationWrapper = build(parseArgs(args,
*options).first, fs)
@Throws(ConfigurationException::class)
override fun build(args: Array<String>, fs: FileSystem, vararg options: CommandLineOption): ConfigurationWrapper = build(parseArgs(args,
*options,
// Core
CommandLineOption(logLevel, description = "Logging level of the entirety of application. Possible values, comma separated: info, debug, trace, warn, error."),
CommandLineOption(configPath, description = "Path to a custom configuration file, which replaces the default configuration.", short = "config"),
CommandLineOption(hostIp, description="allows to specify an adb host different from localhost, i.e. to allow container environments to access host devices"),
// ApiMonitorServer
CommandLineOption(monitorSocketTimeout, description = "Socket timeout to communicate with the API monitor service."),
CommandLineOption(monitorUseLogcat, description = "Use logical for API logging instead of TCPServer (deprecated)."),
CommandLineOption(ConfigProperties.ApiMonitorServer.basePort, description = "The base port for the communication with the the API monitor service. DroidMate communicates over this base port + device index."),
// ExecutionMode
CommandLineOption(inline, description = "If present, instead of normal run, DroidMate will inline all non-inlined apks. Before inlining backup copies of the apks will be created and put into a sub-directory of the directory containing the apks. This flag cannot be combined with another execution mode."),
CommandLineOption(explore, description = "Run DroidMate in exploration mode."),
CommandLineOption(coverage, description = "If present, instead of normal run, DroidMate will run in 'instrument APK for coverage' mode. This flag cannot be combined with another execution mode."),
// Deploy
CommandLineOption(installApk, description = "Reinstall the app to the device. If the app is not previously installed the exploration will fail"),
CommandLineOption(installAux, description = "Reinstall the auxiliary files (UIAutomator and Monitor) to the device. If the auxiliary files are not previously installed the exploration will fail."),
CommandLineOption(uninstallApk, description = "Uninstall the APK after the exploration."),
CommandLineOption(uninstallAux, description = "Uninstall auxiliary files (UIAutomator and Monitor) after the exploration."),
CommandLineOption(replaceResources, description = "Replace the resources from the extracted resources folder upon execution."),
CommandLineOption(shuffleApks, description = "ExplorationStrategy the apks in the input directory in a random order."),
CommandLineOption(deployRawApks, description = "Deploys apks to device in 'raw' form, that is, without instrumenting them. Will deploy them raw even if instrumented version is available from last run."),
CommandLineOption(installMonitor, description = "Install the API monitor into the device."),
// DeviceCommunication
CommandLineOption(checkAppIsRunningRetryAttempts, description = "Number of attempts to check if an app is running on the device."),
CommandLineOption(checkAppIsRunningRetryDelay, description = "Timeout for each attempt to check if an app is running on the device in milliseconds."),
CommandLineOption(checkDeviceAvailableAfterRebootAttempts, description = "Determines how often DroidMate checks if a device is available after a reboot."),
CommandLineOption(checkDeviceAvailableAfterRebootFirstDelay, description = "The first timeout after a device rebooted, before its availability will be checked."),
CommandLineOption(checkDeviceAvailableAfterRebootLaterDelays, description = "The non-first timeout after a device rebooted, before its availability will be checked."),
CommandLineOption(stopAppRetryAttempts, description = "Number of attempts to close an 'application has stopped' dialog."),
CommandLineOption(stopAppSuccessCheckDelay, description = "Delay after each failed attempt close an 'application has stopped' dialog"),
CommandLineOption(waitForCanRebootDelay, description = "Delay (in milliseconds) after an attempt was made to reboot a device, before."),
CommandLineOption(deviceOperationAttempts, description = "Number of attempts to retry other failed device operations."),
CommandLineOption(deviceOperationDelay, description = "Delay (in milliseconds) after an attempt was made to perform a device operation, before retrying again."),
CommandLineOption(waitForDevice, description = "Wait for a device to be connected to the PC instead of cancelling the exploration."),
// Exploration
CommandLineOption(apksDir, description = "Directory containing the apks to be processed by DroidMate."),
CommandLineOption(apksLimit, description = "Limits the number of apks on which DroidMate will run. 0 means no limit."),
CommandLineOption(apkNames, description = "Filters apps on which DroidMate will be run. Supply full file names, separated by commas, surrounded by square brackets. If the list is empty, it will run on all the apps in the apks dir. Example value: [app1.apk, app2.apk]"),
CommandLineOption(deviceIndex, description = "Index of the device to be used (from adb devices). Zero based."),
CommandLineOption(deviceSerialNumber, description = "Serial number of the device to be used. Mutually exclusive to index."),
CommandLineOption(runOnNotInlined, description = "Allow DroidMate to run on non-inlined apks."),
CommandLineOption(launchActivityDelay, description = "Delay (in milliseconds) to wait for the app to load before continuing the exploration after a reset (or exploration start)."),
CommandLineOption(launchActivityTimeout, description = "Maximum amount of time to be waited for an app to start after a reset in milliseconds."),
CommandLineOption(apiVersion, description = "Has to be set to the Android API version corresponding to the (virtual) devices on which DroidMate will run. Currently supported values: api23"),
CommandLineOption(widgetActionDelay, description = "Default delay to be applied after interacting with a widget (click, long click, tick)"),
// Output
CommandLineOption(outputDir, description = "Path to the directory that will contain DroidMate exploration output."),
CommandLineOption(screenshotDir, description = "Path to the directory that will contain the screenshots from an exploration."),
CommandLineOption(reportDir, description = "Path to the directory that will contain the report files."),
// Strategies
CommandLineOption(reset, description = "Enables use of the reset strategy during an exploration."),
CommandLineOption(ConfigProperties.Strategies.explore, description = "Enables use of biased random exploration strategy."),
CommandLineOption(terminate, description = "Enables use of default terminate strategy."),
CommandLineOption(back, description = "Enables use of 'press back button' strategy"),
CommandLineOption(allowRuntimeDialog, description = "Enables use of strategy to always click 'Allow' on permission dialogs."),
CommandLineOption(denyRuntimeDialog, description = "Enables use of strategy to always click 'Deny' on permission dialogs."),
CommandLineOption(playback, description = "Enables use of playback strategy (if a playback model is provided)."),
CommandLineOption(ConfigProperties.Strategies.dfs, description = "Enables use of Depth-First-Search strategy."),
CommandLineOption(rotateUI, description = "Enables use of Rotate UI strategy."),
CommandLineOption(minimizeMaximize, description = "Enables use of Minimize-Maximize strategy to attempt to close the app and reopen it on the same screen."),
// Strategies parameters
CommandLineOption(uiRotation, description = "Value of the UI rotation for Rotate UI strategy. Valid values are: 0, 90, 180, 270. Other values will be rounded to one of these."),
// Selectors
CommandLineOption(pressBackProbability, description = "Probability of randomly pressing the back button while exploring. Set to 0 to disable the press back strategy."),
CommandLineOption(playbackModelDir, description = "Directory of a previous exploration model. Required for playback."),
CommandLineOption(resetEvery, description = "Number of actions to automatically reset the exploration from its initial activity. Set to 0 to disable."),
CommandLineOption(actionLimit, description = "How many actions the GUI exploration strategy can conduct before terminating."),
CommandLineOption(timeLimit, description = "How long the exploration of any given apk should take, in milli seconds. If set to 0, instead actionsLimit will be used."),
CommandLineOption(randomSeed, description = "The seed for a random generator used by a random-clicking GUI exploration strategy. If null, a seed will be randomized."),
CommandLineOption(stopOnExhaustion, description = "Terminate exploration when all widgets have been explored at least 1x."),
CommandLineOption(ConfigProperties.Selectors.dfs, description = "Use Depth-First-Search strategy, if the strategy is registered."),
// Report
CommandLineOption(inputDir, description = "Path to the directory containing report input. The input is to be DroidMate exploration output."),
CommandLineOption(includePlots, description = "Include plots on reports (requires gnu plot)."),
// UiAutomatorServer
CommandLineOption(startTimeout, description = "How long DroidMate should wait, in milliseconds, for message on logcat confirming that UiAutomatorDaemonServer has started on android (virtual) device."),
CommandLineOption(waitForIdleTimeout, description = "Timeout for a device to be idle an operation."),
CommandLineOption(waitForInteractableTimeout, description = "Timeout for a widget to be available after an operation."),
CommandLineOption(enablePrintOuts, description = "Enable or disable debug and performance outputs on the device output (in the LogCat)."),
CommandLineOption(socketTimeout, description = "Socket timeout to communicate with the UiDaemonServer."),
CommandLineOption(basePort, description = "The base port for the communication with the devices. DroidMate communicates over this base port + device index."),
CommandLineOption(delayedImgFetch, description = "Option to allow for faster exploration by delaying screen-shot fetch to an asynchronous call."),
CommandLineOption(imgQuality, description = "Quality of the image to be stored for fetching."),
// StatementCoverage
CommandLineOption(enableCoverage, description = "If true, the statement coverage of the exploration will be measured. This requires the apk to be instrumented with 'coverage' mode."),
CommandLineOption(onlyCoverAppPackageName, description = "Only instrument statement coverage for statements belong inside the app package name scope. Libraries with other package names will be ignored. Be aware that this filtering might not be always correct."),
CommandLineOption(coverageDir, description = "Path to the directory that will contain the coverage data."),
CommandLineOption(org.droidmate.explorationModel.config.ConfigProperties.Output.debugMode, description = "enable debug output")
).first, fs)
@Throws(ConfigurationException::class)
override fun build(cmdLineConfig: Configuration, fs: FileSystem): ConfigurationWrapper {
val defaultConfig = ConfigurationProperties.fromResource("defaultConfig.properties")
val customFile = when {
cmdLineConfig.contains(configPath) -> File(cmdLineConfig[configPath].path)
defaultConfig.contains(configPath) -> File(defaultConfig[configPath].path)
else -> null
}
val config : Configuration =
// command line
cmdLineConfig overriding
// overrides custom config file
(if (customFile?.exists() == true)
ConfigurationProperties.fromFile(customFile)
else
cmdLineConfig) overriding
// overrides default config file
defaultConfig
// Set the logging directory for the logback logger as early as possible
val outputPath = Paths.get(config[outputDir].toString())
.resolve(ConfigurationWrapper.log_dir_name)
System.setProperty("logsDir", outputPath.toString())
assert(System.getProperty("logsDir") == outputPath.toString())
return memoizedBuildConfiguration(config, fs)
}
companion object {
private val log by lazy { LoggerFactory.getLogger(ConfigurationBuilder::class.java) }
@JvmStatic
private fun memoizedBuildConfiguration(cfg: Configuration, fs: FileSystem): ConfigurationWrapper {
log.debug("memoizedBuildConfiguration(args, fileSystem)")
return bindAndValidate(ConfigurationWrapper(cfg, fs))
}
@JvmStatic
@Throws(ConfigurationException::class)
private fun bindAndValidate(config: ConfigurationWrapper): ConfigurationWrapper {
try {
setupResourcesAndPaths(config)
validateExplorationSettings(config)
normalizeAndroidApi(config)
} catch (e: ConfigurationException) {
throw e
}
logConfigurationInEffect(config)
return config
}
@JvmStatic
private fun normalizeAndroidApi(config: ConfigurationWrapper) {
// Currently supports only API23 as configuration (works with API 24, 25 and 26 as well)
assert(config[apiVersion] == ConfigurationWrapper.api23)
}
@JvmStatic
private fun validateExplorationSettings(cfg: ConfigurationWrapper) {
validateExplorationStrategySettings(cfg)
val apkNames = Files.list(cfg.getPath(cfg[apksDir]))
.filter { it.toString().endsWith(".apk") }
.map { it.fileName.toString() }
if (cfg[deployRawApks] && arrayListOf("inlined", "monitored").any { apkNames.anyMatch { s -> s.contains(it) } })
throw ConfigurationException(
"DroidMate was instructed to deploy raw apks, while the apks dir contains an apk " +
"with 'inlined' or 'monitored' in its name. Please do not mix such apk with raw apks in one dir.\n" +
"The searched apks dir path: ${cfg.getPath(cfg[apksDir]).toAbsolutePath()}")
}
@JvmStatic
private fun validateExplorationStrategySettings(cfg: ConfigurationWrapper) {
if (cfg[randomSeed] == -1L) {
log.info("Generated random seed: ${cfg.randomSeed}")
}
}
@JvmStatic
private fun getCompiledResourcePath(cfg: ConfigurationWrapper,
resourceName: String,
compileCommand: (Path) -> Path): Path {
val path = cfg.resourceDir.resolve(resourceName)
if (!cfg[replaceResources] && Files.exists(path))
return path
return compileCommand.invoke(cfg.resourceDir)
}
@JvmStatic
private fun getResourcePath(cfg: ConfigurationWrapper, resourceName: String): Path {
val path = cfg.resourceDir.resolve(resourceName)
if (!cfg[replaceResources] && Files.exists(path))
return path
return Resource(resourceName).extractTo(cfg.resourceDir)
}
@JvmStatic
@Throws(ConfigurationException::class)
private fun setupResourcesAndPaths(cfg: ConfigurationWrapper) {
cfg.droidmateOutputDirPath = cfg.getPath(cfg[outputDir]).toAbsolutePath()
cfg.resourceDir = cfg.droidmateOutputDirPath
.resolve(EnvironmentConstants.dir_name_temp_extracted_resources)
cfg.droidmateOutputReportDirPath = cfg.droidmateOutputDirPath
.resolve(cfg[reportDir]).toAbsolutePath()
cfg.reportInputDirPath = cfg.getPath(cfg[inputDir]).toAbsolutePath()
cfg.uiautomator2DaemonApk = getResourcePath(cfg, "deviceControlDaemon.apk").toAbsolutePath()
log.debug("Using uiautomator2-daemon.apk located at ${cfg.uiautomator2DaemonApk}")
cfg.uiautomator2DaemonTestApk = getResourcePath(cfg, "deviceControlDaemon-test.apk").toAbsolutePath()
log.debug("Using uiautomator2-daemon-test.apk located at ${cfg.uiautomator2DaemonTestApk}")
cfg.monitorApk = try {
if(!cfg[installMonitor]) null
else getCompiledResourcePath(cfg, EnvironmentConstants.monitor_apk_name) {path ->
val customApiFile = cfg.resourceDir.resolve("monitored_apis.json")
val apiPath = if (Files.exists(customApiFile)) {
customApiFile
} else {
null
}
org.droidmate.monitor.Compiler.compile(path, apiPath)
}.toAbsolutePath()
} catch (e:Throwable) {
null
}
log.debug("Using ${EnvironmentConstants.monitor_apk_name} located at ${cfg.monitorApk}")
cfg.apiPoliciesFile = try{
getResourcePath(cfg, EnvironmentConstants.api_policies_file_name).toAbsolutePath()}
catch (e:Throwable){
null
}
log.debug("Using ${EnvironmentConstants.api_policies_file_name} located at ${cfg.apiPoliciesFile}")
cfg.apksDirPath = cfg.getPath(cfg[apksDir]).toAbsolutePath()
Files.createDirectories(cfg.apksDirPath)
log.debug("Reading APKs from: ${cfg.apksDirPath.toAbsolutePath()}")
if (Files.notExists(cfg.droidmateOutputDirPath)) {
Files.createDirectories(cfg.droidmateOutputDirPath)
log.info("Writing output to: ${cfg.droidmateOutputDirPath}")
}
}
/*
* To keep the source DRY, we use apache's ReflectionToStringBuilder, which gets the field names and values using
* reflection.
*/
@JvmStatic
private fun logConfigurationInEffect(config: Configuration) {
// The customized display style strips the output of any data except the field name=value pairs.
val displayStyle = StandardToStringStyle()
displayStyle.isArrayContentDetail = true
displayStyle.isUseClassName = false
displayStyle.isUseIdentityHashCode = false
displayStyle.contentStart = ""
displayStyle.contentEnd = ""
displayStyle.fieldSeparator = System.lineSeparator()
val configurationDump = ReflectionToStringBuilder(config, displayStyle).toString()
.split(System.lineSeparator())
.sorted()
val sb = StringBuilder()
sb.appendln("--------------------------------------------------------------------------------")
.appendln("Working dir: ${System.getProperty("user.dir")}")
.appendln("")
.appendln("JVM arguments: ${readJVMArguments()}")
.appendln("")
.appendln("Configuration dump:")
.appendln("")
configurationDump.forEach { sb.appendln(it) }
sb.appendln("")
.appendln("End of configuration dump")
.appendln("--------------------------------------------------------------------------------")
log.debug(runData, sb.toString())
}
/**
* Based on: http://stackoverflow.com/a/1531999/986533
*/
@JvmStatic
private fun readJVMArguments(): List<String> = ManagementFactory.getRuntimeMXBean().inputArguments
}
}
|
gpl-3.0
|
9959a5ec81adc355c6bb7aa126f7cad5
| 61.781991 | 308 | 0.795878 | 4.630199 | false | true | false | false |
pgutkowski/KGraphQL
|
src/test/kotlin/com/github/pgutkowski/kgraphql/integration/ParallelExecutionTest.kt
|
1
|
2341
|
package com.github.pgutkowski.kgraphql.integration
import com.github.pgutkowski.kgraphql.KGraphQL
import com.github.pgutkowski.kgraphql.assertNoErrors
import com.github.pgutkowski.kgraphql.extract
import com.github.pgutkowski.kgraphql.deserialize
import kotlinx.coroutines.delay
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.Test
class ParallelExecutionTest {
val syncResolversSchema = KGraphQL.schema {
repeat(1000) {
query("automated-${it}") {
resolver { ->
Thread.sleep(3)
"${it}"
}
}
}
}
val suspendResolverSchema = KGraphQL.schema {
repeat(1000) {
query("automated-${it}") {
suspendResolver { ->
delay(3)
"${it}"
}
}
}
}
val query = "{ " + (0..999).map { "automated-${it}" }.joinToString(", ") + " }"
@Test
fun `1000 synchronous resolvers sleeping with Thread sleep`(){
val map = deserialize(syncResolversSchema.execute(query))
MatcherAssert.assertThat(map.extract<String>("data/automated-0"), CoreMatchers.equalTo("0"))
MatcherAssert.assertThat(map.extract<String>("data/automated-271"), CoreMatchers.equalTo("271"))
MatcherAssert.assertThat(map.extract<String>("data/automated-314"), CoreMatchers.equalTo("314"))
MatcherAssert.assertThat(map.extract<String>("data/automated-500"), CoreMatchers.equalTo("500"))
MatcherAssert.assertThat(map.extract<String>("data/automated-999"), CoreMatchers.equalTo("999"))
}
@Test
fun `1000 suspending resolvers sleeping with suspending delay`(){
val map = deserialize(suspendResolverSchema.execute(query))
MatcherAssert.assertThat(map.extract<String>("data/automated-0"), CoreMatchers.equalTo("0"))
MatcherAssert.assertThat(map.extract<String>("data/automated-271"), CoreMatchers.equalTo("271"))
MatcherAssert.assertThat(map.extract<String>("data/automated-314"), CoreMatchers.equalTo("314"))
MatcherAssert.assertThat(map.extract<String>("data/automated-500"), CoreMatchers.equalTo("500"))
MatcherAssert.assertThat(map.extract<String>("data/automated-999"), CoreMatchers.equalTo("999"))
}
}
|
mit
|
88c92f3f7a7856f91847229cf87f67d2
| 40.087719 | 104 | 0.652713 | 4.528046 | false | true | false | false |
jereksel/LibreSubstratum
|
app/src/main/kotlin/com/jereksel/libresubstratum/domain/usecases/CompileThemeUseCase.kt
|
1
|
3727
|
/*
* Copyright (C) 2017 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.domain.usecases
import com.jereksel.libresubstratum.domain.IPackageManager
import com.jereksel.libresubstratum.domain.IThemeReader
import com.jereksel.libresubstratum.domain.ThemeCompiler
import com.jereksel.libresubstratum.extensions.getLogger
import com.jereksel.libresubstratum.utils.ThemeNameUtils
import com.jereksel.libresubstratumlib.Theme
import com.jereksel.libresubstratumlib.ThemePack
import com.jereksel.libresubstratumlib.compilercommon.ThemeToCompile
import com.jereksel.libresubstratumlib.compilercommon.Type1DataToCompile
import io.reactivex.Observable
import java.io.File
class CompileThemeUseCase(
private val packageManager: IPackageManager,
private val themeCompiler: ThemeCompiler
): ICompileThemeUseCase {
val log = getLogger()
override fun execute(
themePack: ThemePack,
themeId: String,
destAppId: String,
type1aName: String?,
type1bName: String?,
type1cName: String?,
type2Name: String?,
type3Name: String?
): Observable<File> = Observable.fromCallable {
val (versionCode, versionName) = packageManager.getAppVersion(themeId)
val theme = themePack.themes.first { it.application == destAppId }
val m = mapOf(
"a" to type1aName,
"b" to type1bName,
"c" to type1cName
)
val type1a = theme.type1.firstOrNull { it.suffix == "a" }?.extension?.firstOrNull { it.name == type1aName }
val type1b = theme.type1.firstOrNull { it.suffix == "b" }?.extension?.firstOrNull { it.name == type1bName }
val type1c = theme.type1.firstOrNull { it.suffix == "c" }?.extension?.firstOrNull { it.name == type1cName }
val type1s = theme.type1.mapNotNull {
val id = it.suffix
val ext = it.extension.find { it.name == m[id] }
if (ext != null) {
Type1DataToCompile(ext, id)
} else {
null
}
}
val type2 = theme.type2?.extensions?.firstOrNull { it.name == type2Name }
val type3 = themePack.type3?.extensions?.firstOrNull { it.name == type3Name }
val originalTargetApp = theme.application
val fixedTargetApp = when {
originalTargetApp.startsWith("com.android.systemui.") -> "com.android.systemui"
originalTargetApp.startsWith("com.android.settings.") -> "com.android.settings"
else -> originalTargetApp
}
val themeName = packageManager.getInstalledTheme(themeId).name
val targetOverlayId = ThemeNameUtils.getTargetOverlayName(destAppId, themeName, type1a, type1b, type1c, type2, type3)
val themeToCompile = ThemeToCompile(targetOverlayId, themeId, originalTargetApp,
fixedTargetApp, type1s, type2, type3, versionCode, versionName)
val file = themeCompiler.compileTheme(themeToCompile)
file
}
}
|
mit
|
7dd4bd6cc4879a065e5bc8b0e296e413
| 37.43299 | 125 | 0.68044 | 4.308671 | false | false | false | false |
nemerosa/ontrack
|
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/Roles.kt
|
1
|
2311
|
package net.nemerosa.ontrack.model.security
/**
* List of predefined roles
*/
interface Roles {
companion object {
/**
* The project owner is allowed to all functions in a project, but for its deletion.
*/
const val PROJECT_OWNER = "OWNER"
/**
* A participant in a project is allowed to change statuses in validation runs.
*/
const val PROJECT_PARTICIPANT = "PARTICIPANT"
/**
* The validation manager can manage the validation stamps.
*/
const val PROJECT_VALIDATION_MANAGER = "VALIDATION_MANAGER"
/**
* The promoter can promote existing builds.
*/
const val PROJECT_PROMOTER = "PROMOTER"
/**
* The project manager can promote existing builds, manage the validation stamps,
* manage the shared build filters and edit some properties.
*/
const val PROJECT_MANAGER = "PROJECT_MANAGER"
/**
* This role grants a read-only access to all components of the projects.
*/
const val PROJECT_READ_ONLY = "READ_ONLY"
@JvmStatic
val PROJECT_ROLES: Set<String> = setOf(
PROJECT_OWNER,
PROJECT_PARTICIPANT,
PROJECT_VALIDATION_MANAGER,
PROJECT_PROMOTER,
PROJECT_MANAGER,
PROJECT_READ_ONLY
)
/**
* List of global roles
*/
const val GLOBAL_ADMINISTRATOR = "ADMINISTRATOR"
const val GLOBAL_CREATOR = "CREATOR"
const val GLOBAL_AUTOMATION = "AUTOMATION"
const val GLOBAL_CONTROLLER = "CONTROLLER"
const val GLOBAL_PARTICIPANT = "PARTICIPANT"
const val GLOBAL_READ_ONLY = "READ_ONLY"
/**
* The global validation manager can manage the validation stamps across all projects.
*/
const val GLOBAL_VALIDATION_MANAGER = "GLOBAL_VALIDATION_MANAGER"
@JvmStatic
val GLOBAL_ROLES: Set<String> = setOf(
GLOBAL_ADMINISTRATOR,
GLOBAL_CREATOR,
GLOBAL_AUTOMATION,
GLOBAL_CONTROLLER,
GLOBAL_READ_ONLY,
GLOBAL_PARTICIPANT,
GLOBAL_VALIDATION_MANAGER
)
}
}
|
mit
|
08404d37c3802d8e8e3dc52b6e1760dd
| 31.549296 | 94 | 0.568585 | 5.056893 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin
|
neuroph-plugin/src/com/thomas/needham/neurophidea/core/JavaNetworkCodeGenerator.kt
|
1
|
20818
|
/* The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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.neurophidea.core
import com.intellij.ide.util.PropertiesComponent
import com.thomas.needham.neurophidea.Constants.VERSION_KEY
import com.thomas.needham.neurophidea.datastructures.LearningRules
import com.thomas.needham.neurophidea.datastructures.NetworkConfiguration
import com.thomas.needham.neurophidea.datastructures.NetworkTypes
import com.thomas.needham.neurophidea.datastructures.TransferFunctions
import com.thomas.needham.neurophidea.exceptions.UnknownLearningRuleException
import com.thomas.needham.neurophidea.exceptions.UnknownNetworkTypeException
import org.jetbrains.annotations.NotNull
/**
* Created by Thomas Needham on 28/05/2016.
*/
class JavaNetworkCodeGenerator : ICodeGenerator {
val network: NetworkConfiguration?
val outputPath: String
var sourceOutput: String = ""
private var braces: Int = 0
companion object Data {
@JvmStatic
var properties = PropertiesComponent.getInstance()
@JvmStatic
var version = properties.getValue(VERSION_KEY)
@JvmStatic
var path: String? = ""
val coreImports = "import java.io.BufferedReader;" + "\n" +
"import java.io.BufferedWriter;" + "\n" +
"import java.io.File;" + "\n" +
"import java.io.FileWriter;" + "\n" +
"import java.io.IOException;" + "\n" +
"import java.io.InputStreamReader;" + "\n" +
"import java.util.ArrayList;" + "\n" +
"import java.util.logging.Level;" + "\n" +
"import java.util.logging.Logger;" + "\n" +
"import java.util.Vector;" + "\n" +
"import org.neuroph.core.NeuralNetwork;" + "\n" +
"import org.neuroph.core.learning.SupervisedTrainingElement;" + "\n" +
"import org.neuroph.core.learning.TrainingSet;" + "\n" +
"import org.neuroph.util.TransferFunctionType;" + "\n" + "\n"
val getLayersString: (Array<Int>) -> String = { layers ->
//Use Some Kotlin Sorcery to convert Array<Int> to comma delimited string
var result = ""
for (i in IntRange(0, layers.size - 1)) {
if (i == layers.size - 1)
result += layers[i].toString()
else
result += (layers[i].toString() + ",")
}
result
}
}
constructor(@NotNull network: NetworkConfiguration?, outputPath: String) {
this.network = network
this.outputPath = outputPath
path = outputPath
}
fun GenerateCode(): String {
sourceOutput += AddImports()
sourceOutput += "\n" + "\n"
sourceOutput += DefineClass()
sourceOutput += "\n"
sourceOutput += DefineGlobalVariables()
sourceOutput += "\n"
sourceOutput += DefineLoadNetwork()
sourceOutput += "\n"
sourceOutput += DefineTrainNetwork()
sourceOutput += "\n"
sourceOutput += DefineTestNetwork()
sourceOutput += "\n"
sourceOutput += DefineTestNetworkAuto()
sourceOutput += "\n"
sourceOutput += AddBraces()
sourceOutput += "\n"
return sourceOutput
}
private fun AddBraces(): String {
var brace = ""
while (braces > 0) {
brace += "}" + "\n"
braces--
}
return brace
}
private fun DefineTestNetworkAuto(): String {
val testNetworkAuto = "static void testNetworkAuto(String setPath) { " + "\n" +
"double total = 0.0;" + "\n" +
"ArrayList<Integer> list = new ArrayList<Integer>();" + "\n" +
"ArrayList<String> outputLine = new ArrayList<String>();" + "\n" +
"for(int layer : layers) { " + "\n" +
"list.add(layer);" + "\n" +
"}" + "\n" + "\n" +
"testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize,\",\");" + "\n" +
"int count = testingSet.elements().size();" + "\n" +
"double averageDeviance = 0;" + "\n" +
"String resultString = \"\";" + "\n" +
"try{" + "\n" +
"File file = new File(\"Results \" + setPath);" + "\n" +
"FileWriter fw = new FileWriter(file);" + "\n" +
"BufferedWriter bw = new BufferedWriter(fw);" + "\n" +
"" + "\n" +
"for(int i = 0; i < testingSet.elements().size(); i ++){" + "\n" +
"double expected;" + "\n" +
"double calculated;" + "\n" +
"network.setInput(testingSet.elementAt(i).getInput());" + "\n" +
"network.calculate();" + "\n" +
"calculated = network.getOutput()[0];" + "\n" +
"expected = testingSet.elementAt(i).getIdealArray()[0];" + "\n" +
"System.out.println(\"Calculated Output: \" + calculated);" + "\n" +
"System.out.println(\"Expected Output: \" + expected);" + "\n" +
"System.out.println(\"Deviance: \" + (calculated - expected));" + "\n" +
"averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected));" + "\n" +
"total += network.getOutput()[0];" + "\n" +
"resultString = \"\";" + "\n" +
"for(int cols = 0; cols < testingSet.elementAt(i).getInputArray().length; cols++) {" + "\n" +
"resultString += testingSet.elementAt(i).getInputArray()[cols] + \", \";" + "\n" +
"}" + "\n" +
"for(int t = 0; t < network.getOutput().length; t++) {" + "\n" +
"resultString += network.getOutput()[t] + \", \";" + "\n" +
"}" + "\n" +
"resultString = resultString.substring(0, resultString.length()-2);" + "\n" +
"resultString += \"\";" + "\n" +
"bw.write(resultString);" + "\n" +
"bw.flush();" + "\n" +
"}" + "\n" +
"System.out.println();" + "\n" +
"System.out.println(\"Average: \" + total / count);" + "\n" +
"System.out.println(\"Average Deviance % : \" + (averageDeviance / count) * 100);" + "\n" +
"bw.flush();" + "\n" +
"bw.close();" + "\n" +
"}" + "\n" +
"catch(IOException ex) {" + "\n" +
"ex.printStackTrace();" + "\n" +
"}" + "\n" +
"}" + "\n"
return testNetworkAuto;
}
private fun DefineTestNetwork(): String {
val testNetwork = "static void testNetwork() { " + "\n" +
"String input = \"\";" + "\n" +
"BufferedReader fromKeyboard = new BufferedReader(new InputStreamReader(System.in));" + "\n" +
"ArrayList<Double> testValues = new ArrayList<Double>();" + "\n" +
"double[] testValuesDouble;" + "\n" +
"do { " + "\n" +
"try { " + "\n" +
"System.out.println(\"Enter test values or \\\"\\\": \");" + "\n" +
"input = fromKeyboard.readLine();" + "\n" +
"if(input.equals(\"\")) { " + "\n" +
"break;" + "\n" +
"}" + "\n" +
"input = input.replace(\" \", \"\");" + "\n" +
"String[] stringVals = input.split(\",\");" + "\n" +
"testValues.clear();" + "\n" +
"for(String val : stringVals) { " + "\n" +
"testValues.add(Double.parseDouble(val));" + "\n" +
"}" + "\n" +
"} catch(IOException ioe) { " + "\n" +
"ioe.printStackTrace(System.err);" + "\n" +
"} catch(NumberFormatException nfe) { " + "\n" +
"nfe.printStackTrace(System.err);" + "\n" +
"}" + "\n" +
"testValuesDouble = new double[testValues.size()];" + "\n" +
"for(int t = 0; t < testValuesDouble.length; t++) {" + "\n" +
"testValuesDouble[t] = testValues.get(t).doubleValue();" + "\n" +
"}" + "\n" +
"network.setInput(testValuesDouble);" + "\n" +
"network.calculate();" + "\n" +
"} while (!input.equals(\"\"));" + "\n" +
"}" + "\n"
return testNetwork
}
private fun DefineTrainNetwork(): String {
val trainNetwork = "static void trainNetwork() { " + "\n" +
"ArrayList<Integer> list = new ArrayList<Integer>();" + "\n" +
"for(int layer : layers) { " + "\n" +
"list.add(layer);" + "\n" +
"}" + "\n" + "\n" +
CreateNetwork(network?.networkType!!) + "\n" +
"trainingSet = new TrainingSet<SupervisedTrainingElement>(inputSize, outputSize);" + "\n" +
"trainingSet = TrainingSet.createFromFile(\"${network?.networkTrainingDataPath}\", inputSize, outputSize, \",\");" + "\n" +
CreateLearningRule(network?.networkLearningRule!!) + "\n" +
"network.setLearningRule(learningRule);" + "\n" +
"network.learn(trainingSet);" + "\n" +
"network.save(\"${network?.networkOutputPath}" + "/" + "${network?.networkName}" + ".nnet\");" + "\n" +
"}" + "\n"
return trainNetwork
}
private fun CreateLearningRule(networkLearningRule: LearningRules.Rules): String {
when (networkLearningRule) {
LearningRules.Rules.ANTI_HEBBAN_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new AntiHebbianLearning();"
LearningRules.Rules.BACK_PROPAGATION -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new BackPropagation();"
LearningRules.Rules.BINARY_DELTA_RULE -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new BinaryDeltaRule();"
LearningRules.Rules.BINARY_HEBBIAN_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new BinaryHebbianLearning();"
LearningRules.Rules.COMPETITIVE_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new CompetitiveLearning();"
LearningRules.Rules.DYNAMIC_BACK_PROPAGATION -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new DynamicBackPropagation();"
LearningRules.Rules.GENERALIZED_HEBBIAN_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new GeneralizedHebbianLearning();"
LearningRules.Rules.HOPFIELD_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new HopfieldLearning();"
LearningRules.Rules.INSTAR_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new InstarLearning();"
LearningRules.Rules.KOHONEN_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new KohonenLearning();"
LearningRules.Rules.LMS -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new LMS();"
LearningRules.Rules.MOMENTUM_BACK_PROPAGATION -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new MomentumBackpropagation();"
LearningRules.Rules.OJA_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new OjaLearning();"
LearningRules.Rules.OUTSTAR_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new OutstarLearning();"
LearningRules.Rules.PERCEPTRON_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new PerceptronLearning();"
LearningRules.Rules.RESILIENT_PROPAGATION -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new ResilientPropagation();"
LearningRules.Rules.SIGMOID_DELTA_RULE -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new SigmoidDeltaRule();"
LearningRules.Rules.SIMULATED_ANNEALING_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new SimulatedAnnealingLearning(network);"
LearningRules.Rules.SUPERVISED_HEBBIAN_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new SupervisedHebbianLearning();"
LearningRules.Rules.UNSUPERVISED_HEBBIAN_LEARNING -> return "${LearningRules.GetClassName(networkLearningRule)} learningRule = new UnsupervisedHebbianLearning();"
else -> UnknownLearningRuleException("Unknown Learning Rule: ${LearningRules.GetClassName(NetworkTrainer.networkConfiguration?.networkLearningRule!!)}")
}
return ""
}
private fun CreateNetwork(networkType: NetworkTypes.Types): String {
when (networkType) {
NetworkTypes.Types.ADALINE -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize);"
NetworkTypes.Types.BAM -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, outputSize);"
NetworkTypes.Types.COMPETITIVE_NETWORK -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, outputSize);"
NetworkTypes.Types.HOPFIELD -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize + outputSize);"
NetworkTypes.Types.INSTAR -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize);"
NetworkTypes.Types.KOHONEN -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, outputSize);"
NetworkTypes.Types.MAX_NET -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize + outputSize);"
NetworkTypes.Types.MULTI_LAYER_PERCEPTRON -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(list, TransferFunctionType.${network?.networkTransferFunction?.name});"
NetworkTypes.Types.NEURO_FUZZY_PERCEPTRON -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, new Vector<Integer>(inputSize), outputSize);"
NetworkTypes.Types.NEUROPH -> return "network = new Perceptron(inputSize, outputSize, TransferFunctionType.${network?.networkTransferFunction?.name});"
NetworkTypes.Types.OUTSTAR -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(outputSize);"
NetworkTypes.Types.PERCEPTRON -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, outputSize, TransferFunctionType.${network?.networkTransferFunction?.name});"
NetworkTypes.Types.RBF_NETWORK -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, inputSize, outputSize);"
NetworkTypes.Types.SUPERVISED_HEBBIAN_NETWORK -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, outputSize, TransferFunctionType.${network?.networkTransferFunction?.name});"
NetworkTypes.Types.UNSUPERVISED_HEBBIAN_NETWORK -> return "network = new ${NetworkTypes.GetClassName(networkType)}" + "(inputSize, outputSize, TransferFunctionType.${network?.networkTransferFunction?.name});"
else -> UnknownNetworkTypeException("Unknown Network Type: ${NetworkTypes.GetClassName(NetworkTrainer.networkConfiguration?.networkType!!)}")
}
return ""
}
private fun DefineLoadNetwork(): String {
val loadNetwork = "static void loadNetwork() { " + "\n" +
"network = NeuralNetwork.load(\"${network?.networkOutputPath + "/" + network?.networkName + ".nnet"}\");" + "\n" +
"}" + "\n"
return loadNetwork
}
private fun DefineGlobalVariables(): String {
val variables = "static int inputSize = ${network?.networkLayers?.first()};" + "\n" +
"static int outputSize = ${network?.networkLayers?.last()};" + "\n" +
"static NeuralNetwork network;" + "\n" +
"static TrainingSet<SupervisedTrainingElement> trainingSet;" + "\n" +
"static TrainingSet<SupervisedTrainingElement> testingSet;" + "\n" +
"static int[] layers = {${getLayersString(network?.networkLayers!!)}};" + "\n"
return variables
}
private fun DefineClass(): String {
val classdef = "public class ${network?.networkName} { "
braces++
return classdef
}
private fun AddImports(): String {
var imports = coreImports
when (network?.networkType) {
NetworkTypes.Types.PERCEPTRON -> imports += "import org.neuroph.nnet.Perceptron;" + "\n"
NetworkTypes.Types.MULTI_LAYER_PERCEPTRON -> imports += "import org.neuroph.nnet.MultiLayerPerceptron;" + "\n"
NetworkTypes.Types.ADALINE -> imports += "import org.neuroph.nnet.Adaline;" + "\n"
NetworkTypes.Types.BAM -> imports += "import org.neuroph.nnet.BAM;" + "\n"
NetworkTypes.Types.COMPETITIVE_NETWORK -> imports += "import org.neuroph.nnet.CompetitiveNetwork;" + "\n"
NetworkTypes.Types.HOPFIELD -> imports += "import org.neuroph.nnet.Hopfield;" + "\n"
NetworkTypes.Types.INSTAR -> imports += "import org.neuroph.nnet.Instar;" + "\n"
NetworkTypes.Types.KOHONEN -> imports += "import org.neuroph.nnet.Kohonen;" + "\n"
NetworkTypes.Types.MAX_NET -> imports += "import org.neuroph.nnet.MaxNet;" + "\n"
NetworkTypes.Types.NEUROPH -> imports += "import org.neuroph.nnet.Perceptron;" + "\n"
NetworkTypes.Types.NEURO_FUZZY_PERCEPTRON -> imports += "import org.neuroph.nnet.NeuroFuzzyPerceptron;" + "\n"
NetworkTypes.Types.OUTSTAR -> imports += "import org.neuroph.nnet.Outstar;" + "\n"
NetworkTypes.Types.RBF_NETWORK -> imports += "import org.neuroph.nnet.RbfNetwork;" + "\n"
NetworkTypes.Types.SUPERVISED_HEBBIAN_NETWORK -> imports += "import org.neuroph.nnet.SupervisedHebbianNetwork;" + "\n"
NetworkTypes.Types.UNSUPERVISED_HEBBIAN_NETWORK -> imports += "import org.neuroph.nnet.UnsupervisedHebbianNetwork;" + "\n"
else -> imports += "import UnknownType;" + "\n"
}
when (network?.networkLearningRule) {
LearningRules.Rules.BACK_PROPAGATION -> imports += "import org.neuroph.nnet.learning.BackPropagation;" + "\n"
LearningRules.Rules.DYNAMIC_BACK_PROPAGATION -> imports += "import org.neuroph.nnet.learning.DynamicBackPropagation;" + "\n"
LearningRules.Rules.ANTI_HEBBAN_LEARNING -> imports += "import org.neuroph.nnet.learning.AntiHebbianLearning;" + "\n"
LearningRules.Rules.BINARY_DELTA_RULE -> imports += "import org.neuroph.nnet.learning.BinaryDeltaRule;" + "\n"
LearningRules.Rules.BINARY_HEBBIAN_LEARNING -> imports += "import org.neuroph.nnet.learning.BinaryHebbianLearning;" + "\n"
LearningRules.Rules.COMPETITIVE_LEARNING -> imports += "import org.neuroph.nnet.learning.CompetitiveLearning" + "\n"
LearningRules.Rules.GENERALIZED_HEBBIAN_LEARNING -> imports += "import org.neuroph.nnet.learning.GeneralizedHebbianLearning;" + "\n"
LearningRules.Rules.HOPFIELD_LEARNING -> imports += "import org.neuroph.nnet.learning.HopfieldLearning;" + "\n"
LearningRules.Rules.INSTAR_LEARNING -> imports += "import org.neuroph.nnet.learning.InstarLearning;" + "\n"
LearningRules.Rules.KOHONEN_LEARNING -> imports += "import org.neuroph.nnet.learning.KohonenLearning;" + "\n"
LearningRules.Rules.LMS -> imports += "import org.neuroph.nnet.learning.LMS;" + "\n"
LearningRules.Rules.MOMENTUM_BACK_PROPAGATION -> imports += "import org.neuroph.nnet.learning.MomentumBackPropagation;" + "\n"
LearningRules.Rules.OJA_LEARNING -> imports += "import org.neuroph.nnet.learning.OjaLearning;" + "\n"
LearningRules.Rules.OUTSTAR_LEARNING -> imports += "import org.neuroph.nnet.learning.OutstarLearning;" + "\n"
LearningRules.Rules.PERCEPTRON_LEARNING -> imports += "import org.neuroph.nnet.learning.PerceptronLearning;" + "\n"
LearningRules.Rules.RESILIENT_PROPAGATION -> imports += "import org.neuroph.nnet.learning.ResilientPropagation;" + "\n"
LearningRules.Rules.SIGMOID_DELTA_RULE -> imports += "import org.neuroph.nnet.learning.SigmoidDeltaRule;" + "\n"
LearningRules.Rules.SIMULATED_ANNEALING_LEARNING -> imports += "import org.neuroph.nnet.learning.SimulatedAnnealingLearning;" + "\n"
LearningRules.Rules.SUPERVISED_HEBBIAN_LEARNING -> imports += "import org.neuroph.nnet.learning.SupervisedHebbianLearning;" + "\n"
LearningRules.Rules.UNSUPERVISED_HEBBIAN_LEARNING -> imports += "import org.neuroph.nnet.learning.UnsupervisedHebbianLearning;" + "\n"
else -> imports += "import UnknownLearningRule;" + "\n"
}
when (network?.networkTransferFunction) {
TransferFunctions.Functions.GAUSSIAN -> imports += "import org.neuroph.core.transfer.Gaussian;" + "\n"
TransferFunctions.Functions.SIGMOID -> imports += "import org.neuroph.core.transfer.Sigmoid;" + "\n"
TransferFunctions.Functions.LINEAR -> imports += "import org.neuroph.core.transfer.Linear;" + "\n"
TransferFunctions.Functions.LOG -> imports += "import org.neuroph.core.transfer.Log;" + "\n"
TransferFunctions.Functions.RAMP -> imports += "import org.neuroph.core.transfer.Ramp;" + "\n"
TransferFunctions.Functions.TRAPEZOID -> imports += "import org.neuroph.core.transfer.Trapezoid;" + "\n"
TransferFunctions.Functions.SGN -> imports += "import org.neuroph.core.transfer.Sgn;" + "\n"
TransferFunctions.Functions.SIN -> imports += "import org.neuroph.core.transfer.Sin;" + "\n"
TransferFunctions.Functions.STEP -> imports += "import org.neuroph.core.transfer.Step;" + "\n"
TransferFunctions.Functions.TANH -> imports += "import org.neuroph.core.transfer.Tanh;" + "\n"
else -> imports += "import UnknownTransferFunction;" + "\n"
}
return imports
}
}
|
mit
|
ac4208d8a4f786abab7cc975cb5017cf
| 58.653295 | 211 | 0.693246 | 3.719493 | false | true | false | false |
bailuk/AAT
|
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/solid/GtkStorage.kt
|
1
|
2519
|
package ch.bailu.aat_gtk.solid
import ch.bailu.aat_gtk.config.Strings
import ch.bailu.aat_lib.logger.AppLog
import ch.bailu.aat_lib.preferences.OnPreferencesChanged
import ch.bailu.aat_lib.preferences.StorageInterface
import java.io.File
import java.util.*
import java.util.prefs.BackingStoreException
import java.util.prefs.Preferences
class GtkStorage : StorageInterface {
companion object {
private val NODE = Preferences.userRoot().node(Strings.appPreferencesNode)
private val OBSERVERS = ArrayList<OnPreferencesChanged>()
fun save() {
try {
NODE.sync()
NODE.flush()
} catch (e: BackingStoreException) {
AppLog.e(e)
}
}
}
override fun backup() {}
override fun getSharedPrefsDirectory(): File {
return File(NODE.absolutePath())
}
override fun restore() {}
override fun readString(key: String): String {
return NODE[key, ""].toString()
}
override fun writeString(key: String, value: String) {
if (value != readString(key)) {
NODE.put(key, value)
propagate(key)
}
}
override fun readInteger(key: String): Int {
return NODE.getInt(key, 0)
}
override fun writeInteger(key: String, value: Int) {
if (value != readInteger(key)) {
NODE.putInt(key, value)
propagate(key)
}
}
override fun writeIntegerForce(key: String, value: Int) {
writeInteger(key, value)
propagate(key)
}
override fun readLong(key: String): Long {
return NODE.getLong(key, 0)
}
override fun writeLong(key: String, value: Long) {
if (value != readLong(key)) {
NODE.putLong(key, value)
propagate(key)
}
}
override fun register(listener: OnPreferencesChanged) {
if (!OBSERVERS.contains(listener)) {
OBSERVERS.add(listener)
}
}
override fun unregister(l: OnPreferencesChanged) {
OBSERVERS.remove(l)
}
override fun isDefaultString(s: String): Boolean {
return "" == s
}
override fun getDefaultString(): String {
return ""
}
private fun propagate(key: String) {
try {
NODE.sync()
for (l in OBSERVERS) {
l.onPreferencesChanged(this, key)
}
} catch (e: BackingStoreException) {
AppLog.e(this, e)
}
}
}
|
gpl-3.0
|
3ea5b3232bc3d8717e2789489da116df
| 24.444444 | 82 | 0.582771 | 4.184385 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/platform/mcp/at/AtFile.kt
|
1
|
1187
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.FileViewProvider
class AtFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, AtLanguage) {
init {
setup()
}
private fun setup() {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val vFile = viewProvider.virtualFile
val module = ModuleUtilCore.findModuleForFile(vFile, project) ?: return
val mcpModule = MinecraftFacet.getInstance(module, McpModuleType) ?: return
mcpModule.addAccessTransformerFile(vFile)
}
override fun getFileType() = AtFileType
override fun toString() = "Access Transformer File"
override fun getIcon(flags: Int) = PlatformAssets.MCP_ICON
}
|
mit
|
5663b3711bb02ca61387bf8c44314b98
| 27.261905 | 86 | 0.733783 | 4.547893 | false | false | false | false |
is00hcw/anko
|
dsl/static/src/common/Arrays.kt
|
2
|
3123
|
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmMultifileClass
@file:JvmName("ArraysKt")
package org.jetbrains.anko.collections
import android.util.SparseArray
import android.util.SparseBooleanArray
import android.util.SparseIntArray
import java.util.*
inline fun <T> Array<T>.forEachByIndex(f: (T) -> Unit) {
val lastIndex = size() - 1
for (i in 0..lastIndex) {
f(get(i))
}
}
inline fun <T> Array<T>.forEachWithIndex(f: (Int, T) -> Unit) {
val lastIndex = size() - 1
for (i in 0..lastIndex) {
f(i, get(i))
}
}
inline fun <T> Array<T>.forEachReversed(f: (T) -> Unit) {
var i = size() - 1
while (i >= 0) {
f(get(i))
i--
}
}
inline fun <T> Array<T>.forEachReversedWithIndex(f: (Int, T) -> Unit) {
var i = size() - 1
while (i >= 0) {
f(i, get(i))
i--
}
}
fun <T> SparseArray<T>.asSequence(): Sequence<T> = SparseArraySequence(this)
fun <T> SparseBooleanArray.asSequence(): Sequence<Boolean> = SparseBooleanArraySequence(this)
fun <T> SparseIntArray.asSequence(): Sequence<Int> = SparseIntArraySequence(this)
private class SparseArraySequence<T>(private val a: SparseArray<T>) : Sequence<T> {
override fun iterator() = SparseArrayIterator()
private inner class SparseArrayIterator : Iterator<T> {
private var index = 0
private val size = a.size()
override fun hasNext() = size > index
override fun next(): T {
if (a.size() != size) throw ConcurrentModificationException()
return a.get(index++)
}
}
}
private class SparseBooleanArraySequence(private val a: SparseBooleanArray) : Sequence<Boolean> {
override fun iterator() = SparseIntArrayIterator()
private inner class SparseIntArrayIterator : Iterator<Boolean> {
private var index = 0
private val size = a.size()
override fun hasNext() = size > index
override fun next(): Boolean {
if (a.size() != size) throw ConcurrentModificationException()
return a.get(index++)
}
}
}
private class SparseIntArraySequence(private val a: SparseIntArray) : Sequence<Int> {
override fun iterator() = SparseIntArrayIterator()
private inner class SparseIntArrayIterator : Iterator<Int> {
private var index = 0
private val size = a.size()
override fun hasNext() = size > index
override fun next(): Int {
if (a.size() != size) throw ConcurrentModificationException()
return a.get(index++)
}
}
}
|
apache-2.0
|
0b6eec069a4b35f02bfa18b46813c21c
| 27.925926 | 97 | 0.647134 | 4.029677 | false | false | false | false |
panpf/sketch
|
sketch-extensions/src/main/java/com/github/panpf/sketch/decode/AppIconBitmapDecoder.kt
|
1
|
4339
|
/*
* Copyright (C) 2022 panpf <[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.github.panpf.sketch.decode
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.annotation.WorkerThread
import androidx.exifinterface.media.ExifInterface
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.datasource.DataFrom.LOCAL
import com.github.panpf.sketch.decode.internal.appliedResize
import com.github.panpf.sketch.decode.internal.logString
import com.github.panpf.sketch.fetch.AppIconUriFetcher
import com.github.panpf.sketch.fetch.AppIconUriFetcher.AppIconDataSource
import com.github.panpf.sketch.fetch.FetchResult
import com.github.panpf.sketch.request.internal.RequestContext
import com.github.panpf.sketch.util.toNewBitmap
/**
* Extract the icon of the installed app and convert it to Bitmap
*/
class AppIconBitmapDecoder(
private val sketch: Sketch,
private val requestContext: RequestContext,
private val packageName: String,
private val versionCode: Int,
) : BitmapDecoder {
companion object {
const val MODULE = "AppIconBitmapDecoder"
}
@WorkerThread
override suspend fun decode(): BitmapDecodeResult {
val request = requestContext.request
val packageManager = request.context.packageManager
val packageInfo: PackageInfo = try {
packageManager.getPackageInfo(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
throw Exception("Not found PackageInfo by '$packageName'", e)
}
@Suppress("DEPRECATION")
if (packageInfo.versionCode != versionCode) {
throw Exception("App versionCode mismatch, ${packageInfo.versionCode} != $versionCode")
}
val iconDrawable = packageInfo.applicationInfo.loadIcon(packageManager)
?: throw Exception("loadIcon return null '$packageName'")
val bitmap = iconDrawable.toNewBitmap(
bitmapPool = sketch.bitmapPool,
disallowReuseBitmap = request.disallowReuseBitmap,
preferredConfig = request.bitmapConfig?.getConfig(AppIconUriFetcher.MIME_TYPE)
)
val imageInfo = ImageInfo(
width = bitmap.width,
height = bitmap.height,
mimeType = AppIconUriFetcher.MIME_TYPE,
exifOrientation = ExifInterface.ORIENTATION_UNDEFINED
)
sketch.logger.d(MODULE) {
"decode. successful. ${bitmap.logString}. ${imageInfo}. '${requestContext.key}'"
}
return BitmapDecodeResult(bitmap, imageInfo, LOCAL, null, null)
.appliedResize(sketch, requestContext)
}
class Factory : BitmapDecoder.Factory {
override fun create(
sketch: Sketch,
requestContext: RequestContext,
fetchResult: FetchResult
): BitmapDecoder? {
val dataSource = fetchResult.dataSource
return if (
AppIconUriFetcher.MIME_TYPE.equals(fetchResult.mimeType, ignoreCase = true)
&& dataSource is AppIconDataSource
) {
AppIconBitmapDecoder(
sketch = sketch,
requestContext = requestContext,
packageName = dataSource.packageName,
versionCode = dataSource.versionCode
)
} else {
null
}
}
override fun toString(): String = "AppIconBitmapDecoder"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return true
}
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
}
|
apache-2.0
|
86b559e48a35bce32b602a7e69fc4d52
| 37.070175 | 99 | 0.664669 | 5.165476 | false | false | false | false |
cicakhq/potato
|
contrib/rqjava/src/com/dhsdevelopments/rqjava/CmdRegistration.kt
|
1
|
1407
|
package com.dhsdevelopments.rqjava
import com.rabbitmq.client.AMQP
import com.rabbitmq.client.Channel
import com.rabbitmq.client.DefaultConsumer
import com.rabbitmq.client.Envelope
import java.nio.charset.Charset
class CmdRegistration(potatoConnection: PotatoConnection, cmd: String, callback: (Command) -> Unit) {
private val rqChannel: Channel
init {
rqChannel = potatoConnection.amqpConn.createChannel()
val q = rqChannel.queueDeclare("", true, false, true, null)
rqChannel.queueBind(q.queue, "slashcommand-ex", "*.*.*.$cmd")
val consumer = object : DefaultConsumer(rqChannel) {
override fun handleDelivery(consumerTag: String, envelope: Envelope, properties: AMQP.BasicProperties, body: ByteArray) {
callback(Command(body, properties))
}
}
rqChannel.basicConsume(q.queue, true, consumer)
}
fun disconnect() {
rqChannel.close()
}
}
class Command(body: ByteArray, props: AMQP.BasicProperties) {
val domain = props.headers.get("domain").toString()
val channel = props.headers.get("channel").toString()
val user = props.headers.get("user").toString()
val cmd: String
val args: String
init {
val data = parseSexp(String(body, CHARSET_NAME_UTF8)) as SexpCons
cmd = data.nthElement(0) as String
args = data.nthElement(1) as String
}
}
|
apache-2.0
|
23366fa8ca31640d6aa42fa2be084f1b
| 32.5 | 133 | 0.677328 | 3.974576 | false | false | false | false |
Cleverdesk/cleverdesk
|
src/main/java/net/cleverdesk/cleverdesk/web/http/JSONResponse.kt
|
1
|
1388
|
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.cleverdesk.cleverdesk.web.http
import com.google.gson.Gson
/**
* Replaced by [WebMessage]
*/
@Deprecated("Replaced with the new channel-based system.", ReplaceWith(expression = "WebMessage(body, CHANNEL, REQUEST_ID)", imports = "net.cleverdesk.cleverdesk.web.WebMessage"), DeprecationLevel.WARNING)
class JSONResponse(status: Int, body: Any) {
internal var status:Int
internal var body:Any
init{
this.status = status
this.body = body
}
/**
* @return Body and Status-Code as Json
*
* Example:
*```
* {"status:200,"body":"Welcome to Cleverdesk"}
*```
*/
fun to_json():String {
val gson = Gson()
return gson.toJson(this)
}
}
|
gpl-3.0
|
75cd14e8d97ed1411abac31a81e66d79
| 32.878049 | 205 | 0.681556 | 4.023188 | false | false | false | false |
paulofernando/localchat
|
app/src/main/kotlin/site/paulo/localchat/ui/dashboard/DashboardActivity.kt
|
1
|
8425
|
/*
* Copyright 2017 Paulo Fernando
*
* 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 site.paulo.localchat.ui.dashboard
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.ViewPager
import android.view.*
import com.google.android.gms.location.FusedLocationProviderClient
import org.jetbrains.anko.startActivity
import site.paulo.localchat.R
import site.paulo.localchat.data.DataManager
import site.paulo.localchat.data.manager.UserLocationManager
import site.paulo.localchat.ui.about.AboutActivity
import site.paulo.localchat.ui.base.BaseActivity
import site.paulo.localchat.ui.dashboard.chat.ChatFragment
import site.paulo.localchat.ui.dashboard.nearby.UsersNearbyFragment
import site.paulo.localchat.ui.settings.SettingsActivity
import javax.inject.Inject
import kotlinx.android.synthetic.main.activity_dashboard.*
class DashboardActivity: BaseActivity() {
/**
* The [android.support.v4.view.PagerAdapter] that will provide
* fragments for each of the sections. We use a
* [FragmentPagerAdapter] derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* [android.support.v4.app.FragmentStatePagerAdapter].
*/
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
/**
* The [ViewPager] that will host the section contents.
*/
private var mViewPager: ViewPager? = null
private var tabLayout: TabLayout? = null
private val tabIcons = intArrayOf(R.drawable.ic_nearby, R.drawable.ic_chat)
private val usersNearbyFragment: UsersNearbyFragment = UsersNearbyFragment()
private val chatFragment: ChatFragment = ChatFragment()
@Inject
lateinit var presenter: DashboardPresenter
@Inject
lateinit var dataManager: DataManager
companion object {
const val REQUEST_PERMISSION = 1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupActivity()
createNotificationChannel()
val params = toolbar.layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = 0
setSupportActionBar(toolbar)
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
// Set up the ViewPager with the sections adapter.
container.adapter = mSectionsPagerAdapter
tabs.setupWithViewPager(container)
//setupTabIcons()
startUserLocationManager()
}
private fun createNotificationChannel() {
val name: CharSequence = getString(R.string.channel_name)
val description = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("MessageReceivedChannel", name, importance)
channel.description = description
val notificationManager: NotificationManager? = this.getSystemService(NotificationManager::class.java)
notificationManager?.createNotificationChannel(channel)
}
fun setupActivity() {
setContentView(R.layout.activity_dashboard)
activityComponent.inject(this)
}
private fun setupTabIcons() {
tabLayout?.getTabAt(0)?.setIcon(tabIcons[0])
tabLayout?.getTabAt(1)?.setIcon(tabIcons[1])
}
private fun startUserLocationManager() {
val permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
when (permissionCheck) {
PackageManager.PERMISSION_GRANTED -> {
UserLocationManager.init(this, dataManager)
}
PackageManager.PERMISSION_DENIED -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSION -> {
UserLocationManager.init(this, dataManager)
usersNearbyFragment.presenter.loadUsers()
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when(item.itemId) {
R.id.action_settings -> {
startActivity<SettingsActivity>()
return true
}
R.id.action_signout -> {
presenter.logout()
finish()
}
R.id.action_about -> {
startActivity<AboutActivity>()
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* A placeholder fragment containing a simple view.
*/
class PlaceholderFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_dashboard, container, false)
}
companion object {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private const val ARG_SECTION_NUMBER = "section_number"
/**
* Returns a new instance of this fragment for the given section
* number.
*/
fun newInstance(sectionNumber: Int): PlaceholderFragment {
val fragment = PlaceholderFragment()
val args = Bundle()
args.putInt(ARG_SECTION_NUMBER, sectionNumber)
fragment.arguments = args
return fragment
}
}
}
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm,
BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int): Fragment {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return if (position == 0) usersNearbyFragment
else chatFragment
}
override fun getCount(): Int {
// Show 2 total pages.
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return resources.getString(R.string.tab_title_1)
1 -> return resources.getString(R.string.tab_title_2)
}
return null
}
}
}
|
apache-2.0
|
36cbda62d6bddc55217eb918898c9e91
| 35.004274 | 141 | 0.67549 | 5.149756 | false | false | false | false |
slartus/4pdaClient-plus
|
app/src/main/java/org/softeg/slartus/forpdaplus/listfragments/next/UserReputationFragment.kt
|
1
|
13339
|
package org.softeg.slartus.forpdaplus.listfragments.next
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.loader.content.AsyncTaskLoader
import androidx.loader.content.Loader
import android.view.*
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.TextView
import org.jsoup.Jsoup
import org.softeg.slartus.forpdaapi.IListItem
import org.softeg.slartus.forpdaapi.ListInfo
import org.softeg.slartus.forpdaapi.ReputationEvent
import org.softeg.slartus.forpdaapi.ReputationsApi.loadReputation
import org.softeg.slartus.forpdaapi.classes.ListData
import org.softeg.slartus.forpdaapi.classes.ReputationsListData
import org.softeg.slartus.forpdaplus.*
import org.softeg.slartus.forpdaplus.classes.ForumUser
import org.softeg.slartus.forpdaplus.classes.MenuListDialog
import org.softeg.slartus.forpdaplus.classes.common.ExtUrl
import org.softeg.slartus.forpdaplus.fragments.GeneralFragment
import org.softeg.slartus.forpdaplus.fragments.profile.ProfileFragment
import org.softeg.slartus.forpdaplus.listtemplates.UserReputationBrickInfo
import org.softeg.slartus.forpdaplus.repositories.UserInfoRepositoryImpl.Companion.instance
import org.softeg.slartus.hosthelper.HostHelper
import java.io.IOException
import java.util.*
/*
* Created by slinkin on 19.02.2015.
*/
class UserReputationFragment : BrickFragmentListBase() {
override fun closeTab(): Boolean {
return false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setArrow()
}
override fun onResume() {
super.onResume()
setArrow()
}
private val userId: String
get() = Args.getString(USER_ID_KEY)?:""
private val userNick: String
get() = Args.getString(USER_NICK_KEY, "")
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(USER_ID_KEY, userId)
outState.putString(USER_NICK_KEY, userNick)
super.onSaveInstanceState(outState)
}
override fun getLoaderId(): Int {
return ItemsLoader.ID
}
override fun createAdapter(): BaseAdapter {
return ListAdapter(activity, data.items)
}
override fun getViewResourceId(): Int {
return R.layout.list_fragment
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
activity!!.openContextMenu(view)
}
override fun onLoadFinished(loader: Loader<ListData>, data: ListData) {
super.onLoadFinished(loader, data)
if (data.ex == null) {
if (data is ReputationsListData) {
if (supportActionBar != null) setSubtitle(data.rep)
Args.putString(USER_NICK_KEY, data.user)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v = super.onCreateView(inflater, container, savedInstanceState)
addLoadMoreFooter(inflater.context)
return v
}
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?) {
val info = menuInfo as AdapterView.AdapterContextMenuInfo
if (info.id == -1L) return
val item = adapter.getItem(info.id.toInt()) as ReputationEvent
val list: MutableList<MenuListDialog> = ArrayList()
if (item.sourceUrl != null && !item.sourceUrl.contains("forum/index.php?showuser=")) {
list.add(MenuListDialog(getString(R.string.jump_to_page), Runnable { IntentActivity.tryShowUrl(activity, Handler(), item.sourceUrl, true, false) }))
}
ForumUser.onCreateContextMenu(activity, list, item.userId, item.user)
ExtUrl.showContextDialog(context, item.user, list)
}
override fun getLoadArgs(): Bundle {
val args = Args
args.putInt(START_KEY, data.items.size)
return args
}
override fun onBackPressed(): Boolean {
return false
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
return false
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.reputation, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.profile_rep_item -> {
ProfileFragment.showProfile(userId, userNick)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
val loginedAndNotSelf = Client.getInstance().logined && userId != instance.getId()
}
override fun createLoader(id: Int, args: Bundle): AsyncTaskLoader<ListData> {
var loader: ItemsLoader? = null
if (id == ItemsLoader.ID) {
setLoading(true)
loader = ItemsLoader(activity, args)
}
return loader!!
}
private class ItemsLoader(context: Context?, val args: Bundle) : AsyncTaskLoader<ListData>(context!!) {
var mApps: ListData? = null
/**
* Загрузка ссылки на изображение, которое является плюсовой репой
*/
@Throws(IOException::class)
private fun loadRepImage() {
val body = Client.getInstance().performGet("https://${HostHelper.host}/forum/index.php?act=rep&view=history&mid=236113&mode=to&order=asc").responseBody
var el = Jsoup
.parse(body)
.select("td.row1>img")
.first()
if (el != null) {
val plusImage = el.attr("src")
if (plusImage != null) {
GeneralFragment.getPreferences().edit()
.putString("repPlusImage", plusImage)
.putBoolean("needLoadRepImage", false)
.apply()
return
}
}
if (el != null) el = el.select("tr:nth-last-child(2) td img").first()
if (el != null) {
val plusImage = el.attr("src")
if (plusImage != null) GeneralFragment.getPreferences().edit()
.putString("repPlusImage", plusImage)
.putBoolean("needLoadRepImage", false)
.apply()
}
}
override fun loadInBackground(): ListData {
return try {
loadRepImage()
val listInfo = ListInfo()
listInfo.from = if (args.getBoolean(IS_REFRESH_KEY)) 0 else args.getInt(START_KEY)
loadReputation(Client.getInstance(),
args.getString(USER_ID_KEY),
args.getBoolean(USER_FROM_KEY), listInfo,
GeneralFragment.getPreferences().getString("repPlusImage", "https://s.4pda.to/ShmfPSURw3VD2aNlTerb3hvYwGCMxd4z0muJ.gif"))
} catch (e: Throwable) {
val forumPage = ListData()
forumPage.ex = e
forumPage
}
}
override fun deliverResult(apps: ListData?) {
mApps = apps
if (isStarted) {
super.deliverResult(apps)
}
}
override fun onStartLoading() {
if (mApps != null) { // If we currently have a result available, deliver it
// immediately.
deliverResult(mApps)
}
if (takeContentChanged() || mApps == null) { // If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad()
}
}
override fun onStopLoading() { // Attempt to cancel the current load task if possible.
cancelLoad()
}
override fun onReset() {
super.onReset()
// Ensure the loader is stopped
onStopLoading()
// At this point we can release the resources associated with 'apps'
// if needed.
if (mApps != null) {
mApps = null
}
}
companion object {
val ID = App.getInstance().uniqueIntValue
}
}
private class ListAdapter(context: Context?, data: ArrayList<out IListItem>) : BaseAdapter() {
private val mInflater: LayoutInflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
private var mData: ArrayList<out IListItem> = data
override fun getCount(): Int {
return mData.size
}
override fun getItem(i: Int): Any {
return mData[i]
}
override fun getItemId(i: Int): Long {
return i.toLong()
}
override fun getView(position: Int, v: View?, parent: ViewGroup): View? {
var view = v
val holder: ViewHolder
if (view == null) {
view = mInflater.inflate(R.layout.list_item_reputation, parent, false)
holder = ViewHolder()
holder.flag = view.findViewById(R.id.imgFlag)
holder.topLeft = view.findViewById(R.id.txtTopLeft)
holder.topRight = view.findViewById(R.id.txtTopRight)
holder.main = view.findViewById(R.id.txtMain)
holder.subMain = view.findViewById(R.id.txtSubMain)
holder.progress = view.findViewById(R.id.progressBar)
view.tag = holder
} else {
holder = view.tag as ViewHolder
}
val topic = mData[position]
holder.topLeft!!.text = topic.topLeft
holder.topRight!!.text = topic.topRight
holder.main!!.text = topic.main
holder.subMain!!.text = topic.subMain
setVisibility(holder.progress, if (topic.isInProgress) View.VISIBLE else View.INVISIBLE)
when (topic.state) {
IListItem.STATE_GREEN -> {
setVisibility(holder.flag, View.VISIBLE)
holder.flag!!.text = "+"
holder.flag!!.setBackgroundResource(R.drawable.plusrep)
}
IListItem.STATE_RED -> {
setVisibility(holder.flag, View.VISIBLE)
holder.flag!!.setBackgroundResource(R.drawable.minusrep)
holder.flag!!.text = "-"
}
else -> setVisibility(holder.flag, View.INVISIBLE)
}
return view
}
private fun setVisibility(v: View?, visibility: Int) {
if (v!!.visibility != visibility) v.visibility = visibility
}
inner class ViewHolder {
var flag: TextView? = null
var progress: View? = null
var topLeft: TextView? = null
var topRight: TextView? = null
var main: TextView? = null
var subMain: TextView? = null
}
}
@JvmOverloads
fun plusRep(uId: String? = userId, uNick: String? = userNick) {
plusRep(activity, Handler(), "0", uId, uNick)
}
@JvmOverloads
fun minusRep(uId: String? = userId, uNick: String? = userNick) {
minusRep(activity, Handler(), "0", uId, uNick)
}
companion object {
const val USER_ID_KEY = "USER_ID_KEY"
const val USER_NICK_KEY = "USER_NICK_KEY"
const val USER_FROM_KEY = "USER_FROM_KEY"
@JvmStatic
fun showActivity(userId: CharSequence, from: Boolean) {
val args = Bundle()
args.putString(USER_ID_KEY, userId.toString())
if (from) args.putBoolean(USER_FROM_KEY, true)
MainActivity.showListFragment(userId.toString(), UserReputationBrickInfo.NAME, args)
}
private const val START_KEY = "START_KEY"
@JvmStatic
fun plusRep(activity: Activity?, handler: Handler?, userId: String?, userNick: String?) {
plusRep(activity, handler, "0", userId, userNick)
}
@JvmStatic
fun minusRep(activity: Activity?, handler: Handler?, userId: String?, userNick: String?) {
minusRep(activity, handler, "0", userId, userNick)
}
@JvmStatic
fun plusRep(activity: Activity?, handler: Handler?, postId: String, userId: String?, userNick: String?) {
showChangeRep(activity, handler, postId, userId, userNick, "add", App.getContext().getString(R.string.increase_reputation))
}
@JvmStatic
fun minusRep(activity: Activity?, handler: Handler?, postId: String, userId: String?, userNick: String?) {
showChangeRep(activity, handler, postId, userId, userNick, "minus", App.getContext().getString(R.string.decrease_reputation))
}
private fun showChangeRep(activity: Activity?, handler: Handler?, postId: String, userId: String?, userNick: String?, type: String, title: String) {
ForumUser.startChangeRep(activity, handler, userId, userNick, postId, type, title)
}
}
}
|
apache-2.0
|
f77018447ee35ffe7b63e0f98a9b4915
| 36.317416 | 163 | 0.602755 | 4.535336 | false | false | false | false |
stripe/stripe-android
|
identity/src/main/java/com/stripe/android/identity/navigation/IdentityDocumentScanFragment.kt
|
1
|
13484
|
package com.stripe.android.identity.navigation
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.stripe.android.camera.CameraAdapter
import com.stripe.android.camera.CameraPreviewImage
import com.stripe.android.camera.CameraXAdapter
import com.stripe.android.camera.DefaultCameraErrorListener
import com.stripe.android.camera.scanui.CameraView
import com.stripe.android.camera.scanui.util.startAnimation
import com.stripe.android.camera.scanui.util.startAnimationIfNotRunning
import com.stripe.android.identity.R
import com.stripe.android.identity.networking.models.CollectedDataParam
import com.stripe.android.identity.networking.models.VerificationPageData.Companion.isMissingBack
import com.stripe.android.identity.networking.models.VerificationPageData.Companion.isMissingSelfie
import com.stripe.android.identity.states.IdentityScanState
import com.stripe.android.identity.states.IdentityScanState.Companion.isFront
import com.stripe.android.identity.states.IdentityScanState.Companion.isNullOrFront
import com.stripe.android.identity.ui.DocumentScanScreen
import com.stripe.android.identity.utils.fragmentIdToScreenName
import com.stripe.android.identity.utils.navigateToDefaultErrorFragment
import com.stripe.android.identity.utils.postVerificationPageData
import com.stripe.android.identity.utils.submitVerificationPageDataAndNavigate
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
/**
* Fragment for scanning ID, Passport and Driver's license
*/
internal abstract class IdentityDocumentScanFragment(
identityCameraScanViewModelFactory: ViewModelProvider.Factory,
identityViewModelFactory: ViewModelProvider.Factory
) : IdentityCameraScanFragment(
identityCameraScanViewModelFactory,
identityViewModelFactory
) {
abstract val frontScanType: IdentityScanState.ScanType
abstract val backScanType: IdentityScanState.ScanType?
override val shouldObserveDisplayState = false
@get:StringRes
abstract val frontTitleStringRes: Int
@get:StringRes
abstract val backTitleStringRes: Int
@get:StringRes
abstract val frontMessageStringRes: Int
@get:StringRes
abstract val backMessageStringRes: Int
abstract val collectedDataParamType: CollectedDataParam.Type
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
val changedDisplayState by identityScanViewModel.displayStateChangedFlow.collectAsState()
val newDisplayState by remember {
derivedStateOf {
changedDisplayState?.first
}
}
val targetScanType by identityScanViewModel.targetScanTypeFlow.collectAsState()
DocumentScanScreen(
title =
if (targetScanType.isNullOrFront()) {
stringResource(id = frontTitleStringRes)
} else {
stringResource(id = backTitleStringRes)
},
message = when (newDisplayState) {
is IdentityScanState.Finished -> stringResource(id = R.string.scanned)
is IdentityScanState.Found -> stringResource(id = R.string.hold_still)
is IdentityScanState.Initial -> {
if (targetScanType.isNullOrFront()) {
stringResource(id = frontMessageStringRes)
} else {
stringResource(id = backMessageStringRes)
}
}
is IdentityScanState.Satisfied -> stringResource(id = R.string.scanned)
is IdentityScanState.TimeOut -> ""
is IdentityScanState.Unsatisfied -> ""
null -> {
if (targetScanType.isNullOrFront()) {
stringResource(id = frontMessageStringRes)
} else {
stringResource(id = backMessageStringRes)
}
}
},
newDisplayState = newDisplayState,
onCameraViewCreated = {
cameraView = it
cameraView.viewFinderWindowView.setBackgroundResource(R.drawable.viewfinder_background)
cameraAdapter = createCameraAdapter()
},
onContinueClicked = {
collectDocumentUploadedStateAndPost(
collectedDataParamType,
requireNotNull(targetScanType) {
"targetScanType is still null"
}.isFront()
)
}
)
LaunchedEffect(newDisplayState) {
when (newDisplayState) {
null -> {
cameraView.toggleInitial()
}
is IdentityScanState.Initial -> {
cameraView.toggleInitial()
}
is IdentityScanState.Found -> {
cameraView.toggleFound()
}
is IdentityScanState.Finished -> {
cameraView.toggleFinished()
}
else -> {} // no-op
}
}
}
}
private fun CameraView.toggleInitial() {
viewFinderBackgroundView.visibility = View.VISIBLE
viewFinderWindowView.visibility = View.VISIBLE
viewFinderBorderView.visibility = View.VISIBLE
viewFinderBorderView.startAnimation(R.drawable.viewfinder_border_initial)
}
private fun CameraView.toggleFound() {
viewFinderBorderView.startAnimationIfNotRunning(R.drawable.viewfinder_border_found)
}
private fun CameraView.toggleFinished() {
viewFinderBackgroundView.visibility = View.INVISIBLE
viewFinderWindowView.visibility = View.INVISIBLE
viewFinderBorderView.visibility = View.INVISIBLE
viewFinderBorderView.startAnimation(R.drawable.viewfinder_border_initial)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
if (!shouldStartFromBack()) {
identityViewModel.resetDocumentUploadedState()
}
super.onViewCreated(view, savedInstanceState)
identityViewModel.observeForVerificationPage(
this,
onSuccess = {
lifecycleScope.launch(identityViewModel.workContext) {
identityViewModel.screenTracker.screenTransitionFinish(fragmentId.fragmentIdToScreenName())
}
identityViewModel.sendAnalyticsRequest(
identityViewModel.identityAnalyticsRequestFactory.screenPresented(
scanType = frontScanType,
screenName = fragmentId.fragmentIdToScreenName()
)
)
}
)
}
/**
* Check if should start scanning from back.
*/
private fun shouldStartFromBack(): Boolean =
arguments?.getBoolean(ARG_SHOULD_START_FROM_BACK) == true
override fun onCameraReady() {
if (shouldStartFromBack()) {
startScanning(
requireNotNull(backScanType) {
"$backScanType should not be null when trying to scan from back"
}
)
} else {
startScanning(frontScanType)
}
}
private fun createCameraAdapter(): CameraAdapter<CameraPreviewImage<Bitmap>> {
return CameraXAdapter(
requireNotNull(activity),
cameraView.previewFrame,
MINIMUM_RESOLUTION,
DefaultCameraErrorListener(requireNotNull(activity)) { cause ->
Log.e(TAG, "scan fails with exception: $cause")
identityViewModel.sendAnalyticsRequest(
identityViewModel.identityAnalyticsRequestFactory.cameraError(
scanType = frontScanType,
throwable = IllegalStateException(cause)
)
)
}
)
}
/**
* Check the upload status of the document, post it with VerificationPageData, and decide
* next step based on result.
*
* If result is missing back, then start scanning back of the document,
* else if result is missing selfie, then start scanning selfie,
* Otherwise submit
*/
@VisibleForTesting
internal fun collectDocumentUploadedStateAndPost(
type: CollectedDataParam.Type,
isFront: Boolean
) = lifecycleScope.launch {
if (isFront) {
identityViewModel.documentFrontUploadedState
} else {
identityViewModel.documentBackUploadedState
}.collectLatest { uploadedState ->
if (uploadedState.hasError()) {
navigateToDefaultErrorFragment(uploadedState.getError())
} else if (uploadedState.isUploaded()) {
identityViewModel.observeForVerificationPage(
viewLifecycleOwner,
onSuccess = {
lifecycleScope.launch {
runCatching {
postVerificationPageData(
identityViewModel = identityViewModel,
collectedDataParam =
if (isFront) {
CollectedDataParam.createFromFrontUploadedResultsForAutoCapture(
type = type,
frontHighResResult = requireNotNull(uploadedState.highResResult.data),
frontLowResResult = requireNotNull(uploadedState.lowResResult.data)
)
} else {
CollectedDataParam.createFromBackUploadedResultsForAutoCapture(
type = type,
backHighResResult = requireNotNull(uploadedState.highResResult.data),
backLowResResult = requireNotNull(uploadedState.lowResResult.data)
)
},
fromFragment = fragmentId
) { verificationPageDataWithNoError ->
if (verificationPageDataWithNoError.isMissingBack()) {
startScanning(
requireNotNull(backScanType) {
"backScanType is null while still missing back"
}
)
} else if (verificationPageDataWithNoError.isMissingSelfie()) {
findNavController().navigate(
R.id.action_global_selfieFragment
)
} else {
submitVerificationPageDataAndNavigate(
identityViewModel,
fragmentId
)
}
}
}.onFailure { throwable ->
Log.e(
TAG,
"fail to submit uploaded files: $throwable"
)
navigateToDefaultErrorFragment(throwable)
}
}
},
onFailure = { throwable ->
Log.e(TAG, "Fail to observeForVerificationPage: $throwable")
navigateToDefaultErrorFragment(throwable)
}
)
}
}
}
internal companion object {
const val ARG_SHOULD_START_FROM_BACK = "startFromBack"
private val TAG: String = IdentityDocumentScanFragment::class.java.simpleName
}
}
|
mit
|
88f5087ed82d93b9792a817b126d5912
| 42.779221 | 114 | 0.57216 | 6.280391 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/process/TensorflowMappingProcess.kt
|
1
|
3724
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.process
import org.nd4j.common.base.Preconditions
import org.nd4j.ir.MapperNamespace
import org.nd4j.samediff.frameworkimport.process.AbstractMappingProcess
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeMappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.tensor.TensorMappingRule
import org.nd4j.samediff.frameworkimport.tensorflow.ir.attributeValueTypeForTensorflowAttribute
import org.tensorflow.framework.*
open class TensorflowMappingProcess(inputFramework: String = "tensorflow",
frameworkVersion: String = "2.3",
inputFrameworkOpName: String,
opName: String,
opMappingRegistry: OpMappingRegistry<GraphDef,
NodeDef, OpDef,
TensorProto, DataType, OpDef.AttrDef, AttrValue>,
tensorMappingRules: List<TensorMappingRule<GraphDef,
OpDef, NodeDef,
OpDef.AttrDef,
AttrValue, TensorProto, DataType>> = emptyList(),
attributeMappingRules: List<AttributeMappingRule<GraphDef,
OpDef, NodeDef,
OpDef.AttrDef,
AttrValue,
TensorProto, DataType>> = emptyList(),
inputIndexOverrides: Map<Int,Int> = emptyMap(),
variableResolutionType: MapperNamespace.VariableResolutionType = MapperNamespace.VariableResolutionType.DIRECT)
: AbstractMappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef,
AttrValue, DataType>(
inputFramework,
frameworkVersion,
inputFrameworkOpName,
inputIndexOverrides,
opName,
opMappingRegistry,
tensorMappingRules,
attributeMappingRules,
variableResolutionType) {
override fun inputOpDefValueTypes(): Map<String, AttributeValueType> {
Preconditions.checkNotNull(inputFrameworkOpName,"No input framework op def name found!")
val opDef = opMappingRegistry.lookupInputFrameworkOpDef(inputFrameworkOpName)
val retMap = HashMap<String,AttributeValueType>()
opDef.attrList.forEach { attrDef ->
retMap[attrDef.name] = attributeValueTypeForTensorflowAttribute(attrDef)
}
return retMap
}
}
|
apache-2.0
|
13bf3cb8fec0323234ffcc93aac44e42
| 48 | 147 | 0.600967 | 5.57485 | false | false | false | false |
deeplearning4j/deeplearning4j
|
omnihub/src/main/kotlin/org/eclipse/deeplearning4j/omnihub/api/Model.kt
|
1
|
1704
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.eclipse.deeplearning4j.omnihub.api
interface ModelLike {
fun modelUrl(): String
fun modelName(): String
fun pretrained(): Boolean
fun documentation(): String
fun framework(): FrameworkNamespace
fun modelType(): ModelType
}
data class Model(val modelUrl: String,
val modelName: String,
val pretrained: Boolean,
val documentation: String,
val framework: FrameworkNamespace,
val modelType: ModelType = ModelType.COMP_GRAPH): ModelLike {
override fun modelUrl() = modelUrl
override fun modelName() = modelName
override fun pretrained() = pretrained
override fun documentation() = documentation
override fun framework() = framework
override fun modelType() = modelType
}
|
apache-2.0
|
091791cd2c36527e05c73bf161d59f5d
| 36.888889 | 82 | 0.619131 | 4.813559 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/psi/ext/RsLabeledExpression.kt
|
2
|
1366
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsBlock
import org.rust.lang.core.psi.RsBreakExpr
import org.rust.lang.core.psi.RsLabelDecl
import org.rust.openapiext.forEachChild
interface RsLabeledExpression : RsElement {
val labelDecl: RsLabelDecl?
val block: RsBlock?
}
fun RsLabeledExpression.processBreakExprs(
label: String?,
matchOnlyByLabel: Boolean,
sink: (RsBreakExpr) -> Unit
) = processBreakExprs(this, label, matchOnlyByLabel, sink)
private fun processBreakExprs(
element: PsiElement,
label: String?,
matchOnlyByLabel: Boolean,
sink: (RsBreakExpr) -> Unit
) {
element.forEachChild { child ->
when (child) {
is RsBreakExpr -> {
processBreakExprs(child, label, matchOnlyByLabel, sink)
if (!matchOnlyByLabel && child.label == null || child.label?.referenceName == label) {
sink(child)
}
}
is RsLooplikeExpr -> {
if (label != null) {
processBreakExprs(child, label, true, sink)
}
}
else -> processBreakExprs(child, label, matchOnlyByLabel, sink)
}
}
}
|
mit
|
6bd1b2bd199806748be49da5c10ced33
| 28.06383 | 102 | 0.624451 | 3.891738 | false | false | false | false |
jk1/youtrack-idea-plugin
|
src/main/kotlin/com/github/jk1/ytplugin/navigator/ResponseFactory.kt
|
1
|
1411
|
package com.github.jk1.ytplugin.navigator
import fi.iki.elonen.NanoHTTPD
import java.io.ByteArrayInputStream
/**
* These are actually gif files of different size used as an operation success markers in YouTrack.
* Strangely enough, HTTP status codes mean very little in this 'contract'.
*/
private val successMarker = byteArrayOf(71, 73, 70, 56, 57, 97, 2, 0, 2, 0, -128, -1, 0, -1, -1, -1, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 68, 1, 0, 59)
private val failureMarker = byteArrayOf(71, 73, 70, 56, 57, 97, 1, 0, 1, 0, -128, -1, 0, -1, -1, -1, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 68, 1, 0, 59)
fun successResponse() : NanoHTTPD.Response {
val response = NanoHTTPD.newFixedLengthResponse(
NanoHTTPD.Response.Status.OK, "image/gif",
ByteArrayInputStream(successMarker), successMarker.size.toLong())
response.closeConnection(true)
return response
}
fun errorResponse() : NanoHTTPD.Response {
val response = NanoHTTPD.newFixedLengthResponse(
NanoHTTPD.Response.Status.OK, "image/gif",
ByteArrayInputStream(failureMarker), failureMarker.size.toLong())
response.closeConnection(true)
return response
}
fun customResponse(status: NanoHTTPD.Response.Status) : NanoHTTPD.Response {
val response = NanoHTTPD.newFixedLengthResponse(status, "text/plain", null, 0)
response.closeConnection(true)
return response
}
|
apache-2.0
|
92a86e86ff7d4886a7a542753083eef5
| 41.757576 | 160 | 0.687456 | 3.266204 | false | false | false | false |
charleskorn/batect
|
app/src/unitTest/kotlin/batect/docker/client/DockerContainersClientSpec.kt
|
1
|
25916
|
/*
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.docker.client
import batect.config.HealthCheckConfig
import batect.docker.ContainerHealthCheckException
import batect.docker.DockerContainer
import batect.docker.DockerContainerConfiguration
import batect.docker.DockerContainerCreationRequest
import batect.docker.DockerContainerHealthCheckConfig
import batect.docker.DockerContainerHealthCheckState
import batect.docker.DockerContainerInfo
import batect.docker.DockerContainerState
import batect.docker.DockerEvent
import batect.docker.DockerException
import batect.docker.DockerHealthCheckResult
import batect.docker.DockerImage
import batect.docker.DockerNetwork
import batect.docker.api.ContainerInspectionFailedException
import batect.docker.api.ContainersAPI
import batect.docker.run.ContainerIOStreamer
import batect.docker.run.ContainerInputStream
import batect.docker.run.ContainerOutputStream
import batect.docker.run.ContainerTTYManager
import batect.docker.run.ContainerWaiter
import batect.docker.run.InputConnection
import batect.docker.run.OutputConnection
import batect.execution.CancellationContext
import batect.os.ConsoleManager
import batect.os.Dimensions
import batect.testutils.createForEachTest
import batect.testutils.createLoggerForEachTest
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.on
import batect.testutils.runForEachTest
import batect.testutils.withMessage
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.throws
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.doThrow
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import okio.Sink
import okio.Source
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.time.Duration
import java.util.concurrent.CompletableFuture
object DockerContainersClientSpec : Spek({
describe("a Docker containers client") {
val api by createForEachTest { mock<ContainersAPI>() }
val consoleManager by createForEachTest { mock<ConsoleManager>() }
val waiter by createForEachTest { mock<ContainerWaiter>() }
val ioStreamer by createForEachTest { mock<ContainerIOStreamer>() }
val ttyManager by createForEachTest { mock<ContainerTTYManager>() }
val logger by createLoggerForEachTest()
val client by createForEachTest { DockerContainersClient(api, consoleManager, waiter, ioStreamer, ttyManager, logger) }
describe("creating a container") {
given("a container configuration and a built image") {
val image = DockerImage("the-image")
val network = DockerNetwork("the-network")
val command = listOf("doStuff")
val entrypoint = listOf("sh")
val request = DockerContainerCreationRequest(image, network, command, entrypoint, "some-host", setOf("some-host"), emptyMap(), "/some-dir", emptySet(), emptySet(), emptySet(), HealthCheckConfig(), null, false, false, emptySet(), emptySet())
on("creating the container") {
beforeEachTest { whenever(api.create(request)).doReturn(DockerContainer("abc123")) }
val result by runForEachTest { client.create(request) }
it("sends a request to the Docker daemon to create the container") {
verify(api).create(request)
}
it("returns the ID of the created container") {
assertThat(result.id, equalTo("abc123"))
}
}
}
}
describe("running a container") {
given("a Docker container") {
val container = DockerContainer("the-container-id")
val outputStream by createForEachTest { mock<ContainerOutputStream>() }
val inputStream by createForEachTest { mock<ContainerInputStream>() }
val frameDimensions = Dimensions(10, 20)
val terminalRestorer by createForEachTest { mock<AutoCloseable>() }
val resizingRestorer by createForEachTest { mock<AutoCloseable>() }
val cancellationContext by createForEachTest { mock<CancellationContext>() }
val onStartedHandler by createForEachTest { mock<() -> Unit>() }
beforeEachTest {
whenever(waiter.startWaitingForContainerToExit(container, cancellationContext)).doReturn(CompletableFuture.completedFuture(123))
whenever(api.attachToOutput(container)).doReturn(outputStream)
whenever(api.attachToInput(container)).doReturn(inputStream)
whenever(consoleManager.enterRawMode()).doReturn(terminalRestorer)
whenever(ttyManager.monitorForSizeChanges(container, frameDimensions)).doReturn(resizingRestorer)
}
given("stdout is connected") {
val stdout by createForEachTest { mock<Sink>() }
given("stdin is connected") {
val stdin by createForEachTest { mock<Source>() }
on("running the container") {
val result by runForEachTest { client.run(container, stdout, stdin, cancellationContext, frameDimensions, onStartedHandler) }
it("returns the exit code from the container") {
assertThat(result.exitCode, equalTo(123))
}
it("starts waiting for the container to exit before starting the container") {
inOrder(api, waiter) {
verify(waiter).startWaitingForContainerToExit(container, cancellationContext)
verify(api).start(container)
}
}
it("starts streaming I/O after putting the terminal into raw mode and starting the container") {
inOrder(api, consoleManager, ioStreamer) {
verify(api).start(container)
verify(consoleManager).enterRawMode()
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Connected(stdin, inputStream), cancellationContext)
}
}
it("starts monitoring for terminal size changes after starting the container but before streaming I/O") {
inOrder(api, ttyManager, ioStreamer) {
verify(api).start(container)
verify(ttyManager).monitorForSizeChanges(container, frameDimensions)
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Connected(stdin, inputStream), cancellationContext)
}
}
it("stops monitoring for terminal size changes after the streaming completes") {
inOrder(ioStreamer, resizingRestorer) {
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Connected(stdin, inputStream), cancellationContext)
verify(resizingRestorer).close()
}
}
it("restores the terminal after streaming completes") {
inOrder(ioStreamer, terminalRestorer) {
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Connected(stdin, inputStream), cancellationContext)
verify(terminalRestorer).close()
}
}
it("attaches to the container output before starting the container") {
inOrder(api) {
verify(api).attachToOutput(container)
verify(api).start(container)
}
}
it("attaches to the container input before starting the container") {
inOrder(api) {
verify(api).attachToInput(container)
verify(api).start(container)
}
}
it("notifies the caller that the container has started after starting the container but before streaming I/O") {
inOrder(api, onStartedHandler, ioStreamer) {
verify(api).start(container)
verify(onStartedHandler).invoke()
verify(ioStreamer).stream(any(), any(), any())
}
}
it("closes the output stream after streaming the output completes") {
inOrder(ioStreamer, outputStream) {
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Connected(stdin, inputStream), cancellationContext)
verify(outputStream).close()
}
}
it("closes the input stream after streaming the output completes") {
inOrder(ioStreamer, inputStream) {
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Connected(stdin, inputStream), cancellationContext)
verify(inputStream).close()
}
}
}
}
given("stdin is not connected") {
val stdin: Source? = null
on("running the container") {
val result by runForEachTest { client.run(container, stdout, stdin, cancellationContext, frameDimensions, onStartedHandler) }
it("returns the exit code from the container") {
assertThat(result.exitCode, equalTo(123))
}
it("starts the container") {
verify(api).start(container)
}
it("streams the container output but not the input") {
verify(ioStreamer).stream(OutputConnection.Connected(outputStream, stdout), InputConnection.Disconnected, cancellationContext)
}
it("attaches to the container output") {
verify(api).attachToOutput(container)
}
it("does not attach to the container input") {
verify(api, never()).attachToInput(container)
}
it("does not enter raw mode") {
verify(consoleManager, never()).enterRawMode()
}
it("starts monitoring for console size changes") {
verify(ttyManager).monitorForSizeChanges(container, frameDimensions)
}
}
}
}
given("stdout is not connected") {
val stdout: Sink? = null
given("stdin is connected") {
val stdin by createForEachTest { mock<Source>() }
it("throws an appropriate exception") {
assertThat({ client.run(container, stdout, stdin, cancellationContext, frameDimensions, onStartedHandler) }, throws<DockerException>(withMessage("Attempted to stream input to container without streaming container output.")))
}
}
given("stdin is not connected") {
val stdin: Source? = null
on("running the container") {
val result by runForEachTest { client.run(container, stdout, stdin, cancellationContext, frameDimensions, onStartedHandler) }
it("returns the exit code from the container") {
assertThat(result.exitCode, equalTo(123))
}
it("starts the container") {
verify(api).start(container)
}
it("streams neither the container output nor the input") {
verify(ioStreamer).stream(OutputConnection.Disconnected, InputConnection.Disconnected, cancellationContext)
}
it("does not attach to the container output") {
verify(api, never()).attachToOutput(container)
}
it("does not attach to the container input") {
verify(api, never()).attachToInput(container)
}
it("does not enter raw mode") {
verify(consoleManager, never()).enterRawMode()
}
it("starts monitoring for console size changes") {
verify(ttyManager).monitorForSizeChanges(container, frameDimensions)
}
}
}
}
}
}
describe("stopping a container") {
given("a Docker container") {
val container = DockerContainer("the-container-id")
on("stopping that container") {
beforeEachTest { client.stop(container) }
it("sends a request to the Docker daemon to stop the container") {
verify(api).stop(container)
}
}
}
}
describe("removing a container") {
given("an existing container") {
val container = DockerContainer("the-container-id")
on("removing that container") {
beforeEachTest { client.remove(container) }
it("sends a request to the Docker daemon to remove the container") {
verify(api).remove(container)
}
}
}
}
describe("waiting for a container to report its health status") {
val cancellationContext by createForEachTest { mock<CancellationContext>() }
given("a Docker container with no health check") {
val container = DockerContainer("the-container-id")
beforeEachTest {
whenever(api.inspect(container)).thenReturn(
DockerContainerInfo(
DockerContainerState(),
DockerContainerConfiguration(
healthCheck = DockerContainerHealthCheckConfig()
)
)
)
}
on("waiting for that container to become healthy") {
val result by runForEachTest { client.waitForHealthStatus(container, cancellationContext) }
it("reports that the container does not have a health check") {
assertThat(result, equalTo(HealthStatus.NoHealthCheck))
}
}
}
given("the Docker client returns an error when checking if the container has a health check") {
val container = DockerContainer("the-container-id")
beforeEachTest {
whenever(api.inspect(container)).thenThrow(ContainerInspectionFailedException("Something went wrong"))
}
on("waiting for that container to become healthy") {
it("throws an appropriate exception") {
assertThat({ client.waitForHealthStatus(container, cancellationContext) }, throws<ContainerHealthCheckException>(withMessage("Checking if container 'the-container-id' has a health check failed: Something went wrong")))
}
}
}
given("a Docker container with a health check") {
val container = DockerContainer("the-container-id")
beforeEachTest {
whenever(api.inspect(container)).thenReturn(
DockerContainerInfo(
DockerContainerState(),
DockerContainerConfiguration(
healthCheck = DockerContainerHealthCheckConfig(
test = listOf("some-command"),
interval = Duration.ofSeconds(2),
timeout = Duration.ofSeconds(1),
startPeriod = Duration.ofSeconds(10),
retries = 4
)
)
)
)
}
given("the health check passes") {
beforeEachTest {
whenever(api.waitForNextEvent(eq(container), eq(setOf("die", "health_status")), any(), eq(cancellationContext)))
.thenReturn(DockerEvent("health_status: healthy"))
}
on("waiting for that container to become healthy") {
val result by runForEachTest { client.waitForHealthStatus(container, cancellationContext) }
it("waits with a timeout that allows the container time to start and become healthy") {
verify(api).waitForNextEvent(any(), any(), eq(Duration.ofSeconds(10 + (3 * 4) + 1)), any())
}
it("reports that the container became healthy") {
assertThat(result, equalTo(HealthStatus.BecameHealthy))
}
}
}
given("the health check fails") {
beforeEachTest {
whenever(api.waitForNextEvent(eq(container), eq(setOf("die", "health_status")), any(), eq(cancellationContext)))
.thenReturn(DockerEvent("health_status: unhealthy"))
}
on("waiting for that container to become healthy") {
val result by runForEachTest { client.waitForHealthStatus(container, cancellationContext) }
it("reports that the container became unhealthy") {
assertThat(result, equalTo(HealthStatus.BecameUnhealthy))
}
}
}
given("the container exits before the health check reports") {
beforeEachTest {
whenever(api.waitForNextEvent(eq(container), eq(setOf("die", "health_status")), any(), eq(cancellationContext)))
.thenReturn(DockerEvent("die"))
}
on("waiting for that container to become healthy") {
val result by runForEachTest { client.waitForHealthStatus(container, cancellationContext) }
it("reports that the container exited") {
assertThat(result, equalTo(HealthStatus.Exited))
}
}
}
given("getting the next event for the container fails") {
beforeEachTest {
whenever(api.waitForNextEvent(eq(container), eq(setOf("die", "health_status")), any(), eq(cancellationContext)))
.thenThrow(DockerException("Something went wrong."))
}
on("waiting for that container to become healthy") {
it("throws an appropriate exception") {
assertThat({ client.waitForHealthStatus(container, cancellationContext) }, throws<ContainerHealthCheckException>(withMessage("Waiting for health status of container 'the-container-id' failed: Something went wrong.")))
}
}
}
}
}
describe("getting the last health check result for a container") {
val container = DockerContainer("some-container")
on("the container only having one last health check result") {
val info = DockerContainerInfo(
DockerContainerState(
DockerContainerHealthCheckState(
listOf(
DockerHealthCheckResult(1, "something went wrong")
)
)
),
DockerContainerConfiguration(DockerContainerHealthCheckConfig())
)
beforeEachTest { whenever(api.inspect(container)).doReturn(info) }
val details by runForEachTest { client.getLastHealthCheckResult(container) }
it("returns the details of the last health check result") {
assertThat(details, equalTo(DockerHealthCheckResult(1, "something went wrong")))
}
}
on("the container having a full set of previous health check results") {
val info = DockerContainerInfo(
DockerContainerState(
DockerContainerHealthCheckState(
listOf(
DockerHealthCheckResult(1, ""),
DockerHealthCheckResult(1, ""),
DockerHealthCheckResult(1, ""),
DockerHealthCheckResult(1, ""),
DockerHealthCheckResult(1, "this is the most recent health check")
)
)
),
DockerContainerConfiguration(DockerContainerHealthCheckConfig())
)
beforeEachTest { whenever(api.inspect(container)).doReturn(info) }
val details by runForEachTest { client.getLastHealthCheckResult(container) }
it("returns the details of the last health check result") {
assertThat(details, equalTo(DockerHealthCheckResult(1, "this is the most recent health check")))
}
}
on("the container not having a health check") {
val info = DockerContainerInfo(
DockerContainerState(health = null),
DockerContainerConfiguration(DockerContainerHealthCheckConfig())
)
beforeEachTest { whenever(api.inspect(container)).doReturn(info) }
it("throws an appropriate exception") {
assertThat(
{ client.getLastHealthCheckResult(container) },
throws<ContainerHealthCheckException>(withMessage("Could not get the last health check result for container 'some-container'. The container does not have a health check."))
)
}
}
on("getting the container's details failing") {
beforeEachTest { whenever(api.inspect(container)).doThrow(ContainerInspectionFailedException("Something went wrong.")) }
it("throws an appropriate exception") {
assertThat(
{ client.getLastHealthCheckResult(container) },
throws<ContainerHealthCheckException>(withMessage("Could not get the last health check result for container 'some-container': Something went wrong."))
)
}
}
}
}
})
|
apache-2.0
|
7a4adda725766d08d8b72ea89982c440
| 48.083333 | 256 | 0.533068 | 6.402174 | false | true | false | false |
djkovrik/YapTalker
|
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/activetopics/adapter/ActiveTopicsDelegateAdapter.kt
|
1
|
2806
|
package com.sedsoftware.yaptalker.presentation.feature.activetopics.adapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.presentation.base.adapter.YapEntityDelegateAdapter
import com.sedsoftware.yaptalker.presentation.extensions.inflate
import com.sedsoftware.yaptalker.presentation.extensions.loadRatingBackground
import com.sedsoftware.yaptalker.presentation.model.DisplayedItemModel
import com.sedsoftware.yaptalker.presentation.model.base.ActiveTopicModel
import kotlinx.android.synthetic.main.fragment_active_topics_list_item.view.active_topic_answers
import kotlinx.android.synthetic.main.fragment_active_topics_list_item.view.active_topic_forum
import kotlinx.android.synthetic.main.fragment_active_topics_list_item.view.active_topic_last_post_date
import kotlinx.android.synthetic.main.fragment_active_topics_list_item.view.active_topic_name
import kotlinx.android.synthetic.main.fragment_active_topics_list_item.view.active_topic_rating
class ActiveTopicsDelegateAdapter(
private val itemClickListener: ActiveTopicsItemClickListener,
private val settings: Settings
) : YapEntityDelegateAdapter {
private val normalFontSize by lazy {
settings.getNormalFontSize()
}
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder =
TopicViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, item: DisplayedItemModel) {
holder as TopicViewHolder
holder.bindTo(item as ActiveTopicModel)
}
inner class TopicViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(parent.inflate(R.layout.fragment_active_topics_list_item)) {
fun bindTo(topicItem: ActiveTopicModel) {
with(itemView) {
active_topic_name.text = topicItem.title
active_topic_forum.text = topicItem.forumTitle
active_topic_last_post_date.text = topicItem.lastPostDate
active_topic_answers.text = topicItem.answers
active_topic_rating.text = topicItem.ratingText
active_topic_rating.loadRatingBackground(topicItem.rating)
active_topic_name.textSize = normalFontSize
active_topic_forum.textSize = normalFontSize
active_topic_last_post_date.textSize = normalFontSize
active_topic_answers.textSize = normalFontSize
setOnClickListener {
val triple = Triple(topicItem.forumId, topicItem.topicId, 0)
itemClickListener.onActiveTopicItemClick(triple)
}
}
}
}
}
|
apache-2.0
|
63136ac1300ae5bd827b18aec78fc328
| 45.766667 | 103 | 0.743763 | 4.6 | false | false | false | false |
androidx/androidx
|
appcompat/appcompat-lint/src/test/kotlin/androidx/appcompat/lint/res/ImageButtonTintDetectorTest.kt
|
3
|
2467
|
/*
* 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.appcompat.lint.res
import androidx.appcompat.res.ImageViewTintDetector
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.junit.Test
class ImageButtonTintDetectorTest {
@Test
fun testUsageOfTintAttribute() {
val layout = LintDetectorTest.xml(
"layout/image_button.xml",
"""
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_delete"
android:tint="#FF0000" />
</LinearLayout>
"""
).indented().within("res")
// We expect the definition of the image button to be flagged since it has
// android:tint instead of app:tint. We also expect a matching
// fix to replace android:tint with app:tint, retaining the same value
lint().files(
layout
).issues(ImageViewTintDetector.USING_ANDROID_TINT)
.run()
.expect(
"""
res/layout/image_button.xml:10: Error: Must use app:tint instead of android:tint [UseAppTint]
android:tint="#FF0000" />
~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
""".trimIndent()
)
.expectFixDiffs(
"""
Fix for res/layout/image_button.xml line 10: Set tint="#FF0000":
@@ -3 +3
+ xmlns:app="http://schemas.android.com/apk/res-auto"
@@ -11 +12
- android:tint="#FF0000" />
+ app:tint="#FF0000" />
""".trimIndent()
)
}
}
|
apache-2.0
|
8439d0e556177b10458a7177c1361f9f
| 34.242857 | 93 | 0.645724 | 4.132328 | false | true | false | false |
noemus/kotlin-eclipse
|
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/resolve/EclipseAnalyzerFacadeForJVM.kt
|
1
|
11125
|
/*******************************************************************************
* 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 org.jetbrains.kotlin.core.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.builtins.JvmBuiltInsPackageFragmentProvider
import org.jetbrains.kotlin.cli.jvm.compiler.CliLightClassGenerationSupport
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.container.ValueDescriptor
import org.jetbrains.kotlin.context.ContextForNewModule
import org.jetbrains.kotlin.context.MutableModuleContext
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.jetbrains.kotlin.core.model.KotlinEnvironment
import org.jetbrains.kotlin.core.model.KotlinScriptEnvironment
import org.jetbrains.kotlin.core.utils.ProjectUtils
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDependenciesImpl
import org.jetbrains.kotlin.frontend.java.di.initJvmBuiltInsForTopDownAnalysis
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.JvmBuiltIns
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer
import org.jetbrains.kotlin.resolve.TopDownAnalysisMode
import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver
import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension
import org.jetbrains.kotlin.resolve.lazy.KotlinCodeAnalyzer
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory
import org.jetbrains.kotlin.util.KotlinFrontEndException
import java.lang.reflect.Type
import java.util.ArrayList
import java.util.LinkedHashSet
import org.jetbrains.kotlin.frontend.java.di.createContainerForTopDownAnalyzerForJvm as createContainerForScript
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.SourceOrBinaryModuleClassResolver
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.load.java.sam.SamWithReceiverResolver
import org.jetbrains.kotlin.core.model.SamWithReceiverResolverExtension
import org.jetbrains.kotlin.script.KotlinScriptDefinition
data class AnalysisResultWithProvider(val analysisResult: AnalysisResult, val componentProvider: ComponentProvider?) {
companion object {
val EMPTY = AnalysisResultWithProvider(AnalysisResult.EMPTY, null)
}
}
public object EclipseAnalyzerFacadeForJVM {
public fun analyzeFilesWithJavaIntegration(
environment: KotlinEnvironment,
filesToAnalyze: Collection<KtFile>): AnalysisResultWithProvider {
val filesSet = filesToAnalyze.toSet()
if (filesSet.size != filesToAnalyze.size) {
KotlinLogger.logWarning("Analyzed files have duplicates")
}
val allFiles = LinkedHashSet<KtFile>(filesSet)
val addedFiles = filesSet.map { getPath(it) }.filterNotNull().toSet()
ProjectUtils.getSourceFilesWithDependencies(environment.javaProject).filterNotTo(allFiles) {
getPath(it) in addedFiles
}
val project = environment.project
val moduleContext = createModuleContext(project, environment.configuration, true)
val storageManager = moduleContext.storageManager
val module = moduleContext.module
val providerFactory = FileBasedDeclarationProviderFactory(moduleContext.storageManager, allFiles)
val trace = CliLightClassGenerationSupport.CliBindingTrace()
val sourceScope = TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, filesToAnalyze)
val moduleClassResolver = SourceOrBinaryModuleClassResolver(sourceScope)
val languageVersionSettings = LanguageVersionSettingsImpl(
LanguageVersionSettingsImpl.DEFAULT.languageVersion,
LanguageVersionSettingsImpl.DEFAULT.apiVersion)
val optionalBuiltInsModule = JvmBuiltIns(storageManager).apply { initialize(module, true) }.builtInsModule
val dependencyModule = run {
val dependenciesContext = ContextForNewModule(
moduleContext, Name.special("<dependencies of ${environment.configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"),
module.builtIns, null
)
val dependencyScope = GlobalSearchScope.notScope(sourceScope)
val dependenciesContainer = createContainerForTopDownAnalyzerForJvm(
dependenciesContext,
trace,
DeclarationProviderFactory.EMPTY,
dependencyScope,
LookupTracker.DO_NOTHING,
KotlinPackagePartProvider(environment),
JvmTarget.DEFAULT,
languageVersionSettings,
moduleClassResolver,
environment.javaProject)
moduleClassResolver.compiledCodeResolver = dependenciesContainer.get<JavaDescriptorResolver>()
dependenciesContext.setDependencies(listOfNotNull(dependenciesContext.module, optionalBuiltInsModule))
dependenciesContext.initializeModuleContents(CompositePackageFragmentProvider(listOf(
moduleClassResolver.compiledCodeResolver.packageFragmentProvider,
dependenciesContainer.get<JvmBuiltInsPackageFragmentProvider>()
)))
dependenciesContext.module
}
val container = createContainerForTopDownAnalyzerForJvm(
moduleContext,
trace,
providerFactory,
sourceScope,
LookupTracker.DO_NOTHING,
KotlinPackagePartProvider(environment),
JvmTarget.DEFAULT,
languageVersionSettings,
moduleClassResolver,
environment.javaProject).apply {
initJvmBuiltInsForTopDownAnalysis()
}
moduleClassResolver.sourceCodeResolver = container.get<JavaDescriptorResolver>()
val additionalProviders = ArrayList<PackageFragmentProvider>()
additionalProviders.add(container.get<JavaDescriptorResolver>().packageFragmentProvider)
PackageFragmentProviderExtension.getInstances(project).mapNotNullTo(additionalProviders) { extension ->
extension.getPackageFragmentProvider(project, module, storageManager, trace, null, LookupTracker.DO_NOTHING)
}
module.setDependencies(ModuleDependenciesImpl(
listOfNotNull(module, dependencyModule, optionalBuiltInsModule),
setOf(dependencyModule)
))
module.initialize(CompositePackageFragmentProvider(
listOf(container.get<KotlinCodeAnalyzer>().packageFragmentProvider) +
additionalProviders
))
try {
container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, filesSet)
} catch(e: KotlinFrontEndException) {
// Editor will break if we do not catch this exception
// and will not be able to save content without reopening it.
// In IDEA this exception throws only in CLI
KotlinLogger.logError(e)
}
return AnalysisResultWithProvider(
AnalysisResult.success(trace.getBindingContext(), module),
container)
}
public fun analyzeScript(
environment: KotlinScriptEnvironment,
scriptFile: KtFile): AnalysisResultWithProvider {
if (environment.isInitializingScriptDefinitions) {
// We can't start resolve when script definitions are not initialized
return AnalysisResultWithProvider.EMPTY
}
val trace = CliLightClassGenerationSupport.CliBindingTrace()
val container = TopDownAnalyzerFacadeForJVM.createContainer(
environment.project,
setOf(scriptFile),
trace,
environment.configuration,
{ KotlinPackagePartProvider(environment) },
{ storageManager: StorageManager, files: Collection<KtFile> -> FileBasedDeclarationProviderFactory(storageManager, files) }
)
try {
container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, setOf(scriptFile))
} catch(e: KotlinFrontEndException) {
// Editor will break if we do not catch this exception
// and will not be able to save content without reopening it.
// In IDEA this exception throws only in CLI
KotlinLogger.logError(e)
}
return AnalysisResultWithProvider(
AnalysisResult.success(trace.getBindingContext(), container.get<ModuleDescriptor>()),
container)
}
private fun getPath(jetFile: KtFile): String? = jetFile.getVirtualFile()?.getPath()
private fun createModuleContext(
project: Project,
configuration: CompilerConfiguration,
createBuiltInsFromModule: Boolean
): MutableModuleContext {
val projectContext = ProjectContext(project)
val builtIns = JvmBuiltIns(projectContext.storageManager, !createBuiltInsFromModule)
return ContextForNewModule(
projectContext, Name.special("<${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"), builtIns, null
).apply {
if (createBuiltInsFromModule) {
builtIns.builtInsModule = module
}
}
}
}
|
apache-2.0
|
00f5106748d5cd4a7964a4d803c447a0
| 46.956897 | 146 | 0.709393 | 5.755303 | false | true | false | false |
pedpess/aurinkoapp
|
app/src/main/java/com/ppes/aurinkoapp/ui/adapters/ForecastListAdapter.kt
|
1
|
1753
|
package com.ppes.aurinkoapp.ui.adapters
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ppes.aurinkoapp.R
import com.ppes.aurinkoapp.domain.model.Forecast
import com.ppes.aurinkoapp.domain.model.ForecastList
import com.ppes.aurinkoapp.ui.utils.ctx
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_forecast.view.*
/**
* Created by ppes on 17/08/2017.
*/
class ForecastListAdapter(private val weekForecast: ForecastList,
private val itemClick: (Forecast) -> Unit) :
RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.ctx).inflate(R.layout.item_forecast, parent, false)
return ViewHolder(view, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindForecast(weekForecast[position])
}
override fun getItemCount() = weekForecast.size()
class ViewHolder(view: View,
private val itemClick: (Forecast) -> Unit) : RecyclerView.ViewHolder(view) {
fun bindForecast(forecast: Forecast) {
with(forecast) {
Picasso.with(itemView.ctx)
.load(iconUrl)
.into(itemView.icon)
itemView.date.text = date
itemView.description.text = description
itemView.maxTemperature.text = "${high}º"
itemView.minTemperature.text = "${low}º"
itemView.setOnClickListener { itemClick(this) }
}
}
}
}
|
apache-2.0
|
76faad6219dc4e7fbfe2d704e2948d5d
| 34.04 | 97 | 0.661907 | 4.281174 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-woof
|
app/src/main/java/com/example/woof/ui/theme/Theme.kt
|
1
|
1618
|
/*
* Copyright (C) 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 com.example.woof.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
background = Cyan900,
surface = Cyan700,
onSurface = White,
primary = Grey900,
onPrimary = White,
secondary = Grey100
)
private val LightColorPalette = lightColors(
background = Green100,
surface = Green50,
onSurface = Grey900,
primary = Grey50,
onPrimary = Grey900,
secondary = Grey700
)
@Composable
fun WoofTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
|
apache-2.0
|
c18561b808caf9cd152a92ceec61861c
| 27.892857 | 92 | 0.714462 | 4.481994 | false | false | false | false |
y2k/JoyReactor
|
core/src/main/kotlin/y2k/joyreactor/services/repository/arraylist/ArrayListDataSet.kt
|
1
|
2066
|
package y2k.joyreactor.services.repository.arraylist
import y2k.joyreactor.services.repository.DataSet
import y2k.joyreactor.services.repository.Dto
import java.lang.reflect.Method
import java.util.*
import kotlin.reflect.KClass
/**
* Created by y2k on 12/23/15.
*/
class ArrayListDataSet<T : Dto>(val type: KClass<T>) : DataSet<T> {
private val items = ArrayList<T>()
override fun clear() {
items.clear()
}
override fun remove(element: T) {
items.remove(element)
}
override fun remove(condition: Pair<String, Any?>) {
filter(condition).forEach { remove(it) }
}
override fun add(element: T): T {
val id = (Math.random() * Long.MAX_VALUE).toLong()
@Suppress("UNCHECKED_CAST")
val e = if (element.id == 0L) element.identify(id) as T else element
items.add(e)
return e
}
override fun toList(): List<T> {
return items.toList()
}
override fun forEach(f: (T) -> Unit) {
items.forEach(f)
}
override fun getById(id: Long): T {
return items.first { it.id == id }
}
override fun getByIdOrNull(id: Long): T? {
return items.firstOrNull { it.id == id }
}
override fun filter(vararg conditions: Pair<String, Any?>): List<T> {
val q = conditions.map { getGetter(it.first) to it.second }
return items.filter { s -> q.all { it.first(s) == it.second } }
}
override fun groupBy(groupProp: String, orderProp: String): List<T> {
val groupGetter = getGetter(groupProp)
val sortGetter = getGetter(orderProp)
return items
.groupBy { groupGetter(it) }
.map { it.value.maxBy { sortGetter(it) as Comparable<Any> }!! }
}
private fun getGetter(propertyName: String): Method {
val getterName = when {
propertyName.startsWith("is") -> propertyName
else -> "get${propertyName.substring(0..0).toUpperCase()}${propertyName.substring(1)}"
}
return type.java.getMethod(getterName)
}
}
|
gpl-2.0
|
98edc97e4f8b00f17dfda4bfb4da38a9
| 27.315068 | 98 | 0.611326 | 3.804788 | false | false | false | false |
googleads/googleads-mobile-android-examples
|
kotlin/admob/RewardedVideoExample/app/src/main/java/com/google/android/gms/example/rewardedvideoexample/MainActivity.kt
|
1
|
5511
|
package com.google.android.gms.example.rewardedvideoexample
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.OnUserEarnedRewardListener
import com.google.android.gms.ads.rewarded.RewardItem
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import kotlinx.android.synthetic.main.activity_main.*
const val AD_UNIT_ID = "ca-app-pub-3940256099942544/5224354917"
const val COUNTER_TIME = 10L
const val GAME_OVER_REWARD = 1
const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
private var mCoinCount: Int = 0
private var mCountDownTimer: CountDownTimer? = null
private var mGameOver = false
private var mGamePaused = false
private var mIsLoading = false
private var mRewardedAd: RewardedAd? = null
private var mTimeRemaining: Long = 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Log the Mobile Ads SDK version.
Log.d(TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion())
MobileAds.initialize(this) {}
loadRewardedAd()
// Create the "retry" button, which tries to show a rewarded video ad between game plays.
retry_button.visibility = View.INVISIBLE
retry_button.setOnClickListener { startGame() }
// Create the "show" button, which shows a rewarded video if one is loaded.
show_video_button.visibility = View.INVISIBLE
show_video_button.setOnClickListener { showRewardedVideo() }
// Display current coin count to user.
coin_count_text.text = "Coins: $mCoinCount"
startGame()
}
public override fun onPause() {
super.onPause()
pauseGame()
}
public override fun onResume() {
super.onResume()
if (!mGameOver && mGamePaused) {
resumeGame()
}
}
private fun pauseGame() {
mCountDownTimer?.cancel()
mGamePaused = true
}
private fun resumeGame() {
createTimer(mTimeRemaining)
mGamePaused = false
}
private fun loadRewardedAd() {
if (mRewardedAd == null) {
mIsLoading = true
var adRequest = AdRequest.Builder().build()
RewardedAd.load(
this,
AD_UNIT_ID,
adRequest,
object : RewardedAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.message)
mIsLoading = false
mRewardedAd = null
}
override fun onAdLoaded(rewardedAd: RewardedAd) {
Log.d(TAG, "Ad was loaded.")
mRewardedAd = rewardedAd
mIsLoading = false
}
}
)
}
}
private fun addCoins(coins: Int) {
mCoinCount += coins
coin_count_text.text = "Coins: $mCoinCount"
}
private fun startGame() {
// Hide the retry button, load the ad, and start the timer.
retry_button.visibility = View.INVISIBLE
show_video_button.visibility = View.INVISIBLE
if (mRewardedAd == null && !mIsLoading) {
loadRewardedAd()
}
createTimer(COUNTER_TIME)
mGamePaused = false
mGameOver = false
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private fun createTimer(time: Long) {
mCountDownTimer?.cancel()
mCountDownTimer =
object : CountDownTimer(time * 1000, 50) {
override fun onTick(millisUnitFinished: Long) {
mTimeRemaining = millisUnitFinished / 1000 + 1
timer.text = "seconds remaining: $mTimeRemaining"
}
override fun onFinish() {
show_video_button.visibility = View.VISIBLE
timer.text = "The game has ended!"
addCoins(GAME_OVER_REWARD)
retry_button.visibility = View.VISIBLE
mGameOver = true
}
}
mCountDownTimer?.start()
}
private fun showRewardedVideo() {
show_video_button.visibility = View.INVISIBLE
if (mRewardedAd != null) {
mRewardedAd?.fullScreenContentCallback =
object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
Log.d(TAG, "Ad was dismissed.")
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
mRewardedAd = null
loadRewardedAd()
}
override fun onAdFailedToShowFullScreenContent(adError: AdError) {
Log.d(TAG, "Ad failed to show.")
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
mRewardedAd = null
}
override fun onAdShowedFullScreenContent() {
Log.d(TAG, "Ad showed fullscreen content.")
// Called when ad is dismissed.
}
}
mRewardedAd?.show(
this,
OnUserEarnedRewardListener() {
fun onUserEarnedReward(rewardItem: RewardItem) {
var rewardAmount = rewardItem.amount
addCoins(rewardAmount)
Log.d("TAG", "User earned the reward.")
}
}
)
}
}
}
|
apache-2.0
|
0fee0f527ab536cb6c6f701bcc40aeb8
| 28.789189 | 93 | 0.655054 | 4.232719 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/EmailNotificationsPreferencesFragment.kt
|
1
|
4139
|
package com.habitrpg.android.habitica.ui.fragments.preferences
import android.content.SharedPreferences
import android.os.Bundle
import androidx.preference.CheckBoxPreference
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.user.User
class EmailNotificationsPreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
private var isInitialSet: Boolean = true
private var isSettingUser: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
HabiticaBaseApplication.userComponent?.inject(this)
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences?.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(this)
}
override fun setupPreferences() { /* no-on */ }
override fun setUser(user: User?) {
super.setUser(user)
isSettingUser = !isInitialSet
updatePreference("preference_email_you_won_challenge", user?.preferences?.emailNotifications?.wonChallenge)
updatePreference("preference_email_received_a_private_message", user?.preferences?.emailNotifications?.newPM)
updatePreference("preference_email_gifted_gems", user?.preferences?.emailNotifications?.giftedGems)
updatePreference("preference_email_gifted_subscription", user?.preferences?.emailNotifications?.giftedSubscription)
updatePreference("preference_email_invited_to_party", user?.preferences?.emailNotifications?.invitedParty)
updatePreference("preference_email_invited_to_guild", user?.preferences?.emailNotifications?.invitedGuild)
updatePreference("preference_email_your_quest_has_begun", user?.preferences?.emailNotifications?.questStarted)
updatePreference("preference_email_invited_to_quest", user?.preferences?.emailNotifications?.invitedQuest)
updatePreference("preference_email_important_announcements", user?.preferences?.emailNotifications?.majorUpdates)
updatePreference("preference_email_kicked_group", user?.preferences?.emailNotifications?.kickedGroup)
updatePreference("preference_email_onboarding", user?.preferences?.emailNotifications?.onboarding)
updatePreference("preference_email_subscription_reminders", user?.preferences?.emailNotifications?.subscriptionReminders)
isSettingUser = false
isInitialSet = false
}
private fun updatePreference(key: String, isChecked: Boolean?) {
val preference = (findPreference(key) as? CheckBoxPreference)
preference?.isChecked = isChecked == true
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (isSettingUser) {
return
}
val pathKey = when (key) {
"preference_email_you_won_challenge" -> "wonChallenge"
"preference_email_received_a_private_message" -> "newPM"
"preference_email_gifted_gems" -> "giftedGems"
"preference_email_gifted_subscription" -> "giftedSubscription"
"preference_email_invited_to_party" -> "invitedParty"
"preference_email_invited_to_guild" -> "invitedGuild"
"preference_email_your_quest_has_begun" -> "questStarted"
"preference_email_invited_to_quest" -> "invitedQuest"
"preference_email_important_announcements" -> "majorUpdates"
"preference_email_kicked_group" -> "kickedGroup"
"preference_email_onboarding" -> "onboarding"
"preference_email_subscription_reminders" -> "subscriptionReminders"
else -> null
}
if (pathKey != null) {
compositeSubscription.add(userRepository.updateUser("preferences.emailNotifications.$pathKey", sharedPreferences.getBoolean(key, false)).subscribe({ }, ExceptionHandler.rx()))
}
}
}
|
gpl-3.0
|
37e9bb4269bb20a6b7f66db7a8d39db3
| 51.392405 | 187 | 0.725054 | 5.186717 | false | false | false | false |
alorma/TimelineView
|
timeline/src/main/java/com/alorma/timeline/painter/point/SquarePointStylePainter.kt
|
1
|
1505
|
package com.alorma.timeline.painter.point
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
class SquarePointStylePainter : PointStylePainter() {
private val fillPaint: Paint by lazy {
Paint().apply {
flags = Paint.ANTI_ALIAS_FLAG
style = Paint.Style.FILL
}
}
private val strokesPaint: Paint by lazy {
Paint().apply {
flags = Paint.ANTI_ALIAS_FLAG
style = Paint.Style.STROKE
}
}
private var fillSize: Float = 0f
override fun initColors(strokeColor: Int, fillColor: Int) {
strokesPaint.color = strokeColor
fillPaint.color = fillColor
}
override fun initSizes(strokeSize: Float, fillSize: Float) {
this.fillSize = fillSize
this.strokesPaint.strokeWidth = strokeSize
}
override fun draw(canvas: Canvas, rect: Rect) {
val boxExtra = fillSize / 2
val boxRect = RectF(
rect.centerX() - boxExtra,
rect.centerY() - boxExtra,
rect.centerX() + boxExtra,
rect.centerY() + boxExtra
)
canvas.drawRect(boxRect, fillPaint)
val strokeRect = RectF(
rect.centerX() - boxExtra,
rect.centerY() - boxExtra,
rect.centerX() + boxExtra,
rect.centerY() + boxExtra
)
canvas.drawRect(strokeRect, strokesPaint)
}
}
|
apache-2.0
|
18911414a3bfc6854e6270f87b704ce4
| 26.888889 | 64 | 0.590033 | 4.452663 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/widget/HabitButtonWidgetProvider.kt
|
1
|
3473
|
package com.habitrpg.android.habitica.widget
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.shared.habitica.models.responses.TaskDirection
import javax.inject.Inject
class HabitButtonWidgetProvider : BaseWidgetProvider() {
@Inject
lateinit var taskRepository: TaskRepository
private fun setUp() {
if (!hasInjected) {
hasInjected = true
HabiticaBaseApplication.userComponent?.inject(this)
}
}
override fun layoutResourceId(): Int {
return R.layout.widget_habit_button
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
super.onUpdate(context, appWidgetManager, appWidgetIds)
setUp()
val thisWidget = ComponentName(
context,
HabitButtonWidgetProvider::class.java
)
val allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget)
for (widgetId in allWidgetIds) {
val options = appWidgetManager.getAppWidgetOptions(widgetId)
appWidgetManager.partiallyUpdateAppWidget(
widgetId,
sizeRemoteViews(context, options, widgetId)
)
}
// Build the intent to call the service
val intent = Intent(context.applicationContext, HabitButtonWidgetService::class.java)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds)
try {
context.startService(intent)
} catch (ignore: IllegalStateException) {
}
}
override fun onReceive(context: Context, intent: Intent) {
setUp()
if (intent.action == HABIT_ACTION) {
val mgr = AppWidgetManager.getInstance(context)
val appWidgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
)
val taskId = intent.getStringExtra(TASK_ID)
val direction = intent.getStringExtra(TASK_DIRECTION)
val ids = intArrayOf(appWidgetId)
if (taskId != null) {
userRepository.getUserFlowable().firstElement().flatMap { user -> taskRepository.taskChecked(user, taskId, TaskDirection.UP.text == direction, false, null) }
.subscribe({ taskDirectionData -> showToastForTaskDirection(context, taskDirectionData) }, ExceptionHandler.rx(), { this.onUpdate(context, mgr, ids) })
}
}
super.onReceive(context, intent)
}
override fun configureRemoteViews(
remoteViews: RemoteViews,
widgetId: Int,
columns: Int,
rows: Int
): RemoteViews {
return remoteViews
}
companion object {
const val HABIT_ACTION = "com.habitrpg.android.habitica.HABIT_ACTION"
const val TASK_ID = "com.habitrpg.android.habitica.TASK_ID_ITEM"
const val TASK_DIRECTION = "com.habitrpg.android.habitica.TASK_DIRECTION"
}
}
|
gpl-3.0
|
a63d5352cd9c72906468e1926221012b
| 33.804124 | 173 | 0.646991 | 5.175857 | false | false | false | false |
westnordost/StreetComplete
|
app/src/test/java/de/westnordost/streetcomplete/data/osm/changes/StringMapEntryModifyTest.kt
|
1
|
1308
|
package de.westnordost.streetcomplete.data.osm.changes
import org.junit.Test
import org.junit.Assert.*
class StringMapEntryModifyTest {
@Test fun `conflicts if already changed to different value`() {
assertTrue(StringMapEntryModify("a", "b", "c").conflictsWith(mutableMapOf("a" to "d")))
}
@Test fun `does not conflict if already changed to the new value`() {
assertFalse(StringMapEntryModify("a", "b", "c").conflictsWith(mutableMapOf("a" to "c")))
}
@Test fun `does not conflict if not changed yet`() {
assertFalse(StringMapEntryModify("a", "b", "c").conflictsWith(mutableMapOf("a" to "b")))
}
@Test fun `toString is as expected`() {
assertEquals(
"MODIFY \"a\"=\"b\" -> \"a\"=\"c\"",
StringMapEntryModify("a", "b", "c").toString()
)
}
@Test fun apply() {
val m = mutableMapOf("a" to "b")
StringMapEntryModify("a", "b", "c").applyTo(m)
assertEquals("c", m["a"])
}
@Test fun reverse() {
val modify = StringMapEntryModify("a", "b", "c")
val reverseModify = modify.reversed()
val m = mutableMapOf("a" to "b")
modify.applyTo(m)
reverseModify.applyTo(m)
assertEquals(1, m.size)
assertEquals("b", m["a"])
}
}
|
gpl-3.0
|
d68c5cd7ecf04186c61c354101b33fa3
| 27.434783 | 96 | 0.581804 | 3.927928 | false | true | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/external/codegen/box/coroutines/intLikeVarSpilling/usedInVarStore.kt
|
2
|
1199
|
// WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
class Controller {
suspend fun suspendHere(): Unit = suspendCoroutineOrReturn { x ->
x.resume(Unit)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend Controller.() -> Unit) {
c.startCoroutine(Controller(), EmptyContinuation)
}
fun box(): String {
builder {
val x = true
suspendHere()
val y: Boolean = x
if (!y) throw IllegalStateException("fail 1")
}
builder {
val x = '1'
suspendHere()
val y: Char = x
if (y != '1') throw IllegalStateException("fail 2")
}
builder {
val x: Byte = 1
suspendHere()
val y: Byte = x
if (y != 1.toByte()) throw IllegalStateException("fail 3")
}
builder {
val x: Short = 1
suspendHere()
val y: Short = x
if (y != 1.toShort()) throw IllegalStateException("fail 4")
}
builder {
val x: Int = 1
suspendHere()
val y: Int = x
if (y != 1) throw IllegalStateException("fail 5")
}
return "OK"
}
|
apache-2.0
|
813bd1ee3778ac3e6af018c17a25199b
| 18.983333 | 69 | 0.557965 | 4.31295 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
common_test/src/main/java/com/vmenon/mpo/test/TestData.kt
|
1
|
2935
|
package com.vmenon.mpo.test
import com.vmenon.mpo.downloads.domain.*
import com.vmenon.mpo.my_library.domain.EpisodeModel
import com.vmenon.mpo.my_library.domain.ShowModel
import com.vmenon.mpo.my_library.domain.ShowUpdateModel
import com.vmenon.mpo.player.domain.PlaybackMedia
import com.vmenon.mpo.player.domain.PlaybackMediaRequest
import com.vmenon.mpo.player.domain.PlaybackState
import com.vmenon.mpo.search.domain.ShowSearchResultDetailsModel
import com.vmenon.mpo.search.domain.ShowSearchResultEpisodeModel
import com.vmenon.mpo.search.domain.ShowSearchResultModel
object TestData {
val show = ShowModel(
name = "show",
artworkUrl = "artwork.com",
genres = emptyList(),
author = "author",
feedUrl = "feedUrl",
description = "description",
lastUpdate = 0L,
lastEpisodePublished = 0L
)
val episode = EpisodeModel(
name = "episode",
description = "description",
published = 0L,
type = "show",
downloadUrl = "www.download.com",
lengthInSeconds = 100,
artworkUrl = "artworkurl",
filename = "filename",
show = show
)
val showUpdate = ShowUpdateModel(episode)
val showSearchResultModel = ShowSearchResultModel(
name = "show",
artworkUrl = "artwork.com",
genres = emptyList(),
author = "author",
feedUrl = "feedUrl",
description = "description",
id = 1L
)
val showSearchResultEpisodeModel = ShowSearchResultEpisodeModel(
name = "episode",
artworkUrl = "artwork.com",
description = "description",
downloadUrl = "downloadUrl",
length = 100L,
published = 1L,
type = "episode"
)
val showSearchResultDetailsModel = ShowSearchResultDetailsModel(
show = showSearchResultModel,
episodes = listOf(showSearchResultEpisodeModel),
subscribed = true
)
val download = DownloadModel(
name = "download",
downloadUrl = "www.download.com",
downloadQueueId = 1L,
downloadRequestType = DownloadRequestType.EPISODE,
requesterId = 1L,
downloadAttempt = 0,
imageUrl = null
)
val queuedDownload = QueuedDownloadModel(
download = download,
total = 100,
progress = 0,
status = QueuedDownloadStatus.NOT_QUEUED
)
val completedDownload = CompletedDownloadModel(
download = download,
pathToFile = "/path/file.mp4"
)
val playbackMedia = PlaybackMedia(
mediaId = "mediaId",
durationInMillis = 120000L
)
val playbackMediaRequest = PlaybackMediaRequest(
media = playbackMedia,
mediaFile = "file"
)
val playbackState = PlaybackState(
media = playbackMedia,
positionInMillis = 0L,
state = PlaybackState.State.NONE,
playbackSpeed = 1F
)
}
|
apache-2.0
|
0f6b9193a88373da3c5ce60d16ff3c37
| 30.569892 | 68 | 0.642249 | 4.550388 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadPresenter.kt
|
1
|
2624
|
package eu.kanade.tachiyomi.ui.download
import android.content.Context
import android.os.Bundle
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.download.model.DownloadQueue
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import logcat.LogPriority
import uy.kohesive.injekt.injectLazy
class DownloadPresenter : BasePresenter<DownloadController>() {
val downloadManager: DownloadManager by injectLazy()
/**
* Property to get the queue from the download manager.
*/
private val downloadQueue: DownloadQueue
get() = downloadManager.queue
private val _state = MutableStateFlow(emptyList<DownloadHeaderItem>())
val state = _state.asStateFlow()
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
presenterScope.launch {
downloadQueue.updatedFlow()
.catch { error -> logcat(LogPriority.ERROR, error) }
.map { downloads ->
downloads
.groupBy { it.source }
.map { entry ->
DownloadHeaderItem(entry.key.id, entry.key.name, entry.value.size).apply {
addSubItems(0, entry.value.map { DownloadItem(it, this) })
}
}
}
.collect { newList -> _state.update { newList } }
}
}
fun getDownloadStatusFlow() = downloadQueue.statusFlow()
fun getDownloadProgressFlow() = downloadQueue.progressFlow()
/**
* Pauses the download queue.
*/
fun pauseDownloads() {
downloadManager.pauseDownloads()
}
/**
* Clears the download queue.
*/
fun clearQueue(context: Context) {
DownloadService.stop(context)
downloadManager.clearQueue()
}
fun reorder(downloads: List<Download>) {
downloadManager.reorderQueue(downloads)
}
fun cancelDownload(download: Download) {
downloadManager.deletePendingDownload(download)
}
fun cancelDownloads(downloads: List<Download>) {
downloadManager.deletePendingDownloads(*downloads.toTypedArray())
}
}
|
apache-2.0
|
83e68a132f17dd5d9aa8cb2b675c3257
| 31 | 102 | 0.662729 | 4.859259 | false | false | false | false |
k9mail/k-9
|
backend/webdav/src/main/java/com/fsck/k9/backend/webdav/CommandRefreshFolderList.kt
|
2
|
1217
|
package com.fsck.k9.backend.webdav
import com.fsck.k9.backend.api.BackendStorage
import com.fsck.k9.backend.api.FolderInfo
import com.fsck.k9.backend.api.updateFolders
import com.fsck.k9.mail.store.webdav.WebDavStore
internal class CommandRefreshFolderList(
private val backendStorage: BackendStorage,
private val webDavStore: WebDavStore
) {
fun refreshFolderList() {
val foldersOnServer = webDavStore.personalNamespaces
val oldFolderServerIds = backendStorage.getFolderServerIds()
backendStorage.updateFolders {
val foldersToCreate = mutableListOf<FolderInfo>()
for (folder in foldersOnServer) {
if (folder.serverId !in oldFolderServerIds) {
foldersToCreate.add(FolderInfo(folder.serverId, folder.name, folder.type))
} else {
changeFolder(folder.serverId, folder.name, folder.type)
}
}
createFolders(foldersToCreate)
val newFolderServerIds = foldersOnServer.map { it.serverId }
val removedFolderServerIds = oldFolderServerIds - newFolderServerIds
deleteFolders(removedFolderServerIds)
}
}
}
|
apache-2.0
|
ffcb0cf1fcd7e2969e0d2082e4409ad5
| 37.03125 | 94 | 0.677075 | 4.524164 | false | false | false | false |
ThoseGrapefruits/intellij-rust
|
src/main/kotlin/org/rust/lang/codestyle/RustLanguageCodeStyleSettingsProvider.kt
|
1
|
1185
|
package org.rust.lang.codestyle
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider
import org.rust.lang.RustLanguage
class RustLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun getLanguage() = RustLanguage
override fun customizeSettings(consumer: CodeStyleSettingsCustomizable,
settingsType: LanguageCodeStyleSettingsProvider.SettingsType) {
if (settingsType == SettingsType.WRAPPING_AND_BRACES_SETTINGS) {
consumer.showStandardOptions("RIGHT_MARGIN");
}
}
override fun getDefaultCommonSettings() = CommonCodeStyleSettings(language).apply {
RIGHT_MARGIN = 99
}
override fun getCodeSample(settingsType: LanguageCodeStyleSettingsProvider.SettingsType) = CODE_SAMPLE
private val CODE_SAMPLE by lazy {
val stream = javaClass.classLoader.getResourceAsStream("org/rust/lang/codestyle/code_sample.rs")
StreamUtil.readText(stream, "UTF-8")
}
}
|
mit
|
ce0fc9408d4cdd2c1eb7cf1f36cca84d
| 38.5 | 106 | 0.756962 | 5.085837 | false | false | false | false |
AcornUI/Acorn
|
acornui-core/src/main/kotlin/com/acornui/di/Context.kt
|
1
|
13969
|
/*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.di
import com.acornui.*
import com.acornui.collection.copy
import kotlinx.coroutines.CoroutineScope
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.coroutines.CoroutineContext
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* An Acorn Context is the base object for providing:
* - Ownership hierarchy
* - Dependency injection
* - Coroutine scoping
* - Disposable cleanup
*/
interface Context : CoroutineScope, Owner, Disposable {
/**
* The context that constructed this context.
*/
val owner: Context?
/**
* If this context represents a special scope (e.g. [ContextMarker.MAIN] or [ContextMarker.APPLICATION]),
* this will be set.
*/
val marker: ContextMarker?
/**
* The map of dependencies to use for injection.
* Don't retrieve dependencies from this map, use [inject] or [injectOptional] which will make use of factories and
* key inheritance.
*
* Any mutation of dependencies _must_ happen before construction of children.
*
* @see inject
*/
var dependencies: DependencyMap
/**
* Returns true if this context contains a dependency with the given key.
*/
fun containsKey(key: Key<*>): Boolean
fun <T : Any> injectOptional(key: Key<T>): T?
fun <T : Any> inject(key: Key<T>): T
/**
* A context key is used for getting and setting dependencies on a [Context].
*/
interface Key<T : Any> {
/**
* This key's supertype.
* If not null, when the context installs a dependency with this key, it will also install that dependency for
* this supertype key.
*
* The parameterized type of this key should be Key<S> where S : T.
*/
val extends: Key<*>?
get() = null
/**
* When a dependency is requested that isn't found, this factory (if not null) will be used to construct a new
* instance.
*/
val factory: DependencyFactory<T>?
get() = null
operator fun provideDelegate(
thisRef: Context,
prop: KProperty<*>
): ReadOnlyProperty<Context, T> = LazyDependency(this)
infix fun to(value: T): DependencyPair<T> = DependencyPair(this, value)
}
/**
* A factory for providing dependency instances.
*/
interface DependencyFactory<out T : Any> {
/**
* Constructs the new dependency using the context found where [Context.marker] == [installTo].
* The new dependency will be installed on that matching context and will be reused on the next injection
* from that context and its children.
*
* @param context The context found where [Context.marker] == [installTo]
*/
operator fun invoke(context: Context): T
/**
* Returns the scope for which the new dependency should be installed.
* If the scope isn't found, a [ContextMarkerNotFoundException] exception will be thrown.
*/
val installTo: ContextMarker
get() = ContextMarker.APPLICATION
}
class ContextMarkerNotFoundException private constructor(message: String) : IllegalStateException(message) {
constructor(key: Key<*>) : this("Scope \"${key.factory!!.installTo.value}\" not found for Context.Key $key")
constructor(marker: ContextMarker) : this("Scope \"${marker.value}\" not found")
}
}
/**
* Creates a new dependency factory for the given scope and constructor.
*/
fun <T : Any> dependencyFactory(
scope: ContextMarker = ContextMarker.APPLICATION,
create: (context: Context) -> T
): Context.DependencyFactory<T> {
return object : Context.DependencyFactory<T> {
override val installTo: ContextMarker = scope
override fun invoke(context: Context): T = create(context)
}
}
/**
* Constructs a new context with the receiver as the owner and [Context.dependencies] as the new dependencies.
*/
fun Context.childContext(): Context = ContextImpl(this, dependencies)
/**
* A basic [Context] implementation.
*/
open class ContextImpl(
final override val owner: Context? = null,
final override var dependencies: DependencyMap = DependencyMap(),
final override val coroutineContext: CoroutineContext = mainContext.coroutineContext,
override val marker: ContextMarker? = null
) : Context, ManagedDisposable, DisposableBase() {
constructor(owner: Context?, dependencies: List<DependencyPair<*>>) : this(owner, DependencyMap(dependencies))
constructor(dependencies: DependencyMap) : this(null, dependencies)
constructor(owner: Context) : this(owner, owner.dependencies)
constructor(dependencies: List<DependencyPair<*>>) : this(null, dependencies)
private val constructing = ArrayList<Context.Key<*>>()
final override fun containsKey(key: Context.Key<*>): Boolean {
return dependencies.containsKey(key)
}
final override fun <T : Any> injectOptional(key: Context.Key<T>): T? {
return dependencies[key] ?: run {
val factory = key.factory ?: return null
val factoryScope = factory.installTo
val contextWithScope = findOwner { it.marker === factoryScope }
?: throw Context.ContextMarkerNotFoundException(key)
if (contextWithScope != this) {
val newInstance = contextWithScope.injectOptional(key) ?: return null
dependencies += key to newInstance
return newInstance
}
if (constructing.contains(key))
throw CyclicDependencyException("Cyclic dependency detected: ${constructing.joinToString(" -> ")} -> $key")
constructing.add(key)
val newInstance: T = factory(this)
dependencies += key to newInstance
constructing.remove(key)
return newInstance
}
}
final override fun <T : Any> inject(key: Context.Key<T>): T {
@Suppress("UNCHECKED_CAST")
return injectOptional(key) ?: error("Dependency not found for key: $key")
}
init {
owner?.ownThis()
}
}
/**
* A `ContextMarker` marks special [Context] objects.
*/
class ContextMarker(val value: String) {
companion object {
/**
* The context created from `runMain`. This will typically be the most global scope.
*/
val MAIN = ContextMarker("Main")
/**
* The context created from an application. There may be multiple applications created from a single `runMain`.
*/
val APPLICATION = ContextMarker("Application")
}
override fun toString(): String {
return "ContextMarker($value)"
}
}
inline fun Context.context(init: ContextImpl.() -> Unit): ContextImpl {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return ContextImpl(this).apply(init)
}
/**
* Returns true if `this` is an ancestor in [other]'s ownership chain.
* Ownership chains are based on construction, not based on display hierarchy.
*/
fun Context?.owns(other: Context?): Boolean {
if (this == null) return false
var p: Context? = other
while (p != null) {
if (p == this) return true
p = p.owner
}
return false
}
/**
* Returns a new context where the new context's owner is `this` and the [Context.coroutineContext] contains elements
* of both this [Context.coroutineContext] and [context].
*
* @see [CoroutineContext.plus]
*/
operator fun Context.plus(context: CoroutineContext): Context {
return ContextImpl(owner = this, dependencies = dependencies, coroutineContext = coroutineContext + context)
}
/**
* Traverses this Owned object's ownership lineage (starting with `this`), invoking a callback on each owner up the
* chain.
* @param callback The callback to invoke on each owner ancestor. If this callback returns true, iteration will
* continue, if it returns false, iteration will be halted.
* @return If [callback] returned false, this method returns the element on which the iteration halted.
*/
fun Context.ownerWalk(callback: (Context) -> Boolean): Context? {
var p: Context? = this
while (p != null) {
val shouldContinue = callback(p)
if (!shouldContinue) return p
p = p.owner
}
return null
}
/**
* Traverses this Owned object's ownership lineage (starting with `this`), returning the first [Context] where
* [callback] returns true.
*
* @param callback Invoked on each ancestor until true is returned.
* @return Returns the first ancestor for which [callback] returned true.
*/
inline fun Context.findOwner(crossinline callback: (Context) -> Boolean): Context? = ownerWalk { !callback(it) }
data class DependencyPair<T : Any>(val key: Context.Key<T>, val value: T)
/**
* A dependency map is a mutable map that enforces that the dependency key is the right type for the value.
*/
class DependencyMap private constructor(private val inner: Map<Context.Key<*>, Any>) : Iterable<DependencyPair<Any>> {
constructor(dependencies: Iterable<DependencyPair<*>>) : this(dependencies.toDependencyMap())
constructor() : this(emptyMap())
/**
* Returns the number of key/value pairs in the map.
*/
val size: Int = inner.size
/**
* Returns `true` if the map is empty (contains no elements), `false` otherwise.
*/
fun isEmpty(): Boolean = inner.isEmpty()
/**
* Returns `true` if this map is not empty.
*/
fun isNotEmpty(): Boolean = inner.isNotEmpty()
/**
* Returns `true` if the map contains the specified [key].
*/
fun containsKey(key: Context.Key<*>): Boolean = inner.containsKey(key)
operator fun <T : Any> get(key: Context.Key<T>): T? {
@Suppress("UNCHECKED_CAST")
return inner[key] as T?
}
/**
* Creates a new read-only dependency map by replacing or adding entries to this map from another.
*/
operator fun plus(other: DependencyMap): DependencyMap {
if (other.isEmpty()) return this
if (isEmpty()) return other
return DependencyMap(inner + other.inner)
}
/**
* Creates a new read-only dependency map by replacing or adding entries to this map from another.
*/
operator fun plus(dependencies: List<DependencyPair<*>>): DependencyMap {
if (dependencies.isEmpty()) return this
if (isEmpty()) return DependencyMap(dependencies)
return DependencyMap(inner + dependencies.toDependencyMap())
}
/**
* Creates a new dependency map with the new dependency added or replacing the existing dependency of that key.
*/
operator fun plus(dependency: DependencyPair<*>): DependencyMap {
val new = inner.copy()
var p: Context.Key<*>? = dependency.key
while (p != null) {
new[p] = dependency.value
p = p.extends
}
return DependencyMap(new)
}
override fun iterator(): Iterator<DependencyPair<Any>> {
return object : Iterator<DependencyPair<Any>> {
private val innerIt = inner.iterator()
override fun hasNext(): Boolean = innerIt.hasNext()
override fun next(): DependencyPair<Any> {
val n = innerIt.next()
@Suppress("UNCHECKED_CAST")
return n.key as Context.Key<Any> to n.value
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as DependencyMap
if (inner != other.inner) return false
return true
}
override fun hashCode(): Int {
return inner.hashCode()
}
}
private fun Iterable<DependencyPair<*>>.toDependencyMap(): Map<Context.Key<*>, Any> {
val map = HashMap<Context.Key<*>, Any>()
for ((key, value) in this) {
var p: Context.Key<*>? = key
while (p != null) {
map[p] = value
p = p.extends
}
}
return map
}
val emptyDependencies = DependencyMap()
fun dependencyMapOf(vararg dependencies: DependencyPair<*>) =
if (dependencies.isEmpty()) emptyDependencies else DependencyMap(dependencies.toList())
/**
* Creates a dependency key with the given factory function.
*/
fun <T : Any> contextKey(): Context.Key<T> {
return object : Context.Key<T> {}
}
fun <T : SuperKey, SuperKey : Any> contextKey(extends: Context.Key<SuperKey>): Context.Key<T> {
return object : Context.Key<T> {
override val extends: Context.Key<SuperKey>? = extends
}
}
fun <T : Any> contextKey(
scope: ContextMarker = ContextMarker.APPLICATION,
create: (context: Context) -> T
): Context.Key<T> {
return object : Context.Key<T> {
override val factory = dependencyFactory(scope, create)
}
}
fun <T : SuperKey, SuperKey : Any> contextKey(
extends: Context.Key<SuperKey>,
scope: ContextMarker = ContextMarker.APPLICATION,
create: (context: Context) -> T
): Context.Key<T> {
return object : Context.Key<T> {
override val extends: Context.Key<SuperKey>? = extends
override val factory = dependencyFactory(scope, create)
}
}
private class LazyDependency<T : Any>(private val key: Context.Key<T>) : ReadOnlyProperty<Context, T> {
private var value: T? = null
override fun getValue(thisRef: Context, property: KProperty<*>): T {
if (value == null)
value = thisRef.inject(key)
return value as T
}
}
private class OptionalLazyDependency<T : Any>(private val key: Context.Key<T>) : ReadOnlyProperty<Context, T?> {
private var valueIsSet = false
private var value: T? = null
override fun getValue(thisRef: Context, property: KProperty<*>): T? {
if (!valueIsSet) {
value = thisRef.injectOptional(key)
valueIsSet = true
}
return value
}
}
class CyclicDependencyException(message: String) : Exception(message)
fun Context.findOwnerWithMarker(marker: ContextMarker): Context {
return findOwner { it.marker === marker } ?: throw Context.ContextMarkerNotFoundException(marker)
}
/**
* Cancels the application's job, thus disposing the application.
*/
fun Context.exit() {
val applicationContext = findOwnerWithMarker(ContextMarker.APPLICATION)
// val job = applicationContext.coroutineContext[Job]!!
// job.cancel()
(applicationContext as Disposable?)?.dispose()
}
|
apache-2.0
|
5f517d15b1e34058ffd81c49a17563e3
| 29.303688 | 118 | 0.709213 | 3.815624 | false | false | false | false |
ingokegel/intellij-community
|
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/EmptyComponentPanel.kt
|
9
|
1357
|
/*
* Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.plugins.notebooks.visualization.r.inlays.components
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import javax.swing.JComponent
import javax.swing.JPanel
/**
* This panel will show [emptyComponent] if current [contentComponent] is `null`.
* That's pretty similar to `emptyView` decorator for Android's `ListView`
*/
class EmptyComponentPanel(private val emptyComponent: JComponent) {
val component = JPanel(GridBagLayout())
var contentComponent: JComponent? = null
set(newComponent) {
if (field != null) {
component.remove(field)
}
if (newComponent != null) {
component.addWithFill(newComponent)
newComponent.isVisible = true
}
component.repaint()
emptyComponent.isVisible = newComponent == null
field = newComponent
}
init {
emptyComponent.isVisible = true
component.addWithFill(emptyComponent)
}
companion object {
private fun JPanel.addWithFill(component: JComponent) {
val constraints = GridBagConstraints().apply {
fill = GridBagConstraints.BOTH
weightx = 1.0
weighty = 1.0
}
add(component, constraints)
}
}
}
|
apache-2.0
|
2b72479d2a8b243c53c0d3467664bb00
| 27.270833 | 140 | 0.694178 | 4.405844 | false | false | false | false |
mdaniel/intellij-community
|
platform/platform-impl/src/com/intellij/ui/layout/LayoutBuilder.kt
|
2
|
4052
|
// 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.ui.layout
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.components.JBRadioButton
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.awt.event.ActionListener
import javax.swing.AbstractButton
import javax.swing.ButtonGroup
open class LayoutBuilder @PublishedApi internal constructor(@PublishedApi internal val builder: LayoutBuilderImpl) : RowBuilder by builder.rootRow {
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) {
builder.withButtonGroup(buttonGroup, body)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
inline fun buttonGroup(crossinline elementActionListener: () -> Unit, crossinline init: LayoutBuilder.() -> Unit): ButtonGroup {
val group = ButtonGroup()
builder.withButtonGroup(group) {
LayoutBuilder(builder).init()
}
val listener = ActionListener { elementActionListener() }
for (button in group.elements) {
button.addActionListener(listener)
}
return group
}
@Suppress("PropertyName")
@PublishedApi
@get:Deprecated("", replaceWith = ReplaceWith("builder"), level = DeprecationLevel.ERROR)
@get:ApiStatus.ScheduledForRemoval
internal val `$`: LayoutBuilderImpl
get() = builder
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
class CellBuilderWithButtonGroupProperty<T : Any>
@PublishedApi internal constructor(private val prop: PropertyBinding<T>) {
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun Cell.radioButton(@NlsContexts.RadioButton text: String, value: T, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text, prop.get() == value)
return component(comment = comment).bindValue(value)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
fun CellBuilder<JBRadioButton>.bindValue(value: T): CellBuilder<JBRadioButton> = bindValueToProperty(prop, value)
}
@Deprecated("Use Kotlin UI DSL Version 2")
class RowBuilderWithButtonGroupProperty<T : Any>
@PublishedApi internal constructor(private val builder: RowBuilder, private val prop: PropertyBinding<T>) : RowBuilder by builder {
@Deprecated("Use Kotlin UI DSL Version 2")
fun Row.radioButton(@NlsContexts.RadioButton text: String, value: T, @Nls comment: String? = null): CellBuilder<JBRadioButton> {
val component = JBRadioButton(text, prop.get() == value)
attachSubRowsEnabled(component)
return component(comment = comment).bindValue(value)
}
@Deprecated("Use Kotlin UI DSL Version 2")
fun CellBuilder<JBRadioButton>.bindValue(value: T): CellBuilder<JBRadioButton> = bindValueToProperty(prop, value)
}
@Deprecated("Use Kotlin UI DSL Version 2")
private fun <T> CellBuilder<JBRadioButton>.bindValueToProperty(prop: PropertyBinding<T>, value: T): CellBuilder<JBRadioButton> = apply {
onApply { if (component.isSelected) prop.set(value) }
onReset { component.isSelected = prop.get() == value }
onIsModified { component.isSelected != (prop.get() == value) }
}
fun FileChooserDescriptor.chooseFile(event: AnActionEvent, fileChosen: (chosenFile: VirtualFile) -> Unit) {
FileChooser.chooseFile(this, event.getData(PlatformDataKeys.PROJECT), event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT), null, fileChosen)
}
fun Row.attachSubRowsEnabled(component: AbstractButton) {
enableSubRowsIf(component.selected)
}
|
apache-2.0
|
44c03b33ce6650237d678735935847c5
| 41.208333 | 148 | 0.773939 | 4.502222 | false | false | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/erg/ErgTransaction.kt
|
1
|
3497
|
/*
* ErgTransaction.kt
*
* Copyright 2015-2019 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.erg
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.Epoch
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.transit.Transaction
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.TransitCurrency.Companion.XXX
import au.id.micolous.metrodroid.transit.TransitCurrencyRef
import au.id.micolous.metrodroid.transit.erg.record.ErgPurseRecord
@Parcelize
class ErgUnknownTransaction(
override val purse: ErgPurseRecord,
override val epoch: Int) : ErgTransaction() {
override val currency: TransitCurrencyRef get() = ::XXX
override val timezone get() = MetroTimeZone.UNKNOWN
}
/**
* Represents a transaction on an ERG MIFARE Classic card.
*/
abstract class ErgTransaction : Transaction() {
abstract val purse: ErgPurseRecord
abstract val epoch: Int
protected abstract val currency: TransitCurrencyRef
protected abstract val timezone: MetroTimeZone
// Implemented functionality.
override val timestamp get(): TimestampFull =
convertTimestamp(epoch, timezone, purse.day, purse.minute)
override val isTapOff get(): Boolean = false
override val fare get(): TransitCurrency {
var o = purse.transactionValue
if (purse.isCredit) {
o *= -1
}
return currency(o)
}
override fun isSameTrip(other: Transaction): Boolean {
return false
}
override val isTapOn get(): Boolean {
return true
}
override val isTransfer get(): Boolean {
// TODO
return false
}
override fun compareTo(other: Transaction): Int {
// This prepares ordering for a later merge
val ret = super.compareTo(other)
return when {
// Transactions are sorted by time alone -- but Erg transactions will have the same
// timestamp for many things
ret != 0 || other !is ErgTransaction -> ret
// Put "top-ups" first
purse.isCredit && purse.transactionValue != 0 -> -1
other.purse.isCredit && other.purse.transactionValue != 0 -> 1
// Then put "trips" first
purse.isTrip -> -1
other.purse.isTrip -> 1
// Otherwise sort by value
else -> purse.transactionValue.compareTo(other.purse.transactionValue)
}
}
companion object {
fun convertTimestamp(epoch: Int, tz: MetroTimeZone, day: Int = 0, minute: Int = 0): TimestampFull {
val g = Epoch.utc(2000, tz)
return g.dayMinute(epoch + day, minute)
}
}
}
|
gpl-3.0
|
a4ff0701c5388c9ccdb52bbecfef795e
| 32.625 | 107 | 0.681441 | 4.322621 | false | false | false | false |
Major-/Vicis
|
modern/src/main/kotlin/rs/emulate/modern/codec/VersionedContainer.kt
|
1
|
1160
|
package rs.emulate.modern.codec
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import rs.emulate.util.crc32
class VersionedContainer(private var buffer: ByteBuf, version: Int) {
val checksum: Int
get() = buffer.crc32()
var version: Int = version
set(value) {
field = value and 0xFFFF
}
/* returns an immutable buffer */
fun getBuffer(): ByteBuf {
return buffer.slice()
}
/* accepts an immutable buffer */
fun setBuffer(buffer: ByteBuf) {
this.buffer = buffer
}
/* returns an immutable buffer */
fun write(): ByteBuf {
val trailer = Unpooled.buffer(2, 2)
trailer.writeShort(version)
return Unpooled.wrappedBuffer(buffer, trailer).asReadOnly()
}
companion object {
/* accepts an immutable buffer */
fun ByteBuf.readVersionedContainer(): VersionedContainer {
require(readableBytes() >= 2) { "No version trailer" }
val data = readSlice(readableBytes() - 2)
val version = readUnsignedShort()
return VersionedContainer(data, version)
}
}
}
|
isc
|
533524c3ad9a88fbcab635520d181a71
| 24.777778 | 69 | 0.618103 | 4.58498 | false | false | false | false |
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/BitmapHunter.kt
|
1
|
10218
|
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.net.NetworkInfo
import com.squareup.picasso3.MemoryPolicy.Companion.shouldReadFromMemoryCache
import com.squareup.picasso3.Picasso.LoadedFrom
import com.squareup.picasso3.RequestHandler.Result.Bitmap
import com.squareup.picasso3.Utils.OWNER_HUNTER
import com.squareup.picasso3.Utils.THREAD_IDLE_NAME
import com.squareup.picasso3.Utils.THREAD_PREFIX
import com.squareup.picasso3.Utils.VERB_DECODED
import com.squareup.picasso3.Utils.VERB_EXECUTING
import com.squareup.picasso3.Utils.VERB_JOINED
import com.squareup.picasso3.Utils.VERB_REMOVED
import com.squareup.picasso3.Utils.VERB_TRANSFORMED
import com.squareup.picasso3.Utils.getLogIdsForHunter
import com.squareup.picasso3.Utils.log
import java.io.IOException
import java.io.InterruptedIOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Future
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
internal open class BitmapHunter(
val picasso: Picasso,
private val dispatcher: Dispatcher,
private val cache: PlatformLruCache,
action: Action,
val requestHandler: RequestHandler
) : Runnable {
val sequence: Int = SEQUENCE_GENERATOR.incrementAndGet()
var priority: Picasso.Priority = action.request.priority
var data: Request = action.request
val key: String = action.request.key
var retryCount: Int = requestHandler.retryCount
var action: Action? = action
private set
var actions: MutableList<Action>? = null
private set
var future: Future<*>? = null
var result: RequestHandler.Result? = null
private set
var exception: Exception? = null
private set
val isCancelled: Boolean
get() = future?.isCancelled ?: false
override fun run() {
try {
updateThreadName(data)
if (picasso.isLoggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this))
}
result = hunt()
dispatcher.dispatchComplete(this)
} catch (e: IOException) {
exception = e
if (retryCount > 0) {
dispatcher.dispatchRetry(this)
} else {
dispatcher.dispatchFailed(this)
}
} catch (e: Exception) {
exception = e
dispatcher.dispatchFailed(this)
} finally {
Thread.currentThread().name = THREAD_IDLE_NAME
}
}
fun hunt(): Bitmap? {
if (shouldReadFromMemoryCache(data.memoryPolicy)) {
cache[key]?.let { bitmap ->
picasso.cacheHit()
if (picasso.isLoggingEnabled) {
log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache")
}
return Bitmap(bitmap, LoadedFrom.MEMORY)
}
}
if (retryCount == 0) {
data = data.newBuilder().networkPolicy(NetworkPolicy.OFFLINE).build()
}
val resultReference = AtomicReference<RequestHandler.Result?>()
val exceptionReference = AtomicReference<Throwable>()
val latch = CountDownLatch(1)
try {
requestHandler.load(
picasso = picasso,
request = data,
callback = object : RequestHandler.Callback {
override fun onSuccess(result: RequestHandler.Result?) {
resultReference.set(result)
latch.countDown()
}
override fun onError(t: Throwable) {
exceptionReference.set(t)
latch.countDown()
}
}
)
latch.await()
} catch (ie: InterruptedException) {
val interruptedIoException = InterruptedIOException()
interruptedIoException.initCause(ie)
throw interruptedIoException
}
exceptionReference.get()?.let { throwable ->
when (throwable) {
is IOException, is Error, is RuntimeException -> throw throwable
else -> throw RuntimeException(throwable)
}
}
val result = resultReference.get() as? Bitmap ?: return null
val bitmap = result.bitmap
if (picasso.isLoggingEnabled) {
log(OWNER_HUNTER, VERB_DECODED, data.logId())
}
picasso.bitmapDecoded(bitmap)
val transformations = ArrayList<Transformation>(data.transformations.size + 1)
if (data.needsMatrixTransform() || result.exifRotation != 0) {
transformations += MatrixTransformation(data)
}
transformations += data.transformations
val transformedResult =
applyTransformations(picasso, data, transformations, result) ?: return null
val transformedBitmap = transformedResult.bitmap
picasso.bitmapTransformed(transformedBitmap)
return transformedResult
}
fun attach(action: Action) {
val loggingEnabled = picasso.isLoggingEnabled
val request = action.request
if (this.action == null) {
this.action = action
if (loggingEnabled) {
if (actions.isNullOrEmpty()) {
log(OWNER_HUNTER, VERB_JOINED, request.logId(), "to empty hunter")
} else {
log(OWNER_HUNTER, VERB_JOINED, request.logId(), getLogIdsForHunter(this, "to "))
}
}
return
}
if (actions == null) {
actions = ArrayList(3)
}
actions!!.add(action)
if (loggingEnabled) {
log(OWNER_HUNTER, VERB_JOINED, request.logId(), getLogIdsForHunter(this, "to "))
}
val actionPriority = action.request.priority
if (actionPriority.ordinal > priority.ordinal) {
priority = actionPriority
}
}
fun detach(action: Action) {
val detached = when {
this.action === action -> {
this.action = null
true
}
else -> actions?.remove(action) ?: false
}
// The action being detached had the highest priority. Update this
// hunter's priority with the remaining actions.
if (detached && action.request.priority == priority) {
priority = computeNewPriority()
}
if (picasso.isLoggingEnabled) {
log(OWNER_HUNTER, VERB_REMOVED, action.request.logId(), getLogIdsForHunter(this, "from "))
}
}
fun cancel(): Boolean =
action == null && actions.isNullOrEmpty() && future?.cancel(false) ?: false
fun shouldRetry(airplaneMode: Boolean, info: NetworkInfo?): Boolean {
val hasRetries = retryCount > 0
if (!hasRetries) {
return false
}
retryCount--
return requestHandler.shouldRetry(airplaneMode, info)
}
fun supportsReplay(): Boolean = requestHandler.supportsReplay()
private fun computeNewPriority(): Picasso.Priority {
val hasMultiple = actions?.isNotEmpty() ?: false
val hasAny = action != null || hasMultiple
// Hunter has no requests, low priority.
if (!hasAny) {
return Picasso.Priority.LOW
}
var newPriority = action?.request?.priority ?: Picasso.Priority.LOW
actions?.let { actions ->
// Index-based loop to avoid allocating an iterator.
for (i in actions.indices) {
val priority = actions[i].request.priority
if (priority.ordinal > newPriority.ordinal) {
newPriority = priority
}
}
}
return newPriority
}
companion object {
internal val NAME_BUILDER: ThreadLocal<StringBuilder> = object : ThreadLocal<StringBuilder>() {
override fun initialValue(): StringBuilder = StringBuilder(THREAD_PREFIX)
}
val SEQUENCE_GENERATOR = AtomicInteger()
internal val ERRORING_HANDLER: RequestHandler = object : RequestHandler() {
override fun canHandleRequest(data: Request): Boolean = true
override fun load(picasso: Picasso, request: Request, callback: Callback) {
callback.onError(IllegalStateException("Unrecognized type of request: $request"))
}
}
fun forRequest(
picasso: Picasso,
dispatcher: Dispatcher,
cache: PlatformLruCache,
action: Action
): BitmapHunter {
val request = action.request
val requestHandlers = picasso.requestHandlers
// Index-based loop to avoid allocating an iterator.
for (i in requestHandlers.indices) {
val requestHandler = requestHandlers[i]
if (requestHandler.canHandleRequest(request)) {
return BitmapHunter(picasso, dispatcher, cache, action, requestHandler)
}
}
return BitmapHunter(picasso, dispatcher, cache, action, ERRORING_HANDLER)
}
fun updateThreadName(data: Request) {
val name = data.name
val builder = NAME_BUILDER.get()!!.also {
it.ensureCapacity(THREAD_PREFIX.length + name.length)
it.replace(THREAD_PREFIX.length, it.length, name)
}
Thread.currentThread().name = builder.toString()
}
fun applyTransformations(
picasso: Picasso,
data: Request,
transformations: List<Transformation>,
result: Bitmap
): Bitmap? {
var res = result
for (i in transformations.indices) {
val transformation = transformations[i]
val newResult = try {
val transformedResult = transformation.transform(res)
if (picasso.isLoggingEnabled) {
log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), "from transformations")
}
transformedResult
} catch (e: RuntimeException) {
Picasso.HANDLER.post {
throw RuntimeException(
"Transformation ${transformation.key()} crashed with exception.", e
)
}
return null
}
val bitmap = newResult.bitmap
if (bitmap.isRecycled) {
Picasso.HANDLER.post {
throw IllegalStateException(
"Transformation ${transformation.key()} returned a recycled Bitmap."
)
}
return null
}
res = newResult
}
return res
}
}
}
|
apache-2.0
|
a3049f2a4099b4c96a9f6063d2053da2
| 29.052941 | 99 | 0.664416 | 4.487484 | false | false | false | false |
florent37/Flutter-AssetsAudioPlayer
|
android/src/main/kotlin/com/github/florent37/assets_audio_player/notification/NotificationAction.kt
|
1
|
1356
|
package com.github.florent37.assets_audio_player.notification
import java.io.Serializable
sealed class NotificationAction : Serializable {
companion object {
const val ACTION_STOP = "stop"
const val ACTION_NEXT = "next"
const val ACTION_PREV = "prev"
const val ACTION_TOGGLE = "toggle"
const val ACTION_SELECT = "select"
}
class Show(
val isPlaying: Boolean,
val audioMetas: AudioMetas,
val playerId: String,
val notificationSettings: NotificationSettings,
val durationMs: Long
) : NotificationAction() {
fun copyWith(isPlaying: Boolean? = null,
audioMetas: AudioMetas? = null,
playerId: String? = null,
notificationSettings: NotificationSettings? = null,
durationMs: Long? = null
) : Show{
return Show(
isPlaying= isPlaying ?: this.isPlaying,
audioMetas = audioMetas ?: this.audioMetas,
playerId = playerId ?: this.playerId,
notificationSettings = notificationSettings ?: this.notificationSettings,
durationMs = durationMs ?: this.durationMs
)
}
}
class Hide() : NotificationAction()
}
|
apache-2.0
|
551593cb3e8c0b52b90a8a9b59f20a4c
| 33.769231 | 93 | 0.564159 | 5.557377 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/nullability/NullabilityConstraintsCollector.kt
|
2
|
4170
|
// 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.j2k.post.processing.inference.nullability
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.BoundTypeCalculator
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintBuilder
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.InferenceContext
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.ConstraintsCollector
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.*
class NullabilityConstraintsCollector : ConstraintsCollector() {
override fun ConstraintBuilder.collectConstraints(
element: KtElement,
boundTypeCalculator: BoundTypeCalculator,
inferenceContext: InferenceContext,
resolutionFacade: ResolutionFacade
) {
when {
element is KtBinaryExpression &&
(element.left?.isNullExpression() == true
|| element.right?.isNullExpression() == true) -> {
val notNullOperand =
if (element.left?.isNullExpression() == true) element.right
else element.left
notNullOperand?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.UPPER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.COMPARE_WITH_NULL
)
}
element is KtQualifiedExpression -> {
element.receiverExpression.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
}
element is KtForExpression -> {
element.loopRange?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
}
element is KtWhileExpressionBase -> {
element.condition?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
}
element is KtIfExpression -> {
element.condition?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
}
element is KtValueArgument && element.isSpread -> {
element.getArgumentExpression()?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
}
element is KtBinaryExpression && !KtPsiUtil.isAssignment(element) -> {
element.left?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
element.right?.isTheSameTypeAs(
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER
)
}
}
}
}
|
apache-2.0
|
3be0a26f5dc620ce7e49a7cf056577ff
| 51.1375 | 158 | 0.64988 | 4.826389 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/FunctionalInterfacesConversion.kt
|
2
|
1530
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase
import org.jetbrains.kotlin.nj2k.annotationByFqName
import org.jetbrains.kotlin.nj2k.tree.*
private const val FUNCTIONAL_INTERFACE = "java.lang.FunctionalInterface"
internal class FunctionalInterfacesConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (!context.functionalInterfaceConversionEnabled) return recurse(element)
if (element !is JKClass) return recurse(element)
if (element.classKind != JKClass.ClassKind.INTERFACE) return recurse(element)
if (element.inheritance.extends.isNotEmpty()) return recurse(element)
val functionalInterfaceMarker = element.annotationList.annotationByFqName(FUNCTIONAL_INTERFACE) ?: return recurse(element)
val samMethod = element.classBody.declarations.filterIsInstance<JKMethod>().singleOrNull { it.block is JKBodyStub }
if (samMethod == null || samMethod.typeParameterList.typeParameters.isNotEmpty()) return recurse(element)
element.otherModifierElements += JKOtherModifierElement(OtherModifier.FUN)
element.annotationList.annotations -= functionalInterfaceMarker
return recurse(element)
}
}
|
apache-2.0
|
b68b154ec2600b4b51a9a4aa2582c4a1
| 51.758621 | 130 | 0.787582 | 4.78125 | false | false | false | false |
NiciDieNase/chaosflix
|
common/src/main/java/de/nicidienase/chaosflix/common/mediadata/entities/recording/persistence/ConferenceDao.kt
|
1
|
1602
|
package de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
@Dao
abstract class ConferenceDao : BaseDao<Conference>() {
@Query("SELECT * FROM conference")
abstract fun getAllConferences(): LiveData<List<Conference>>
@Query("SELECT * FROM conference WHERE title LIKE :search")
abstract fun findConferenceByTitle(search: String): LiveData<List<Conference>>
@Query("SELECT * FROM conference WHERE id = :id LIMIT 1")
abstract fun findConferenceById(id: Long): LiveData<Conference>
@Query("SELECT * FROM conference WHERE acronym = :acronym LIMIT 1")
abstract suspend fun findConferenceByAcronym(acronym: String): Conference?
@Query("SELECT * FROM conference WHERE acronym = :acronym LIMIT 1")
abstract suspend fun findConferenceByAcronymSuspend(acronym: String): Conference?
@Query("SELECT * FROM conference WHERE conferenceGroupId = :id ORDER BY acronym DESC")
abstract fun findConferenceByGroup(id: Long): LiveData<List<Conference>>
@Query("DELETE FROM conference")
abstract fun delete()
override suspend fun updateOrInsertInternal(item: Conference): Long {
if (item.id != 0L) {
update(item)
} else {
val existingEvent = findConferenceByAcronym(item.acronym)
if (existingEvent != null) {
item.id = existingEvent.id
update(item)
} else {
item.id = insert(item)
}
}
return item.id
}
}
|
mit
|
721ab746292a66689587f3f8ab4cfabd
| 34.6 | 90 | 0.6804 | 4.603448 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/stories/StorySlateView.kt
|
1
|
4953
|
package org.thoughtcrime.securesms.stories
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.blurhash.BlurHash
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.util.visible
/**
* Displays loading / error slate in Story viewer.
*/
class StorySlateView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
companion object {
private val TAG = Log.tag(StorySlateView::class.java)
}
var callback: Callback? = null
var state: State = State.HIDDEN
private set
private var postId: Long = 0L
init {
inflate(context, R.layout.stories_slate_view, this)
}
private val background: ImageView = findViewById(R.id.background)
private val loadingSpinner: View = findViewById(R.id.loading_spinner)
private val errorCircle: View = findViewById(R.id.error_circle)
private val unavailableText: View = findViewById(R.id.unavailable)
private val errorText: TextView = findViewById(R.id.error_text)
fun moveToState(state: State, postId: Long) {
if (this.state == state && this.postId == postId) {
return
}
if (this.postId != postId) {
this.postId = postId
moveToHiddenState()
callback?.onStateChanged(State.HIDDEN, postId)
}
if (this.state.isValidTransitionTo(state)) {
when (state) {
State.LOADING -> moveToProgressState(State.LOADING)
State.ERROR -> moveToErrorState()
State.RETRY -> moveToProgressState(State.RETRY)
State.NOT_FOUND -> moveToNotFoundState()
State.HIDDEN -> moveToHiddenState()
}
callback?.onStateChanged(state, postId)
} else {
Log.d(TAG, "Invalid state transfer: ${this.state} -> $state")
}
}
fun setBackground(blur: BlurHash?) {
if (blur != null) {
GlideApp.with(background)
.load(blur)
.into(background)
} else {
GlideApp.with(background).clear(background)
}
}
private fun moveToProgressState(state: State) {
this.state = state
visible = true
background.visible = true
loadingSpinner.visible = true
errorCircle.visible = false
unavailableText.visible = false
errorText.visible = false
}
private fun moveToErrorState() {
state = State.ERROR
visible = true
background.visible = true
loadingSpinner.visible = false
errorCircle.visible = true
unavailableText.visible = false
errorText.visible = true
if (NetworkConstraint.isMet(ApplicationDependencies.getApplication())) {
errorText.setText(R.string.StorySlateView__couldnt_load_content)
} else {
errorText.setText(R.string.StorySlateView__no_internet_connection)
}
}
private fun moveToNotFoundState() {
state = State.NOT_FOUND
visible = true
background.visible = true
loadingSpinner.visible = false
errorCircle.visible = false
unavailableText.visible = true
errorText.visible = false
}
private fun moveToHiddenState() {
state = State.HIDDEN
visible = false
}
override fun onSaveInstanceState(): Parcelable {
val rootState = super.onSaveInstanceState()
return Bundle().apply {
putParcelable("ROOT", rootState)
putInt("STATE", state.code)
putLong("ID", postId)
}
}
override fun onRestoreInstanceState(state: Parcelable?) {
if (state is Bundle) {
val rootState: Parcelable? = state.getParcelable("ROOT")
this.state = State.fromCode(state.getInt("STATE", State.HIDDEN.code))
this.postId = state.getLong("ID")
super.onRestoreInstanceState(rootState)
} else {
super.onRestoreInstanceState(state)
}
}
init {
errorCircle.setOnClickListener { moveToState(State.RETRY, postId) }
}
interface Callback {
fun onStateChanged(state: State, postId: Long)
}
enum class State(val code: Int) {
LOADING(0),
ERROR(1),
RETRY(2),
NOT_FOUND(3),
HIDDEN(4);
fun isValidTransitionTo(newState: State): Boolean {
if (newState in listOf(HIDDEN, NOT_FOUND)) {
return true
}
if (newState == this) {
return true
}
return when (this) {
LOADING -> newState == ERROR
ERROR -> newState == RETRY
RETRY -> newState == ERROR
HIDDEN -> newState == LOADING
else -> false
}
}
companion object {
fun fromCode(code: Int): State {
return values().firstOrNull {
it.code == code
} ?: HIDDEN
}
}
}
}
|
gpl-3.0
|
3af79071348cfffd5fd29733f5a65b44
| 25.629032 | 76 | 0.67656 | 4.229718 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-plugins/ktor-server-resources/jvmAndNix/src/io/ktor/server/resources/Routing.kt
|
1
|
6987
|
/*
* 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.server.resources
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.routing.*
import io.ktor.util.*
import io.ktor.util.pipeline.*
import kotlinx.serialization.*
/**
* Registers a route [body] for a resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*/
public inline fun <reified T : Any> Route.resource(noinline body: Route.() -> Unit): Route {
val serializer = serializer<T>()
return resource(serializer, body)
}
/**
* Registers a typed handler [body] for a `GET` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.get(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Get) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a typed handler [body] for a `OPTIONS` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.options(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Options) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a typed handler [body] for a `HEAD` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.head(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Head) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a typed handler [body] for a `POST` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.post(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Post) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a typed handler [body] for a `PUT` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.put(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Put) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a typed handler [body] for a `DELETE` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.delete(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Delete) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a typed handler [body] for a `PATCH` resource defined by the [T] class.
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.patch(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
): Route {
lateinit var builtRoute: Route
resource<T> {
builtRoute = method(HttpMethod.Patch) {
handle(body)
}
}
return builtRoute
}
/**
* Registers a handler [body] for a resource defined by the [T] class.
*
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public inline fun <reified T : Any> Route.handle(
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
) {
val serializer = serializer<T>()
handle(serializer, body)
}
@PublishedApi
internal val ResourceInstanceKey: AttributeKey<Any> = AttributeKey("ResourceInstance")
/**
* Registers a route [body] for a resource defined by the [T] class.
*
* @param serializer is used to decode the parameters of the request to an instance of the typed resource [T].
*
* A class [T] **must** be annotated with [io.ktor.resources.Resource].
*/
public fun <T : Any> Route.resource(
serializer: KSerializer<T>,
body: Route.() -> Unit
): Route {
val resources = application.plugin(Resources)
val path = resources.resourcesFormat.encodeToPathPattern(serializer)
val queryParameters = resources.resourcesFormat.encodeToQueryParameters(serializer)
val route = createRouteFromPath(path)
return queryParameters.fold(route) { entry, query ->
val selector = if (query.isOptional) {
OptionalParameterRouteSelector(query.name)
} else {
ParameterRouteSelector(query.name)
}
entry.createChild(selector)
}.apply(body)
}
/**
* Registers a handler [body] for a resource defined by the [T] class.
*
* @param serializer is used to decode the parameters of the request to an instance of the typed resource [T].
* @param body receives an instance of the typed resource [T] as the first parameter.
*/
public fun <T : Any> Route.handle(
serializer: KSerializer<T>,
body: suspend PipelineContext<Unit, ApplicationCall>.(T) -> Unit
) {
intercept(ApplicationCallPipeline.Plugins) {
val resources = application.plugin(Resources)
try {
val resource = resources.resourcesFormat.decodeFromParameters(serializer, call.parameters)
call.attributes.put(ResourceInstanceKey, resource)
} catch (cause: Throwable) {
throw BadRequestException("Can't transform call to resource", cause)
}
}
handle {
@Suppress("UNCHECKED_CAST")
val resource = call.attributes[ResourceInstanceKey] as T
body(resource)
}
}
|
apache-2.0
|
f11725f89ff847efce014a30ce5d18cb
| 30.191964 | 119 | 0.669672 | 3.949689 | false | false | false | false |
ClearVolume/scenery
|
src/main/kotlin/graphics/scenery/utils/SceneryJPanel.kt
|
2
|
2177
|
package graphics.scenery.utils
import cleargl.ClearGLWindow
import graphics.scenery.backends.ResizeHandler
import graphics.scenery.backends.SceneryWindow
import java.awt.Component
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.nio.ByteBuffer
import javax.swing.JPanel
/**
* Swing panel scenery can be embedded into.
*
* @author Ulrik Guenther <[email protected]>
*/
class SceneryJPanel : JPanel(), SceneryPanel {
/** Refresh rate. */
override var refreshRate: Int = 60
/** Updates the backing buffer of the window. Does nothing for Swing. */
override fun update(buffer: ByteBuffer, id: Int) { }
private val logger by LazyLogger()
/** Width of the panel, cannot be reset. */
@Suppress("UNUSED_PARAMETER")
override var panelWidth: Int
get() = super.getWidth()
set(value) {}
/** Height of the panel, cannot be reset. */
@Suppress("UNUSED_PARAMETER")
override var panelHeight: Int
get() = super.getHeight()
set(value) { }
/** Embedded component that receives the actual rendering, e.g. via a native surface. */
var component: Component? = null
/** [ClearGLWindow] the [OpenGLRenderer] is rendering to. */
var cglWindow: ClearGLWindow? = null
/** Displayed frames so far. */
override var displayedFrames: Long = 0L
/** Image scale, no flipping needed here. */
override var imageScaleY: Float = 1.0f
/** Sets the preferred dimensions of the panel. */
override fun setPreferredDimensions(w: Int, h: Int) {
logger.info("Preferred dimensions=$w,$h")
}
override fun init(resizeHandler : ResizeHandler) : SceneryWindow {
this.addComponentListener(object: ComponentAdapter() {
override fun componentResized(e: ComponentEvent) {
super.componentResized(e)
logger.debug("SceneryJPanel component resized to ${e.component.width} ${e.component.height}")
resizeHandler.lastWidth = e.component.width
resizeHandler.lastHeight = e.component.height
}
})
return SceneryWindow.SwingWindow(this)
}
}
|
lgpl-3.0
|
f7e5a7a0de454eb4ae2b32d457ed7849
| 31.492537 | 109 | 0.670188 | 4.389113 | false | false | false | false |
iSoron/uhabits
|
uhabits-core-legacy/src/main/jvm/org/isoron/platform/gui/JavaCanvas.kt
|
1
|
5654
|
/*
* Copyright (C) 2016-2019 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.platform.gui
import kotlinx.coroutines.*
import org.isoron.platform.io.*
import java.awt.*
import java.awt.RenderingHints.*
import java.awt.font.*
import java.awt.image.*
import kotlin.math.*
class JavaCanvas(val image: BufferedImage,
val pixelScale: Double = 2.0) : Canvas {
override fun toImage(): Image {
return JavaImage(image)
}
private val frc = FontRenderContext(null, true, true)
private var fontSize = 12.0
private var font = Font.REGULAR
private var textAlign = TextAlign.CENTER
val widthPx = image.width
val heightPx = image.height
val g2d = image.createGraphics()
private val NOTO_REGULAR_FONT = createFont("fonts/NotoSans-Regular.ttf")
private val NOTO_BOLD_FONT = createFont("fonts/NotoSans-Bold.ttf")
private val FONT_AWESOME_FONT = createFont("fonts/FontAwesome.ttf")
init {
g2d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(KEY_FRACTIONALMETRICS, VALUE_FRACTIONALMETRICS_ON);
updateFont()
}
private fun toPixel(x: Double): Int {
return (pixelScale * x).toInt()
}
private fun toDp(x: Int): Double {
return x / pixelScale
}
override fun setColor(color: Color) {
g2d.color = java.awt.Color(color.red.toFloat(),
color.green.toFloat(),
color.blue.toFloat(),
color.alpha.toFloat())
}
override fun drawLine(x1: Double, y1: Double, x2: Double, y2: Double) {
g2d.drawLine(toPixel(x1), toPixel(y1), toPixel(x2), toPixel(y2))
}
override fun drawText(text: String, x: Double, y: Double) {
updateFont()
val bounds = g2d.font.getStringBounds(text, frc)
val bWidth = bounds.width.roundToInt()
val bHeight = bounds.height.roundToInt()
val bx = bounds.x.roundToInt()
val by = bounds.y.roundToInt()
if (textAlign == TextAlign.CENTER) {
g2d.drawString(text,
toPixel(x) - bx - bWidth / 2,
toPixel(y) - by - bHeight / 2)
} else if (textAlign == TextAlign.LEFT) {
g2d.drawString(text,
toPixel(x) - bx,
toPixel(y) - by - bHeight / 2)
} else {
g2d.drawString(text,
toPixel(x) - bx - bWidth,
toPixel(y) - by - bHeight / 2)
}
}
override fun fillRect(x: Double, y: Double, width: Double, height: Double) {
g2d.fillRect(toPixel(x), toPixel(y), toPixel(width), toPixel(height))
}
override fun drawRect(x: Double, y: Double, width: Double, height: Double) {
g2d.drawRect(toPixel(x), toPixel(y), toPixel(width), toPixel(height))
}
override fun getHeight(): Double {
return toDp(heightPx)
}
override fun getWidth(): Double {
return toDp(widthPx)
}
override fun setFont(font: Font) {
this.font = font
updateFont()
}
override fun setFontSize(size: Double) {
fontSize = size
updateFont()
}
override fun setStrokeWidth(size: Double) {
g2d.stroke = BasicStroke((size * pixelScale).toFloat())
}
private fun updateFont() {
val size = (fontSize * pixelScale).toFloat()
g2d.font = when (font) {
Font.REGULAR -> NOTO_REGULAR_FONT.deriveFont(size)
Font.BOLD -> NOTO_BOLD_FONT.deriveFont(size)
Font.FONT_AWESOME -> FONT_AWESOME_FONT.deriveFont(size)
}
}
override fun fillCircle(centerX: Double, centerY: Double, radius: Double) {
g2d.fillOval(toPixel(centerX - radius),
toPixel(centerY - radius),
toPixel(radius * 2),
toPixel(radius * 2))
}
override fun fillArc(centerX: Double,
centerY: Double,
radius: Double,
startAngle: Double,
swipeAngle: Double) {
g2d.fillArc(toPixel(centerX - radius),
toPixel(centerY - radius),
toPixel(radius * 2),
toPixel(radius * 2),
startAngle.roundToInt(),
swipeAngle.roundToInt())
}
override fun setTextAlign(align: TextAlign) {
this.textAlign = align
}
private fun createFont(path: String) = runBlocking<java.awt.Font> {
val file = JavaFileOpener().openResourceFile(path) as JavaResourceFile
if (!file.exists()) throw RuntimeException("File not found: ${file.path}")
java.awt.Font.createFont(0, file.stream())
}
}
|
gpl-3.0
|
a4619464cf2b5fb36bcad6aa05e78a67
| 32.654762 | 82 | 0.593313 | 4.090449 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/GroovyElementActionsFactory.kt
|
19
|
2674
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator.intentions.elements
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateConstructorRequest
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.CreateMethodRequest
import com.intellij.lang.jvm.actions.JvmElementActionsFactory
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiModifier
class GroovyElementActionsFactory : JvmElementActionsFactory() {
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val groovyClass = targetClass.toGroovyClassOrNull() ?: return emptyList()
val constantRequested = request.isConstant || javaClass.isInterface || request.modifiers.containsAll(constantModifiers)
val result = ArrayList<IntentionAction>()
if (constantRequested || StringUtil.isCapitalized(request.fieldName)) {
result += CreateFieldAction(groovyClass, request, true)
}
if (!constantRequested) {
result += CreateFieldAction(groovyClass, request, false)
}
if (canCreateEnumConstant(groovyClass, request)) {
result += CreateEnumConstantAction(groovyClass, request)
}
return result
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val groovyClass = targetClass.toGroovyClassOrNull() ?: return emptyList()
val requestedModifiers = request.modifiers
val staticMethodRequested = JvmModifier.STATIC in requestedModifiers
val result = ArrayList<IntentionAction>()
if (groovyClass.isInterface) {
return if (staticMethodRequested) emptyList() else listOf(CreateMethodAction(groovyClass, request, true))
} else {
result += CreatePropertyAction(groovyClass, request, true)
result += CreatePropertyAction(groovyClass, request, false)
}
result += CreateMethodAction(groovyClass, request, false)
if (!staticMethodRequested && groovyClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
result += CreateMethodAction(groovyClass, request, true)
}
return result
}
override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> {
val groovyClass = targetClass.toGroovyClassOrNull() ?: return emptyList()
return listOf(CreateConstructorAction(groovyClass, request))
}
}
|
apache-2.0
|
a39db1d07f009de7de68c3720005e2fb
| 43.566667 | 140 | 0.776739 | 4.809353 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/projectRootUtils.kt
|
4
|
7120
|
// 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.roots
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.project.ContentRootData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.NonPhysicalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiCodeFragment
import com.intellij.psi.PsiFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.URLUtil
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.ex.JpsElementBase
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.idea.util.KOTLIN_AWARE_SOURCE_ROOT_TYPES
private fun JpsModuleSourceRoot.getOrCreateProperties() =
getProperties(rootType)?.also { (it as? JpsElementBase<*>)?.setParent(null) } ?: rootType.createDefaultProperties()
fun JpsModuleSourceRoot.getMigratedSourceRootTypeWithProperties(): Pair<JpsModuleSourceRootType<JpsElement>, JpsElement>? {
val currentRootType = rootType
@Suppress("UNCHECKED_CAST")
val newSourceRootType: JpsModuleSourceRootType<JpsElement> = when (currentRootType) {
JavaSourceRootType.SOURCE -> SourceKotlinRootType as JpsModuleSourceRootType<JpsElement>
JavaSourceRootType.TEST_SOURCE -> TestSourceKotlinRootType
JavaResourceRootType.RESOURCE -> ResourceKotlinRootType
JavaResourceRootType.TEST_RESOURCE -> TestResourceKotlinRootType
else -> return null
} as JpsModuleSourceRootType<JpsElement>
return newSourceRootType to getOrCreateProperties()
}
fun migrateNonJvmSourceFolders(modifiableRootModel: ModifiableRootModel) {
for (contentEntry in modifiableRootModel.contentEntries) {
for (sourceFolder in contentEntry.sourceFolders) {
val (newSourceRootType, properties) = sourceFolder.jpsElement.getMigratedSourceRootTypeWithProperties() ?: continue
val url = sourceFolder.url
contentEntry.removeSourceFolder(sourceFolder)
contentEntry.addSourceFolder(url, newSourceRootType, properties)
}
}
KotlinSdkType.setUpIfNeeded()
}
@IntellijInternalApi
val ContentRootData.SourceRoot.pathAsUrl
get() = VirtualFileManager.constructUrl(URLUtil.FILE_PROTOCOL, FileUtil.toSystemIndependentName(path))
fun getKotlinAwareDestinationSourceRoots(project: Project): List<VirtualFile> {
return ModuleManager.getInstance(project).modules.flatMap { it.collectKotlinAwareDestinationSourceRoots() }
}
fun Module.collectKotlinAwareDestinationSourceRoots(): List<VirtualFile> {
return rootManager
.contentEntries
.asSequence()
.flatMap { it.getSourceFolders(KOTLIN_AWARE_SOURCE_ROOT_TYPES).asSequence() }
.filterNot { isForGeneratedSources(it) }
.mapNotNull { it.file }
.toList()
}
fun isOutsideSourceRootSet(psiFile: PsiFile?, sourceRootTypes: Set<JpsModuleSourceRootType<*>>): Boolean {
if (psiFile == null || psiFile is PsiCodeFragment) return false
val file = psiFile.virtualFile ?: return false
if (file.fileSystem is NonPhysicalFileSystem) return false
val projectFileIndex = ProjectRootManager.getInstance(psiFile.project).fileIndex
return !projectFileIndex.isUnderSourceRootOfType(file, sourceRootTypes) && !projectFileIndex.isInLibrary(file)
}
fun isOutsideKotlinAwareSourceRoot(psiFile: PsiFile?) = isOutsideSourceRootSet(psiFile, KOTLIN_AWARE_SOURCE_ROOT_TYPES)
/**
* @return list of all java source roots in the project which can be suggested as a target directory for a class created by user
*/
fun getSuitableDestinationSourceRoots(project: Project): List<VirtualFile> {
val roots = ArrayList<VirtualFile>()
for (module in ModuleManager.getInstance(project).modules) {
collectSuitableDestinationSourceRoots(module, roots)
}
return roots
}
fun getSuitableDestinationSourceRoots(module: Module): MutableList<VirtualFile> {
val roots = ArrayList<VirtualFile>()
collectSuitableDestinationSourceRoots(module, roots)
return roots
}
fun collectSuitableDestinationSourceRoots(module: Module, result: MutableList<VirtualFile>) {
for (entry in ModuleRootManager.getInstance(module).contentEntries) {
for (sourceFolder in entry.getSourceFolders(KOTLIN_AWARE_SOURCE_ROOT_TYPES)) {
if (!isForGeneratedSources(sourceFolder)) {
ContainerUtil.addIfNotNull(result, sourceFolder.file)
}
}
}
}
fun isForGeneratedSources(sourceFolder: SourceFolder): Boolean {
val properties = sourceFolder.jpsElement.getProperties(KOTLIN_AWARE_SOURCE_ROOT_TYPES)
val javaResourceProperties = sourceFolder.jpsElement.getProperties(JavaModuleSourceRootTypes.RESOURCES)
val kotlinResourceProperties = sourceFolder.jpsElement.getProperties(ALL_KOTLIN_RESOURCE_ROOT_TYPES)
return properties != null && properties.isForGeneratedSources
|| (javaResourceProperties != null && javaResourceProperties.isForGeneratedSources)
|| (kotlinResourceProperties != null && kotlinResourceProperties.isForGeneratedSources)
}
class NodeWithData<T>(val node: DataNode<*>, val data: T)
fun <T : Any> DataNode<*>.findAll(key: Key<T>): List<NodeWithData<T>> {
val nodes = ExternalSystemApiUtil.findAll(this, key)
return nodes.mapNotNull {
val data = it.getData(key) ?: return@mapNotNull null
NodeWithData(it, data)
}
}
fun findGradleProjectStructure(file: PsiFile) =
ModuleUtilCore.findModuleForFile(file.virtualFile, file.project)?.let { findGradleProjectStructure(it) }
fun findGradleProjectStructure(module: Module): DataNode<ProjectData>? {
val externalProjectPath = ExternalSystemApiUtil.getExternalProjectPath(module) ?: return null
val projectInfo = ExternalSystemUtil.getExternalProjectInfo(module.project, GRADLE_SYSTEM_ID, externalProjectPath) ?: return null
return projectInfo.externalProjectStructure
}
|
apache-2.0
|
b02defce4b24a1a9081ceffb09e4304b
| 47.114865 | 158 | 0.7875 | 4.906961 | false | false | false | false |
JonathanxD/CodeAPI
|
src/main/kotlin/com/github/jonathanxd/kores/inspect/IfExpressionInspect.kt
|
1
|
7236
|
/*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* 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.github.jonathanxd.kores.inspect
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.base.IfExpr
import com.github.jonathanxd.kores.base.IfExpressionHolder
import com.github.jonathanxd.kores.base.IfGroup
import com.github.jonathanxd.kores.literal.Literal
import com.github.jonathanxd.kores.literal.Literals
import com.github.jonathanxd.kores.operator.Operator
import com.github.jonathanxd.kores.operator.Operators
import com.github.jonathanxd.iutils.annotation.Wip
/**
* Returns `true` if the body is only reached when [matched][matcher] [Instruction] returns `true`.
*
* **The `receiver` list must contains entirely expressions of if statement.**
*
* Examples:
*
* ```
* if (x == y && (x % 2 == 0 || x == 3))
* ```
*
* - [alwaysBranch] returns `true` for `x == y` because whenever the body of the flow is reached, `x` is equal to `y`.
* - [alwaysBranch] returns `false` for `x % 2 == 0` because when the body of flow is reached,
* `x % 2 == 0` may or may not be `true`, the same condition applies to `x == 3`.
*
*
* An example of where this function can be useful:
*
* ```
* if (a instanceof AccountManager) { body }
* ```
*
* You can use this function to ensures that `a instanceof AccountManager` is always true when `body` is reached
* to allow smart casting of `a` to `AccountManager` (inside the body).
*/
@Wip
fun List<Instruction>.alwaysBranch(matcher: (Instruction) -> Boolean): Boolean {
var found = false
for (i in this) {
val i2 = i.removeRedundantNot()
if (!found && matcher(i2)) {
found = true
}
// Always keep this logic:
// never reaches the `if (!found)` (code below) if any `operator != Operators.AND`
// Or changes the logic of `if (!found)`
if (i is Operator && i != Operators.AND) {
return false
}
}
if (!found) {
for (i in this) {
if (i is IfGroup) {
if (i.alwaysBranch(matcher))
return true
}
}
}
return found
}
/**
* @see alwaysBranch
*/
@Wip
fun IfExpressionHolder.alwaysBranch(matcher: (Instruction) -> Boolean) =
this.expressions.alwaysBranch(matcher)
/**
* Removes redundant not check.
*/
fun List<Instruction>.removeRedundantNot(): List<Instruction> =
this.map { it.removeRedundantNot() }
/**
* Returns `true` if `receiver` [IfExpr] is a check of [Instruction] equality to `true` constant.
*/
fun IfExpr.isCheckTrue() = this.getRuntimeBooleanEqCheck()?.booleanConstant == true
/**
* Returns `true` if `receiver` [IfExpr] is a check of [Instruction] equality to `false` constant.
*/
fun IfExpr.isCheckFalse() = this.getRuntimeBooleanEqCheck()?.booleanConstant == false
/**
* Returns `true` if `receiver` [IfExpr] is a check of [instruction][Instruction] equality to `true` constant
* and [predicate] returns true for the [instruction][Instruction].
*/
inline fun IfExpr.isCheckTrueAnd(predicate: (Instruction) -> Boolean) =
this.getRuntimeBooleanEqCheck()?.let { (ins, _, const) -> const && predicate(ins) } ?: false
/**
* Returns `true` if `receiver` [IfExpr] is a check of [instruction][Instruction] equality to `false` constant
* and [predicate] returns true for the [instruction][Instruction].
*/
inline fun IfExpr.isCheckFalseAnd(predicate: (Instruction) -> Boolean) =
this.getRuntimeBooleanEqCheck()?.let { (ins, _, const) -> const && predicate(ins) } ?: false
/**
* Removes redundant not check.
*/
fun Instruction.removeRedundantNot(): Instruction =
(this as? IfExpr)?.removeRedundantNot() ?: this
/**
* Removes redundant not check. Example `if (!(!a))` is simplified to `if (a)`
*/
fun IfExpr.removeRedundantNot(): IfExpr =
this.getRuntimeBooleanEqCheck()?.let { (expr, _, const) ->
val ifGpExprBConst = when (expr) {
is IfGroup -> (expr.expressions.singleOrNull() as? IfExpr)?.getRuntimeBooleanEqCheck()
is IfExpr -> expr.getRuntimeBooleanEqCheck()
else -> null
}
if (ifGpExprBConst != null) {
val (xp, _, const2) = ifGpExprBConst
val value = const == const2
return@let this.builder()
.expr1(xp.removeRedundantNot())
.operation(Operators.EQUAL_TO)
.expr2(Literals.BOOLEAN(value))
.build()
}
return@let this
} ?: this
/**
* Gets the runtime [Boolean] value that [IfExpr] check equality to. Returns `null` if [IfExpr] does not check
* [Instruction] against a boolean.
*/
fun IfExpr.getRuntimeBooleanEqCheck(): EqCheck? {
val constant = (this.expr1 as? Literal) ?: (this.expr2 as? Literal)
val expr2 = if (this.expr2 == constant) this.expr1 else this.expr2
val op = this.operation
if (op != Operators.NOT_EQUAL_TO && op != Operators.EQUAL_TO)
return null
if (constant != null && (constant.value == "true" || constant.value == "false")) {
val bConstant = ((constant.value as String).toBoolean())
val boolValue =
if (op == Operators.NOT_EQUAL_TO) !bConstant
else bConstant
return EqCheck(expr2, op, boolValue)
}
return null
}
/**
* Data class to hold equality check against a boolean constant.
*
* @property instruction Instruction to check if is equal to [booleanConstant]
* @property operator Operator used in [IfExpr] to denote the comparison, does not have any direct
* relation to comparison against [booleanConstant].
* @property booleanConstant Boolean constant to compare to, does not have any direct relation to [operator].
*/
data class EqCheck(
val instruction: Instruction,
val operator: Operator,
val booleanConstant: Boolean
)
|
mit
|
d85fd4a0a83fc1c2fd79f54a1189e13b
| 34.131068 | 118 | 0.662797 | 3.980198 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/features/scoreboard/ScoreboardConfiguration.kt
|
1
|
879
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.features.scoreboard
data class ScoreboardConfiguration(
var showTitle: Boolean = false,
var showProperties: Boolean = false,
var showTable: Boolean = false,
var showStatistics: Boolean = false,
var showComments: Boolean = false,
var showPointsColored: Boolean = false,
var showSignature: Boolean = false
)
|
gpl-2.0
|
43ad23f13f554b47adb91c5123357313
| 32.807692 | 68 | 0.740614 | 4.417085 | false | false | false | false |
kurtyan/fanfou4j
|
src/main/java/com/github/kurtyan/fanfou4j/http/SimpleHttpClient.kt
|
1
|
2200
|
package com.github.kurtyan.fanfou4j.http
import com.github.kurtyan.fanfou4j.exception.FanfouClientException
import java.io.Reader
import java.net.HttpURLConnection
import java.net.URL
/**
* A simple http client written in pure java, based on java.net.URLConnection.
* At this time, http methods other than 'POST with urlencoded form' are not implemented because they are not necessary in this project.
* Created by kurtyan on 16-2-26.
*/
class SimpleHttpClient(private val charset: String = "utf-8", private val authenticator: Authenticator? = null) {
fun <T> get(url: String, query: Map<String, String>, responseParser: (Reader) -> T): T {
val finalUrl = "${url}?${buildQueryString(query)}"
val conn = URL(finalUrl).openConnection() as HttpURLConnection
authenticator?.auth(conn)
conn.doOutput = false
conn.requestMethod = "GET"
return parseResponse(conn, responseParser)
}
fun <T> post(url: String, form: Map<String, String>, responseParser: (Reader) -> T): T {
val queryString = this.buildQueryString(form)
val conn = URL(url).openConnection() as HttpURLConnection
authenticator?.auth(conn)
conn.doOutput = true
conn.requestMethod = "POST"
conn.setRequestProperty("Accept-Charset", charset)
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset)
conn.outputStream.bufferedWriter(charset(charset)).use {
it.write(queryString)
it.flush()
}
return parseResponse(conn, responseParser)
}
private fun <T> parseResponse(conn: HttpURLConnection, parser: (Reader) -> T): T {
try {
val reader = conn.inputStream.bufferedReader(charset(charset))
return parser.invoke(reader)
} catch (e: Exception) {
val text = conn.errorStream.bufferedReader(charset(charset)).readText()
throw FanfouClientException(conn.responseCode, text, e)
}
}
private fun buildQueryString(form: Map<String, String>): String {
return form.entries.map { "${it.key}=${it.value}" }.joinToString(separator = "&")
}
}
|
mit
|
8facf5741d6303a5bab4ad78f11a4349
| 35.065574 | 136 | 0.666818 | 4.296875 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/asset/PlatformAssets.kt
|
1
|
2292
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.asset
@Suppress("unused")
object PlatformAssets : Assets() {
val MINECRAFT_ICON = loadIcon("/assets/icons/platform/Minecraft.png")
val MINECRAFT_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val BUKKIT_ICON = loadIcon("/assets/icons/platform/Bukkit.png")
val BUKKIT_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPIGOT_ICON = loadIcon("/assets/icons/platform/Spigot.png")
val SPIGOT_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val PAPER_ICON = loadIcon("/assets/icons/platform/Paper.png")
val PAPER_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val FORGE_ICON = loadIcon("/assets/icons/platform/Forge.png")
val FORGE_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPONGE_ICON = loadIcon("/assets/icons/platform/Sponge.png")
val SPONGE_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPONGE_ICON_DARK = loadIcon("/assets/icons/platform/Sponge_dark.png")
val SPONGE_ICON_2X_DARK = loadIcon("/assets/icons/platform/Sponge@2x_dark.png")
val BUNGEECORD_ICON = loadIcon("/assets/icons/platform/BungeeCord.png")
val BUNGEECORD_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val WATERFALL_ICON = loadIcon("/assets/icons/platform/Waterfall.png")
val WATERFALL_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val LITELOADER_ICON = loadIcon("/assets/icons/platform/LiteLoader.png")
val LITELOADER_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val MIXIN_ICON = loadIcon("/assets/icons/platform/Mixins.png")
val MIXIN_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val MIXIN_ICON_DARK = loadIcon("/assets/icons/platform/Mixins_dark.png")
val MIXIN_ICON_2X_DARK = loadIcon("/assets/icons/platform/Mixins@2x_dark.png")
val MCP_ICON = loadIcon("/assets/icons/platform/MCP.png")
val MCP_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val MCP_ICON_DARK = loadIcon("/assets/icons/platform/MCP_dark.png")
val MCP_ICON_2X_DARK = loadIcon("/assets/icons/platform/MCP@2x_dark.png")
}
|
mit
|
b6d4c0f6a1a527316f9d24adf026e763
| 44.84 | 83 | 0.716841 | 3.187761 | false | false | false | false |
vladmm/intellij-community
|
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/ExecutionStackImpl.kt
|
1
|
3214
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.frame
import com.intellij.xdebugger.frame.XExecutionStack
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.settings.XDebuggerSettingsManager
import org.jetbrains.debugger.DebuggerViewSupport
import org.jetbrains.debugger.Script
import org.jetbrains.debugger.SuspendContext
import org.jetbrains.debugger.done
import java.util.*
internal class ExecutionStackImpl(private val suspendContext: SuspendContext, private val viewSupport: DebuggerViewSupport, private val topFrameScript: Script?) : XExecutionStack("") {
private var topCallFrameView: CallFrameView? = null
override fun getTopFrame(): CallFrameView? {
val topCallFrame = suspendContext.topFrame
if (topCallFrameView == null || topCallFrameView!!.callFrame != topCallFrame) {
topCallFrameView = if (topCallFrame == null) null else CallFrameView(topCallFrame, viewSupport, topFrameScript)
}
return topCallFrameView
}
override fun computeStackFrames(firstFrameIndex: Int, container: XExecutionStack.XStackFrameContainer) {
val suspendContext = viewSupport.vm!!.suspendContextManager.context ?: return
// WipSuspendContextManager set context to null on resume _before_ vm.getDebugListener().resumed() call() (in any case, XFramesView can queue event to EDT), so, IDE state could be outdated compare to VM (our) state
suspendContext.frames
.done(suspendContext) { frames ->
val count = frames.size - firstFrameIndex
val result: List<XStackFrame>
if (count < 1) {
result = emptyList()
}
else {
result = ArrayList<XStackFrame>(count)
for (i in firstFrameIndex..frames.size - 1) {
if (i == 0) {
result.add(topFrame!!)
continue
}
val frame = frames[i]
// if script is null, it is native function (Object.forEach for example), so, skip it
val script = suspendContext.valueManager.vm.scriptManager.getScript(frame)
if (script != null) {
val sourceInfo = viewSupport.getSourceInfo(script, frame)
val isInLibraryContent = sourceInfo != null && viewSupport.isInLibraryContent(sourceInfo, script)
if (isInLibraryContent && !XDebuggerSettingsManager.getInstance().dataViewSettings.isShowLibraryStackFrames) {
continue
}
result.add(CallFrameView(frame, viewSupport, script, sourceInfo, isInLibraryContent))
}
}
}
container.addStackFrames(result, true)
}
}
}
|
apache-2.0
|
2f2df78b43cfe4e647e5a08b5793012d
| 43.041096 | 218 | 0.701929 | 4.884498 | false | false | false | false |
google/intellij-community
|
plugins/gradle/java/src/config/GradleUseScopeEnlarger.kt
|
2
|
4594
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.config
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.*
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.UseScopeEnlarger
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.Processor
import com.intellij.util.castSafelyTo
import org.gradle.initialization.BuildLayoutParameters
import org.jetbrains.plugins.gradle.service.GradleBuildClasspathManager
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.nio.file.Path
/**
* @author Vladislav.Soroka
*/
class GradleUseScopeEnlarger : UseScopeEnlarger() {
override fun getAdditionalUseScope(element: PsiElement): SearchScope? {
return try {
getScope(element)
}
catch (e: IndexNotReadyException) {
null
}
}
companion object {
private fun getScope(element: PsiElement): SearchScope? {
val virtualFile = PsiUtilCore.getVirtualFile(element.containingFile) ?: return null
val project = element.project
if (!isInBuildSrc(project, virtualFile) && !isInGradleDistribution(project, virtualFile)) return null
return object : GlobalSearchScope(element.project) {
override fun contains(file: VirtualFile): Boolean {
return GradleConstants.EXTENSION == file.extension || file.name.endsWith(GradleConstants.KOTLIN_DSL_SCRIPT_EXTENSION)
}
override fun isSearchInModuleContent(aModule: Module) = true
override fun isSearchInLibraries() = false
}
}
private fun isInGradleDistribution(project: Project, file: VirtualFile) : Boolean {
val actualPath = file.fileSystem.castSafelyTo<JarFileSystem>()?.getLocalByEntry(file) ?: file
val paths : MutableList<String?> = mutableListOf(BuildLayoutParameters().gradleUserHomeDir.path)
val settings = GradleSettings.getInstance(project).linkedProjectsSettings
for (linkedProjectSettings in settings) {
paths.add(linkedProjectSettings.gradleHome)
}
for (distributionPath in paths.filterNotNull()) {
val distributionDir = VirtualFileManager.getInstance().findFileByNioPath(Path.of(distributionPath)) ?: continue
if (VfsUtil.isAncestor(distributionDir, actualPath, false)) {
return true
}
}
return false
}
private fun isInBuildSrc(project: Project, file: VirtualFile) : Boolean {
val fileIndex = ProjectRootManager.getInstance(project).fileIndex
val module = fileIndex.getModuleForFile(file) ?: return false
if (!isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, module)) {
return false
}
val rootProjectPath = getExternalRootProjectPath(module) ?: return false
return isApplicable(project, module, rootProjectPath, file, fileIndex)
}
private fun isApplicable(project: Project,
module: Module,
rootProjectPath: String,
virtualFile: VirtualFile,
fileIndex: ProjectFileIndex): Boolean {
val projectPath = getExternalProjectPath(module) ?: return false
if (projectPath.endsWith("/buildSrc")) return true
val sourceRoot = fileIndex.getSourceRootForFile(virtualFile)
return sourceRoot in GradleBuildClasspathManager.getInstance(project).getModuleClasspathEntries(rootProjectPath)
}
fun search(element: PsiMember, consumer: Processor<PsiReference>) {
val scope: SearchScope = ReadAction.compute<SearchScope, RuntimeException> { getScope(element) } ?: return
val newParams = ReferencesSearch.SearchParameters(element, scope, true)
ReferencesSearch.search(newParams).forEach(consumer)
}
}
}
|
apache-2.0
|
12208bb329cbfeef2cef0a999296285d
| 42.752381 | 127 | 0.747061 | 4.971861 | false | false | false | false |
allotria/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/data/index/IndexedDetails.kt
|
3
|
3143
|
// 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.vcs.log.data.index
import com.intellij.openapi.util.NlsSafe
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsLogObjectsFactory
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.data.LoadingDetails
import com.intellij.vcs.log.data.VcsLogStorage
class IndexedDetails(private val dataGetter: IndexDataGetter,
storage: VcsLogStorage,
private val commitIndex: Int,
loadingTaskIndex: Long) : LoadingDetails({ storage.getCommitId(commitIndex) }, loadingTaskIndex) {
private val _parents by lazy { dataGetter.getParents(commitIndex) }
private val _author by lazy { dataGetter.getAuthor(commitIndex) }
private val _committer by lazy { dataGetter.getCommitter(commitIndex) }
private val _authorTime by lazy { dataGetter.getAuthorTime(commitIndex) }
private val _commitTime by lazy { dataGetter.getCommitTime(commitIndex) }
private val _fullMessage by lazy { dataGetter.getFullMessage(commitIndex) }
override fun getFullMessage(): String {
return _fullMessage ?: super.getFullMessage()
}
override fun getSubject(): String {
return _fullMessage?.let { getSubject(it) } ?: super.getSubject()
}
override fun getParents(): List<Hash> {
return _parents ?: super.getParents()
}
override fun getAuthor(): VcsUser {
return _author ?: super.getAuthor()
}
override fun getCommitter(): VcsUser {
return _committer ?: super.getCommitter()
}
override fun getAuthorTime(): Long {
return _authorTime ?: super.getAuthorTime()
}
override fun getCommitTime(): Long {
return _commitTime ?: super.getCommitTime()
}
companion object {
@JvmStatic
@NlsSafe
fun getSubject(fullMessage: String): String {
val subjectEnd = fullMessage.indexOf("\n\n")
return if (subjectEnd > 0) fullMessage.substring(0, subjectEnd).replace("\n", " ") else fullMessage.replace("\n", " ")
}
@JvmStatic
fun createMetadata(commitIndex: Int,
dataGetter: IndexDataGetter,
storage: VcsLogStorage,
factory: VcsLogObjectsFactory): VcsCommitMetadata? {
val commitId = storage.getCommitId(commitIndex) ?: return null
val parents = dataGetter.getParents(commitIndex) ?: return null
val author = dataGetter.getAuthor(commitIndex) ?: return null
val committer = dataGetter.getCommitter(commitIndex) ?: return null
val authorTime = dataGetter.getAuthorTime(commitIndex) ?: return null
val commitTime = dataGetter.getCommitTime(commitIndex) ?: return null
val fullMessage = dataGetter.getFullMessage(commitIndex) ?: return null
return factory.createCommitMetadata(commitId.hash, parents, commitTime, commitId.root, getSubject(fullMessage), author.name,
author.email, fullMessage, committer.name, committer.email, authorTime)
}
}
}
|
apache-2.0
|
768f3ea2a94d1bc14e86a73744e21e5a
| 40.368421 | 140 | 0.702832 | 4.684054 | false | false | false | false |
allotria/intellij-community
|
build/tasks/src/org/jetbrains/intellij/build/tasks/PackageIndexBuilder.kt
|
1
|
2844
|
// 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 org.jetbrains.intellij.build.tasks
import com.intellij.util.io.Murmur3_32Hash
import com.intellij.util.zip.ImmutableZipEntry
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import org.jetbrains.intellij.build.io.ZipFileWriter
internal class PackageIndexBuilder {
val classPackageHashSet = IntOpenHashSet()
val resourcePackageHashSet = IntOpenHashSet()
val dirsToCreate = HashSet<String>()
private var wasWritten = false
fun add(entries: List<ImmutableZipEntry>) {
for (entry in entries) {
val name = entry.name
if (entry.isDirectory) {
continue
}
if (name.endsWith(".class")) {
classPackageHashSet.add(getPackageNameHash(name))
}
else {
resourcePackageHashSet.add(getPackageNameHash(name))
computeDirsToCreate(entry)
}
}
if (!resourcePackageHashSet.isEmpty()) {
// add empty package if top-level directory will be requested
resourcePackageHashSet.add(0)
}
}
fun writePackageIndex(zipCreator: ZipFileWriter) {
assert(!wasWritten)
wasWritten = true
zipCreator.writeUncompressedEntry(PACKAGE_INDEX_NAME,
(2 * Int.SIZE_BYTES) + ((classPackageHashSet.size + resourcePackageHashSet.size) * Int.SIZE_BYTES)) {
val classPackages = classPackageHashSet.toIntArray()
val resourcePackages = resourcePackageHashSet.toIntArray()
// same content for same data
classPackages.sort()
resourcePackages.sort()
it.putInt(classPackages.size)
it.putInt(resourcePackages.size)
val intBuffer = it.asIntBuffer()
intBuffer.put(classPackages)
intBuffer.put(resourcePackages)
it.position(it.position() + (intBuffer.position() * Int.SIZE_BYTES))
}
}
// leave only directories where some non-class files are located (as it can be requested in runtime, e.g. stubs, fileTemplates)
private fun computeDirsToCreate(entry: ImmutableZipEntry) {
val name = entry.name
if (name.endsWith("/package.html") || name == "META-INF/MANIFEST.MF") {
return
}
var slashIndex = name.lastIndexOf('/')
if (slashIndex == -1) {
return
}
var dirName = name.substring(0, slashIndex)
while (dirsToCreate.add(dirName)) {
resourcePackageHashSet.add(Murmur3_32Hash.MURMUR3_32.hashString(dirName, 0, dirName.length))
slashIndex = dirName.lastIndexOf('/')
if (slashIndex == -1) {
break
}
dirName = name.substring(0, slashIndex)
}
}
}
private fun getPackageNameHash(name: String): Int {
val i = name.lastIndexOf('/')
if (i == -1) {
return 0
}
return Murmur3_32Hash.MURMUR3_32.hashString(name, 0, i)
}
|
apache-2.0
|
eb9d4a144b881ec16fc450f9a5ae452d
| 30.263736 | 140 | 0.679677 | 4.011283 | false | false | false | false |
leafclick/intellij-community
|
platform/vcs-api/src/com/intellij/openapi/vcs/ui/VcsCloneComponentStub.kt
|
1
|
1681
|
// 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.openapi.vcs.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.vcs.CheckoutProvider
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class VcsCloneComponentStub(
private val checkoutProvider: CheckoutProvider,
@Nls private val primaryActionText: String = VcsBundle.getString("clone.dialog.clone.button")
) : VcsCloneComponent {
override fun getView(): JComponent {
val panel = JPanel(BorderLayout()).apply {
border = JBEmptyBorder(JBUI.insetsLeft(UIUtil.PANEL_REGULAR_INSETS.left))
}
// todo: replace with better help text
// todo: or add additional button closer to vcs combo
panel.add(JLabel(VcsBundle.message("action.clone.dialog.stub.click.to.continue", primaryActionText)), BorderLayout.NORTH)
return panel
}
override fun doClone(project: Project, listener: CheckoutProvider.Listener) = checkoutProvider.doCheckout(project, listener)
override fun isOkEnabled() = true
override fun doValidateAll() = emptyList<ValidationInfo>()
override fun getOkButtonText() = primaryActionText
override fun getPreferredFocusedComponent(): JComponent? {
// TODO: implement obtaining focus for GitHub
return null
}
override fun dispose() {}
}
|
apache-2.0
|
4ebfed1077b0cd933af1ece2ac2486e0
| 35.565217 | 140 | 0.779298 | 4.332474 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/reflection/call/bound/extensionPropertyAccessors.kt
|
2
|
818
|
// TODO: investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.*
import kotlin.test.assertEquals
class C(val x: Int, var y: Int)
val C.xx: Int
get() = x
var C.yy: Int
get() = y
set(value) { y = value }
val c = C(1, 2)
val c_xx = c::xx
val c_y = c::y
val c_yy = c::yy
fun box(): String {
assertEquals(1, c_xx.getter())
assertEquals(1, c_xx.getter.call())
assertEquals(2, c_yy.getter())
assertEquals(2, c_yy.getter.call())
c_y.setter(10)
assertEquals(10, c_yy.getter())
c_yy.setter(20)
assertEquals(20, c_y.getter())
assertEquals(20, c_yy.getter())
c_y.setter.call(100)
assertEquals(100, c_yy.getter.call())
c_yy.setter.call(200)
assertEquals(200, c_y.getter.call())
return "OK"
}
|
apache-2.0
|
d7eac5a67642bacf3001b5a142a3e575
| 17.177778 | 51 | 0.611247 | 2.791809 | false | false | false | false |
micabytes/lib_game
|
src/main/java/com/micabytes/ui/component/LinearListView.kt
|
2
|
2015
|
package com.micabytes.ui.component
import android.annotation.TargetApi
import android.content.Context
import android.database.DataSetObserver
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.widget.Adapter
import android.widget.BaseAdapter
import android.widget.LinearLayout
import android.widget.ListView
import androidx.databinding.BindingAdapter
import java.util.*
class LinearListView : LinearLayout {
var adapter: Adapter? = null
set(adp) {
if (this.adapter != null) {
this.adapter!!.unregisterDataSetObserver(observer)
}
field = adp
adp?.registerDataSetObserver(observer)
observer.onChanged()
}
private val observer = Observer(this)
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
private class Observer internal constructor(internal val listView: LinearListView) : DataSetObserver() {
override fun onChanged() {
val oldViews = ArrayList<View>(listView.childCount)
(0 until listView.childCount).mapTo(oldViews) { listView.getChildAt(it) }
val itr = oldViews.iterator()
listView.removeAllViews()
for (i in 0 until listView.adapter!!.count) {
val convertView = if (itr.hasNext()) itr.next() else null
listView.addView(listView.adapter!!.getView(i, convertView, listView))
}
super.onChanged()
}
override fun onInvalidated() {
listView.removeAllViews()
super.onInvalidated()
}
}
companion object {
@JvmStatic
@BindingAdapter("adapter")
fun bindList(view: LinearListView, adapter: BaseAdapter) {
view.adapter = adapter
}
@JvmStatic
@BindingAdapter("adapter")
fun bindList(view: ListView, adapter: BaseAdapter) {
view.adapter = adapter
}
}
}
|
apache-2.0
|
3c5663c2c428c33604172721aac11a61
| 27.380282 | 106 | 0.712655 | 4.352052 | false | false | false | false |
peervalhoegen/SudoQ
|
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/actionTree/NoteAction.kt
|
1
|
1889
|
/*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.model.actionTree
import de.sudoq.model.sudoku.Cell
/**
* This class represents an action that adds or removes notes from a [cell].
*/
class NoteAction(diff: Int, val actionType: Action, cell: Cell) : Action(diff, cell) {
enum class Action {SET, REMOVE}
init {
XML_ATTRIBUTE_NAME = "NoteAction"
}
/**
* {@inheritDoc}
*/
override fun execute() {
if (actionType == Action.SET && !cell.isNoteSet(diff)
|| actionType == Action.REMOVE && cell.isNoteSet(diff))
cell.toggleNote(diff)
}
/**
* {@inheritDoc}
*/
override fun undo() {
if (actionType == Action.SET && cell.isNoteSet(diff)
|| actionType == Action.REMOVE && !cell.isNoteSet(diff))
cell.toggleNote(diff)
}
override fun inverse(a: de.sudoq.model.actionTree.Action): Boolean {
//ensure type, inherited equals can be reused as NoteActions are self inverse.
if (a !is NoteAction) return false
return equals(a) && actionType == a.actionType
}
}
|
gpl-3.0
|
36705ee75f9757cda9578a1256db5d43
| 38.354167 | 243 | 0.676377 | 4.176991 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/ProjectDataProvider.kt
|
2
|
5221
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import com.jetbrains.packagesearch.api.v2.ApiRepository
import com.jetbrains.packagesearch.api.v2.ApiStandardPackage
import com.jetbrains.packagesearch.intellij.plugin.api.PackageSearchApiClient
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
internal class ProjectDataProvider(
private val apiClient: PackageSearchApiClient,
private val packageCache: CoroutineLRUCache<InstalledDependency, ApiStandardPackage>
) {
suspend fun fetchKnownRepositories(): List<ApiRepository> = apiClient.repositories().repositories
suspend fun doSearch(
searchQuery: String,
filterOptions: FilterOptions
): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> {
val repositoryIds = filterOptions.onlyRepositoryIds
return apiClient.packagesByQuery(
searchQuery = searchQuery,
onlyStable = filterOptions.onlyStable,
onlyMpp = filterOptions.onlyKotlinMultiplatform,
repositoryIds = repositoryIds.toList()
)
}
suspend fun fetchInfoFor(installedDependencies: List<InstalledDependency>, traceInfo: TraceInfo): Map<InstalledDependency, ApiStandardPackage> {
if (installedDependencies.isEmpty()) {
return emptyMap()
}
val apiInfoByDependency = fetchInfoFromCacheOrApiFor(installedDependencies, traceInfo)
val (emptyApiInfoByDependency, successfulApiInfoByDependency) =
apiInfoByDependency.partition { (_, v) -> v == null }
if (emptyApiInfoByDependency.isNotEmpty() && emptyApiInfoByDependency.size != installedDependencies.size) {
val failedDependencies = emptyApiInfoByDependency.keys
logInfo(traceInfo, "ProjectDataProvider#fetchInfoFor()") {
"Failed obtaining data for ${failedDependencies.size} dependencies"
}
}
return successfulApiInfoByDependency.filterNotNullValues()
}
private suspend fun fetchInfoFromCacheOrApiFor(
dependencies: List<InstalledDependency>,
traceInfo: TraceInfo
): Map<InstalledDependency, ApiStandardPackage?> {
logDebug(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Fetching data for ${dependencies.count()} dependencies..."
}
val remoteInfoByDependencyMap = mutableMapOf<InstalledDependency, ApiStandardPackage?>()
val packagesToFetch = mutableListOf<InstalledDependency>()
for (dependency in dependencies) {
val standardV2Package = packageCache.get(dependency)
remoteInfoByDependencyMap[dependency] = standardV2Package
if (standardV2Package == null) {
packagesToFetch += dependency
}
}
if (packagesToFetch.isEmpty()) {
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found all ${dependencies.count() - packagesToFetch.count()} packages in cache"
}
return remoteInfoByDependencyMap
}
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found ${dependencies.count() - packagesToFetch.count()} packages in cache, still need to fetch ${packagesToFetch.count()} from API"
}
val fetchedPackages = packagesToFetch.asSequence()
.map { dependency -> dependency.coordinatesString }
.chunked(size = 25)
.asFlow()
.map { dependenciesToFetch -> apiClient.packagesByRange(dependenciesToFetch) }
.map { it.packages }
.catch {
logDebug(
"${this::class.run { qualifiedName ?: simpleName ?: this }}#fetchedPackages",
it,
) { "Error while retrieving packages" }
emit(emptyList())
}
.toList()
.flatten()
for (v2Package in fetchedPackages) {
val dependency = InstalledDependency.from(v2Package)
packageCache.put(dependency, v2Package)
remoteInfoByDependencyMap[dependency] = v2Package
}
return remoteInfoByDependencyMap
}
}
private fun <K, V> Map<K, V>.partition(transform: (Map.Entry<K, V>) -> Boolean): Pair<Map<K, V>, Map<K, V>> {
val trueMap = mutableMapOf<K, V>()
val falseMap = mutableMapOf<K, V>()
forEach { if (transform(it)) trueMap[it.key] = it.value else falseMap[it.key] = it.value }
return trueMap to falseMap
}
private fun <K, V> Map<K, V?>.filterNotNullValues() = buildMap<K, V> {
[email protected] { (k, v) -> if (v != null) put(k, v) }
}
|
apache-2.0
|
95154fff76dd1ed9cadd7f5f0a98612f
| 41.447154 | 148 | 0.684352 | 5.153998 | false | false | false | false |
kohesive/kohesive-iac
|
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonPinpoint.kt
|
1
|
1704
|
package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.pinpoint.AbstractAmazonPinpoint
import com.amazonaws.services.pinpoint.AmazonPinpoint
import com.amazonaws.services.pinpoint.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAmazonPinpoint(val context: IacContext) : AbstractAmazonPinpoint(), AmazonPinpoint {
override fun createCampaign(request: CreateCampaignRequest): CreateCampaignResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateCampaignRequest, CreateCampaignResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createImportJob(request: CreateImportJobRequest): CreateImportJobResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateImportJobRequest, CreateImportJobResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createSegment(request: CreateSegmentRequest): CreateSegmentResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateSegmentRequest, CreateSegmentResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
}
class DeferredAmazonPinpoint(context: IacContext) : BaseDeferredAmazonPinpoint(context)
|
mit
|
f9ae03d5fb5b55716be4a7c0fcbca0eb
| 35.255319 | 107 | 0.657277 | 5.375394 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveToKotlinFileProcessor.kt
|
1
|
3607
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.util.containers.MultiMap
import com.intellij.util.text.UniqueNameGenerator
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
class MoveToKotlinFileProcessor @JvmOverloads constructor(
project: Project,
private val sourceFile: KtFile,
private val targetDirectory: PsiDirectory,
private val targetFileName: String,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean,
moveCallback: MoveCallback?,
prepareSuccessfulCallback: Runnable = EmptyRunnable.INSTANCE,
private val throwOnConflicts: Boolean = false
) : MoveFilesOrDirectoriesProcessor(
project,
arrayOf(sourceFile),
targetDirectory,
true,
searchInComments,
searchInNonJavaFiles,
moveCallback,
prepareSuccessfulCallback
) {
override fun getCommandName() = KotlinBundle.message("text.move.file.0", sourceFile.name)
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
return MoveFilesWithDeclarationsViewDescriptor(arrayOf(sourceFile), targetDirectory)
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
val (conflicts, usages) = preprocessConflictUsages(refUsages)
return showConflicts(conflicts, usages)
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
private fun renameFileTemporarilyIfNeeded() {
if (targetDirectory.findFile(sourceFile.name) == null) return
val containingDirectory = sourceFile.containingDirectory ?: return
val temporaryName = UniqueNameGenerator.generateUniqueName("temp", "", ".kt") {
containingDirectory.findFile(it) == null
}
sourceFile.name = temporaryName
}
override fun performRefactoring(usages: Array<UsageInfo>) {
renameFileTemporarilyIfNeeded()
super.performRefactoring(usages)
sourceFile.name = targetFileName
}
companion object {
data class ConflictUsages(val conflicts: MultiMap<PsiElement, String>, @Suppress("ArrayInDataClass") val usages: Array<UsageInfo>)
fun preprocessConflictUsages(refUsages: Ref<Array<UsageInfo>>): ConflictUsages {
val usages: Array<UsageInfo> = refUsages.get()
val (conflictUsages, usagesToProcess) = usages.partition { it is ConflictUsageInfo }
val conflicts = MultiMap<PsiElement, String>()
for (conflictUsage in conflictUsages) {
conflicts.putValues(conflictUsage.element, (conflictUsage as ConflictUsageInfo).messages)
}
refUsages.set(usagesToProcess.toTypedArray())
return ConflictUsages(conflicts, usages)
}
}
}
|
apache-2.0
|
df3539ad17de44c145628e883f68f035
| 39.077778 | 158 | 0.744663 | 5.073136 | false | false | false | false |
kivensolo/UiUsingListView
|
module-Demo/src/main/java/com/zeke/demo/customview/CustomViewsDemoActivity.kt
|
1
|
6412
|
package com.zeke.demo.customview
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.zeke.demo.R
import com.zeke.demo.base.AbsCardDemoActivity
import com.zeke.demo.customview.views.ChartMusicView
import com.zeke.demo.customview.views.ChartTextView
import com.zeke.demo.model.CardItemModel
import com.zeke.demo.model.DemoContentModel
/**
* author: King.Z <br>
* date: 2020/4/19 11:32 <br>
* description: 自定义view Demo展示的页面 <br>
*/
class CustomViewsDemoActivity : AbsCardDemoActivity() {
override fun initCardListData() {
super.initCardListData()
// 创建卡片数据
cardList.add(CardItemModel("ChartMusicView", ChartMusicView(this)))
cardList.add(CardItemModel("带音乐跳动效果的TextView", ChartTextView(this)))
cardList.add(CardItemModel("SimpleChartView", createSimpleChartView()))
}
/**
* 对于图表关键需要知道并理解的是图、数据、数据集以及 Entry,
* 这是定义并显示图表的关键概念,
* 它们的关系是Entry 添加到数据集中,数据集被添加到数据中,数据被添加到图表中。
*
* 如果要对 X 轴和 Y 轴进行设置可分别通过 XAxis 和 YAxis 进行设置
* 如果要对数据进行设置,则通过 DataSet 进行设置
* 如果要设置手势等,可通过图表 Chart 进行设置
*/
private fun createSimpleChartView(): View {
val chartView = LineChart(baseContext)
chartView.apply {
//设置边框颜色
setDrawBorders(false)
// setBorderColor(Color.TRANSPARENT)
// setBorderWidth(2f)
//Description object of the chart
description.isEnabled = false
//Sets the Legend
legend.apply {
isEnabled = false
// other setXXX methods
}
// 自定义 MarkView,当数据被选择时会展示
// val mv = MyMarkerView(this, R.layout.custom_marker_view)
// mv.setChartView(chart)
// setMarker(mv)
// 背景色
setBackgroundColor(Color.WHITE)
setDrawGridBackground(false)
// 添加监听器
setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
override fun onNothingSelected() {}
override fun onValueSelected(e: Entry?, h: Highlight?) {}
})
// <editor-fold defaultstate="collapsed" desc="滑动&缩放设置">
// enable touch gestures
// setTouchEnabled(true)
// dragDecelerationFrictionCoef = 0.9f
// enable scaling and dragging
// isDragEnabled = true
// isScaleXEnabled = true // Enable scale x
// isScaleYEnabled = true // Enable scale y
setScaleEnabled(true) // Enable scale x & y
setPinchZoom(true) // 双指缩放
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="坐标轴设置">
// 允许显示 X 轴的垂直网格线
// xAxis.enableGridDashedLine(10f, 10f, 0f)
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.setDrawGridLines(false)
//左/右侧间距 value值 不是px
xAxis.axisMinimum = 0.5f
xAxis.axisMaximum = 0.5f
// xAxis.axisLineColor = Color.TRANSPARENT
// 禁止右轴
axisRight.isEnabled = false
// Y 轴为起点的水平网格线()
axisLeft.enableGridDashedLine(10f, 10f, 0f);
// 设置 Y 轴的数值范围
axisLeft.axisMaximum = 200f
axisLeft.axisMinimum = 0f
// axisLeft.axisLineColor = Color.TRANSPARENT
// </editor-fold>
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 800)
// 手势设置
setTouchEnabled(true)
}
// 1. 每个数据是一个 Entry 创建假数据集合
val valuesList: MutableList<Entry> = ArrayList()
for (i in 0 until 30) {
val value: Float = (Math.random() * 150f + 30f).toFloat()
valuesList.add(
Entry(i.toFloat(),value)
)
}
// 2. 创建一个数据集 DataSet ,用来添加 Entry。一个图中可以包含多个数据集
// val dataSet = LineDataSet(valuesList, "DataSet 1")
val dataSet = LineDataSet(valuesList, null) // 不显示数据集描述
// 3. 通过数据集设置数据的样式,如字体颜色、线型、线型颜色、填充色、线宽等属性
with(dataSet){
// draw/nodraw dashed line
// enableDashedLine(10f, 5f, 0f)
disableDashedLine()
// Set lines and points color
color = Color.RED
setCircleColor(Color.RED)
lineWidth = 1f //line thickness of data set
circleRadius = 1f //point size of data point
// draw points as solid circles
setDrawCircleHole(false)
setDrawCircles(false) // 不绘制数据集的数据点
setDrawValues(false) // 不绘制数据集的值
//set gradient color 无效
// setGradientColor(Color.RED,Color.WHITE)
setDrawFilled(true)
fillDrawable = resources.getDrawable(R.drawable.chart_fill)
// 曲线风格
// mode = LineDataSet.Mode.HORIZONTAL_BEZIER FIXME
// cubicIntensity = 0.05f //设置曲线的平滑度
}
// 4.将数据集添加到数据 ChartData 中
val data = LineData(dataSet)
// 5. 将数据添加到图表中
chartView.data = data
return chartView
}
override fun inflatePageData() {
super.inflatePageData()
pageModels.add(DemoContentModel("自定义views", cardList))
}
}
|
gpl-2.0
|
1d1cf8462b9ba064758dfcac9f4b5b5c
| 33.042169 | 91 | 0.606903 | 3.867214 | false | false | false | false |
Zhouzhouzhou/AndroidDemo
|
app/src/main/java/com/zhou/android/skin/SkinManager.kt
|
1
|
1997
|
package com.zhou.android.skin
import android.graphics.drawable.Drawable
import android.support.annotation.ColorInt
import com.zhou.android.R
import com.zhou.android.ZApplication
import java.util.*
/**
* Created by mxz on 2021/3/17.
*/
object SkinManager : Observable() {
private val resource = ZApplication.context.resources
private val daySkin = mapOf(
"shape_button" to R.drawable.shape_button_day,
"text_color" to R.color.text_color_day,
"button_color" to R.color.button_color_day,
"page_color" to R.color.page_color_day,
"shape_linear" to R.drawable.shape_linear_day,
"shape_skin_item" to R.drawable.shape_skin_item_day)
private val nightSkin = mapOf(
"shape_button" to R.drawable.shape_button_night,
"text_color" to R.color.text_color_night,
"button_color" to R.color.button_color_night,
"page_color" to R.color.page_color_night,
"shape_linear" to R.drawable.shape_linear_night,
"shape_skin_item" to R.drawable.shape_skin_item_night)
private var map = daySkin
fun isDayMode() = map === daySkin
fun switchMode() = switchMode(!isDayMode())
fun switchMode(dayMode: Boolean = true) {
map = if (dayMode) daySkin else nightSkin
setChanged()
notifyObservers()
}
//资源名称
fun getDrawable(entryName: String): Drawable {
val id = map[entryName] ?: R.drawable.shape_button_day
return resource.getDrawable(id)
}
//资源名称
fun getDrawableRes(entryName: String): Int {
val name = entryName.substring(0, entryName.lastIndexOf("_"))
return map[name] ?: R.drawable.shape_button_day
}
//属性名称
@ColorInt
fun getColor(entryName: String): Int {
val name = entryName.substring(0, entryName.lastIndexOf("_"))
val id = map[name] ?: R.color.text_color_day
return resource.getColor(id)
}
}
|
mit
|
d8000e4a3e9b2be5f8443a6a4238df08
| 29.84375 | 69 | 0.637101 | 3.701689 | false | false | false | false |
siosio/intellij-community
|
plugins/grazie/yaml/main/kotlin/com/intellij/grazie/ide/language/yaml/YamlTextExtractor.kt
|
1
|
1610
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.language.yaml
import com.intellij.grazie.text.TextContent
import com.intellij.grazie.text.TextContentBuilder
import com.intellij.grazie.text.TextExtractor
import com.intellij.grazie.utils.getNotSoDistantSimilarSiblings
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.elementType
import org.jetbrains.yaml.YAMLTokenTypes.*
class YamlTextExtractor : TextExtractor() {
private val commentBuilder = TextContentBuilder.FromPsi.removingIndents(" \t#")
override fun buildTextContent(root: PsiElement, allowedDomains: MutableSet<TextContent.TextDomain>): TextContent? {
when (root.node.elementType) {
COMMENT -> {
val siblings = getNotSoDistantSimilarSiblings(root, TokenSet.create(WHITESPACE, INDENT, EOL)) { it.elementType == COMMENT }
return TextContent.joinWithWhitespace(siblings.mapNotNull { commentBuilder.build(it, TextContent.TextDomain.COMMENTS) })
}
TEXT, SCALAR_STRING, SCALAR_DSTRING, SCALAR_LIST, SCALAR_TEXT ->
return TextContentBuilder.FromPsi.excluding { isStealth(it) }.build(root, TextContent.TextDomain.LITERALS)
else -> return null
}
}
private fun isStealth(element: PsiElement) = when (element.node.elementType) {
INDENT -> true
SCALAR_LIST -> element.textLength == 1 && element.textContains('|')
SCALAR_TEXT -> element.textLength == 1 && element.textContains('>')
else -> false
}
}
|
apache-2.0
|
9dcc12906468091f508e086f2c939af2
| 46.352941 | 140 | 0.75528 | 4.035088 | false | false | false | false |
mseroczynski/CityBikes
|
app/src/test/kotlin/pl/ches/citybikes/testing/extensions/Hamcrest.kt
|
1
|
1461
|
package pl.ches.citybikes.testing.extensions
import org.hamcrest.CoreMatchers
import org.hamcrest.Matcher
import org.junit.Assert
fun <T> assertThat(actual: T, matcher: Matcher<in T>) = Assert.assertThat(actual, matcher)
// ==============================================================================
// Matchers
// ==============================================================================
// ------------------------------------------------------------------------------
// aliases
// ------------------------------------------------------------------------------
fun isTrue() = isEqualTo(true)
fun isFalse() = isEqualTo(false)
fun isEmptyString() = isEqualTo("")
fun <T> isNot(value: T) = CoreMatchers.`is`(CoreMatchers.not(value))
fun <T> isNot(value: Matcher<T>) = CoreMatchers.`is`(CoreMatchers.not(value))
fun nullValue() = CoreMatchers.nullValue()
// ------------------------------------------------------------------------------
// simple delegation
// ------------------------------------------------------------------------------
fun <T> isEqualTo(value: T) = CoreMatchers.`is`(value)
fun <T> isEqualTo(matcher: Matcher<T>) = CoreMatchers.`is`(matcher)
fun <T> sameInstance(value: T) = CoreMatchers.sameInstance(value)
fun <T> not(value: T) = CoreMatchers.not(value)
fun <T> not(value: Matcher<T>) = CoreMatchers.not(value)
fun <T> isA(type: Class<T>) = CoreMatchers.isA(type)
fun <T> hasItem(item: T) = CoreMatchers.hasItem(item)
|
gpl-3.0
|
92e2808eb749e83f51c319662d8223ec
| 34.658537 | 90 | 0.482546 | 4.565625 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/UsePropertyAccessSyntaxIntention.kt
|
1
|
15304
|
// 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.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.util.Key
import com.intellij.profile.codeInspection.InspectionProjectProfileManager
import com.intellij.psi.PsiElement
import org.jdom.Element
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.configuration.ui.NotPropertyListPanel
import org.jetbrains.kotlin.idea.core.NotPropertiesService
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.synthetic.canBePropertyAccessor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.util.shouldNotConvertToProperty
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import javax.swing.JComponent
@Suppress("DEPRECATION")
class UsePropertyAccessSyntaxInspection : IntentionBasedInspection<KtCallExpression>(UsePropertyAccessSyntaxIntention::class),
CleanupLocalInspectionTool {
val fqNameList = NotPropertiesServiceImpl.default.map(::FqNameUnsafe).toMutableList()
@Suppress("CAN_BE_PRIVATE")
var fqNameStrings = NotPropertiesServiceImpl.default.toMutableList()
override fun readSettings(node: Element) {
super.readSettings(node)
fqNameList.clear()
fqNameStrings.mapTo(fqNameList, ::FqNameUnsafe)
}
override fun writeSettings(node: Element) {
fqNameStrings.clear()
fqNameList.mapTo(fqNameStrings) { it.asString() }
super.writeSettings(node)
}
override fun createOptionsPanel(): JComponent? {
val list = NotPropertyListPanel(fqNameList)
return LabeledComponent.create(list, KotlinBundle.message("excluded.methods"))
}
override fun inspectionTarget(element: KtCallExpression): PsiElement? {
return element.calleeExpression
}
override fun inspectionProblemText(element: KtCallExpression): String? {
val accessor = when (element.valueArguments.size) {
0 -> "getter"
1 -> "setter"
else -> null
}
return KotlinBundle.message("use.of.0.method.instead.of.property.access.syntax", accessor.toString())
}
}
class NotPropertiesServiceImpl(private val project: Project) : NotPropertiesService {
override fun getNotProperties(element: PsiElement): Set<FqNameUnsafe> {
val profile = InspectionProjectProfileManager.getInstance(project).currentProfile
val tool = profile.getUnwrappedTool(USE_PROPERTY_ACCESS_INSPECTION, element)
return (tool?.fqNameList ?: default.map(::FqNameUnsafe)).toSet()
}
companion object {
private val atomicMethods = listOf(
"getAndIncrement", "getAndDecrement", "getAcquire", "getOpaque", "getPlain"
)
private val atomicClasses = listOf("AtomicInteger", "AtomicLong")
val default: List<String> = listOf(
"java.net.Socket.getInputStream",
"java.net.Socket.getOutputStream",
"java.net.URLConnection.getInputStream",
"java.net.URLConnection.getOutputStream"
) + atomicClasses.flatMap { klass ->
atomicMethods.map { method -> "java.util.concurrent.atomic.$klass.$method" }
}
val USE_PROPERTY_ACCESS_INSPECTION: Key<UsePropertyAccessSyntaxInspection> = Key.create("UsePropertyAccessSyntax")
}
}
class UsePropertyAccessSyntaxIntention : SelfTargetingOffsetIndependentIntention<KtCallExpression>(
KtCallExpression::class.java,
KotlinBundle.lazyMessage("use.property.access.syntax")
) {
override fun isApplicableTo(element: KtCallExpression): Boolean = detectPropertyNameToUse(element) != null
override fun applyTo(element: KtCallExpression, editor: Editor?) {
val propertyName = detectPropertyNameToUse(element) ?: return
runWriteActionIfPhysical(element) {
applyTo(element, propertyName, reformat = true)
}
}
fun applyTo(element: KtCallExpression, propertyName: Name, reformat: Boolean): KtExpression = when (element.valueArguments.size) {
0 -> replaceWithPropertyGet(element, propertyName)
1 -> replaceWithPropertySet(element, propertyName, reformat)
else -> error("More than one argument in call to accessor")
}
fun detectPropertyNameToUse(callExpression: KtCallExpression): Name? {
if (callExpression.getQualifiedExpressionForSelector()
?.receiverExpression is KtSuperExpression
) return null // cannot call extensions on "super"
val callee = callExpression.calleeExpression as? KtNameReferenceExpression ?: return null
if (!canBePropertyAccessor(callee.getReferencedName())) return null
val resolutionFacade = callExpression.getResolutionFacade()
val bindingContext = callExpression.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL_FOR_COMPLETION)
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null
if (!resolvedCall.isReallySuccess()) return null
val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return null
val notProperties =
(inspection as? UsePropertyAccessSyntaxInspection)?.fqNameList?.toSet() ?: NotPropertiesService.getNotProperties(callExpression)
if (function.shouldNotConvertToProperty(notProperties)) return null
val resolutionScope = callExpression.getResolutionScope(bindingContext, resolutionFacade)
@OptIn(FrontendInternals::class)
val property = findSyntheticProperty(function, resolutionFacade.getFrontendService(SyntheticScopes::class.java)) ?: return null
if (KtTokens.KEYWORDS.types.any { it.toString() == property.name.asString() }) return null
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(callee)
val qualifiedExpression = callExpression.getQualifiedExpressionForSelectorOrThis()
val expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, qualifiedExpression] ?: TypeUtils.NO_EXPECTED_TYPE
if (!checkWillResolveToProperty(
resolvedCall,
property,
bindingContext,
resolutionScope,
dataFlowInfo,
expectedType,
resolutionFacade
)
) return null
val isSetUsage = callExpression.valueArguments.size == 1
val valueArgumentExpression = callExpression.valueArguments.firstOrNull()?.getArgumentExpression()?.takeUnless {
it is KtLambdaExpression || it is KtNamedFunction || it is KtCallableReferenceExpression
}
if (isSetUsage && valueArgumentExpression == null) {
return null
}
if (isSetUsage && qualifiedExpression.isUsedAsExpression(bindingContext)) {
// call to the setter used as expression can be converted in the only case when it's used as body expression for some declaration and its type is Unit
val parent = qualifiedExpression.parent
if (parent !is KtDeclarationWithBody || qualifiedExpression != parent.bodyExpression) return null
if (function.returnType?.isUnit() != true) return null
}
if (isSetUsage && property.type != function.valueParameters.single().type) {
val qualifiedExpressionCopy = qualifiedExpression.copied()
val callExpressionCopy =
((qualifiedExpressionCopy as? KtQualifiedExpression)?.selectorExpression ?: qualifiedExpressionCopy) as KtCallExpression
val newExpression = applyTo(callExpressionCopy, property.name, reformat = false)
val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace")
val newBindingContext = newExpression.analyzeInContext(
resolutionScope,
contextExpression = callExpression,
trace = bindingTrace,
dataFlowInfo = dataFlowInfo,
expectedType = expectedType,
isStatement = true
)
if (newBindingContext.diagnostics.any { it.severity == Severity.ERROR }) return null
}
return property.name
}
private fun checkWillResolveToProperty(
resolvedCall: ResolvedCall<out CallableDescriptor>,
property: SyntheticJavaPropertyDescriptor,
bindingContext: BindingContext,
resolutionScope: LexicalScope,
dataFlowInfo: DataFlowInfo,
expectedType: KotlinType,
facade: ResolutionFacade
): Boolean {
val project = resolvedCall.call.callElement.project
val newCall = object : DelegatingCall(resolvedCall.call) {
private val newCallee = KtPsiFactory(project).createExpressionByPattern("$0", property.name, reformat = false)
override fun getCalleeExpression() = newCallee
override fun getValueArgumentList(): KtValueArgumentList? = null
override fun getValueArguments(): List<ValueArgument> = emptyList()
override fun getFunctionLiteralArguments(): List<LambdaArgument> = emptyList()
}
val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace")
val context = BasicCallResolutionContext.create(
bindingTrace, resolutionScope, newCall, expectedType, dataFlowInfo,
ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS,
false, facade.languageVersionSettings,
facade.dataFlowValueFactory
)
@OptIn(FrontendInternals::class)
val callResolver = facade.frontendService<CallResolver>()
val result = callResolver.resolveSimpleProperty(context)
return result.isSuccess && result.resultingDescriptor.original == property
}
private fun findSyntheticProperty(function: FunctionDescriptor, syntheticScopes: SyntheticScopes): SyntheticJavaPropertyDescriptor? {
SyntheticJavaPropertyDescriptor.findByGetterOrSetter(function, syntheticScopes)?.let { return it }
for (overridden in function.overriddenDescriptors) {
findSyntheticProperty(overridden, syntheticScopes)?.let { return it }
}
return null
}
private fun replaceWithPropertyGet(callExpression: KtCallExpression, propertyName: Name): KtExpression {
val newExpression = KtPsiFactory(callExpression).createExpression(propertyName.render())
return callExpression.replaced(newExpression)
}
private fun replaceWithPropertySet(callExpression: KtCallExpression, propertyName: Name, reformat: Boolean): KtExpression {
val call = callExpression.getQualifiedExpressionForSelector() ?: callExpression
val callParent = call.parent
var callToConvert = callExpression
if (callParent is KtDeclarationWithBody && call == callParent.bodyExpression) {
ConvertToBlockBodyIntention.convert(callParent, true)
val firstStatement = callParent.bodyBlockExpression?.statements?.first()
callToConvert = (firstStatement as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression
?: firstStatement as? KtCallExpression
?: throw KotlinExceptionWithAttachments("Unexpected contents of function after conversion: ${callParent::class.java}")
.withPsiAttachment("callParent", callParent)
}
val qualifiedExpression = callToConvert.getQualifiedExpressionForSelector()
val argument = callToConvert.valueArguments.single()
if (qualifiedExpression != null) {
val pattern = when (qualifiedExpression) {
is KtDotQualifiedExpression -> "$0.$1=$2"
is KtSafeQualifiedExpression -> "$0?.$1=$2"
else -> error(qualifiedExpression) //TODO: make it sealed?
}
val newExpression = KtPsiFactory(callToConvert).createExpressionByPattern(
pattern,
qualifiedExpression.receiverExpression,
propertyName,
argument.getArgumentExpression()!!,
reformat = reformat
)
return qualifiedExpression.replaced(newExpression)
} else {
val newExpression =
KtPsiFactory(callToConvert).createExpressionByPattern("$0=$1", propertyName, argument.getArgumentExpression()!!)
return callToConvert.replaced(newExpression)
}
}
}
|
apache-2.0
|
2b93696eca1ba35318bde826b39b9825
| 47.584127 | 162 | 0.733534 | 5.597659 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KtSimpleNameReference.kt
|
1
|
11920
|
// 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.references
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.isDispatchThread
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.name.isOneSegmentFQN
import org.jetbrains.kotlin.plugin.references.SimpleNameReferenceExtension
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.expressions.OperatorConventions
class KtSimpleNameReferenceDescriptorsImpl(
expression: KtSimpleNameExpression
) : KtSimpleNameReference(expression), KtDescriptorsBasedReference {
override fun canBeReferenceTo(candidateTarget: PsiElement): Boolean {
return element.containingFile == candidateTarget.containingFile
|| ProjectRootsUtil.isInProjectOrLibSource(element, includeScriptsOutsideSourceRoots = true)
}
override fun isReferenceToImportAlias(alias: KtImportAlias): Boolean {
return super<KtDescriptorsBasedReference>.isReferenceToImportAlias(alias)
}
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
return SmartList<DeclarationDescriptor>().apply {
// Replace Java property with its accessor(s)
for (descriptor in expression.getReferenceTargets(context)) {
val sizeBefore = size
if (descriptor !is JavaPropertyDescriptor) {
add(descriptor)
continue
}
val readWriteAccess = expression.readWriteAccess(true)
descriptor.getter?.let {
if (readWriteAccess.isRead) add(it)
}
descriptor.setter?.let {
if (readWriteAccess.isWrite) add(it)
}
if (size == sizeBefore) {
add(descriptor)
}
}
}
}
override fun isReferenceToViaExtension(element: PsiElement): Boolean {
for (extension in element.project.extensionArea.getExtensionPoint(SimpleNameReferenceExtension.EP_NAME).extensions) {
if (extension.isReferenceTo(this, element)) return true
}
return false
}
override fun handleElementRename(newElementName: String): PsiElement {
if (!canRename()) throw IncorrectOperationException()
if (newElementName.unquote() == "") {
return when (val qualifiedElement = expression.getQualifiedElement()) {
is KtQualifiedExpression -> {
expression.replace(qualifiedElement.receiverExpression)
qualifiedElement.replaced(qualifiedElement.selectorExpression!!)
}
is KtUserType -> expression.replaced(
KtPsiFactory(expression).createSimpleName(
SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.asString()
)
)
else -> expression
}
}
// Do not rename if the reference corresponds to synthesized component function
val expressionText = expression.text
if (expressionText != null && Name.isValidIdentifier(expressionText)) {
if (DataClassDescriptorResolver.isComponentLike(Name.identifier(expressionText)) && resolve() is KtParameter) {
return expression
}
}
val psiFactory = KtPsiFactory(expression)
val element = expression.project.extensionArea.getExtensionPoint(SimpleNameReferenceExtension.EP_NAME).extensions
.asSequence()
.map { it.handleElementRename(this, psiFactory, newElementName) }
.firstOrNull { it != null } ?: psiFactory.createNameIdentifier(newElementName.quoteIfNeeded())
val nameElement = expression.getReferencedNameElement()
val elementType = nameElement.node.elementType
if (elementType is KtToken && OperatorConventions.getNameForOperationSymbol(elementType) != null) {
val opExpression = expression.parent as? KtOperationExpression
if (opExpression != null) {
val (newExpression, newNameElement) = OperatorToFunctionIntention.convert(opExpression)
newNameElement.replace(element)
return newExpression
}
}
if (element.node.elementType == KtTokens.IDENTIFIER) {
nameElement.astReplace(element)
} else {
nameElement.replace(element)
}
return expression
}
override fun bindToElement(element: PsiElement, shorteningMode: ShorteningMode): PsiElement =
element.getKotlinFqName()?.let { fqName -> bindToFqName(fqName, shorteningMode, element) } ?: expression
override fun bindToFqName(
fqName: FqName,
shorteningMode: ShorteningMode,
targetElement: PsiElement?
): PsiElement {
val expression = expression
if (fqName.isRoot) return expression
// not supported for infix calls and operators
if (expression !is KtNameReferenceExpression) return expression
if (expression.parent is KtThisExpression || expression.parent is KtSuperExpression) return expression // TODO: it's a bad design of PSI tree, we should change it
val newExpression = expression.changeQualifiedName(
fqName.quoteIfNeeded().let {
if (shorteningMode == ShorteningMode.NO_SHORTENING)
it
else
it.withRootPrefixIfNeeded(expression)
},
targetElement
)
val newQualifiedElement = newExpression.getQualifiedElementOrCallableRef()
if (shorteningMode == ShorteningMode.NO_SHORTENING) return newExpression
val needToShorten = PsiTreeUtil.getParentOfType(expression, KtImportDirective::class.java, KtPackageDirective::class.java) == null
if (!needToShorten) {
return newExpression
}
return if (shorteningMode == ShorteningMode.FORCED_SHORTENING || !isDispatchThread()) {
ShortenReferences.DEFAULT.process(newQualifiedElement)
} else {
newQualifiedElement.addToShorteningWaitSet()
newExpression
}
}
/**
* Replace [[KtNameReferenceExpression]] (and its enclosing qualifier) with qualified element given by FqName
* Result is either the same as original element, or [[KtQualifiedExpression]], or [[KtUserType]]
* Note that FqName may not be empty
*/
private fun KtNameReferenceExpression.changeQualifiedName(
fqName: FqName,
targetElement: PsiElement? = null
): KtNameReferenceExpression {
assert(!fqName.isRoot) { "Can't set empty FqName for element $this" }
val shortName = fqName.shortName().asString()
val psiFactory = KtPsiFactory(this)
val parent = parent
if (parent is KtUserType && !fqName.isOneSegmentFQN()) {
val qualifier = parent.qualifier
val qualifierReference = qualifier?.referenceExpression as? KtNameReferenceExpression
if (qualifierReference != null && qualifier.typeArguments.isNotEmpty()) {
qualifierReference.changeQualifiedName(fqName.parent(), targetElement)
return this
}
}
val targetUnwrapped = targetElement?.unwrapped
if (targetUnwrapped != null && targetUnwrapped.isTopLevelKtOrJavaMember() && fqName.isOneSegmentFQN()) {
addDelayedImportRequest(targetUnwrapped, containingKtFile)
}
var parentDelimiter = "."
val fqNameBase = when {
parent is KtCallElement -> {
val callCopy = parent.copied()
callCopy.calleeExpression!!.replace(psiFactory.createSimpleName(shortName)).parent!!.text
}
parent is KtCallableReferenceExpression && parent.callableReference == this -> {
parentDelimiter = ""
val callableRefCopy = parent.copied()
callableRefCopy.receiverExpression?.delete()
val newCallableRef = callableRefCopy
.callableReference
.replace(psiFactory.createSimpleName(shortName))
.parent as KtCallableReferenceExpression
if (targetUnwrapped != null && targetUnwrapped.isTopLevelKtOrJavaMember()) {
addDelayedImportRequest(targetUnwrapped, parent.containingKtFile)
return parent.replaced(newCallableRef).callableReference as KtNameReferenceExpression
}
newCallableRef.text
}
else -> shortName
}
val text = if (!fqName.isOneSegmentFQN()) "${fqName.parent().asString()}$parentDelimiter$fqNameBase" else fqNameBase
val elementToReplace = getQualifiedElementOrCallableRef()
val newElement = when (elementToReplace) {
is KtUserType -> {
val typeText = "$text${elementToReplace.typeArgumentList?.text ?: ""}"
elementToReplace.replace(psiFactory.createType(typeText).typeElement!!)
}
else -> KtPsiUtil.safeDeparenthesize(elementToReplace.replaced(psiFactory.createExpression(text)))
} as KtElement
val selector = (newElement as? KtCallableReferenceExpression)?.callableReference
?: newElement.getQualifiedElementSelector()
?: error("No selector for $newElement")
return selector as KtNameReferenceExpression
}
override fun getImportAlias(): KtImportAlias? {
fun DeclarationDescriptor.unwrap() = if (this is ImportedFromObjectCallableDescriptor<*>) callableFromObject else this
val element = element
val name = element.getReferencedName()
val file = element.containingKtFile
val importDirective = file.findImportByAlias(name) ?: return null
val fqName = importDirective.importedFqName ?: return null
val importedDescriptors = file.resolveImportReference(fqName).map { it.unwrap() }
if (getTargetDescriptors(element.analyze(BodyResolveMode.PARTIAL)).any {
it.unwrap().getImportableDescriptor() in importedDescriptors
}) {
return importDirective.alias
}
return null
}
}
|
apache-2.0
|
309ba3ec296a051ec2c374efce0afd94
| 44.151515 | 170 | 0.677601 | 5.744578 | false | false | false | false |
GunoH/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenExternalAnnotationsConfigurator.kt
|
2
|
5104
|
// 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.idea.maven.importing
import com.intellij.codeInsight.ExternalAnnotationsArtifactsResolver
import com.intellij.codeInsight.externalAnnotation.location.AnnotationsLocation
import com.intellij.codeInsight.externalAnnotation.location.AnnotationsLocationSearcher
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.findLibraryBridge
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectChanges
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.tasks.TasksBundle
@ApiStatus.Internal
private class MavenExternalAnnotationsConfigurator : MavenImporter("org.apache.maven.plugins", "maven-compiler-plugin"),
MavenWorkspaceConfigurator {
private val myProcessedLibraries = hashSetOf<MavenArtifact>()
override fun processChangedModulesOnly(): Boolean = false
override fun isMigratedToConfigurator(): Boolean = true
override fun afterModelApplied(context: MavenWorkspaceConfigurator.AppliedModelContext) {
if (!shouldRun(context.project)) return
val projectsWithChanges = context.mavenProjectsWithModules.filter { it.hasChanges() }.map { it.mavenProject }
if (projectsWithChanges.none()) return
val libraryNameMap = context.importedEntities(LibraryEntity::class.java)
.mapNotNull { it.findLibraryBridge(context.storage) }
.associateBy { it.name }
doConfigure(context.project, projectsWithChanges) { libraryName -> libraryNameMap[libraryName] }
}
override fun postProcess(module: Module,
mavenProject: MavenProject,
changes: MavenProjectChanges,
modifiableModelsProvider: IdeModifiableModelsProvider) {
if (!shouldRun(module.project)) return
doConfigure(module.project, sequenceOf(mavenProject)) { libraryName ->
modifiableModelsProvider.getLibraryByName(libraryName)
}
}
private fun shouldRun(project: Project): Boolean {
if (!shouldImportExternalAnnotations(project)) {
return false
}
val resolvers = getResolvers()
if (resolvers.isEmpty()) {
return false
}
return true
}
private fun getResolvers(): List<ExternalAnnotationsArtifactsResolver> = ExternalAnnotationsArtifactsResolver.EP_NAME.extensionList
private fun doConfigure(project: Project, mavenProjects: Sequence<MavenProject>, libraryFinder: (libraryName: String) -> Library?) {
val toProcess = mutableMapOf<MavenArtifact, Library>()
mavenProjects.forEach { eachMavenProject ->
eachMavenProject.dependencies.asSequence()
.filter { !myProcessedLibraries.contains(it) }
.forEach {
val library = libraryFinder.invoke(it.libraryName)
if (library != null) {
toProcess[it] = library
myProcessedLibraries.add(it)
}
}
}
if (toProcess.isEmpty()) {
return
}
val totalSize = toProcess.size
var count = 0
val locationsToSkip = mutableSetOf<AnnotationsLocation>()
runBackgroundableTask(TasksBundle.message("maven.tasks.external.annotations.resolving.title"), project) { indicator ->
val resolvers = getResolvers()
indicator.isIndeterminate = false
toProcess.forEach { (mavenArtifact, library) ->
if (indicator.isCanceled) {
return@forEach
}
indicator.text = TasksBundle.message("maven.tasks.external.annotations.looking.for", mavenArtifact.libraryName)
val locations = AnnotationsLocationSearcher.findAnnotationsLocation(project, library, mavenArtifact.artifactId,
mavenArtifact.groupId, mavenArtifact.version)
locations.forEach locations@{ location ->
if (locationsToSkip.contains(location)) return@locations
if (!resolvers.fold(false) { acc, res -> acc || res.resolve(project, library, location) } ) {
locationsToSkip.add(location)
}
}
indicator.fraction = (++count).toDouble() / totalSize
}
}
}
private fun shouldImportExternalAnnotations(project: Project) =
MavenProjectsManager.getInstance(project).run {
importingSettings.isDownloadAnnotationsAutomatically && !generalSettings.isWorkOffline
}
companion object {
val LOG = Logger.getInstance(MavenExternalAnnotationsConfigurator::class.java)
}
}
|
apache-2.0
|
e7b029da1a167cb7f686801eb2ea1f96
| 39.832 | 134 | 0.727469 | 5.088734 | false | true | false | false |
ThePreviousOne/Untitled
|
app/src/main/java/eu/kanade/tachiyomi/data/source/online/english/MangaedenEN.kt
|
1
|
2981
|
/*
* This file is part of TachiyomiEX.
*
* TachiyomiEX 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.
*
* TachiyomiEX 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 TachiyomiEX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.kanade.tachiyomi.data.source.online.english
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.EN
import eu.kanade.tachiyomi.data.source.Language
import eu.kanade.tachiyomi.data.source.Sources
import eu.kanade.tachiyomi.data.source.online.multi.Mangaeden
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
class MangaedenEN(override val source: Sources) : Mangaeden(){
override val lang: Language = EN
override val langcode = lang.code.toLowerCase()
override fun popularMangaNextPageSelector() = "div.pagination.pagination_bottom > a:has(span:contains(Next))"
override fun searchMangaNextPageSelector() = "div.pagination.pagination_bottom > a:has(span:contains(Next))"
override fun mangaDetailsParse(document: Document, manga: Manga) {
val ielement = document.select("div#mangaPage")
val info = getInfoList(ielement.select("div#rightContent").first().childNode(3).childNodes())
manga.thumbnail_url = "http:" + ielement.select("div#rightContent div.mangaImage2 > img").attr("src")
manga.author = info[info.indexOf("Author") + 1]
manga.artist = info[info.indexOf("Artist") + 1]
val s = StringBuilder()
for (i in info.indexOf("Genres") + 1 .. info.indexOf("Type") - 3) {
s.append(info[i])
}
manga.genre = s.toString()
manga.status = info[info.indexOf("Status") + 1].let { parseStatus(it) }
manga.description = ielement.select("h2#mangaDescription").text()
}
override fun parseStatus(status: String) = when {
status.contains("Ongoing") -> Manga.ONGOING
status.contains("Completed") -> Manga.COMPLETED
else -> Manga.UNKNOWN
}
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select("td > a.chapterLink")
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.select("b").text()
chapter.date_upload = element.select("td.chapterDate").text()?.let {
SimpleDateFormat("MMM dd, yyyy", Locale(langcode)).parse(it).time
} ?: 0
}
}
|
gpl-3.0
|
d0aa02ac03d2c9ec2aa8c6128249c043
| 40.402778 | 113 | 0.703455 | 4.061308 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/maxMin/KT14210.kt
|
3
|
310
|
// WITH_RUNTIME
// INTENTION_TEXT: "Replace with 'filter{}.maxOrNull()'"
// INTENTION_TEXT_2: "Replace with 'asSequence().filter{}.maxOrNull()'"
fun f(list: List<Int>) {
var result = -1
<caret>for (item in list)
if (item % 2 == 0)
if (result <= item)
result = item
}
|
apache-2.0
|
7f4f02c5acd9cc4af569b7423d35834a
| 30.1 | 71 | 0.558065 | 3.647059 | false | false | false | false |
jwren/intellij-community
|
platform/credential-store/src/PasswordSafeImpl.kt
|
1
|
9265
|
// 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.
@file:Suppress("PackageDirectoryMismatch")
package com.intellij.ide.passwordSafe.impl
import com.intellij.configurationStore.SettingsSavingComponent
import com.intellij.credentialStore.*
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.credentialStore.keePass.*
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.passwordSafe.PasswordStorage
import com.intellij.notification.NotificationAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.serviceContainer.NonInjectable
import com.intellij.util.SingleAlarm
import com.intellij.util.concurrency.SynchronizedClearableLazy
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.runAsync
import java.io.Closeable
import java.nio.file.Path
import java.nio.file.Paths
open class BasePasswordSafe @NonInjectable constructor(val settings: PasswordSafeSettings, provider: CredentialStore? = null /* TestOnly */) : PasswordSafe() {
@Suppress("unused")
constructor() : this(service<PasswordSafeSettings>(), null)
override var isRememberPasswordByDefault: Boolean
get() = settings.state.isRememberPasswordByDefault
set(value) {
settings.state.isRememberPasswordByDefault = value
}
private val _currentProvider = SynchronizedClearableLazy { computeProvider(settings) }
protected val currentProviderIfComputed: CredentialStore?
get() = if (_currentProvider.isInitialized()) _currentProvider.value else null
var currentProvider: CredentialStore
get() = _currentProvider.value
set(value) {
_currentProvider.value = value
}
fun closeCurrentStore(isSave: Boolean, isEvenMemoryOnly: Boolean) {
val store = currentProviderIfComputed ?: return
if (!isEvenMemoryOnly && store is InMemoryCredentialStore) {
return
}
_currentProvider.drop()
if (isSave && store is KeePassCredentialStore) {
try {
store.save(createMasterKeyEncryptionSpec())
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.warn(e)
}
}
else if (store is Closeable) {
store.close()
}
}
internal fun createMasterKeyEncryptionSpec(): EncryptionSpec =
when (val pgpKey = settings.state.pgpKeyId) {
null -> EncryptionSpec(type = getDefaultEncryptionType(), pgpKeyId = null)
else -> EncryptionSpec(type = EncryptionType.PGP_KEY, pgpKeyId = pgpKey)
}
// it is helper storage to support set password as memory-only (see setPassword memoryOnly flag)
protected val memoryHelperProvider: Lazy<CredentialStore> = lazy { InMemoryCredentialStore() }
override val isMemoryOnly: Boolean
get() = settings.providerType == ProviderType.MEMORY_ONLY
init {
provider?.let {
currentProvider = it
}
}
override fun get(attributes: CredentialAttributes): Credentials? {
val value = currentProvider.get(attributes)
if ((value == null || value.password.isNullOrEmpty()) && memoryHelperProvider.isInitialized()) {
// if password was set as `memoryOnly`
memoryHelperProvider.value.get(attributes)?.let {
return it
}
}
return value
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
currentProvider.set(attributes, credentials)
if (attributes.isPasswordMemoryOnly && !credentials?.password.isNullOrEmpty()) {
// we must store because otherwise on get will be no password
memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials)
}
else if (memoryHelperProvider.isInitialized()) {
memoryHelperProvider.value.set(attributes, null)
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?, memoryOnly: Boolean) {
if (memoryOnly) {
memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials)
// remove to ensure that on getPassword we will not return some value from default provider
currentProvider.set(attributes, null)
}
else {
set(attributes, credentials)
}
}
// maybe in the future we will use native async, so, this method added here instead "if need, just use runAsync in your code"
override fun getAsync(attributes: CredentialAttributes): Promise<Credentials?> = runAsync { get(attributes) }
open suspend fun save() {
val keePassCredentialStore = currentProviderIfComputed as? KeePassCredentialStore ?: return
keePassCredentialStore.save(createMasterKeyEncryptionSpec())
}
override fun isPasswordStoredOnlyInMemory(attributes: CredentialAttributes, credentials: Credentials): Boolean {
if (isMemoryOnly || credentials.password.isNullOrEmpty()) {
return true
}
if (!memoryHelperProvider.isInitialized()) {
return false
}
return memoryHelperProvider.value.get(attributes)?.let {
!it.password.isNullOrEmpty()
} ?: false
}
}
class PasswordSafeImpl : BasePasswordSafe(), SettingsSavingComponent {
// SecureRandom (used to generate master password on first save) can be blocking on Linux
private val saveAlarm = SingleAlarm.pooledThreadSingleAlarm(delay = 0, ApplicationManager.getApplication()) {
val currentThread = Thread.currentThread()
ShutDownTracker.getInstance().executeWithStopperThread(currentThread) {
(currentProviderIfComputed as? KeePassCredentialStore)?.save(createMasterKeyEncryptionSpec())
}
}
override suspend fun save() {
val keePassCredentialStore = currentProviderIfComputed as? KeePassCredentialStore ?: return
if (keePassCredentialStore.isNeedToSave()) {
saveAlarm.request()
}
}
@Suppress("unused", "DeprecatedCallableAddReplaceWith")
@get:Deprecated("Do not use it")
@get:ApiStatus.ScheduledForRemoval
// public - backward compatibility
val memoryProvider: PasswordStorage
get() = memoryHelperProvider.value as PasswordStorage
}
fun getDefaultKeePassDbFile() = getDefaultKeePassBaseDirectory().resolve(DB_FILE_NAME)
private fun computeProvider(settings: PasswordSafeSettings): CredentialStore {
if (settings.providerType == ProviderType.MEMORY_ONLY || (ApplicationManager.getApplication()?.isUnitTestMode == true)) {
return InMemoryCredentialStore()
}
fun showError(@NlsContexts.NotificationTitle title: String) {
CredentialStoreUiService.getInstance().notify(title,
CredentialStoreBundle.message("notification.content.in.memory.storage"), null,
NotificationAction.createExpiring(CredentialStoreBundle.message("notification.content.password.settings.action"))
{ e, _ -> CredentialStoreUiService.getInstance().openSettings(e.project) })
}
if (settings.providerType == ProviderType.KEEPASS) {
try {
val dbFile = settings.keepassDb?.let { Paths.get(it) } ?: getDefaultKeePassDbFile()
return KeePassCredentialStore(dbFile, getDefaultMasterPasswordFile())
}
catch (e: IncorrectMasterPasswordException) {
LOG.warn(e)
showError(if (e.isFileMissed) CredentialStoreBundle.message("notification.title.password.missing")
else CredentialStoreBundle.message("notification.title.password.incorrect"))
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
showError(CredentialStoreBundle.message("notification.title.database.error"))
}
}
else {
try {
val store = createPersistentCredentialStore()
if (store == null) {
showError(CredentialStoreBundle.message("notification.title.keychain.not.available"))
}
else {
return store
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
showError(CredentialStoreBundle.message("notification.title.cannot.use.keychain"))
}
}
settings.providerType = ProviderType.MEMORY_ONLY
return InMemoryCredentialStore()
}
fun createPersistentCredentialStore(): CredentialStore? {
for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensionList) {
return factory.create() ?: continue
}
return null
}
@TestOnly
fun createKeePassStore(dbFile: Path, masterPasswordFile: Path): PasswordSafe {
val store = KeePassCredentialStore(dbFile, masterPasswordFile)
val settings = PasswordSafeSettings()
settings.loadState(PasswordSafeSettings.PasswordSafeOptions().apply {
provider = ProviderType.KEEPASS
keepassDb = store.dbFile.toString()
})
return BasePasswordSafe(settings, store)
}
private fun CredentialAttributes.toPasswordStoreable() = if (isPasswordMemoryOnly) CredentialAttributes(serviceName, userName, requestor) else this
|
apache-2.0
|
45f9d03a1b638d012fe2304e41ddf167
| 37.127572 | 163 | 0.735132 | 4.820499 | false | false | false | false |
GunoH/intellij-community
|
platform/vcs-impl/src/com/intellij/codeInsight/actions/ChangedRangesShifter.kt
|
2
|
2926
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.actions
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.comparison.iterables.FairDiffIterable
import com.intellij.diff.util.Range
import com.intellij.util.containers.PeekableIteratorWrapper
import kotlin.math.max
/**
* Input: given 3 revisions: A -> B -> C and 2 sets of differences between them: earlyChanges 'A -> B' and laterChanges 'B -> C'.
* We want to translate earlyChanges into 'A -> C' offsets.
* 'laterChanges' are ignored, unless they conflict with earlyChanges.
* In case of conflict, we want to 'merge' them into a single big range.
*
* @see com.intellij.openapi.vcs.ex.BulkRangeChangeHandler
*/
class ChangedRangesShifter {
private val result = mutableListOf<Range>()
private var dirtyStart = -1
private var dirtyEnd = -1
private var dirtyHasEarly = false
private var earlyShift: Int = 0
private var laterShift: Int = 0
private var dirtyEarlyShift: Int = 0
private var dirtyLaterShift: Int = 0
fun execute(earlyChanges: FairDiffIterable,
laterChanges: FairDiffIterable): List<Range> {
val it1 = PeekableIteratorWrapper(earlyChanges.changes())
val it2 = PeekableIteratorWrapper(laterChanges.changes())
while (it1.hasNext() || it2.hasNext()) {
if (!it2.hasNext()) {
handleEarly(it1.next())
continue
}
if (!it1.hasNext()) {
handleLater(it2.next())
continue
}
val range1 = it1.peek()
val range2 = it2.peek()
if (range1.start2 <= range2.start1) {
handleEarly(it1.next())
}
else {
handleLater(it2.next())
}
}
flush(Int.MAX_VALUE)
return result
}
private fun handleEarly(range: Range) {
flush(range.start2)
dirtyEarlyShift -= DiffIterableUtil.getRangeDelta(range)
markDirtyRange(range.start2, range.end2)
dirtyHasEarly = true
}
private fun handleLater(range: Range) {
flush(range.start1)
dirtyLaterShift += DiffIterableUtil.getRangeDelta(range)
markDirtyRange(range.start1, range.end1)
}
private fun markDirtyRange(start: Int, end: Int) {
if (dirtyEnd == -1) {
dirtyStart = start
dirtyEnd = end
}
else {
dirtyEnd = max(dirtyEnd, end)
}
}
private fun flush(nextLine: Int) {
if (dirtyEnd != -1 && dirtyEnd < nextLine) {
if (dirtyHasEarly) {
result.add(Range(dirtyStart + earlyShift, dirtyEnd + earlyShift + dirtyEarlyShift,
dirtyStart + laterShift, dirtyEnd + laterShift + dirtyLaterShift)
)
}
dirtyStart = -1
dirtyEnd = -1
dirtyHasEarly = false
earlyShift += dirtyEarlyShift
laterShift += dirtyLaterShift
dirtyEarlyShift = 0
dirtyLaterShift = 0
}
}
}
|
apache-2.0
|
3c86f4d273fe1ca5b308c1a09e93cbb8
| 26.603774 | 129 | 0.66473 | 3.911765 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/ide/wizard/NewProjectWizardStepPanel.kt
|
8
|
829
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.wizard
import com.intellij.ui.dsl.builder.panel
import com.intellij.util.ui.JBUI
class NewProjectWizardStepPanel(val step: NewProjectWizardStep) {
fun getPreferredFocusedComponent() = component.preferredFocusedComponent
fun validate() = component.validateAll().all { it.okEnabled }
fun isModified() = component.isModified()
fun apply() = component.apply()
fun reset() = component.reset()
val component by lazy {
panel {
step.setupUI(this)
}.withVisualPadding(topField = true)
.apply {
registerValidators(step.context.disposable)
setMinimumWidthForAllRowLabels(JBUI.scale(90))
}
}
}
|
apache-2.0
|
5ad50dd5df3f338ccc52cf268cc2121b
| 28.642857 | 158 | 0.731001 | 4.251282 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/base/scripting/ScriptingTargetPlatformDetector.kt
|
2
|
6471
|
// 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.base.scripting
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.facet.platform.TargetPlatformDetector
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettingsTracker
import org.jetbrains.kotlin.idea.core.script.ScriptRelatedModuleNameFile
import org.jetbrains.kotlin.idea.facet.KotlinFacetModificationTracker
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.platform.jvm.JdkPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
private val SCRIPT_LANGUAGE_SETTINGS = Key.create<CachedValue<ScriptLanguageSettings>>("SCRIPT_LANGUAGE_SETTINGS")
private data class ScriptLanguageSettings(
val languageVersionSettings: LanguageVersionSettings,
val targetPlatformVersion: TargetPlatformVersion
)
internal object ScriptingTargetPlatformDetector : TargetPlatformDetector {
override fun detectPlatform(file: KtFile): TargetPlatform? {
val definition = runReadAction {
file.takeIf { it.isValid && it.isScript() }?.findScriptDefinition()
} ?: return null
val virtualFile = file.originalFile.virtualFile ?: return null
return getPlatform(file.project, virtualFile, definition)
}
fun getLanguageVersionSettings(project: Project, virtualFile: VirtualFile, definition: ScriptDefinition): LanguageVersionSettings {
return getScriptSettings(project, virtualFile, definition).languageVersionSettings
}
fun getTargetPlatformVersion(project: Project, virtualFile: VirtualFile, definition: ScriptDefinition): TargetPlatformVersion {
return getScriptSettings(project, virtualFile, definition).targetPlatformVersion
}
fun getPlatform(project: Project, virtualFile: VirtualFile, definition: ScriptDefinition): TargetPlatform {
val targetPlatformVersion = getScriptSettings(project, virtualFile, definition).targetPlatformVersion
if (targetPlatformVersion != TargetPlatformVersion.NoVersion) {
for (compilerPlatform in CommonPlatforms.allSimplePlatforms) {
if (compilerPlatform.single().targetPlatformVersion == targetPlatformVersion) {
return compilerPlatform
}
}
}
val platformNameFromDefinition = definition.platform
for (compilerPlatform in CommonPlatforms.allSimplePlatforms) {
// FIXME(dsavvinov): get rid of matching by name
if (compilerPlatform.single().platformName == platformNameFromDefinition) {
return compilerPlatform
}
}
return JvmPlatforms.defaultJvmPlatform
}
private fun getScriptSettings(project: Project, virtualFile: VirtualFile, definition: ScriptDefinition): ScriptLanguageSettings {
val scriptModule = getScriptModule(project, virtualFile)
val environmentCompilerOptions = definition.defaultCompilerOptions
val args = definition.compilerOptions
return if (environmentCompilerOptions.none() && args.none()) {
val languageVersionSettings = scriptModule?.languageVersionSettings ?: project.languageVersionSettings
val platformVersion = detectDefaultTargetPlatformVersion(scriptModule?.platform)
ScriptLanguageSettings(languageVersionSettings, platformVersion)
} else {
val settings = definition.getUserData(SCRIPT_LANGUAGE_SETTINGS) ?: createCachedValue(project) {
val compilerArguments = K2JVMCompilerArguments()
parseCommandLineArguments(environmentCompilerOptions.toList(), compilerArguments)
parseCommandLineArguments(args.toList(), compilerArguments)
// TODO: reporting
val languageVersionSettings = compilerArguments.toLanguageVersionSettings(MessageCollector.NONE)
val platformVersion = compilerArguments.jvmTarget?.let { JvmTarget.fromString(it) }
?: detectDefaultTargetPlatformVersion(scriptModule?.platform)
ScriptLanguageSettings(languageVersionSettings, platformVersion)
}.also { definition.putUserData(SCRIPT_LANGUAGE_SETTINGS, it) }
settings.value
}
}
private fun getScriptModule(project: Project, virtualFile: VirtualFile): Module? {
val scriptModuleName = ScriptRelatedModuleNameFile[project, virtualFile]
return if (scriptModuleName != null) {
ModuleManager.getInstance(project).findModuleByName(scriptModuleName)
} else {
ProjectFileIndex.getInstance(project).getModuleForFile(virtualFile)
}
}
private fun detectDefaultTargetPlatformVersion(platform: TargetPlatform?): TargetPlatformVersion {
return platform?.subplatformsOfType<JdkPlatform>()?.firstOrNull()?.targetVersion ?: TargetPlatformVersion.NoVersion
}
}
private inline fun createCachedValue(project: Project, crossinline body: () -> ScriptLanguageSettings): CachedValue<ScriptLanguageSettings> {
return CachedValuesManager.getManager(project).createCachedValue {
CachedValueProvider.Result(
body(),
KotlinFacetModificationTracker.getInstance(project),
KotlinCompilerSettingsTracker.getInstance(project)
)
}
}
|
apache-2.0
|
a926b066969c1b98ecd193322a2a4b58
| 49.96063 | 141 | 0.759079 | 5.592913 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightProfile.kt
|
2
|
2385
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.maddyhome.idea.copyright
import com.intellij.configurationStore.SerializableScheme
import com.intellij.configurationStore.serializeObjectInto
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.options.ExternalizableScheme
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
import com.maddyhome.idea.copyright.pattern.EntityUtil
import org.jdom.Element
@JvmField
val DEFAULT_COPYRIGHT_NOTICE: String = EntityUtil.encode(
"Copyright (c) \$originalComment.match(\"Copyright \\(c\\) (\\d+)\", 1, \"-\", \"\$today.year\")\$today.year. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n" +
"Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. \n" +
"Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. \n" +
"Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. \n" +
"Vestibulum commodo. Ut rhoncus gravida arcu. ")
class CopyrightProfile @JvmOverloads constructor(profileName: String? = null) : ExternalizableScheme, BaseState(), SerializableScheme {
// ugly name to preserve compatibility
// must be not private because otherwise binding is not created for private accessor
@Suppress("MemberVisibilityCanBePrivate")
@get:OptionTag("myName")
var profileName: String? by string()
var notice: String? by string(DEFAULT_COPYRIGHT_NOTICE)
var keyword: String? by string(EntityUtil.encode("Copyright"))
var allowReplaceRegexp: String? by string()
@Deprecated("use allowReplaceRegexp instead", ReplaceWith(""))
var allowReplaceKeyword: String? by string()
init {
// otherwise will be as default value and name will be not serialized
this.profileName = profileName
}
// ugly name to preserve compatibility
@Transient
@NlsSafe
override fun getName(): String = profileName ?: ""
override fun setName(value: String) {
profileName = value
}
override fun toString(): String = profileName ?: ""
override fun writeScheme(): Element {
val element = Element("copyright")
serializeObjectInto(this, element)
return element
}
}
|
apache-2.0
|
1a9dccbf252aa97e06e96108dbdf910c
| 41.589286 | 174 | 0.761006 | 4.126298 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.