repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/fonts/FontManager.kt | 1 | 2782 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.monksanctum.xand11.fonts
import org.monksanctum.xand11.core.FONT_DEBUG
import org.monksanctum.xand11.core.Font
import org.monksanctum.xand11.core.Platform
import org.monksanctum.xand11.core.Platform.Companion.intToHexString
class FontManager {
private val mFonts = mutableMapOf<Int, Font>()
private val mDefaultFonts: Array<FontSpec>
init {
mDefaultFonts = FontSpec.defaultSpecs
}
fun openFont(fid: Int, name: String) {
if (DEBUG) Platform.logd(TAG, "openFont " + intToHexString(fid) + " " + name)
val font = openFont(name)
synchronized(mFonts) {
mFonts.put(fid, font)
}
}
private fun openFont(name: String): Font {
for (i in mDefaultFonts.indices) {
val fontSpec = mDefaultFonts[i].matches(name)
if (fontSpec != null) {
if (DEBUG) Platform.logd(TAG, "openFont " + fontSpec.toString())
return Font(fontSpec, name)
}
}
if (DEBUG) Platform.logd(TAG, "Unknown font $name")
return Font(FontSpec(name), name)
}
fun closeFont(fid: Int) {
if (DEBUG) Platform.logd(TAG, "closeFont " + intToHexString(fid))
synchronized(mFonts) {
mFonts.remove(fid)
}
}
fun getFont(fid: Int): Font? {
synchronized(mFonts) {
if (DEBUG) Platform.logd(TAG, "getFont " + intToHexString(fid))
return mFonts.get(fid)
}
}
fun getFontsMatching(pattern: String, max: Int): List<Font> {
val fonts = ArrayList<Font>()
for (i in mDefaultFonts.indices) {
val fontSpec = mDefaultFonts[i].matches(pattern)
if (fontSpec != null) {
// if (DEBUG) Platform.logd(TAG, "Adding " + fontSpec.toString());
fonts.add(Font(fontSpec, null))
}
if (fonts.size == max) {
break
}
}
if (DEBUG) Platform.logd(TAG, "getFontsMatching " + pattern + " " + fonts.size)
return fonts
}
companion object {
private val TAG = "FontManager"
val DEBUG = FONT_DEBUG
}
}
| apache-2.0 | b0824f509262a831bdf11abd5e331c1f | 30.977011 | 97 | 0.607836 | 4.002878 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLines.kt | 1 | 3282 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.editor.Editor
import com.intellij.util.EventDispatcher
import java.util.*
val NOTEBOOK_CELL_LINES_INTERVAL_DATA_KEY = DataKey.create<NotebookCellLines.Interval>("NOTEBOOK_CELL_LINES_INTERVAL")
/**
* Incrementally iterates over Notebook document, calculates line ranges of cells using lexer.
* Fast enough for running in EDT, but could be used in any other thread.
*
* Note: there's a difference between this model and the PSI model.
* If a document starts not with a cell marker, this class treat the text before the first cell marker as a raw cell.
* PSI model treats such cell as a special "stem" cell which is not a Jupyter cell at all.
* We haven't decided which model is correct and which should be fixed. So, for now avoid using stem cells in tests,
* while UI of PyCharm DS doesn't allow to create a stem cell at all.
*/
interface NotebookCellLines {
enum class CellType {
CODE, MARKDOWN, RAW
}
data class Marker(
val ordinal: Int,
val type: CellType,
val offset: Int,
val length: Int
) : Comparable<Marker> {
override fun compareTo(other: Marker): Int = offset - other.offset
}
enum class MarkersAtLines(val hasTopLine: Boolean, val hasBottomLine: Boolean) {
NO(false, false),
TOP(true, false),
BOTTOM(false, true),
TOP_AND_BOTTOM(true, true)
}
data class Interval(
val ordinal: Int,
val type: CellType,
val lines: IntRange,
val markers: MarkersAtLines,
) : Comparable<Interval> {
override fun compareTo(other: Interval): Int = lines.first - other.lines.first
}
interface IntervalListener : EventListener {
/**
* Called when amount of intervals is changed, or types of some intervals are changed,
* or line counts of intervals is changed.
*
* Intervals that were just shifted are included neither [oldIntervals], nor in [newIntervals].
*
* Intervals in the lists are valid only until the document changes. Check their validity
* when postponing handling of intervals.
*
* It is guaranteed that:
* * At least one of [oldIntervals] and [newIntervals] is not empty.
* * Ordinals from every list defines an arithmetical progression where
* every next element has ordinal of the previous element incremented by one.
* * If both lists are not empty, the first elements of both lists has the same ordinal.
* * Both lists don't contain any interval that has been only shifted, shrank or enlarged.
*
* See `NotebookCellLinesTest` for examples of calls for various changes.
*/
fun segmentChanged(oldIntervals: List<Interval>, newIntervals: List<Interval>)
}
fun intervalsIterator(startLine: Int = 0): ListIterator<Interval>
val intervals: List<Interval>
val intervalListeners: EventDispatcher<IntervalListener>
val modificationStamp: Long
companion object {
fun get(editor: Editor): NotebookCellLines =
editor.notebookCellLinesProvider?.create(editor.document)
?: error("Can't get for $editor with document ${editor.document}")
fun hasSupport(editor: Editor): Boolean =
editor.notebookCellLinesProvider != null
}
} | apache-2.0 | 8fb5f5efb4de913be03b427b1057960d | 36.306818 | 118 | 0.721511 | 4.358566 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringSupport.kt | 4 | 7707 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.suggested
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtension
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.hasErrorElementInRange
import com.intellij.psi.util.parents
/**
* Language extension to implement to support suggested Rename and/or Change Signature refactorings.
*/
interface SuggestedRefactoringSupport {
companion object : LanguageExtension<SuggestedRefactoringSupport>("com.intellij.suggestedRefactoringSupport") {
@Suppress("RedundantOverride")
override fun forLanguage(l: Language): SuggestedRefactoringSupport? {
return super.forLanguage(l)
}
}
/**
* Returns true, if given PsiElement is a declaration which may be subject of suggested refactoring.
*
* Note, that if Change Signature is supported then individual parameters must not be considered as declarations
* for they are part of a bigger declaration.
*/
fun isDeclaration(psiElement: PsiElement): Boolean
/**
* Returns "signature range" for a given declaration.
*
* Signature range is a range that contains all properties taken into account by Change Signature refactoring.
* If only Rename refactoring is supported for the given declaration, the name identifier range must be returned.
*
* Only PsiElement's that are classified as declarations by [isDeclaration] method must be passed to this method.
* @return signature range for the declaration, or *null* if declaration is considered unsuitable for refactoring
* (usually when it has syntax error).
*/
fun signatureRange(declaration: PsiElement): TextRange?
/**
* Returns range in the given file taken by imports (if supported by the language).
*
* If no imports exist yet in the given file, it must return an empty range within whitespace where the imports are to be inserted.
* @return range taken by imports, or *null* if imports are not supported by the language.
*/
fun importsRange(psiFile: PsiFile): TextRange?
/**
* Returns name range for a given declaration.
*
* Only PsiElement's that are classified as declarations by [isDeclaration] method must be passed to this method.
* @return name range for the declaration, or *null* if declaration does not have a name.
*/
fun nameRange(declaration: PsiElement): TextRange?
@JvmDefault
open fun hasSyntaxError(declaration: PsiElement): Boolean {
val signatureRange = signatureRange(declaration) ?: return true
return declaration.containingFile.hasErrorElementInRange(signatureRange)
}
/**
* Determines if the character can start an identifier in the language.
*
* This method is used for suppression of refactoring for a declaration which has been just typed by the user.
*/
fun isIdentifierStart(c: Char): Boolean
/**
* Determines if an identifier can contain the character.
*
* This method is used for suppression of refactoring for a declaration which has been just typed by the user.
*/
fun isIdentifierPart(c: Char): Boolean
/**
* A service transforming a sequence of declaration states into [SuggestedRefactoringState].
*
* Use [SuggestedRefactoringStateChanges.RenameOnly] if only Rename refactoring is supported.
*/
val stateChanges: SuggestedRefactoringStateChanges
/**
* A service determining available refactoring for a given [SuggestedRefactoringState].
*
* Use [SuggestedRefactoringAvailability.RenameOnly] if only Rename refactoring is supported.
*/
val availability: SuggestedRefactoringAvailability
/**
* A service providing information required for building user-interface of Change Signature refactoring.
*
* Use [SuggestedRefactoringUI.RenameOnly] if only Rename refactoring is supported.
*/
val ui: SuggestedRefactoringUI
/**
* A service performing actual changes in the code when user executes suggested refactoring.
*
* Use [SuggestedRefactoringExecution.RenameOnly] if only Rename refactoring is supported.
*/
val execution: SuggestedRefactoringExecution
/**
* A class with data representing declaration signature.
*
* This data is used mainly for signature change presentation and for detection of refactoring availability.
* No PSI-related objects must be referenced by instances of this class and all PSI-related information
* that is required to perform the refactoring must be extracted from the declaration itself prior to perform the refactoring.
*/
class Signature private constructor(
val name: String,
val type: String?,
val parameters: List<Parameter>,
val additionalData: SignatureAdditionalData?,
private val nameToParameter: Map<String, Parameter>
) {
private val idToParameter: Map<Any, Parameter> = mutableMapOf<Any, Parameter>().apply {
for (parameter in parameters) {
val prev = this.put(parameter.id, parameter)
require(prev == null) { "Duplicate parameter id: ${parameter.id}" }
}
}
private val parameterToIndex = parameters.withIndex().associate { (index, parameter) -> parameter to index }
fun parameterById(id: Any): Parameter? = idToParameter[id]
fun parameterByName(name: String): Parameter? = nameToParameter[name]
fun parameterIndex(parameter: Parameter): Int = parameterToIndex[parameter]!!
override fun equals(other: Any?): Boolean {
return other is Signature &&
name == other.name &&
type == other.type &&
additionalData == other.additionalData &&
parameters == other.parameters
}
override fun hashCode(): Int {
return 0
}
companion object {
/**
* Factory method, used to create instances of [Signature] class.
*
* @return create instance of [Signature], or *null* if it cannot be created due to duplicated parameter names
*/
@JvmStatic
fun create(
name: String,
type: String?,
parameters: List<Parameter>,
additionalData: SignatureAdditionalData?
): Signature? {
val nameToParameter = mutableMapOf<String, Parameter>()
for (parameter in parameters) {
val key = parameter.name
if (nameToParameter.containsKey(key)) return null
nameToParameter[key] = parameter
}
return Signature(name, type, parameters, additionalData, nameToParameter)
}
}
}
/**
* A class representing a parameter in [Signature].
*
* Parameters with the same [id] represent the same parameter in the old and new signatures.
* All parameters in the same [Signature] must have unique [id].
*/
data class Parameter(
val id: Any,
@NlsSafe val name: String,
val type: String,
val additionalData: ParameterAdditionalData? = null
)
/**
* Language-specific information to be stored in [Signature].
*
* Don't put any PSI-related objects here.
*/
interface SignatureAdditionalData {
override fun equals(other: Any?): Boolean
}
/**
* Language-specific information to be stored in [Parameter].
*
* Don't put any PSI-related objects here.
*/
interface ParameterAdditionalData {
override fun equals(other: Any?): Boolean
}
}
fun SuggestedRefactoringSupport.declarationByOffset(psiFile: PsiFile, offset: Int): PsiElement? {
return psiFile.findElementAt(offset)
?.parents(true)
?.firstOrNull { isDeclaration(it) }
}
| apache-2.0 | ecf7cb8b3c8efa90e903d92ed044594c | 35.875598 | 140 | 0.717789 | 4.874763 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/model/mesh/MeshFactory.kt | 1 | 2440 | package com.cout970.modeler.core.model.mesh
import com.cout970.modeler.api.model.mesh.IMesh
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.plus
import com.cout970.vector.extensions.times
import com.cout970.vector.extensions.vec2Of
import com.cout970.vector.extensions.vec3Of
/**
* Created by cout970 on 2017/05/28.
*/
object MeshFactory {
fun createPlaneY(size: IVector2): IMesh {
return Mesh(
listOf(vec3Of(0, 0, 0), vec3Of(0, 0, 1), vec3Of(1, 0, 1), vec3Of(1, 0, 0))
.map { it * vec3Of(size.x, 1, size.y) },
listOf(vec2Of(0, 0), vec2Of(1, 0), vec2Of(1, 1), vec2Of(0, 1)),
listOf(FaceIndex.from(listOf(0, 1, 2, 3), listOf(0, 1, 2, 3)))
)
}
fun createPlaneZ(size: IVector2): IMesh {
return Mesh(
listOf(vec3Of(0, 0, 0), vec3Of(0, 1, 0), vec3Of(1, 1, 0), vec3Of(1, 0, 0))
.map { it * vec3Of(size.x, size.y, 1) },
listOf(vec2Of(0, 0), vec2Of(1, 0), vec2Of(1, 1), vec2Of(0, 1)),
listOf(FaceIndex.from(listOf(0, 1, 2, 3), listOf(0, 1, 2, 3)))
)
}
fun createCube(size: IVector3, offset: IVector3): IMesh {
val n: IVector3 = offset
val p: IVector3 = size + offset
return createAABB(n, p)
}
fun createAABB(n: IVector3, p: IVector3): IMesh {
val pos = listOf(
vec3Of(p.x, n.y, n.z), //0
vec3Of(p.x, n.y, p.z), //1
vec3Of(n.x, n.y, p.z), //2
vec3Of(n.x, n.y, n.z), //3
vec3Of(n.x, p.y, p.z), //4
vec3Of(p.x, p.y, p.z), //5
vec3Of(p.x, p.y, n.z), //6
vec3Of(n.x, p.y, n.z) //7
)
val tex = listOf(vec2Of(0, 0), vec2Of(1, 0), vec2Of(1, 1), vec2Of(0, 1))
val faces = listOf(
FaceIndex.from(listOf(0, 1, 2, 3), listOf(0, 1, 2, 3)), // down
FaceIndex.from(listOf(4, 5, 6, 7), listOf(0, 1, 2, 3)), // up
FaceIndex.from(listOf(7, 6, 0, 3), listOf(0, 1, 2, 3)), // north
FaceIndex.from(listOf(1, 5, 4, 2), listOf(0, 1, 2, 3)), // south
FaceIndex.from(listOf(2, 4, 7, 3), listOf(0, 1, 2, 3)), // west
FaceIndex.from(listOf(6, 5, 1, 0), listOf(0, 1, 2, 3)) // east
)
return Mesh(pos, tex, faces)
}
} | gpl-3.0 | 9765d377f274491845b4b2668f6ecca9 | 36.553846 | 90 | 0.514754 | 2.791762 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/CreatorDashboardReferrerStatsHolderViewModel.kt | 1 | 4155 | package com.kickstarter.viewmodels
import android.util.Pair
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.PairUtils
import com.kickstarter.libs.utils.extensions.compareDescending
import com.kickstarter.models.Project
import com.kickstarter.services.apiresponses.ProjectStatsEnvelope.ReferrerStats
import com.kickstarter.ui.viewholders.CreatorDashboardReferrerStatsViewHolder
import rx.Observable
import rx.subjects.PublishSubject
import java.util.Collections
interface CreatorDashboardReferrerStatsHolderViewModel {
interface Inputs {
/** Current project and list of referrer stats. */
fun projectAndReferrerStatsInput(projectAndReferrerStats: Pair<Project, List<ReferrerStats>>)
}
interface Outputs {
/** Emits current project and sorted referrer stats. */
fun projectAndReferrerStats(): Observable<Pair<Project, List<ReferrerStats>>>
/** Emits when there are no referrer stats. */
fun referrerStatsListIsGone(): Observable<Boolean>
/** Emits when there are more than 10 referrer stats and title copy should reflect limited list. */
fun referrersTitleIsTopTen(): Observable<Boolean>
}
class ViewModel(environment: Environment) :
ActivityViewModel<CreatorDashboardReferrerStatsViewHolder>(environment), Inputs, Outputs {
private val projectAndReferrerStatsInput =
PublishSubject.create<Pair<Project, List<ReferrerStats>>>()
private val projectAndReferrerStats: Observable<Pair<Project, List<ReferrerStats>>>
private val referrerStatsListIsGone = PublishSubject.create<Boolean>()
private val referrersTitleIsLimitedCopy = PublishSubject.create<Boolean>()
val inputs: Inputs = this
val outputs: Outputs = this
init {
val sortedReferrerStats = projectAndReferrerStatsInput
.map { PairUtils.second(it) }
.map { sortReferrerStats(it) }
val limitedSortedReferrerStats = sortedReferrerStats
.map<List<ReferrerStats>> { stats: List<ReferrerStats> ->
ArrayList(
stats.subList(
0,
Math.min(stats.size, 10)
)
)
}
projectAndReferrerStats = projectAndReferrerStatsInput
.map { PairUtils.first(it) }
.compose(Transformers.combineLatestPair(limitedSortedReferrerStats))
sortedReferrerStats
.map { it.isEmpty() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(referrerStatsListIsGone)
sortedReferrerStats
.map { it.size > 10 }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(referrersTitleIsLimitedCopy)
}
private inner class OrderByBackersReferrerStatsComparator : Comparator<ReferrerStats> {
override fun compare(o1: ReferrerStats, o2: ReferrerStats): Int {
return o1.pledged().compareDescending(o2.pledged())
}
}
private fun sortReferrerStats(referrerStatsList: List<ReferrerStats>): List<ReferrerStats> {
val referrerStatsComparator = OrderByBackersReferrerStatsComparator()
Collections.sort(referrerStatsList, referrerStatsComparator)
return referrerStatsList
}
override fun projectAndReferrerStatsInput(projectAndReferrerStats: Pair<Project, List<ReferrerStats>>) {
projectAndReferrerStatsInput.onNext(projectAndReferrerStats)
}
override fun projectAndReferrerStats(): Observable<Pair<Project, List<ReferrerStats>>> = projectAndReferrerStats
override fun referrerStatsListIsGone(): Observable<Boolean> = referrerStatsListIsGone
override fun referrersTitleIsTopTen(): Observable<Boolean> = referrersTitleIsLimitedCopy
}
}
| apache-2.0 | b0fd8265c498d402e8060a9eb0e40322 | 41.397959 | 120 | 0.676775 | 5.252845 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/ProjectStructureProviderIdeImpl.kt | 1 | 2372 | // 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.base.projectStructure
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.project.structure.KtBinaryModule
import org.jetbrains.kotlin.analysis.project.structure.KtModule
import org.jetbrains.kotlin.analysis.project.structure.ProjectStructureProvider
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.base.util.Frontend10ApiUsage
@OptIn(Frontend10ApiUsage::class)
internal class ProjectStructureProviderIdeImpl(private val project: Project) : ProjectStructureProvider() {
override fun getKtModuleForKtElement(element: PsiElement): KtModule {
val config = ModuleInfoProvider.Configuration(createSourceLibraryInfoForLibraryBinaries = false)
val moduleInfo = ModuleInfoProvider.getInstance(element.project).firstOrNull(element, config)
?: NotUnderContentRootModuleInfo
return getKtModuleByModuleInfo(moduleInfo)
}
// TODO maybe introduce some cache?
fun getKtModuleByModuleInfo(moduleInfo: ModuleInfo): KtModule =
createKtModuleByModuleInfo(moduleInfo)
private fun createKtModuleByModuleInfo(moduleInfo: ModuleInfo): KtModule = when (moduleInfo) {
is ModuleSourceInfo -> KtSourceModuleByModuleInfo(moduleInfo, this)
is LibraryInfo -> KtLibraryModuleByModuleInfo(moduleInfo, this)
is SdkInfo -> SdkKtModuleByModuleInfo(moduleInfo, this)
is LibrarySourceInfo -> KtLibrarySourceModuleByModuleInfo(moduleInfo, this)
is NotUnderContentRootModuleInfo -> NotUnderContentRootModuleByModuleInfo(moduleInfo, this)
else -> NotUnderContentRootModuleByModuleInfo(moduleInfo as IdeaModuleInfo, this)
}
override fun getKtBinaryModules(): Collection<KtBinaryModule> {
TODO("This is a temporary function used for Android LINT, and should not be called in the IDE")
}
companion object {
fun getInstance(project: Project): ProjectStructureProviderIdeImpl {
return project.getService(ProjectStructureProvider::class.java) as ProjectStructureProviderIdeImpl
}
}
}
| apache-2.0 | 1fe20e56466b1602a7f8fceb209e31d1 | 50.565217 | 158 | 0.783727 | 5.112069 | false | true | false | false |
SimpleMobileTools/Simple-Music-Player | app/src/main/kotlin/com/simplemobiletools/musicplayer/dialogs/RemovePlaylistDialog.kt | 1 | 1334 | package com.simplemobiletools.musicplayer.dialogs
import android.app.Activity
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.musicplayer.R
import com.simplemobiletools.musicplayer.models.Playlist
import kotlinx.android.synthetic.main.dialog_remove_playlist.view.*
class RemovePlaylistDialog(val activity: Activity, val playlist: Playlist? = null, val callback: (deleteFiles: Boolean) -> Unit) {
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_remove_playlist, null).apply {
remove_playlist_description.text = getDescriptionText()
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { dialog, which -> callback(view.remove_playlist_checkbox.isChecked) }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this, R.string.remove_playlist)
}
}
private fun getDescriptionText(): String {
return if (playlist == null) {
activity.getString(R.string.remove_playlist_description)
} else
String.format(activity.resources.getString(R.string.remove_playlist_description_placeholder), playlist.title)
}
}
| gpl-3.0 | 5e5c25d1f7c6379e74d78f6633010d22 | 43.466667 | 130 | 0.721889 | 4.648084 | false | false | false | false |
simoneapp/S3-16-simone | app/src/main/java/app/simone/multiplayer/view/newmatch/FriendsListAdapter.kt | 2 | 1401 | package app.simone.multiplayer.view.newmatch
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import app.simone.R.layout
import app.simone.multiplayer.model.FacebookUser
import app.simone.multiplayer.view.FriendsCellFiller
/**
* Created by nicola on 23/06/2017.
*/
class FriendsListAdapter//val config = ImageLoaderConfiguration.createDefault(getContext())
//ImageLoader.getInstance().init(config)
(context: Context, data: List<FacebookUser>, fragment: FriendsListFragment) : ArrayAdapter<FacebookUser>(context, layout.cell_friends) {
var fragment : FriendsListFragment? = fragment
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
var convertView = convertView
if(convertView == null) {
convertView = LayoutInflater.from(context).inflate(layout.cell_friends, parent, false)
}
val friend = getItem(position).let { it } ?: return convertView!!
FriendsCellFiller.setName(convertView, friend.name)
FriendsCellFiller.setImage(convertView, friend.picture, fragment?.activity)
if(fragment?.selectedUsers != null) {
FriendsCellFiller.setSelected(convertView, fragment!!.selectedUsers.contains(friend), fragment?.activity)
}
return convertView
}
} | mit | dda703f79a5a1fb3690de62ec83d8b73 | 34.05 | 136 | 0.739472 | 4.461783 | false | true | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/idea/IdeStarter.kt | 1 | 12658 | // 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.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.idea
import com.intellij.diagnostic.*
import com.intellij.diagnostic.StartUpMeasurer.startActivity
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.customize.CommonCustomizeIDEWizardDialog
import com.intellij.ide.customize.CustomizeIDEWizardDialog
import com.intellij.ide.customize.CustomizeIDEWizardStepsProvider
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.plugins.DisabledPluginsState
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.notification.Notification
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.SystemDock
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.ui.AppUIUtil
import com.intellij.ui.mac.touchbar.TouchBarsManager
import com.intellij.util.ui.accessibility.ScreenReader
import java.awt.EventQueue
import java.beans.PropertyChangeListener
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ForkJoinPool
import javax.swing.JOptionPane
open class IdeStarter : ApplicationStarter {
companion object {
@JvmStatic
private var filesToLoad: List<Path> = emptyList()
@JvmStatic
private var wizardStepProvider: CustomizeIDEWizardStepsProvider? = null
@JvmStatic
fun openFilesOnLoading(value: List<Path>) {
filesToLoad = value
}
@JvmStatic
fun setWizardStepsProvider(provider: CustomizeIDEWizardStepsProvider) {
wizardStepProvider = provider
}
}
override fun isHeadless() = false
override fun getCommandName(): String? = null
final override fun getRequiredModality() = ApplicationStarter.NOT_IN_EDT
override fun main(args: List<String>) {
val app = ApplicationManagerEx.getApplicationEx()
assert(!app.isDispatchThread)
if (app.isLightEditMode && !app.isHeadlessEnvironment) {
// In a light mode UI is shown very quickly, tab layout requires ActionManager but it is forbidden to init ActionManager in EDT,
// so, preload
ForkJoinPool.commonPool().execute {
ActionManager.getInstance()
}
}
val frameInitActivity = startActivity("frame initialization")
val windowManager = WindowManagerEx.getInstanceEx()
runActivity("IdeEventQueue informing about WindowManager") {
IdeEventQueue.getInstance().setWindowManager(windowManager)
}
val lifecyclePublisher = app.messageBus.syncPublisher(AppLifecycleListener.TOPIC)
openProjectIfNeeded(args, app, frameInitActivity, lifecyclePublisher)
reportPluginErrors()
if (!app.isHeadlessEnvironment) {
postOpenUiTasks(app)
}
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.APP_STARTED)
lifecyclePublisher.appStarted()
if (!app.isHeadlessEnvironment && PluginManagerCore.isRunningFromSources()) {
AppUIUtil.updateWindowIcon(JOptionPane.getRootFrame())
}
}
protected open fun openProjectIfNeeded(args: List<String>,
app: ApplicationEx,
frameInitActivity: Activity,
lifecyclePublisher: AppLifecycleListener) {
frameInitActivity.runChild("app frame created callback") {
lifecyclePublisher.appFrameCreated(args)
}
// must be after appFrameCreated because some listeners can mutate state of RecentProjectsManager
if (app.isHeadlessEnvironment) {
frameInitActivity.end()
LifecycleUsageTriggerCollector.onIdeStart()
lifecyclePublisher.appStarting(null)
return
}
if (JetBrainsProtocolHandler.appStartedWithCommand()) {
val needToOpenProject = showWizardAndWelcomeFrame(lifecyclePublisher, willOpenProject = false)
frameInitActivity.end()
LifecycleUsageTriggerCollector.onIdeStart()
val project = when {
!needToOpenProject -> null
!filesToLoad.isEmpty() -> ProjectUtil.tryOpenFiles(null, filesToLoad, "MacMenu")
!args.isEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
lifecyclePublisher.appStarting(project)
}
else {
val recentProjectManager = RecentProjectsManager.getInstance()
val willReopenRecentProjectOnStart = recentProjectManager.willReopenProjectOnStart()
val willOpenProject = willReopenRecentProjectOnStart || !args.isEmpty() || !filesToLoad.isEmpty()
val needToOpenProject = showWizardAndWelcomeFrame(lifecyclePublisher, willOpenProject)
frameInitActivity.end()
ForkJoinPool.commonPool().execute {
LifecycleUsageTriggerCollector.onIdeStart()
}
if (!needToOpenProject) {
lifecyclePublisher.appStarting(null)
return
}
val project = when {
!filesToLoad.isEmpty() -> ProjectUtil.tryOpenFiles(null, filesToLoad, "MacMenu")
!args.isEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
lifecyclePublisher.appStarting(project)
if (project == null && willReopenRecentProjectOnStart) {
recentProjectManager.reopenLastProjectsOnStart().thenAccept { isOpened ->
if (!isOpened) {
WelcomeFrame.showIfNoProjectOpened()
}
}
}
}
}
private fun showWizardAndWelcomeFrame(lifecyclePublisher: AppLifecycleListener, willOpenProject: Boolean): Boolean {
val doShowWelcomeFrame = if (willOpenProject) null else WelcomeFrame.prepareToShow()
// do not show Customize IDE Wizard [IDEA-249516]
val wizardStepProvider = wizardStepProvider
if (wizardStepProvider == null || System.getProperty("idea.show.customize.ide.wizard")?.toBoolean() != true) {
if (doShowWelcomeFrame == null) {
return true
}
ApplicationManager.getApplication().invokeLater {
doShowWelcomeFrame.run()
lifecyclePublisher.welcomeScreenDisplayed()
}
return false
}
// temporary until 211 release
val stepDialogName = System.getProperty("idea.temp.change.ide.wizard")
?: ApplicationInfoImpl.getShadowInstance().customizeIDEWizardDialog
ApplicationManager.getApplication().invokeLater {
val wizardDialog: CommonCustomizeIDEWizardDialog?
if (stepDialogName.isNullOrBlank()) {
wizardDialog = CustomizeIDEWizardDialog(wizardStepProvider, null, false, true)
}
else {
wizardDialog = try {
Class.forName(stepDialogName).getConstructor(StartupUtil.AppStarter::class.java)
.newInstance(null) as CommonCustomizeIDEWizardDialog
}
catch (e: Throwable) {
Main.showMessage(BootstrapBundle.message("bootstrap.error.title.configuration.wizard.failed"), e)
null
}
}
wizardDialog?.showIfNeeded()
if (doShowWelcomeFrame != null) {
doShowWelcomeFrame.run()
lifecyclePublisher.welcomeScreenDisplayed()
}
}
return false
}
internal class StandaloneLightEditStarter : IdeStarter() {
override fun openProjectIfNeeded(args: List<String>,
app: ApplicationEx,
frameInitActivity: Activity,
lifecyclePublisher: AppLifecycleListener) {
val project = when {
!filesToLoad.isEmpty() -> ProjectUtil.tryOpenFiles(null, filesToLoad, "MacMenu")
!args.isEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
if (project == null && !JetBrainsProtocolHandler.appStartedWithCommand()) {
val recentProjectManager = RecentProjectsManager.getInstance()
(if (recentProjectManager.willReopenProjectOnStart()) recentProjectManager.reopenLastProjectsOnStart()
else CompletableFuture.completedFuture(true))
.thenAccept { isOpened ->
if (!isOpened) {
ApplicationManager.getApplication().invokeLater {
LightEditService.getInstance().showEditorWindow()
}
}
}
}
}
}
}
private fun loadProjectFromExternalCommandLine(commandLineArgs: List<String>): Project? {
val currentDirectory = System.getenv(SocketLock.LAUNCHER_INITIAL_DIRECTORY_ENV_VAR)
@Suppress("SSBasedInspection")
Logger.getInstance("#com.intellij.idea.ApplicationLoader").info("ApplicationLoader.loadProject (cwd=${currentDirectory})")
val result = CommandLineProcessor.processExternalCommandLine(commandLineArgs, currentDirectory)
if (result.hasError) {
ApplicationManager.getApplication().invokeAndWait {
result.showErrorIfFailed()
ApplicationManager.getApplication().exit(true, true, false)
}
}
return result.project
}
private fun postOpenUiTasks(app: Application) {
if (SystemInfoRt.isMac) {
ForkJoinPool.commonPool().execute {
runActivity("mac touchbar on app init") {
TouchBarsManager.onApplicationInitialized()
if (TouchBarsManager.isTouchBarAvailable()) {
CustomActionsSchema.addSettingsGroup(IdeActions.GROUP_TOUCHBAR, IdeBundle.message("settings.menus.group.touch.bar"))
}
}
}
}
else if (SystemInfoRt.isXWindow && SystemInfo.isJetBrainsJvm) {
ForkJoinPool.commonPool().execute {
runActivity("input method disabling on Linux") {
disableInputMethodsIfPossible()
}
}
}
invokeLaterWithAnyModality("system dock menu") {
SystemDock.updateMenu()
}
invokeLaterWithAnyModality("ScreenReader") {
val generalSettings = GeneralSettings.getInstance()
generalSettings.addPropertyChangeListener(GeneralSettings.PROP_SUPPORT_SCREEN_READERS, app, PropertyChangeListener { e ->
ScreenReader.setActive(e.newValue as Boolean)
})
ScreenReader.setActive(generalSettings.isSupportScreenReaders)
}
}
private fun invokeLaterWithAnyModality(name: String, task: () -> Unit) {
EventQueue.invokeLater {
runActivity(name, task = task)
}
}
private fun reportPluginErrors() {
val pluginErrors = PluginManagerCore.getAndClearPluginLoadingErrors()
if (pluginErrors.isEmpty()) {
return
}
ApplicationManager.getApplication().invokeLater({
val title = IdeBundle.message("title.plugin.error")
val content = HtmlBuilder().appendWithSeparators(HtmlChunk.p(), pluginErrors).toString()
Notification(NotificationGroup.createIdWithTitle("Plugin Error", title), title, content, NotificationType.ERROR) { notification, event ->
notification.expire()
val description = event.description
if (PluginManagerCore.EDIT == description) {
PluginManagerConfigurable.showPluginConfigurable(
WindowManagerEx.getInstanceEx().findFrameFor(null)?.component,
null,
emptyList(),
)
return@Notification
}
if (PluginManagerCore.ourPluginsToDisable != null && PluginManagerCore.DISABLE == description) {
DisabledPluginsState.enablePluginsById(PluginManagerCore.ourPluginsToDisable, false)
}
else if (PluginManagerCore.ourPluginsToEnable != null && PluginManagerCore.ENABLE == description) {
DisabledPluginsState.enablePluginsById(PluginManagerCore.ourPluginsToEnable, true)
@Suppress("SSBasedInspection")
PluginManagerMain.notifyPluginsUpdated(null)
}
PluginManagerCore.ourPluginsToEnable = null
PluginManagerCore.ourPluginsToDisable = null
}.notify(null)
}, ModalityState.NON_MODAL)
} | apache-2.0 | 34a02196a307dae6b54fa3d535e08e90 | 37.594512 | 141 | 0.726734 | 5.043028 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/UserSearchWebApi.kt | 1 | 2529 | package alraune
import alraune.entity.*
import pieces100.*
import routine.sendJson
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class UserSearchWebApi(val req: HttpServletRequest, val resp: HttpServletResponse) {
companion object {
val path = "/api-search-users"
val pageSize = AlConst.pageSize
}
class Response(val totalCount: Long, val items: List<Item>)
class Item(val id: Long, val text: String)
enum class Simulate {Nothing, NotSignedIn, LowLevelFuckup, RandomFuckYou}
val simulate = Simulate.Nothing
fun user() =
if (simulate == Simulate.NotSignedIn) null
else rctx0.al.maybeUser()
fun fart() {
class UserFacingError(message: String) : Exception(message)
try {
val user = user() ?: throw UserFacingError(t("TOTE", "Залогинься сперва"))
if (user.kind != AlUserKind.Admin) throw UserFacingError(t("TOTE", "Тебе это, дружок, не положено"))
if (simulate == Simulate.LowLevelFuckup) throw Exception("Testing low-level fuckup")
if (simulate == Simulate.RandomFuckYou && Random().nextInt(2) == 1) throw UserFacingError("Fuck you, dear user")
val params = GetParams()
val q = params.q.let {
it.get() ?: throw UserFacingError(t("TOTE", "Я хочу `${it.name}`"))
}
val m = User.Meta
val boobs = PaginationBoobs(UsualPaginationPussy(
itemClass = User::class, table = m.table, pageSize = pageSize,
shitIntoWhere = {
it.text("and (")
it.text(" ${m.email} ilike", "$q%")
it.text(" or ${m.firstNameForSearch} ilike", "$q%")
it.text(" or ${m.lastNameForSearch} ilike", "$q%")
it.text(")")
it.text("and ${m.kind} =", AlUserKind.Writer)
it.text("and ${m.profileState} =", User.ProfileState.Approved)
},
shitOrderBy = {shitOrderById(it, params.ordering.get()!!)}
))
boobs.fart()
sendJson(resp, Response(totalCount = boobs.count, items = boobs.items.map {
Item(id = it.id, text = it.textForUserPickerEtc())
}))
} catch (e: UserFacingError) {
sendJson(resp, object {val error = e.message})
}
}
}
| apache-2.0 | 8882460a1c47eecd4226f96ba69d5da3 | 32.133333 | 124 | 0.569416 | 4.053834 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/fromJavaToKotlin/delegateToKotlinFunction.kt | 24 | 1318 | fun functionFromKotlin(): Int = 42
fun a() {
JavaClass().field
val d = JavaClass()
d.field
d.let {
it.field
}
d.also {
it.field
}
with(d) {
field
}
with(d) out@{
with(4) {
[email protected]
}
}
}
fun a2() {
val d: JavaClass? = null
d?.field
d?.let {
it.field
}
d?.also {
it.field
}
with(d) {
this?.field
}
with(d) out@{
with(4) {
this@out?.field
}
}
}
fun a3() {
val d: JavaClass? = null
val a1 = d?.field
val a2 = d?.let {
it.field
}
val a3 = d?.also {
it.field
}
val a4 = with(d) {
this?.field
}
val a5 = with(d) out@{
with(4) {
this@out?.field
}
}
}
fun a4() {
val d: JavaClass? = null
d?.field?.dec()
val a2 = d?.let {
it.field
}
a2?.toLong()
d?.also {
it.field
}?.field?.and(4)
val a4 = with(d) {
this?.field
}
val a5 = with(d) out@{
with(4) {
this@out?.field
}
}
val a6 = a4?.let { out -> a5?.let { out + it } }
}
fun JavaClass.b(): Int? = field
fun JavaClass.c(): Int = this.field
fun d(d: JavaClass) = d.field
| apache-2.0 | 565d882c45f03ca30b3535accabdcc45 | 11.921569 | 52 | 0.409712 | 3.123223 | false | false | false | false |
josecefe/Rueda | src/es/um/josecefe/rueda/persistencia/Persistencia.kt | 1 | 14271 | /*
* Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero
*
* 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 es.um.josecefe.rueda.persistencia
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import es.um.josecefe.rueda.COPYRIGHT
import es.um.josecefe.rueda.TITLE
import es.um.josecefe.rueda.VERSION
import es.um.josecefe.rueda.modelo.*
import htmlflow.HtmlView
import org.apache.commons.text.StringEscapeUtils.escapeHtml4
import java.beans.*
import java.io.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
/**
* @author josec
*/
object Persistencia {
fun guardaDatosRuedaXML(xmlfile: File, datosRueda: DatosRueda) {
try {
XMLEncoder(BufferedOutputStream(FileOutputStream(xmlfile))).use { encoder ->
with(encoder) {
exceptionListener = ExceptionListener { it.printStackTrace() }
setPersistenceDelegate(Pair::class.java, PairPersistenceDelegate())
writeObject(ArrayList(datosRueda.dias))
writeObject(ArrayList(datosRueda.lugares))
writeObject(ArrayList(datosRueda.participantes))
writeObject(ArrayList(datosRueda.horarios))
writeObject(ArrayList(datosRueda.asignacion))
writeObject(datosRueda.costeAsignacion)
}
}
} catch (ex: Exception) {
Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, null, ex)
}
}
fun cargaDatosRuedaXML(xmlfile: File): DatosRueda {
try {
XMLDecoder(
BufferedInputStream(
FileInputStream(xmlfile))).use { decoder ->
decoder.setExceptionListener { e -> Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, null, e) }
val ld = decoder.readObject() as List<*>
val dias = ld.map { e -> e as Dia }.toMutableList()
val ll = decoder.readObject() as List<*>
val lugares = ll.map { e -> e as Lugar }.toMutableList()
val lp = decoder.readObject() as List<*>
val participantes = lp.map { e -> e as Participante }.toMutableList()
val lh = decoder.readObject() as List<*>
val horarios = lh.map { e -> e as Horario }.toMutableList()
val la = decoder.readObject() as List<*>
val asignacion = la.map { e -> e as Asignacion }.toMutableList()
val costeAsignacion = decoder.readObject() as Int
return DatosRueda(dias, lugares, participantes, horarios, asignacion, costeAsignacion)
}
} catch (ex: Exception) {
Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, null, ex)
}
return DatosRueda()
}
fun guardaAsignacionRuedaXML(xmlfile: String, solucionFinal: Map<Dia, AsignacionDia>) {
try {
XMLEncoder(BufferedOutputStream(FileOutputStream(xmlfile))).use { encoder -> encoder.writeObject(solucionFinal) }
} catch (ex: FileNotFoundException) {
Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, null, ex)
}
}
fun exportaAsignacionHTML(htmlfile: File, datosRueda: DatosRueda) {
try {
PrintStream(htmlfile).use { out ->
val conLugar = datosRueda.asignacion.flatMap { a -> a.peIda }.map { it.second }.distinct().count() > 1
// Todas las horas con actividad:
val horasActivas = datosRueda.horarios.map { it.entrada }.toMutableSet()
horasActivas.addAll(datosRueda.horarios.map { it.salida }.toSet())
// Vamos a guardar en una tabla "virtual"
val datosTabla: MutableMap<Dia, MutableMap<Int, MutableList<ParticipanteIdaConduceLugar>>> = HashMap(datosRueda.dias.size)
for (a in datosRueda.asignacion) {
val d = a.dia
datosRueda.horarios.filter { h -> h.dia == d }.forEach { h ->
var horasDia = datosTabla[d]
if (horasDia == null) {
horasDia = HashMap(horasActivas.size)
datosTabla[d] = horasDia
}
val celdaIda = horasDia.computeIfAbsent(h.entrada) { ArrayList() }
val celdaVuelta = horasDia.computeIfAbsent(h.salida) { ArrayList() }
// Datos de la IDA y la VUELTA
val pIda = ParticipanteIdaConduceLugar()
val pVuelta = ParticipanteIdaConduceLugar()
pIda.ida = true
pVuelta.ida = false
pVuelta.participante = h.participante
pIda.participante = pVuelta.participante
pVuelta.conduce = a.conductores.contains(pIda.participante)
pIda.conduce = pVuelta.conduce
a.peIda.find { it.first == pIda.participante }?.let {
pIda.lugar = it.second
celdaIda.add(pIda)
}
a.peVuelta.find { p -> p.first == pVuelta.participante }?.let {
pVuelta.lugar = it.second
celdaVuelta.add(pVuelta)
}
}
}
//Ahora generamos la tabla en HTML
val htmlView = HtmlView<Any>()
htmlView.head()
.title(escapeHtml4("Asignación Rueda - " + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)))
.linkCss("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
val table = htmlView
.body().classAttr("container")
.heading(3, escapeHtml4("Asignación Rueda - " + LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT))))
.div()
.table().classAttr("table table-bordered")
val headerRow = table.tr()
headerRow.th().text("Hora")
datosRueda.dias.sorted().forEach { d -> headerRow.th().text(escapeHtml4(d.toString())) }
horasActivas.sorted().forEach { hora ->
val tr = table.tr()
tr.td().text(hora.toString()) //Hora
datosRueda.dias.sorted().forEach { dia ->
val dd = datosTabla[dia]
val t = if (dd != null) dd[hora] else null
var valor = ""
if (t != null) {
valor = t.sortedWith(kotlin.Comparator { p1, p2 ->
if (p1.ida != p2.ida)
if (p1.ida) -1 else 1
else if (p1.lugar!!.compareTo(p2.lugar!!) != 0)
p1.lugar!!.compareTo(p2.lugar!!)
else
if (p1.conduce != p2.conduce)
if (p1.conduce) -1 else 1
else
p1.participante!!.compareTo(p2.participante!!)
})
.joinToString(separator = "<br>\n") { p ->
val res = StringBuilder()
if (p.ida) {
res.append("<i>")
}
if (p.conduce) {
res.append("<b>").append(escapeHtml4("*"))
}
res.append(escapeHtml4(p.participante!!.toString()))
if (conLugar) {
res.append(" [")
res.append(escapeHtml4(p.lugar!!.toString()))
res.append("]")
}
if (p.conduce) {
res.append("</b>")
}
if (p.ida) {
res.append("</i>")
}
res.toString()
}
}
tr.td().text(valor)
}
}
// Leyenda
if (conLugar) {
htmlView.body().div().text("Leyenda: <i><b>*Conductor [Lugar de Ida]</b></i> | <i>Pasajero [Lugar de Ida]</i> | <b>*Conductor [Lugar de Vuelta]</b> | Pasajero [Lugar de Vuelta]").addAttr("style", "color:green;text-align:center")
} else {
htmlView.body().div().text("Leyenda: <i><b>*Conductor Ida</b></i> | <i>Pasajero Ida</i> | <b>*Conductor Vuelta</b> | Pasajero Vuelta").addAttr("style", "color:green;text-align:center")
}
// Coste
htmlView.body().div().text(String.format("%s <b>%,d</b>", escapeHtml4("Coste total asignación: "), datosRueda.costeAsignacion)).addAttr("style", "color:royal-blue;text-align:right")
// Cuadro de conductor/dias
htmlView.body().heading(4, escapeHtml4("Cuadro de conductor/días"))
val tabla = htmlView.body().table().classAttr("table table-bordered")
val cabecera = tabla.tr()
cabecera.th().text(escapeHtml4("Conductor"))
cabecera.th().text(escapeHtml4("Días"))
cabecera.th().text(escapeHtml4("Total"))
datosRueda.participantes.sorted().forEach { participante ->
val dias = datosRueda.asignacion.filter { a -> a.conductores.contains(participante) }.map { it.dia }.sorted()
if (dias.isNotEmpty()) {
val tr = tabla.tr()
tr.td().text(escapeHtml4(participante.nombre))
tr.td().text(escapeHtml4(dias.toString()))
tr.td().text(dias.size.toString())
}
}
// Cuadro de dia/conductores
htmlView.body().heading(4, escapeHtml4("Cuadro de día/conductores"))
val tablaDias = htmlView.body().table().classAttr("table table-bordered")
val cabeceraDias = tablaDias.tr()
cabeceraDias.th().text(escapeHtml4("Día"))
cabeceraDias.th().text(escapeHtml4("Conductores"))
cabeceraDias.th().text(escapeHtml4("Total"))
datosRueda.asignacion.sorted().forEach { a ->
val tr = tablaDias.tr()
tr.td().text(escapeHtml4(a.dia.descripcion))
tr.td().text(escapeHtml4(a.conductores.toString()))
tr.td().text(a.conductores.size.toString())
}
// Pie de pagina
htmlView.body().hr().div().text("Generado con <b>$TITLE $VERSION</b> <i>$COPYRIGHT</i>").addAttr("style", "color:royalblue;text-align:right")
htmlView.setPrintStream(out)
htmlView.write()
}
} catch (ex: Exception) {
Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, "Problemas generando la exportación a HTML: ", ex)
}
}
private class ParticipanteIdaConduceLugar {
internal var participante: Participante? = null
internal var ida: Boolean = false
internal var conduce: Boolean = false
internal var lugar: Lugar? = null
}
private class PairPersistenceDelegate : DefaultPersistenceDelegate(arrayOf("first", "second")) {
override fun instantiate(oldInstance: Any, out: Encoder): Expression {
val par = oldInstance as Pair<*, *>
val constructorArgs = arrayOf(par.first, par.second)
return Expression(oldInstance, oldInstance::class.java, "new", constructorArgs)
}
}
fun guardaDatosRuedaJSON(file: File, datosRueda: DatosRueda) {
try {
BufferedOutputStream(
FileOutputStream(file)).use { f ->
val mapper = jacksonObjectMapper()
with(mapper) {
writeValue(f, datosRueda)
}
}
} catch (ex: Exception) {
Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, null, ex)
}
}
fun cargaDatosRuedaJSON(file: File): DatosRueda {
try {
BufferedInputStream(
FileInputStream(file)).use { f ->
val mapper = jacksonObjectMapper()
return mapper.readValue(f)
}
} catch (ex: Exception) {
Logger.getLogger(Persistencia::class.java.name).log(Level.SEVERE, null, ex)
}
return DatosRueda()
}
}
| gpl-3.0 | 7ba2a6e1cdcd796c90023593d8db02b4 | 48.352941 | 248 | 0.512234 | 4.398088 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/JavaToJKTreeBuilder.kt | 1 | 56607 | // 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
import com.intellij.codeInsight.AnnotationTargetUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddTypeArgumentsFix
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.*
import com.intellij.psi.JavaTokenType.SUPER_KEYWORD
import com.intellij.psi.JavaTokenType.THIS_KEYWORD
import com.intellij.psi.impl.light.LightRecordMethod
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.impl.source.tree.ChildRole
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.java.PsiClassObjectAccessExpressionImpl
import com.intellij.psi.impl.source.tree.java.PsiLabeledStatementImpl
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.impl.source.tree.java.PsiNewExpressionImpl
import com.intellij.psi.infos.MethodCandidateInfo
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.JavaPsiRecordUtil.getFieldForComponent
import com.intellij.psi.util.TypeConversionUtil.calcTypeForBinaryExpression
import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.j2k.content
import org.jetbrains.kotlin.j2k.ReferenceSearcher
import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull
import org.jetbrains.kotlin.j2k.getContainingClass
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.JKLiteralExpression.LiteralType.*
import org.jetbrains.kotlin.nj2k.tree.Mutability.IMMUTABLE
import org.jetbrains.kotlin.nj2k.tree.Mutability.UNKNOWN
import org.jetbrains.kotlin.nj2k.types.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration
import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class JavaToJKTreeBuilder constructor(
private val symbolProvider: JKSymbolProvider,
private val typeFactory: JKTypeFactory,
converterServices: NewJavaToKotlinServices,
private val importStorage: JKImportStorage,
private val bodyFilter: ((PsiElement) -> Boolean)?,
) {
private fun todoExpression(): JKExpression = JKCallExpressionImpl(
symbolProvider.provideMethodSymbol("kotlin.TODO"),
JKArgumentList(
JKArgumentImpl(
JKLiteralExpression(
"\"${QualifiedExpressionResolver.ROOT_PREFIX_FOR_IDE_RESOLUTION_MODE}\"",
STRING,
)
)
),
)
private fun PsiType?.toJK(): JKType {
if (this == null) return JKNoType
return typeFactory.fromPsiType(this)
}
private val expressionTreeMapper = ExpressionTreeMapper()
private val referenceSearcher: ReferenceSearcher = converterServices.oldServices.referenceSearcher
private val declarationMapper = DeclarationMapper(expressionTreeMapper, bodyFilter == null)
private val formattingCollector = FormattingCollector()
// we don't want to capture comments of previous declaration/statement
private fun PsiElement.takeLeadingCommentsNeeded() =
this !is PsiMember && this !is PsiStatement
private fun <T : JKFormattingOwner> T.withFormattingFrom(
psi: PsiElement?,
assignLineBreaks: Boolean = false,
takeTrailingComments: Boolean = true,
takeLeadingComments: Boolean = psi?.takeLeadingCommentsNeeded() ?: false
): T = with(formattingCollector) {
takeFormattingFrom(this@withFormattingFrom, psi, assignLineBreaks, takeTrailingComments, takeLeadingComments)
this@withFormattingFrom
}
private fun <O : JKFormattingOwner> O.withLineBreaksFrom(psi: PsiElement?) = with(formattingCollector) {
takeLineBreaksFrom(this@withLineBreaksFrom, psi)
this@withLineBreaksFrom
}
private fun <O : JKFormattingOwner> O.withLeadingCommentsWithParent(psi: PsiElement?) = with(formattingCollector) {
if (psi == null) return@with this@withLeadingCommentsWithParent
[email protected] += psi.leadingCommentsWithParent()
return this@withLeadingCommentsWithParent
}
private fun PsiJavaFile.toJK(): JKFile =
JKFile(
packageStatement?.toJK() ?: JKPackageDeclaration(JKNameIdentifier("")),
importList.toJK(saveImports = false),
with(declarationMapper) { classes.map { it.toJK() } }
)
private fun PsiImportList?.toJK(saveImports: Boolean): JKImportList =
JKImportList(this?.allImportStatements?.mapNotNull { it.toJK(saveImports) }.orEmpty()).also { importList ->
val innerComments = this?.collectDescendantsOfType<PsiComment>()?.map { comment ->
JKComment(comment.text)
}.orEmpty()
importList.trailingComments += innerComments
}
private fun PsiPackageStatement.toJK(): JKPackageDeclaration =
JKPackageDeclaration(JKNameIdentifier(packageName))
.also {
it.withFormattingFrom(this)
symbolProvider.provideUniverseSymbol(this, it)
}
private fun PsiImportStatementBase.toJK(saveImports: Boolean): JKImportStatement? {
val target = when (this) {
is PsiImportStaticStatement -> resolveTargetClass()
else -> resolve()
}
val rawName = (importReference?.canonicalText ?: return null) + if (isOnDemand) ".*" else ""
// We will save only unresolved imports and print all static calls with fqNames
// to avoid name clashes in future
if (!saveImports) {
return if (target == null)
JKImportStatement(JKNameIdentifier(rawName))
else null
}
fun KtLightClassForDecompiledDeclaration.fqName(): FqName =
kotlinOrigin?.fqName ?: FqName(qualifiedName.orEmpty())
val name =
target.safeAs<KtLightElement<*, *>>()?.kotlinOrigin?.kotlinFqName?.asString()
?: target.safeAs<KtLightClass>()?.containingFile?.safeAs<KtFile>()?.packageFqName?.asString()?.let { "$it.*" }
?: target.safeAs<KtLightClassForFacade>()?.facadeClassFqName?.parent()?.asString()?.let { "$it.*" }
?: target.safeAs<KtLightClassForDecompiledDeclaration>()?.fqName()?.parent()?.asString()?.let { "$it.*" }
?: rawName
return JKImportStatement(JKNameIdentifier(name)).also {
it.withFormattingFrom(this)
}
}
private fun PsiIdentifier?.toJK(): JKNameIdentifier = this?.let {
JKNameIdentifier(it.text).also { identifier ->
identifier.withFormattingFrom(this)
}
} ?: JKNameIdentifier("")
private inner class ExpressionTreeMapper {
fun PsiExpression?.toJK(): JKExpression = when (this) {
null -> JKStubExpression()
is PsiBinaryExpression -> toJK()
is PsiPrefixExpression -> toJK()
is PsiPostfixExpression -> toJK()
is PsiLiteralExpression -> toJK()
is PsiMethodCallExpression -> toJK()
is PsiReferenceExpression -> toJK()
is PsiNewExpression -> toJK()
is PsiArrayAccessExpression -> toJK()
is PsiTypeCastExpression -> toJK()
is PsiParenthesizedExpression -> toJK()
is PsiAssignmentExpression -> toJK()
is PsiInstanceOfExpression -> toJK()
is PsiThisExpression ->
JKThisExpression(
qualifier?.referenceName?.let { JKLabelText(JKNameIdentifier(it)) } ?: JKLabelEmpty(),
type.toJK()
)
is PsiSuperExpression -> {
val qualifyingType = qualifier?.resolve() as? PsiClass
if (qualifyingType == null) {
// Case 0: plain "super.foo()" call
JKSuperExpression(type.toJK())
} else {
// Java's qualified super call syntax "A.super.foo()" is represented by two different cases in Kotlin.
// See https://kotlinlang.org/docs/inheritance.html#calling-the-superclass-implementation
val isQualifiedSuperTypeCall = getContainingClass()?.supers?.contains(qualifyingType) == true
var superTypeQualifier: JKClassSymbol? = null
var outerTypeQualifier: JKLabel = JKLabelEmpty()
if (isQualifiedSuperTypeCall) {
// Case 1: "super<A>.foo()" for accessing the superclass of the current class
superTypeQualifier = symbolProvider.provideDirectSymbol(qualifyingType) as? JKClassSymbol
} else {
// Case 2: "[email protected]()" for accessing the superclass of the outer class
outerTypeQualifier = qualifier?.referenceName?.let { JKLabelText(JKNameIdentifier(it)) } ?: outerTypeQualifier
}
JKSuperExpression(type.toJK(), superTypeQualifier, outerTypeQualifier)
}
}
is PsiConditionalExpression -> JKIfElseExpression(
condition.toJK(),
thenExpression.toJK(),
elseExpression.toJK(),
type.toJK()
)
is PsiPolyadicExpression -> {
val token = JKOperatorToken.fromElementType(operationTokenType)
val jkOperandsWithPsiTypes = operands.map { it.toJK().withLineBreaksFrom(it).parenthesizeIfCompoundExpression() to it.type }
jkOperandsWithPsiTypes.reduce { (left, leftType), (right, rightType) ->
val psiType = calcTypeForBinaryExpression(leftType, rightType, operationTokenType, true)
val jkType = psiType?.toJK() ?: typeFactory.types.nullableAny
JKBinaryExpression(left, right, JKKtOperatorImpl(token, jkType)) to psiType
}.let { (folded, _) ->
if (jkOperandsWithPsiTypes.any { it.first.containsNewLine() }) folded.parenthesize()
else folded
}
}
is PsiArrayInitializerExpression -> toJK()
is PsiLambdaExpression -> toJK()
is PsiClassObjectAccessExpressionImpl -> toJK()
is PsiSwitchExpression -> JKJavaSwitchExpression(expression.toJK(), collectSwitchCases())
else -> createErrorExpression()
}.also {
if (this != null) {
(it as PsiOwner).psi = this
it.withFormattingFrom(this)
}
}
fun PsiClassObjectAccessExpressionImpl.toJK(): JKClassLiteralExpression {
val type = operand.type.toJK().updateNullabilityRecursively(NotNull)
return JKClassLiteralExpression(
JKTypeElement(type),
when (type) {
is JKJavaPrimitiveType -> JKClassLiteralExpression.ClassLiteralType.JAVA_PRIMITIVE_CLASS
is JKJavaVoidType -> JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE
else -> JKClassLiteralExpression.ClassLiteralType.JAVA_CLASS
}
).also {
it.withFormattingFrom(this)
}
}
fun PsiInstanceOfExpression.toJK(): JKIsExpression {
val pattern = pattern.safeAs<PsiTypeTestPattern>()
val psiTypeElement = checkType ?: pattern?.checkType
val type = psiTypeElement?.type?.toJK() ?: JKNoType
val typeElement = with(declarationMapper) { JKTypeElement(type, psiTypeElement.annotationList()) }
val expr = JKIsExpression(operand.toJK(), typeElement).also { it.withFormattingFrom(this) }
val patternVariable = pattern?.patternVariable
if (patternVariable != null) {
val name = expr.expression.safeAs<JKFieldAccessExpression>()?.identifier?.name ?: patternVariable.name
val typeElementForPattern =
with(declarationMapper) { JKTypeElement(type, psiTypeElement.annotationList()) }
// Executed for the side effect of binding the symbol to a valid target
JKParameter(typeElementForPattern, JKNameIdentifier(name)).also {
symbolProvider.provideUniverseSymbol(patternVariable, it)
it.psi = this
}
}
return expr
}
fun PsiAssignmentExpression.toJK(): JKJavaAssignmentExpression {
return JKJavaAssignmentExpression(
lExpression.toJK(),
rExpression.toJK(),
createOperator(operationSign.tokenType, type)
).also {
it.withFormattingFrom(this)
}
}
fun PsiBinaryExpression.toJK(): JKExpression {
val token = when (operationSign.tokenType) {
JavaTokenType.EQEQ, JavaTokenType.NE ->
when {
canKeepEqEq(lOperand, rOperand) -> JKOperatorToken.fromElementType(operationSign.tokenType)
operationSign.tokenType == JavaTokenType.EQEQ -> JKOperatorToken.fromElementType(KtTokens.EQEQEQ)
else -> JKOperatorToken.fromElementType(KtTokens.EXCLEQEQEQ)
}
else -> JKOperatorToken.fromElementType(operationSign.tokenType)
}
return JKBinaryExpression(
lOperand.toJK().withLineBreaksFrom(lOperand),
rOperand.toJK().withLineBreaksFrom(rOperand),
JKKtOperatorImpl(
token,
type?.toJK() ?: typeFactory.types.nullableAny
)
).also {
it.withFormattingFrom(this)
}
}
fun PsiLiteralExpression.toJK(): JKExpression {
require(this is PsiLiteralExpressionImpl)
return when (literalElementType) {
JavaTokenType.NULL_KEYWORD -> JKLiteralExpression("null", NULL)
JavaTokenType.TRUE_KEYWORD -> JKLiteralExpression("true", BOOLEAN)
JavaTokenType.FALSE_KEYWORD -> JKLiteralExpression("false", BOOLEAN)
JavaTokenType.STRING_LITERAL -> JKLiteralExpression(text, STRING)
JavaTokenType.TEXT_BLOCK_LITERAL -> JKLiteralExpression(text, TEXT_BLOCK)
JavaTokenType.CHARACTER_LITERAL -> JKLiteralExpression(text, CHAR)
JavaTokenType.INTEGER_LITERAL -> JKLiteralExpression(text, INT)
JavaTokenType.LONG_LITERAL -> JKLiteralExpression(text, LONG)
JavaTokenType.FLOAT_LITERAL -> JKLiteralExpression(text, FLOAT)
JavaTokenType.DOUBLE_LITERAL -> JKLiteralExpression(text, DOUBLE)
else -> createErrorExpression()
}.also {
it.withFormattingFrom(this)
}
}
private fun createOperator(elementType: IElementType, type: PsiType?) =
JKKtOperatorImpl(
JKOperatorToken.fromElementType(elementType),
type?.toJK() ?: typeFactory.types.nullableAny
)
fun PsiPrefixExpression.toJK(): JKExpression = when (operationSign.tokenType) {
JavaTokenType.TILDE -> operand.toJK().callOn(symbolProvider.provideMethodSymbol("kotlin.Int.inv"))
else -> JKPrefixExpression(operand.toJK(), createOperator(operationSign.tokenType, type))
}.also {
it.withFormattingFrom(this)
}
fun PsiPostfixExpression.toJK(): JKExpression =
JKPostfixExpression(operand.toJK(), createOperator(operationSign.tokenType, type)).also {
it.withFormattingFrom(this)
}
fun PsiLambdaExpression.toJK(): JKExpression {
return JKLambdaExpression(
body.let {
when (it) {
is PsiExpression -> JKExpressionStatement(it.toJK())
is PsiCodeBlock -> JKBlockStatement(with(declarationMapper) { it.toJK() })
else -> JKBlockStatement(JKBodyStub)
}
},
with(declarationMapper) { parameterList.parameters.map { it.toJK() } },
functionalType()
).also {
it.withFormattingFrom(this)
}
}
private fun PsiMethodCallExpression.getExplicitTypeArguments(): PsiReferenceParameterList {
if (typeArguments.isNotEmpty()) return typeArgumentList
val resolveResult = resolveMethodGenerics()
if (resolveResult is MethodCandidateInfo && resolveResult.isApplicable) {
val method = resolveResult.element
if (method.isConstructor || !method.hasTypeParameters()) return typeArgumentList
}
return AddTypeArgumentsFix.addTypeArguments(this, null, false)
?.safeAs<PsiMethodCallExpression>()
?.typeArgumentList
?: typeArgumentList
}
//TODO mostly copied from old j2k, refactor
fun PsiMethodCallExpression.toJK(): JKExpression {
val arguments = argumentList
val typeArguments = getExplicitTypeArguments().toJK()
val qualifier = methodExpression.qualifierExpression?.toJK()?.withLineBreaksFrom(methodExpression.qualifierExpression)
var target = methodExpression.resolve()
if (target is PsiMethodImpl && target.name.canBeGetterOrSetterName()) {
val baseCallable = target.findSuperMethods().firstOrNull()
if (baseCallable is KtLightMethod) {
target = baseCallable
}
}
val symbol = target?.let {
symbolProvider.provideDirectSymbol(it)
} ?: JKUnresolvedMethod(methodExpression, typeFactory)
return when {
methodExpression.referenceNameElement is PsiKeyword -> {
val callee = when ((methodExpression.referenceNameElement as PsiKeyword).tokenType) {
SUPER_KEYWORD -> JKSuperExpression()
THIS_KEYWORD -> JKThisExpression(JKLabelEmpty(), JKNoType)
else -> createErrorExpression("unknown keyword in callee position")
}
val calleeSymbol = when {
symbol is JKMethodSymbol -> symbol
target is KtLightMethod -> KtClassImplicitConstructorSymbol(target, typeFactory)
else -> JKUnresolvedMethod(methodExpression, typeFactory)
}
JKDelegationConstructorCall(calleeSymbol, callee, arguments.toJK())
}
target is KtLightMethod -> {
when (val origin = target.kotlinOrigin) {
is KtNamedFunction -> {
if (origin.isExtensionDeclaration()) {
val receiver = arguments.expressions.firstOrNull()?.toJK()?.parenthesizeIfCompoundExpression()
origin.fqName?.also { importStorage.addImport(it) }
JKCallExpressionImpl(
symbolProvider.provideDirectSymbol(origin) as JKMethodSymbol,
arguments.expressions.drop(1).map { it.toJK() }.toArgumentList(),
typeArguments
).qualified(receiver)
} else {
origin.fqName?.also { importStorage.addImport(it) }
JKCallExpressionImpl(
symbolProvider.provideDirectSymbol(origin) as JKMethodSymbol,
arguments.toJK(),
typeArguments
).qualified(qualifier)
}
}
is KtProperty, is KtPropertyAccessor, is KtParameter -> {
origin.kotlinFqName?.also { importStorage.addImport(it) }
val property =
if (origin is KtPropertyAccessor) origin.parent as KtProperty
else origin as KtNamedDeclaration
val parameterCount = target.parameterList.parameters.size
val propertyAccessExpression =
JKFieldAccessExpression(symbolProvider.provideDirectSymbol(property) as JKFieldSymbol)
val isExtension = property.isExtensionDeclaration()
val isTopLevel = origin.getStrictParentOfType<KtClassOrObject>() == null
val propertyAccess = if (isTopLevel) {
if (isExtension) JKQualifiedExpression(
arguments.expressions.first().toJK(),
propertyAccessExpression
)
else propertyAccessExpression
} else propertyAccessExpression.qualified(qualifier)
when (if (isExtension) parameterCount - 1 else parameterCount) {
0 /* getter */ ->
propertyAccess
1 /* setter */ -> {
val argument = (arguments.expressions[if (isExtension) 1 else 0]).toJK()
JKJavaAssignmentExpression(
propertyAccess,
argument,
createOperator(JavaTokenType.EQ, type) //TODO correct type
)
}
else -> createErrorExpression("expected getter or setter call")
}
}
else -> {
JKCallExpressionImpl(
JKMultiverseMethodSymbol(target, typeFactory),
arguments.toJK(),
typeArguments
).qualified(qualifier)
}
}
}
target is LightRecordMethod -> {
val field = getFieldForComponent(target.recordComponent) ?: return createErrorExpression()
JKFieldAccessExpression(symbolProvider.provideDirectSymbol(field) as JKFieldSymbol)
.qualified(qualifier ?: JKThisExpression(JKLabelEmpty()))
}
symbol is JKMethodSymbol ->
JKCallExpressionImpl(symbol, arguments.toJK(), typeArguments)
.qualified(qualifier)
symbol is JKFieldSymbol ->
JKFieldAccessExpression(symbol).qualified(qualifier)
else -> createErrorExpression()
}.also {
it.withFormattingFrom(this)
}
}
fun PsiFunctionalExpression.functionalType(): JKTypeElement =
functionalInterfaceType
?.takeUnless { type ->
type.safeAs<PsiClassType>()?.parameters?.any { it is PsiCapturedWildcardType } == true
}?.takeUnless { type ->
type.isKotlinFunctionalType
}?.toJK()
?.asTypeElement() ?: JKTypeElement(JKNoType)
fun PsiMethodReferenceExpression.toJK(): JKMethodReferenceExpression {
val symbol = symbolProvider.provideSymbolForReference<JKSymbol>(this).let { symbol ->
when {
symbol.isUnresolved && isConstructor -> JKUnresolvedClassSymbol(qualifier?.text ?: text, typeFactory)
symbol.isUnresolved && !isConstructor -> JKUnresolvedMethod(referenceName ?: text, typeFactory)
else -> symbol
}
}
return JKMethodReferenceExpression(
methodReferenceQualifier(),
symbol,
functionalType(),
isConstructor
)
}
fun PsiMethodReferenceExpression.methodReferenceQualifier(): JKExpression {
val qualifierType = qualifierType
if (qualifierType != null) return JKTypeQualifierExpression(typeFactory.fromPsiType(qualifierType.type))
return qualifierExpression?.toJK() ?: JKStubExpression()
}
fun PsiReferenceExpression.toJK(): JKExpression {
if (this is PsiMethodReferenceExpression) return toJK()
val target = resolve()
if (target is KtLightClassForFacade
|| target is KtLightClassForDecompiledDeclaration
) return JKStubExpression()
if (target is KtLightField
&& target.name == "INSTANCE"
&& target.containingClass.kotlinOrigin is KtObjectDeclaration
) {
return qualifierExpression?.toJK() ?: JKStubExpression()
}
val symbol = symbolProvider.provideSymbolForReference<JKSymbol>(this)
return when (symbol) {
is JKClassSymbol -> JKClassAccessExpression(symbol)
is JKFieldSymbol -> JKFieldAccessExpression(symbol)
is JKPackageSymbol -> JKPackageAccessExpression(symbol)
is JKMethodSymbol -> JKMethodAccessExpression(symbol)
is JKTypeParameterSymbol -> JKTypeQualifierExpression(JKTypeParameterType(symbol))
else -> createErrorExpression()
}.qualified(qualifierExpression?.toJK()).also {
it.withFormattingFrom(this)
}
}
fun PsiArrayInitializerExpression.toJK(): JKExpression {
return JKJavaNewArray(
initializers.map { it.toJK().withLineBreaksFrom(it) },
JKTypeElement(type?.toJK().safeAs<JKJavaArrayType>()?.type ?: JKContextType)
).also {
it.withFormattingFrom(this)
}
}
fun PsiNewExpression.toJK(): JKExpression {
require(this is PsiNewExpressionImpl)
val newExpression =
if (findChildByRole(ChildRole.LBRACKET) != null) {
arrayInitializer?.toJK() ?: run {
val dimensions = mutableListOf<JKExpression>()
var child = firstChild
while (child != null) {
if (child.node.elementType == JavaTokenType.LBRACKET) {
child = child.getNextSiblingIgnoringWhitespaceAndComments()
if (child.node.elementType == JavaTokenType.RBRACKET) {
dimensions += JKStubExpression()
} else {
child.safeAs<PsiExpression>()?.toJK()?.also { dimensions += it }
}
}
child = child.nextSibling
}
JKJavaNewEmptyArray(
dimensions,
JKTypeElement(generateSequence(type?.toJK()) { it.safeAs<JKJavaArrayType>()?.type }.last())
).also {
it.psi = this
}
}
} else {
val classSymbol =
classOrAnonymousClassReference?.resolve()?.let {
symbolProvider.provideDirectSymbol(it) as JKClassSymbol
} ?: JKUnresolvedClassSymbol(
classOrAnonymousClassReference?.referenceName ?: NO_NAME_PROVIDED,
typeFactory
)
val typeArgumentList =
this.typeArgumentList.toJK()
.takeIf { it.typeArguments.isNotEmpty() }
?: classOrAnonymousClassReference
?.typeParameters
?.let { typeParameters ->
JKTypeArgumentList(typeParameters.map { JKTypeElement(it.toJK()) })
} ?: JKTypeArgumentList()
JKNewExpression(
classSymbol,
argumentList?.toJK() ?: JKArgumentList(),
typeArgumentList,
with(declarationMapper) { anonymousClass?.createClassBody() } ?: JKClassBody(),
anonymousClass != null
).also {
it.psi = this
}
}
return newExpression.qualified(qualifier?.toJK())
}
fun PsiReferenceParameterList.toJK(): JKTypeArgumentList =
JKTypeArgumentList(
typeParameterElements.map { JKTypeElement(it.type.toJK(), with(declarationMapper) { it.annotationList() }) }
).also {
it.withFormattingFrom(this)
}
fun PsiArrayAccessExpression.toJK(): JKExpression =
arrayExpression.toJK()
.callOn(
symbolProvider.provideMethodSymbol("kotlin.Array.get"),
arguments = listOf(indexExpression?.toJK() ?: JKStubExpression())
).also {
it.withFormattingFrom(this)
}
fun PsiTypeCastExpression.toJK(): JKExpression {
return JKTypeCastExpression(
operand?.toJK() ?: createErrorExpression(),
(castType?.type?.toJK() ?: JKNoType).asTypeElement(with(declarationMapper) { castType.annotationList() })
).also {
it.withFormattingFrom(this)
}
}
fun PsiParenthesizedExpression.toJK(): JKExpression {
return JKParenthesizedExpression(expression.toJK())
.also {
it.withFormattingFrom(this)
}
}
fun PsiExpressionList.toJK(): JKArgumentList {
val jkExpressions = expressions.map { it.toJK().withLineBreaksFrom(it) }
return ((parent as? PsiCall)?.resolveMethod()
?.let { method ->
val lastExpressionType = expressions.lastOrNull()?.type
if (jkExpressions.size == method.parameterList.parameters.size
&& method.parameterList.parameters.getOrNull(jkExpressions.lastIndex)?.isVarArgs == true
&& lastExpressionType is PsiArrayType
) {
val staredExpression =
JKPrefixExpression(
jkExpressions.last(),
JKKtSpreadOperator(lastExpressionType.toJK())
).withFormattingFrom(jkExpressions.last())
staredExpression.expression.also {
it.hasLeadingLineBreak = false
it.hasTrailingLineBreak = false
}
jkExpressions.dropLast(1) + staredExpression
} else jkExpressions
} ?: jkExpressions)
.toArgumentList()
.also {
it.withFormattingFrom(this)
}
}
}
private inner class DeclarationMapper(val expressionTreeMapper: ExpressionTreeMapper, var withBody: Boolean) {
fun <R> withBodyGeneration(
elementToCheck: PsiElement,
trueBranch: DeclarationMapper.() -> R,
elseBranch: DeclarationMapper.() -> R = trueBranch
): R = when {
withBody -> trueBranch()
bodyFilter?.invoke(elementToCheck) == true -> {
withBody = true
trueBranch().also { withBody = false }
}
else -> elseBranch()
}
fun PsiTypeParameterList.toJK(): JKTypeParameterList =
JKTypeParameterList(typeParameters.map { it.toJK() })
.also {
it.withFormattingFrom(this)
}
fun PsiTypeParameter.toJK(): JKTypeParameter =
JKTypeParameter(
nameIdentifier.toJK(),
extendsListTypes.map { type -> JKTypeElement(type.toJK(), JKAnnotationList(type.annotations.map { it.toJK() })) },
JKAnnotationList(annotations.mapNotNull { it?.toJK() })
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.withFormattingFrom(this)
}
fun PsiClass.toJK(): JKClass =
JKClass(
nameIdentifier.toJK(),
inheritanceInfo(),
classKind(),
typeParameterList?.toJK() ?: JKTypeParameterList(),
createClassBody(),
annotationList(this),
otherModifiers(),
visibility(),
modality(),
recordComponents()
).also { klass ->
klass.psi = this
symbolProvider.provideUniverseSymbol(this, klass)
klass.withFormattingFrom(this)
}
private fun PsiClass.recordComponents(): List<JKJavaRecordComponent> =
recordComponents.map { component ->
val psiTypeElement = component.typeElement
val type = psiTypeElement?.type?.toJK() ?: JKNoType
val typeElement = with(declarationMapper) { JKTypeElement(type, psiTypeElement.annotationList()) }
JKJavaRecordComponent(
typeElement,
JKNameIdentifier(component.name),
component.isVarArgs,
component.annotationList(docCommentOwner = this)
).also {
it.withFormattingFrom(component)
symbolProvider.provideUniverseSymbol(component, it)
it.psi = component
}
}
fun PsiClass.inheritanceInfo(): JKInheritanceInfo {
val implementsTypes = implementsList?.referencedTypes?.map { type ->
JKTypeElement(
type.toJK().updateNullability(NotNull),
JKAnnotationList(type.annotations.map { it.toJK() })
)
}.orEmpty()
val extendsTypes = extendsList?.referencedTypes?.map { type ->
JKTypeElement(
type.toJK().updateNullability(NotNull),
JKAnnotationList(type.annotations.map { it.toJK() })
)
}.orEmpty()
return JKInheritanceInfo(extendsTypes, implementsTypes)
.also {
if (implementsList != null) {
it.withFormattingFrom(implementsList!!)
}
}
}
fun PsiClass.createClassBody() =
JKClassBody(
children.mapNotNull {
when (it) {
is PsiEnumConstant -> it.toJK()
is PsiClass -> it.toJK()
is PsiAnnotationMethod -> it.toJK()
is PsiMethod -> it.toJK()
is PsiField -> it.toJK()
is PsiClassInitializer -> it.toJK()
else -> null
}
}
).also {
it.leftBrace.withFormattingFrom(
lBrace,
takeLeadingComments = false
) // do not capture comments which belongs to following declarations
it.rightBrace.withFormattingFrom(rBrace)
it.declarations.lastOrNull()?.let { lastMember ->
lastMember.withLeadingCommentsWithParent(lastMember.psi)
}
}
fun PsiClassInitializer.toJK(): JKDeclaration = when {
hasModifier(JvmModifier.STATIC) -> JKJavaStaticInitDeclaration(body.toJK())
else -> JKKtInitDeclaration(body.toJK())
}.also {
it.withFormattingFrom(this)
}
fun PsiEnumConstant.toJK(): JKEnumConstant =
JKEnumConstant(
nameIdentifier.toJK(),
with(expressionTreeMapper) { argumentList?.toJK() ?: JKArgumentList() },
initializingClass?.createClassBody() ?: JKClassBody(),
JKTypeElement(
containingClass?.let { klass ->
JKClassType(
symbolProvider.provideDirectSymbol(klass) as JKClassSymbol,
emptyList()
)
} ?: JKNoType
),
annotationList(this),
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.psi = this
it.withFormattingFrom(this)
}
fun PsiMember.modality() =
modality { ast, psi -> ast.withFormattingFrom(psi) }
fun PsiMember.otherModifiers() =
modifierList?.children?.mapNotNull { child ->
if (child !is PsiKeyword) return@mapNotNull null
when (child.text) {
PsiModifier.NATIVE -> OtherModifier.NATIVE
PsiModifier.STATIC -> OtherModifier.STATIC
PsiModifier.STRICTFP -> OtherModifier.STRICTFP
PsiModifier.SYNCHRONIZED -> OtherModifier.SYNCHRONIZED
PsiModifier.TRANSIENT -> OtherModifier.TRANSIENT
PsiModifier.VOLATILE -> OtherModifier.VOLATILE
else -> null
}?.let {
JKOtherModifierElement(it).withFormattingFrom(child)
}
}.orEmpty()
private fun PsiMember.visibility(): JKVisibilityModifierElement =
visibility(referenceSearcher) { ast, psi -> ast.withFormattingFrom(psi) }
fun PsiField.toJK(): JKField = JKField(
JKTypeElement(type.toJK(), typeElement.annotationList()).withFormattingFrom(typeElement),
nameIdentifier.toJK(),
with(expressionTreeMapper) {
withBodyGeneration(
this@toJK,
trueBranch = { initializer.toJK() },
elseBranch = { todoExpression() }
)
},
annotationList(this),
otherModifiers(),
visibility(),
modality(),
JKMutabilityModifierElement(
if (containingClass?.isInterface == true) IMMUTABLE else UNKNOWN
)
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.psi = this
it.withFormattingFrom(this)
}
fun <T : PsiModifierListOwner> T.annotationList(docCommentOwner: PsiDocCommentOwner?): JKAnnotationList {
val deprecatedAnnotation = docCommentOwner?.docComment?.deprecatedAnnotation()
val plainAnnotations = annotations.mapNotNull { annotation ->
when {
annotation !is PsiAnnotation -> null
annotation.qualifiedName == DEPRECATED_ANNOTATION_FQ_NAME && deprecatedAnnotation != null -> null
AnnotationTargetUtil.isTypeAnnotation(annotation) -> null
else -> annotation.toJK()
}
}
return JKAnnotationList(plainAnnotations + listOfNotNull(deprecatedAnnotation))
}
fun PsiTypeElement?.annotationList(): JKAnnotationList {
return JKAnnotationList(this?.applicableAnnotations?.map { it.toJK() }.orEmpty())
}
fun PsiAnnotation.toJK(): JKAnnotation {
val symbol = when (val reference = nameReferenceElement) {
null -> JKUnresolvedClassSymbol(NO_NAME_PROVIDED, typeFactory)
else -> symbolProvider.provideSymbolForReference<JKSymbol>(reference).safeAs<JKClassSymbol>()
?: JKUnresolvedClassSymbol(nameReferenceElement?.text ?: NO_NAME_PROVIDED, typeFactory)
}
return JKAnnotation(
symbol,
parameterList.attributes.map { parameter ->
if (parameter.nameIdentifier != null) {
JKAnnotationNameParameter(
parameter.value?.toJK() ?: JKStubExpression(),
JKNameIdentifier(parameter.name ?: NO_NAME_PROVIDED)
)
} else {
JKAnnotationParameterImpl(
parameter.value?.toJK() ?: JKStubExpression()
)
}
}
).also {
it.withFormattingFrom(this)
}
}
fun PsiDocComment.deprecatedAnnotation(): JKAnnotation? =
findTagByName("deprecated")?.let { tag ->
JKAnnotation(
symbolProvider.provideClassSymbol("kotlin.Deprecated"),
listOf(
JKAnnotationParameterImpl(stringLiteral(tag.content(), typeFactory))
)
)
}
private fun PsiAnnotationMemberValue.toJK(): JKAnnotationMemberValue =
when (this) {
is PsiExpression -> with(expressionTreeMapper) { toJK() }
is PsiAnnotation -> toJK()
is PsiArrayInitializerMemberValue ->
JKKtAnnotationArrayInitializerExpression(initializers.map { it.toJK() })
else -> createErrorExpression()
}.also {
it.withFormattingFrom(this)
}
fun PsiAnnotationMethod.toJK(): JKJavaAnnotationMethod =
JKJavaAnnotationMethod(
JKTypeElement(
returnType?.toJK()
?: JKJavaVoidType.takeIf { isConstructor }
?: JKNoType,
returnTypeElement?.annotationList() ?: JKAnnotationList()
),
nameIdentifier.toJK(),
defaultValue?.toJK() ?: JKStubExpression(),
annotationList(this),
otherModifiers(),
visibility(),
modality()
).also {
it.psi = this
symbolProvider.provideUniverseSymbol(this, it)
it.withFormattingFrom(this)
}
fun PsiMethod.toJK(): JKMethod {
return JKMethodImpl(
JKTypeElement(
returnType?.toJK()
?: JKJavaVoidType.takeIf { isConstructor }
?: JKNoType,
returnTypeElement.annotationList()),
nameIdentifier.toJK(),
parameterList.parameters.map { it.toJK().withLineBreaksFrom(it) },
withBodyGeneration(this, trueBranch = { body?.toJK() ?: JKBodyStub }),
typeParameterList?.toJK() ?: JKTypeParameterList(),
annotationList(this),
throwsList.referencedTypes.map { JKTypeElement(it.toJK()) },
otherModifiers(),
visibility(),
modality()
).also { jkMethod ->
jkMethod.psi = this
symbolProvider.provideUniverseSymbol(this, jkMethod)
parameterList.node
?.safeAs<CompositeElement>()
?.also {
jkMethod.leftParen.withFormattingFrom(it.findChildByRoleAsPsiElement(ChildRole.LPARENTH))
jkMethod.rightParen.withFormattingFrom(it.findChildByRoleAsPsiElement(ChildRole.RPARENTH))
}
}.withFormattingFrom(this)
}
fun PsiParameter.toJK(): JKParameter {
val rawType = type.toJK()
val type =
if (isVarArgs && rawType is JKJavaArrayType) JKTypeElement(rawType.type, typeElement.annotationList())
else rawType.asTypeElement(typeElement.annotationList())
val name = if (nameIdentifier != null) nameIdentifier.toJK() else JKNameIdentifier(name)
return JKParameter(
type,
name,
isVarArgs,
annotationList = annotationList(null)
).also {
symbolProvider.provideUniverseSymbol(this, it)
it.psi = this
it.withFormattingFrom(this)
}
}
fun PsiCodeBlock.toJK(): JKBlock = JKBlockImpl(
if (withBody) statements.map { it.toJK() } else listOf(todoExpression().asStatement())
).withFormattingFrom(this).also {
it.leftBrace.withFormattingFrom(lBrace)
it.rightBrace.withFormattingFrom(rBrace)
}
fun PsiLocalVariable.toJK(): JKLocalVariable {
return JKLocalVariable(
JKTypeElement(type.toJK(), typeElement.annotationList()).withFormattingFrom(typeElement),
nameIdentifier.toJK(),
with(expressionTreeMapper) { initializer.toJK() },
JKMutabilityModifierElement(
if (hasModifierProperty(PsiModifier.FINAL)) IMMUTABLE else UNKNOWN
),
annotationList(null)
).also { i ->
symbolProvider.provideUniverseSymbol(this, i)
i.psi = this
}.also {
it.withFormattingFrom(this)
}
}
fun PsiStatement?.asJKStatementsList() = when (this) {
null -> emptyList()
is PsiExpressionListStatement -> expressionList.expressions.map { expression ->
JKExpressionStatement(with(expressionTreeMapper) { expression.toJK() })
}
else -> listOf(toJK())
}
fun PsiStatement?.toJK(): JKStatement {
return when (this) {
null -> JKExpressionStatement(JKStubExpression())
is PsiExpressionStatement -> JKExpressionStatement(with(expressionTreeMapper) { expression.toJK() })
is PsiReturnStatement -> JKReturnStatement(with(expressionTreeMapper) { returnValue.toJK() })
is PsiDeclarationStatement ->
JKDeclarationStatement(declaredElements.mapNotNull {
when (it) {
is PsiClass -> it.toJK()
is PsiLocalVariable -> it.toJK()
else -> null
}
})
is PsiAssertStatement ->
JKJavaAssertStatement(
with(expressionTreeMapper) { assertCondition.toJK() },
with(expressionTreeMapper) { assertDescription?.toJK() } ?: JKStubExpression())
is PsiIfStatement ->
with(expressionTreeMapper) {
JKIfElseStatement(condition.toJK(), thenBranch.toJK(), elseBranch.toJK())
}
is PsiForStatement -> JKJavaForLoopStatement(
initialization.asJKStatementsList(),
with(expressionTreeMapper) { condition.toJK() },
update.asJKStatementsList(),
body.toJK()
)
is PsiForeachStatement ->
JKForInStatement(
iterationParameter.toJK(),
with(expressionTreeMapper) { iteratedValue?.toJK() ?: JKStubExpression() },
body?.toJK() ?: blockStatement()
)
is PsiBlockStatement -> JKBlockStatement(codeBlock.toJK())
is PsiWhileStatement -> JKWhileStatement(with(expressionTreeMapper) { condition.toJK() }, body.toJK())
is PsiDoWhileStatement -> JKDoWhileStatement(body.toJK(), with(expressionTreeMapper) { condition.toJK() })
is PsiSwitchStatement -> JKJavaSwitchStatement(with(expressionTreeMapper) { expression.toJK() }, collectSwitchCases())
is PsiBreakStatement ->
JKBreakStatement(labelIdentifier?.let { JKLabelText(JKNameIdentifier(it.text)) } ?: JKLabelEmpty())
is PsiContinueStatement -> {
val label = labelIdentifier?.let {
JKLabelText(JKNameIdentifier(it.text))
} ?: JKLabelEmpty()
JKContinueStatement(label)
}
is PsiLabeledStatement -> {
val (labels, statement) = collectLabels()
JKLabeledExpression(statement.toJK(), labels.map { JKNameIdentifier(it.text) }).asStatement()
}
is PsiEmptyStatement -> JKEmptyStatement()
is PsiThrowStatement ->
JKThrowExpression(with(expressionTreeMapper) { exception.toJK() }).asStatement()
is PsiTryStatement ->
JKJavaTryStatement(
resourceList?.toList()?.map { (it as PsiResourceListElement).toJK() }.orEmpty(),
tryBlock?.toJK() ?: JKBodyStub,
finallyBlock?.toJK() ?: JKBodyStub,
catchSections.map { it.toJK() }
)
is PsiSynchronizedStatement ->
JKJavaSynchronizedStatement(
with(expressionTreeMapper) { lockExpression?.toJK() } ?: JKStubExpression(),
body?.toJK() ?: JKBodyStub
)
is PsiYieldStatement -> JKJavaYieldStatement(with(expressionTreeMapper) { expression.toJK() })
else -> createErrorStatement()
}.also {
if (this != null) {
(it as PsiOwner).psi = this
it.withFormattingFrom(this)
}
}
}
fun PsiResourceListElement.toJK(): JKJavaResourceElement =
when (this) {
is PsiResourceVariable -> JKJavaResourceDeclaration((this as PsiLocalVariable).toJK())
is PsiResourceExpression -> JKJavaResourceExpression(with(expressionTreeMapper) { [email protected]() })
else -> error("Unexpected resource list ${this::class.java}")
}
fun PsiCatchSection.toJK(): JKJavaTryCatchSection =
JKJavaTryCatchSection(
parameter?.toJK()
?: JKParameter(JKTypeElement(JKNoType), JKNameIdentifier(NO_NAME_PROVIDED)),
catchBlock?.toJK() ?: JKBodyStub
).also {
it.psi = this
it.withFormattingFrom(this)
}
}
fun PsiLabeledStatement.collectLabels(): Pair<List<PsiIdentifier>, PsiStatement> {
val labels = mutableListOf<PsiIdentifier>()
var currentStatement: PsiStatement? = this
while (currentStatement is PsiLabeledStatementImpl) {
labels += currentStatement.labelIdentifier
currentStatement = currentStatement.statement ?: return labels to currentStatement
}
return labels to currentStatement!!
}
fun buildTree(psi: PsiElement, saveImports: Boolean): JKTreeRoot? =
when (psi) {
is PsiJavaFile -> psi.toJK()
is PsiExpression -> with(expressionTreeMapper) { psi.toJK() }
is PsiStatement -> with(declarationMapper) { psi.toJK() }
is PsiTypeParameter -> with(declarationMapper) { psi.toJK() }
is PsiClass -> with(declarationMapper) { psi.toJK() }
is PsiField -> with(declarationMapper) { psi.toJK() }
is PsiMethod -> with(declarationMapper) { psi.toJK() }
is PsiAnnotation -> with(declarationMapper) { psi.toJK() }
is PsiImportList -> psi.toJK(saveImports)
is PsiImportStatementBase -> psi.toJK(saveImports)
is PsiJavaCodeReferenceElement ->
if (psi.parent is PsiReferenceList) {
val factory = JavaPsiFacade.getInstance(psi.project).elementFactory
val type = factory.createType(psi)
JKTypeElement(type.toJK().updateNullabilityRecursively(NotNull))
} else null
else -> null
}?.let { JKTreeRoot(it) }
private fun PsiElement.createErrorExpression(message: String? = null): JKExpression {
return JKErrorExpression(this, message)
}
private fun PsiElement.createErrorStatement(message: String? = null): JKStatement {
return JKErrorStatement(this, message)
}
private fun PsiSwitchBlock.collectSwitchCases(): List<JKJavaSwitchCase> = with(declarationMapper) {
val statements = body?.statements ?: return emptyList()
val cases = mutableListOf<JKJavaSwitchCase>()
for (statement in statements) {
when (statement) {
is PsiSwitchLabelStatement ->
cases += when {
statement.isDefaultCase -> JKJavaDefaultSwitchCase(emptyList())
else -> JKJavaClassicLabelSwitchCase(
with(expressionTreeMapper) {
statement.caseLabelElementList?.elements?.map { (it as? PsiExpression).toJK() }.orEmpty()
},
emptyList()
)
}.withFormattingFrom(statement)
is PsiSwitchLabeledRuleStatement -> {
val body = statement.body.toJK()
cases += when {
statement.isDefaultCase -> JKJavaDefaultSwitchCase(listOf(body))
else -> {
JKJavaArrowSwitchLabelCase(
with(expressionTreeMapper) {
statement.caseLabelElementList?.elements?.map { (it as? PsiExpression).toJK() }.orEmpty()
},
listOf(body),
)
}
}.withFormattingFrom(statement)
}
else ->
cases.lastOrNull()?.also { it.statements = it.statements + statement.toJK() } ?: run {
cases += JKJavaClassicLabelSwitchCase(
listOf(JKStubExpression()),
listOf(statement.toJK())
)
}
}
}
return cases
}
companion object {
private const val DEPRECATED_ANNOTATION_FQ_NAME = "java.lang.Deprecated"
private const val NO_NAME_PROVIDED = "NO_NAME_PROVIDED"
}
}
| apache-2.0 | 84b7d2dd49da9f68ffad8b09e0421958 | 44.984565 | 140 | 0.555514 | 6.139588 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/SetHeaderLevelImpl.kt | 5 | 7142 | package org.intellij.plugins.markdown.ui.actions.styling
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.suggested.endOffset
import com.intellij.refactoring.suggested.startOffset
import com.intellij.util.DocumentUtil
import org.intellij.plugins.markdown.MarkdownBundle.messagePointer
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeader
import org.intellij.plugins.markdown.lang.psi.util.hasType
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil
import org.intellij.plugins.markdown.util.MarkdownPsiUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.util.function.Supplier
import javax.swing.Icon
@ApiStatus.Internal
abstract class SetHeaderLevelImpl(
val level: Int,
text: Supplier<@Nls String>,
val secondaryText: Supplier<@Nls String>? = null,
description: Supplier<@Nls String> = text,
icon: Icon? = null
): ToggleAction(text, description, icon) {
class Normal: SetHeaderLevelImpl(level = 0, messagePointer("markdown.header.level.popup.normal.action.text"))
class Title: SetHeaderLevelImpl(
level = 1,
messagePointer("markdown.header.level.popup.title.action.text"),
messagePointer("markdown.header.level.popup.heading.action.secondary.text", 1)
)
class Subtitle: SetHeaderLevelImpl(
level = 2,
messagePointer("markdown.header.level.popup.subtitle.action.text"),
messagePointer("markdown.header.level.popup.heading.action.secondary.text", 2)
)
class Heading(level: Int): SetHeaderLevelImpl(
level,
messagePointer("markdown.header.level.popup.heading.action.text", level - 2),
messagePointer("markdown.header.level.popup.heading.action.secondary.text", level)
)
override fun isSelected(event: AnActionEvent): Boolean {
val file = event.getData(CommonDataKeys.PSI_FILE) ?: return false
val editor = event.getData(CommonDataKeys.EDITOR) ?: return false
val caret = SelectionUtil.obtainPrimaryCaretSnapshot(this, event) ?: return false
val element = findParent(file, editor.document, caret.selectionStart, caret.selectionEnd)
val header = element?.parentOfType<MarkdownHeader>(withSelf = true)
return when {
header == null && level == 0 -> true
header != null -> header.level == level
else -> false
}
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun setSelected(event: AnActionEvent, state: Boolean) {
if (!state) {
return
}
val file = event.getData(CommonDataKeys.PSI_FILE) ?: return
val editor = event.getData(CommonDataKeys.EDITOR) ?: return
val caret = event.getData(CommonDataKeys.CARET) ?: return
val element = findParent(file, editor.document, caret.selectionStart, caret.selectionEnd)
if (element == null) {
tryToCreateHeaderFromRawLine(editor, caret)
return
}
val header = PsiTreeUtil.getParentOfType(element, MarkdownHeader::class.java, false)
val project = file.project
runWriteAction {
executeCommand(project) {
when {
header != null -> handleExistingHeader(header, editor)
level != 0 -> element.replace(MarkdownPsiElementFactory.createHeader(project, level, element.text))
}
}
}
}
/**
* Simply adds `#` at the line start. If there are no empty lines around new header, new lines will be added them.
*/
private fun tryToCreateHeaderFromRawLine(editor: Editor, caret: Caret) {
val document = editor.document
val selectionStart = caret.selectionStart
val selectionEnd = caret.selectionEnd
val line = document.getLineNumber(selectionStart)
if (line != document.getLineNumber(selectionEnd)) {
return
}
val lineStartOffset = document.getLineStartOffset(line)
runWriteAction {
executeCommand(editor.project) {
val nextLine = line + 1
if (nextLine < document.lineCount && !DocumentUtil.isLineEmpty(document, nextLine)) {
val lineEndOffset = document.getLineEndOffset(line)
document.insertString(lineEndOffset, "\n")
}
document.insertString(lineStartOffset, "${"#".repeat(level)} ")
val previousLine = line - 1
if (previousLine >= 0 && !DocumentUtil.isLineEmpty(document, previousLine)) {
document.insertString(lineStartOffset, "\n")
}
}
}
}
private fun handleExistingHeader(header: MarkdownHeader, editor: Editor) {
when {
level == 0 -> editor.document.replaceString(header.startOffset, header.endOffset, header.name ?: return)
header.level != level -> header.replace(MarkdownPsiElementFactory.createHeader(header.project, header.name ?: return, level))
}
}
companion object {
private val inlineElements = TokenSet.orSet(
MarkdownTokenTypeSets.INLINE_HOLDING_ELEMENT_TYPES,
MarkdownTokenTypeSets.INLINE_HOLDING_ELEMENT_PARENTS_TYPES
)
@JvmStatic
internal fun findParent(file: PsiFile, document: Document, selectionStart: Int, selectionEnd: Int): PsiElement? {
val (left, right) = MarkdownActionUtil.getElementsUnderCaretOrSelection(file, selectionStart, selectionEnd)
val startElement = when {
MarkdownPsiUtil.WhiteSpaces.isNewLine(left) -> PsiTreeUtil.nextVisibleLeaf(left)
else -> left
}
val endElement = when {
MarkdownPsiUtil.WhiteSpaces.isNewLine(right) -> PsiTreeUtil.prevVisibleLeaf(right)
else -> right
}
if (startElement == null || endElement == null || startElement.textOffset > endElement.textOffset) {
return null
}
val parent = MarkdownActionUtil.getCommonParentOfTypes(startElement, endElement, inlineElements)
if (parent?.hasType(MarkdownElementTypes.PARAGRAPH) != true) {
return parent
}
val startOffset = parent.textRange.startOffset
val endOffset = parent.textRange.endOffset
if (startOffset < 0 || endOffset > document.textLength) {
return null
}
return when {
isSameLine(document, startOffset, endOffset) -> parent
else -> null
}
}
private fun isSameLine(document: Document, firstOffset: Int, secondOffset: Int): Boolean {
return document.getLineNumber(firstOffset) == document.getLineNumber(secondOffset)
}
}
}
| apache-2.0 | 4f815e9140063d4e56c9198788f497ed | 39.579545 | 131 | 0.731868 | 4.572343 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/persistence/query/QueryCriteria.kt | 1 | 6455 | package com.onyx.persistence.query
import com.onyx.buffer.BufferStreamable
import com.onyx.descriptor.AttributeDescriptor
import java.util.*
/**
* Specified query filter criteria. This equates to a query predicates as well as relationship joins. This can have nested query criteria.
*
*
* @author Chris Osborn
* @since 1.0.0
*
*
* PersistenceManager manager = factory.getPersistenceManager(); // Get the Persistence manager from the persistence manager factory
*
* QueryCriteria criteria = new QueryCriteria("name", QueryCriteriaOperator.EQUAL, "Bob")
* .or("name", QueryCriteriaOperator.LIKE "Jame")
* .and(
* new QueryCriteria("title", QueryCriteriaOperator.NOT_EQUAL, "The Boss")
* .or(new QueryCriteria("job.positionCode", QueryCriteriaOperator.EQUAL, 3)
* ));
*
* Query query = new Query(MyEntity.class, criteria);
* query.setFirstRow(100);
* query.setMaxResults(1000);
*
* List results = manager.executeQuery(query);
*
*
* @see com.onyx.persistence.manager.PersistenceManager
*
* @see com.onyx.persistence.query.Query
*/
class QueryCriteria : BufferStreamable {
constructor()
var isNot = false
var level: Int = 0
var isAnd = false
var isOr = false
var flip = false
var meetsCriteria = false
var attribute: String? = null
var operator: QueryCriteriaOperator? = null
var value:Any? = null
var subCriteria: MutableList<QueryCriteria> = ArrayList()
@Transient
var parentCriteria: QueryCriteria? = null
@Transient
var attributeDescriptor: AttributeDescriptor? = null
@Transient
var isRelationship:Boolean? = null
get() {
if(field == null)
field = attribute?.contains(".") == true
return field
}
/**
* Constructor with attribute and operator
* @since 1.0.0
* @param attribute Attribute
* @param criteriaEnum Criteria Operator e.x QueryCriteriaOperator.EQUAL
*/
constructor(attribute: String, criteriaEnum: QueryCriteriaOperator) {
this.attribute = attribute
this.operator = criteriaEnum
}
/**
* Constructor with long key
* @since 1.0.0
* @param attribute Attribute
* @param criteriaEnum Criteria Operator e.x QueryCriteriaOperator.EQUAL
* @param value Long key
*/
constructor(attribute: String, criteriaEnum: QueryCriteriaOperator, value: Any?) {
this.attribute = attribute
this.operator = criteriaEnum
this.value = value
}
/**
* And sub criteria with long key
*
* @since 1.0.0
* @param attribute Attribute
* @param criteriaEnum Criteria Operator e.x QueryCriteriaOperator.EQUAL
* @param value Long key
* @return New Query Criteria with added and sub query
*/
fun <K : Any> and(attribute: String, criteriaEnum: QueryCriteriaOperator, value: K): QueryCriteria {
val criteria = QueryCriteria(attribute, criteriaEnum, value)
criteria.isAnd = true
subCriteria.add(criteria)
return this
}
/**
* And with sub-query
*
* @since 1.0.0
* @param andGroup And sub query
* @return New Query Criteria with added and sub query
*/
infix fun and(andGroup: QueryCriteria): QueryCriteria {
andGroup.isAnd = true
this.subCriteria.add(andGroup)
return this
}
/**
* Or with long
*
* @since 1.0.0
* @param attribute Attribute
* @param criteriaEnum Criteria Operator e.x QueryCriteriaOperator.EQUAL
* @param value long key
* @return New Query Criteria with added or sub query
*/
fun <R : Any> or(attribute: String, criteriaEnum: QueryCriteriaOperator, value: R): QueryCriteria {
val criteria = QueryCriteria(attribute, criteriaEnum, value)
criteria.isOr = true
subCriteria.add(criteria)
return this
}
/**
* Or with sub-query
*
* @since 1.0.0
* @param orGroup Or Sub Query
* @return New Query Criteria with added or sub query
*/
infix fun or(orGroup: QueryCriteria): QueryCriteria {
orGroup.isOr = true
this.subCriteria.add(orGroup)
return this
}
/**
* Indicate you would like the inverse of the QueryCriteria grouping.
*
*
* Usage:
*
*
* QueryCriteria firstCriteria = new QueryCriteria("age", QueryCriteriaOperator.GREATER_THAN, 18);
* QueryCriteria secondCriteria = new QueryCriteria("canDrive", QueryCriteriaOperator.EQUAL, true);
*
*
* // first.and(second).not() Criteria
* persistenceManager.executeQuery(new Query(Person.class, first.and(second).not());
*
* The equivalent using DSL would be:
*
*
* val unqualifiedDrivers = db.query(Driver.Data)
* .where [ !(age > 18 && canDrive == true) ]
* .list
*
* @since 1.3.0 Added as enhancement #69
*/
operator fun not(): QueryCriteria {
if(subCriteria.isEmpty()) {
operator = operator!!.inverse // Invert the criteria rather than checking all the criteria
this.isNot = false
}
else {
val referenceCriteria = QueryCriteria("", QueryCriteriaOperator.EQUAL, "")
referenceCriteria.flip = true
and(referenceCriteria)
isNot = true
}
return this
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as QueryCriteria
if (isNot != other.isNot) return false
if (isAnd != other.isAnd) return false
if (isOr != other.isOr) return false
if (attribute != other.attribute) return false
if (operator != other.operator) return false
if (value != other.value) return false
if (subCriteria != other.subCriteria) return false
return true
}
override fun hashCode(): Int {
var result = isNot.hashCode()
result = 31 * result + isAnd.hashCode()
result = 31 * result + isOr.hashCode()
result = 31 * result + flip.hashCode()
result = 31 * result + (attribute?.hashCode() ?: 0)
result = 31 * result + (operator?.hashCode() ?: 0)
result = 31 * result + (value?.hashCode() ?: 0)
result = 31 * result + subCriteria.hashCode()
return result
}
}
| agpl-3.0 | 48d6e8983bc342352c5fc8d76f01e422 | 29.163551 | 140 | 0.627111 | 4.473319 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinEqualityInstruction.kt | 4 | 3608 | // 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.inspections.dfa
import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter
import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState
import com.intellij.codeInspection.dataFlow.lang.ir.ExpressionPushingInstruction
import com.intellij.codeInspection.dataFlow.lang.ir.Instruction
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.KotlinExpressionAnchor
import org.jetbrains.kotlin.psi.KtExpression
/**
* Instruction that processes kotlin == or != operators between unknown reference values, assuming the following contract:
* if x == y => true
* else if x == null => false
* else if y == null => false
* else unknown
*/
class KotlinEqualityInstruction(
equality: KtExpression,
private val negated: Boolean,
private val exceptionTransfer: DfaControlTransferValue?
) : ExpressionPushingInstruction(KotlinExpressionAnchor(equality)) {
override fun bindToFactory(factory: DfaValueFactory): Instruction =
if (exceptionTransfer == null) this
else KotlinEqualityInstruction((dfaAnchor as KotlinExpressionAnchor).expression, negated, exceptionTransfer.bindToFactory(factory))
override fun accept(interpreter: DataFlowInterpreter, stateBefore: DfaMemoryState): Array<DfaInstructionState> {
val right = stateBefore.pop()
val left = stateBefore.pop()
val result = mutableListOf<DfaInstructionState>()
if (exceptionTransfer != null) {
val exceptional = stateBefore.createCopy()
result += exceptionTransfer.dispatch(exceptional, interpreter)
}
val eqState = stateBefore.createCopy()
val leftEqRight = left.eq(right)
if (eqState.applyCondition(leftEqRight)) {
pushResult(interpreter, eqState, DfTypes.booleanValue(!negated))
result += nextState(interpreter, eqState)
}
if (stateBefore.applyCondition(leftEqRight.negate())) {
val leftNullState = stateBefore.createCopy()
val nullValue = interpreter.factory.fromDfType(DfTypes.NULL)
val leftEqNull = left.eq(nullValue)
if (leftNullState.applyCondition(leftEqNull)) {
pushResult(interpreter, leftNullState, DfTypes.booleanValue(negated))
result += nextState(interpreter, leftNullState)
}
if (stateBefore.applyCondition(leftEqNull.negate())) {
val rightNullState = stateBefore.createCopy()
val rightEqNull = right.eq(nullValue)
if (rightNullState.applyCondition(rightEqNull)) {
pushResult(interpreter, rightNullState, DfTypes.booleanValue(negated))
result += nextState(interpreter, rightNullState)
}
if (stateBefore.applyCondition(rightEqNull.negate())) {
pushResult(interpreter, stateBefore, DfTypes.BOOLEAN)
result += nextState(interpreter, stateBefore)
}
}
}
return result.toTypedArray()
}
override fun toString(): String {
return if (negated) "NOT_EQUAL" else "EQUAL"
}
} | apache-2.0 | bdab5179cfa61d2611403eeee764cd7c | 48.438356 | 158 | 0.70316 | 5.018081 | false | false | false | false |
googlearchive/android-FingerprintDialog | kotlinApp/app/src/main/java/com/example/android/fingerprintdialog/FingerprintAuthenticationDialogFragment.kt | 3 | 9074 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.example.android.fingerprintdialog
import android.app.DialogFragment
import android.content.Context
import android.content.SharedPreferences
import android.hardware.fingerprint.FingerprintManager
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
/**
* A dialog which uses fingerprint APIs to authenticate the user, and falls back to password
* authentication if fingerprint is not available.
*/
class FingerprintAuthenticationDialogFragment : DialogFragment(),
TextView.OnEditorActionListener,
FingerprintUiHelper.Callback {
private lateinit var backupContent: View
private lateinit var cancelButton: Button
private lateinit var fingerprintContainer: View
private lateinit var fingerprintEnrolledTextView: TextView
private lateinit var passwordDescriptionTextView: TextView
private lateinit var passwordEditText: EditText
private lateinit var secondDialogButton: Button
private lateinit var useFingerprintFutureCheckBox: CheckBox
private lateinit var callback: Callback
private lateinit var cryptoObject: FingerprintManager.CryptoObject
private lateinit var fingerprintUiHelper: FingerprintUiHelper
private lateinit var inputMethodManager: InputMethodManager
private lateinit var sharedPreferences: SharedPreferences
private var stage = Stage.FINGERPRINT
private val showKeyboardRunnable = Runnable {
inputMethodManager.showSoftInput(passwordEditText, 0)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Do not create a new Fragment when the Activity is re-created such as orientation changes.
retainInstance = true
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dialog.setTitle(getString(R.string.sign_in))
return inflater.inflate(R.layout.fingerprint_dialog_container, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
backupContent = view.findViewById(R.id.backup_container)
cancelButton = view.findViewById(R.id.cancel_button)
fingerprintContainer = view.findViewById(R.id.fingerprint_container)
fingerprintEnrolledTextView = view.findViewById(R.id.new_fingerprint_enrolled_description)
passwordDescriptionTextView = view.findViewById(R.id.password_description)
passwordEditText = view.findViewById(R.id.password)
secondDialogButton = view.findViewById(R.id.second_dialog_button)
useFingerprintFutureCheckBox = view.findViewById(R.id.use_fingerprint_in_future_check)
cancelButton.setOnClickListener { dismiss() }
passwordEditText.setOnEditorActionListener(this)
secondDialogButton.setOnClickListener {
if (stage == Stage.FINGERPRINT) goToBackup() else verifyPassword()
}
fingerprintUiHelper = FingerprintUiHelper(
activity.getSystemService(FingerprintManager::class.java),
view.findViewById(R.id.fingerprint_icon),
view.findViewById(R.id.fingerprint_status),
this
)
updateStage()
// If fingerprint authentication is not available, switch immediately to the backup
// (password) screen.
if (!fingerprintUiHelper.isFingerprintAuthAvailable) {
goToBackup()
}
}
override fun onResume() {
super.onResume()
if (stage == Stage.FINGERPRINT) {
fingerprintUiHelper.startListening(cryptoObject)
}
}
override fun onPause() {
super.onPause()
fingerprintUiHelper.stopListening()
}
override fun onAttach(context: Context) {
super.onAttach(context)
inputMethodManager = context.getSystemService(InputMethodManager::class.java)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
}
fun setCallback(callback: Callback) {
this.callback = callback
}
fun setCryptoObject(cryptoObject: FingerprintManager.CryptoObject) {
this.cryptoObject = cryptoObject
}
fun setStage(stage: Stage) {
this.stage = stage
}
/**
* Switches to backup (password) screen. This either can happen when fingerprint is not
* available or the user chooses to use the password authentication method by pressing the
* button. This can also happen when the user has too many invalid fingerprint attempts.
*/
private fun goToBackup() {
stage = Stage.PASSWORD
updateStage()
passwordEditText.run {
requestFocus()
// Show the keyboard.
postDelayed(showKeyboardRunnable, 500)
}
// Fingerprint is not used anymore. Stop listening for it.
fingerprintUiHelper.stopListening()
}
/**
* Checks whether the current entered password is correct, and dismisses the dialog and
* informs the activity about the result.
*/
private fun verifyPassword() {
if (!checkPassword(passwordEditText.text.toString())) {
return
}
if (stage == Stage.NEW_FINGERPRINT_ENROLLED) {
sharedPreferences.edit()
.putBoolean(getString(R.string.use_fingerprint_to_authenticate_key),
useFingerprintFutureCheckBox.isChecked)
.apply()
if (useFingerprintFutureCheckBox.isChecked) {
// Re-create the key so that fingerprints including new ones are validated.
callback.createKey(DEFAULT_KEY_NAME)
stage = Stage.FINGERPRINT
}
}
passwordEditText.setText("")
callback.onPurchased(withFingerprint = false)
dismiss()
}
/**
* Checks if the given password is valid. Assume that the password is always correct.
* In a real world situation, the password needs to be verified via the server.
*
* @param password The password String
*
* @return true if `password` is correct, false otherwise
*/
private fun checkPassword(password: String) = password.isNotEmpty()
private fun updateStage() {
when (stage) {
Stage.FINGERPRINT -> {
cancelButton.setText(R.string.cancel)
secondDialogButton.setText(R.string.use_password)
fingerprintContainer.visibility = View.VISIBLE
backupContent.visibility = View.GONE
}
Stage.NEW_FINGERPRINT_ENROLLED, // Intentional fall through
Stage.PASSWORD -> {
cancelButton.setText(R.string.cancel)
secondDialogButton.setText(R.string.ok)
fingerprintContainer.visibility = View.GONE
backupContent.visibility = View.VISIBLE
if (stage == Stage.NEW_FINGERPRINT_ENROLLED) {
passwordDescriptionTextView.visibility = View.GONE
fingerprintEnrolledTextView.visibility = View.VISIBLE
useFingerprintFutureCheckBox.visibility = View.VISIBLE
}
}
}
}
override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent?): Boolean {
return if (actionId == EditorInfo.IME_ACTION_GO) { verifyPassword(); true } else false
}
override fun onAuthenticated() {
// Callback from FingerprintUiHelper. Let the activity know that authentication succeeded.
callback.onPurchased(withFingerprint = true, crypto = cryptoObject)
dismiss()
}
override fun onError() {
goToBackup()
}
interface Callback {
fun onPurchased(withFingerprint: Boolean, crypto: FingerprintManager.CryptoObject? = null)
fun createKey(keyName: String, invalidatedByBiometricEnrollment: Boolean = true)
}
}
| apache-2.0 | 704e5c30eb3e4385e7244dfadb9a8e2e | 37.12605 | 100 | 0.686687 | 5.220944 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupCancelService.kt | 4 | 3417 | // 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.completion
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.codeInsight.lookup.LookupListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.psi.KtTypeArgumentList
class LookupCancelService {
internal class Reminiscence(editor: Editor, offset: Int) {
var editor: Editor? = editor
private var marker: RangeMarker? = editor.document.createRangeMarker(offset, offset)
// forget about auto-popup cancellation when the caret is moved to the start or before it
private var editorListener: CaretListener? = object : CaretListener {
override fun caretPositionChanged(e: CaretEvent) {
if (marker != null && (!marker!!.isValid || editor.logicalPositionToOffset(e.newPosition) <= offset)) {
dispose()
}
}
}
init {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
editor.caretModel.addCaretListener(editorListener!!)
}
fun matches(editor: Editor, offset: Int): Boolean {
return editor == this.editor && marker?.startOffset == offset
}
fun dispose() {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
if (marker != null) {
editor!!.caretModel.removeCaretListener(editorListener!!)
marker = null
editor = null
editorListener = null
}
}
}
internal val lookupCancelListener = object : LookupListener {
override fun lookupCanceled(event: LookupEvent) {
val lookup = event.lookup
if (event.isCanceledExplicitly && lookup.isCompletion) {
val offset = lookup.currentItem?.getUserData(LookupCancelService.AUTO_POPUP_AT)
if (offset != null) {
lastReminiscence?.dispose()
if (offset <= lookup.editor.document.textLength) {
lastReminiscence = Reminiscence(lookup.editor, offset)
}
}
}
}
}
internal fun disposeLastReminiscence(editor: Editor) {
if (lastReminiscence?.editor == editor) {
lastReminiscence!!.dispose()
lastReminiscence = null
}
}
private var lastReminiscence: Reminiscence? = null
companion object {
fun getInstance(project: Project): LookupCancelService = project.service()
fun getServiceIfCreated(project: Project): LookupCancelService? = project.getServiceIfCreated(LookupCancelService::class.java)
val AUTO_POPUP_AT = Key<Int>("LookupCancelService.AUTO_POPUP_AT")
}
fun wasAutoPopupRecentlyCancelled(editor: Editor, offset: Int): Boolean {
return lastReminiscence?.matches(editor, offset) ?: false
}
}
| apache-2.0 | 9ed73dc1cdf155f82aa029cc9e4e6704 | 38.275862 | 158 | 0.654668 | 5.16944 | false | false | false | false |
smmribeiro/intellij-community | java/idea-ui/src/com/intellij/ide/starters/local/Starters.kt | 10 | 2055 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.local
import com.intellij.ide.starters.shared.LibraryInfo
import com.intellij.ide.starters.shared.LibraryLink
import com.intellij.ide.starters.shared.StarterWizardSettings
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.annotations.Nls
import java.net.URL
import javax.swing.Icon
data class Dependency(
val group: String,
val artifact: String,
val version: String
)
data class DependencyConfig(
val version: String,
val properties: Map<String, String>,
val dependencies: List<Dependency>
) {
fun getVersion(group: String, artifact: String): String? {
return dependencies.find { it.group == group && it.artifact == artifact }?.version
}
}
data class LibraryCategory(
val id: String,
val icon: Icon?,
@Nls val title: String,
@Nls val description: String
)
class Library (
val id: String,
val icon: Icon?,
@NlsSafe
override val title: String,
@Nls
override val description: String,
val group: String?,
val artifact: String?,
override val links: List<LibraryLink> = emptyList(),
val category: LibraryCategory? = null,
override val isRequired: Boolean = false,
override val isDefault: Boolean = false,
val includesLibraries: Set<String> = emptySet()
) : LibraryInfo {
override fun toString(): String {
return "Library($id)"
}
}
data class Starter(
val id: String,
val title: String,
val versionConfigUrl: URL,
val libraries: List<Library>
)
data class StarterPack(
val defaultStarterId: String,
val starters: List<Starter>
)
class StarterContextProvider(
val moduleBuilder: StarterModuleBuilder,
val parentDisposable: Disposable,
val starterContext: StarterContext,
val wizardContext: WizardContext,
val settings: StarterWizardSettings,
val starterPackProvider: () -> StarterPack
) | apache-2.0 | d80629b930ee80fef25e808e5914808e | 26.052632 | 140 | 0.751825 | 4.069307 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.kt | 1 | 20815 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui
import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.application.options.editor.checkBox
import com.intellij.ide.DataManager
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.QuickChangeLookAndFeel
import com.intellij.ide.ui.search.OptionDescription
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.PlatformEditorBundle
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.keymap.KeyMapBundle
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameDecorator
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.FontComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.UIUtil
import java.awt.RenderingHints
import java.awt.Window
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.*
private val settings: UISettings
get() = UISettings.instance
private val generalSettings
get() = GeneralSettings.getInstance()
private val lafManager
get() = LafManager.getInstance()
private val cdShowToolWindowBars
get() = CheckboxDescriptor(message("checkbox.show.tool.window.bars"), PropertyBinding({ !settings.hideToolStripes },
{ settings.hideToolStripes = !it }),
groupName = windowOptionGroupName)
private val cdShowToolWindowNumbers
get() = CheckboxDescriptor(message("checkbox.show.tool.window.numbers"), settings::showToolWindowsNumbers,
groupName = windowOptionGroupName)
private val cdEnableMenuMnemonics
get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.menu.check.box"), PropertyBinding({ !settings.disableMnemonics },
{ settings.disableMnemonics = !it }),
groupName = windowOptionGroupName)
private val cdEnableControlsMnemonics
get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.controls.check.box"),
PropertyBinding({ !settings.disableMnemonicsInControls }, { settings.disableMnemonicsInControls = !it }),
groupName = windowOptionGroupName)
private val cdSmoothScrolling
get() = CheckboxDescriptor(message("checkbox.smooth.scrolling"), settings::smoothScrolling, groupName = uiOptionGroupName)
private val cdWidescreenToolWindowLayout
get() = CheckboxDescriptor(message("checkbox.widescreen.tool.window.layout"), settings::wideScreenSupport,
groupName = windowOptionGroupName)
private val cdLeftToolWindowLayout
get() = CheckboxDescriptor(message("checkbox.left.toolwindow.layout"), settings::leftHorizontalSplit, groupName = windowOptionGroupName)
private val cdRightToolWindowLayout
get() = CheckboxDescriptor(message("checkbox.right.toolwindow.layout"), settings::rightHorizontalSplit, groupName = windowOptionGroupName)
private val cdUseCompactTreeIndents
get() = CheckboxDescriptor(message("checkbox.compact.tree.indents"), settings::compactTreeIndents, groupName = uiOptionGroupName)
private val cdShowTreeIndents
get() = CheckboxDescriptor(message("checkbox.show.tree.indent.guides"), settings::showTreeIndentGuides, groupName = uiOptionGroupName)
private val cdDnDWithAlt
get() = CheckboxDescriptor(message("dnd.with.alt.pressed.only"), settings::dndWithPressedAltOnly, groupName = uiOptionGroupName)
private val cdSeparateMainMenu
get() = CheckboxDescriptor(message("checkbox.main.menu.separate.toolbar"), settings::separateMainMenu, groupName = uiOptionGroupName)
private val cdUseTransparentMode
get() = CheckboxDescriptor(message("checkbox.use.transparent.mode.for.floating.windows"),
PropertyBinding({ settings.state.enableAlphaMode }, { settings.state.enableAlphaMode = it }))
private val cdOverrideLaFFont get() = CheckboxDescriptor(message("checkbox.override.default.laf.fonts"), settings::overrideLafFonts)
private val cdUseContrastToolbars
get() = CheckboxDescriptor(message("checkbox.acessibility.contrast.scrollbars"), settings::useContrastScrollbars)
private val cdMergeMainMenuWithWindowTitle
get() = CheckboxDescriptor(message("checkbox.merge.main.menu.with.window.title"), settings::mergeMainMenuWithWindowTitle, groupName = windowOptionGroupName)
private val cdFullPathsInTitleBar
get() = CheckboxDescriptor(message("checkbox.full.paths.in.window.header"), settings::fullPathsInWindowHeader)
private val cdShowMenuIcons
get() = CheckboxDescriptor(message("checkbox.show.icons.in.menu.items"), settings::showIconsInMenus, groupName = windowOptionGroupName)
internal fun getAppearanceOptionDescriptors(): Sequence<OptionDescription> {
return sequenceOf(
cdShowToolWindowBars,
cdShowToolWindowNumbers,
cdEnableMenuMnemonics,
cdEnableControlsMnemonics,
cdSmoothScrolling,
cdWidescreenToolWindowLayout,
cdLeftToolWindowLayout,
cdRightToolWindowLayout,
cdUseCompactTreeIndents,
cdShowTreeIndents,
cdDnDWithAlt,
cdFullPathsInTitleBar,
cdSeparateMainMenu
).map(CheckboxDescriptor::asUiOptionDescriptor)
}
internal class AppearanceConfigurable : BoundSearchableConfigurable(message("title.appearance"), "preferences.lookFeel") {
private var shouldUpdateLaF = false
private val propertyGraph = PropertyGraph()
private val lafProperty = propertyGraph.graphProperty { lafManager.lookAndFeelReference }
private val syncThemeProperty = propertyGraph.graphProperty { lafManager.autodetect }
override fun createPanel(): DialogPanel {
lafProperty.afterChange({ QuickChangeLookAndFeel.switchLafAndUpdateUI(lafManager, lafManager.findLaf(it), true) }, disposable!!)
syncThemeProperty.afterChange({ lafManager.autodetect = it }, disposable!!)
return panel {
row(message("combobox.look.and.feel")) {
val theme = comboBox(lafManager.lafComboBoxModel, lafManager.lookAndFeelCellRenderer)
.bindItem(lafProperty)
.accessibleName(message("combobox.look.and.feel"))
val syncCheckBox = checkBox(message("preferred.theme.autodetect.selector"))
.bindSelected(syncThemeProperty)
.visible(lafManager.autodetectSupported)
.gap(RightGap.SMALL)
theme.enabledIf(syncCheckBox.selected.not())
cell(lafManager.settingsToolbar)
.visibleIf(syncCheckBox.selected)
}.layout(RowLayout.INDEPENDENT)
row {
link(message("link.get.more.themes")) {
val settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(it.source as ActionLink))
settings?.select(settings.find("preferences.pluginManager"), "/tag:theme")
}
}
row {
val overrideLaF = checkBox(cdOverrideLaFFont)
.shouldUpdateLaF()
.gap(RightGap.SMALL)
cell(FontComboBox())
.bind(
{ it.fontName },
{ it, value -> it.fontName = value },
PropertyBinding({ if (settings.overrideLafFonts) settings.fontFace else JBFont.label().family },
{ settings.fontFace = it })
)
.shouldUpdateLaF()
.enabledIf(overrideLaF.selected)
.accessibleName(cdOverrideLaFFont.name)
fontSizeComboBox({ if (settings.overrideLafFonts) settings.fontSize else JBFont.label().size },
{ settings.fontSize = it },
settings.fontSize)
.label(message("label.font.size"))
.shouldUpdateLaF()
.enabledIf(overrideLaF.selected)
.accessibleName(message("label.font.size"))
}.topGap(TopGap.SMALL)
group(message("title.accessibility")) {
row {
val isOverridden = GeneralSettings.isSupportScreenReadersOverridden()
checkBox(message("checkbox.support.screen.readers"))
.bindSelected(generalSettings::isSupportScreenReaders, generalSettings::setSupportScreenReaders)
.comment(if (isOverridden) message("option.is.overridden.by.jvm.property", GeneralSettings.SUPPORT_SCREEN_READERS) else null)
.enabled(!isOverridden)
comment(message("support.screen.readers.comment"))
val mask = if (SystemInfo.isMac) InputEvent.META_MASK else InputEvent.CTRL_MASK
val ctrlTab = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, mask))
val ctrlShiftTab = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, mask + InputEvent.SHIFT_MASK))
rowComment(message("support.screen.readers.tab", ctrlTab, ctrlShiftTab))
}
row {
checkBox(cdUseContrastToolbars)
}
val supportedValues = ColorBlindness.values().filter { ColorBlindnessSupport.get(it) != null }
if (supportedValues.isNotEmpty()) {
val modelBinding = PropertyBinding({ settings.colorBlindness }, { settings.colorBlindness = it })
val onApply = {
// callback executed not when all changes are applied, but one component by one, so, reload later when everything were applied
ApplicationManager.getApplication().invokeLater(Runnable {
DefaultColorSchemesManager.getInstance().reload()
(EditorColorsManager.getInstance() as EditorColorsManagerImpl).schemeChangedOrSwitched(null)
})
}
row {
if (supportedValues.size == 1) {
checkBox(UIBundle.message("color.blindness.checkbox.text"))
.comment(UIBundle.message("color.blindness.checkbox.comment"))
.bind({ if (it.isSelected) supportedValues.first() else null },
{ it, value -> it.isSelected = value != null },
modelBinding)
.onApply(onApply)
}
else {
val enableColorBlindness = checkBox(UIBundle.message("color.blindness.combobox.text"))
.applyToComponent { isSelected = modelBinding.get() != null }
comboBox(supportedValues)
.enabledIf(enableColorBlindness.selected)
.applyToComponent { renderer = SimpleListCellRenderer.create("") { PlatformEditorBundle.message(it.key) } }
.comment(UIBundle.message("color.blindness.combobox.comment"))
.bind({ if (enableColorBlindness.component.isSelected) it.selectedItem as? ColorBlindness else null },
{ it, value -> it.selectedItem = value ?: supportedValues.first() },
modelBinding)
.onApply(onApply)
.accessibleName(UIBundle.message("color.blindness.checkbox.text"))
}
link(UIBundle.message("color.blindness.link.to.help")
) { HelpManager.getInstance().invokeHelp("Colorblind_Settings") }
}
}
}
group(message("group.ui.options")) {
val leftColumnControls = sequence<Row.() -> Unit> {
yield({ checkBox(cdShowTreeIndents) })
yield({ checkBox(cdUseCompactTreeIndents) })
yield({ checkBox(cdEnableMenuMnemonics) })
yield({ checkBox(cdEnableControlsMnemonics) })
if (SystemInfo.isWindows && ExperimentalUI.isNewToolbar()) {
yield({ checkBox(cdSeparateMainMenu) })
}
}
val rightColumnControls = sequence<Row.() -> Unit> {
yield({
checkBox(cdSmoothScrolling)
.gap(RightGap.SMALL)
contextHelp(message("checkbox.smooth.scrolling.description"))
})
yield({ checkBox(cdDnDWithAlt) })
if (IdeFrameDecorator.isCustomDecorationAvailable()) {
yield({
val overridden = UISettings.isMergeMainMenuWithWindowTitleOverridden
checkBox(cdMergeMainMenuWithWindowTitle)
.enabled(!overridden)
.gap(RightGap.SMALL)
if (overridden) {
contextHelp(message("option.is.overridden.by.jvm.property", UISettings.MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY))
}
comment(message("checkbox.merge.main.menu.with.window.title.comment"))
})
}
yield({ checkBox(cdFullPathsInTitleBar) })
yield({ checkBox(cdShowMenuIcons) })
}
// Since some of the columns have variable number of items, enumerate them in a loop, while moving orphaned items from the right
// column to the left one:
val leftIt = leftColumnControls.iterator()
val rightIt = rightColumnControls.iterator()
while (leftIt.hasNext() || rightIt.hasNext()) {
when {
leftIt.hasNext() && rightIt.hasNext() -> twoColumnsRow(leftIt.next(), rightIt.next())
leftIt.hasNext() -> twoColumnsRow(leftIt.next())
rightIt.hasNext() -> twoColumnsRow(rightIt.next()) // move from right to left
}
}
val backgroundImageAction = ActionManager.getInstance().getAction("Images.SetBackgroundImage")
if (backgroundImageAction != null) {
row {
button(message("background.image.button"), backgroundImageAction)
.enabled(ProjectManager.getInstance().openProjects.isNotEmpty())
}
}
}
if (Registry.`is`("ide.transparency.mode.for.windows") &&
WindowManagerEx.getInstanceEx().isAlphaModeSupported) {
val settingsState = settings.state
group(message("group.transparency")) {
lateinit var checkbox: Cell<JBCheckBox>
row {
checkbox = checkBox(cdUseTransparentMode)
}
row(message("label.transparency.delay.ms")) {
intTextField()
.bindIntText(settingsState::alphaModeDelay)
.columns(4)
}.enabledIf(checkbox.selected)
row(message("label.transparency.ratio")) {
slider(0, 100, 10, 50)
.labelTable(mapOf(
0 to JLabel("0%"),
50 to JLabel("50%"),
100 to JLabel("100%")))
.bindValue({ (settingsState.alphaModeRatio * 100f).toInt() }, { settingsState.alphaModeRatio = it / 100f })
.showValueHint()
}.enabledIf(checkbox.selected)
.layout(RowLayout.INDEPENDENT)
}
}
groupRowsRange(message("group.antialiasing.mode")) {
twoColumnsRow(
{
val ideAAOptions =
if (!AntialiasingType.canUseSubpixelAAForIDE())
arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
else
AntialiasingType.values()
comboBox(DefaultComboBoxModel(ideAAOptions), renderer = AAListCellRenderer(false))
.label(message("label.text.antialiasing.scope.ide"))
.bindItem(settings::ideAAType)
.shouldUpdateLaF()
.accessibleName(message("label.text.antialiasing.scope.ide"))
.onApply {
for (w in Window.getWindows()) {
for (c in UIUtil.uiTraverser(w).filter(JComponent::class.java)) {
GraphicsUtil.setAntialiasingType(c, AntialiasingType.getAAHintForSwingComponent())
}
}
}
},
{
val editorAAOptions =
if (!AntialiasingType.canUseSubpixelAAForEditor())
arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
else
AntialiasingType.values()
comboBox(DefaultComboBoxModel(editorAAOptions), renderer = AAListCellRenderer(true))
.label(message("label.text.antialiasing.scope.editor"))
.bindItem(settings::editorAAType)
.shouldUpdateLaF()
.accessibleName(message("label.text.antialiasing.scope.editor"))
}
)
}
groupRowsRange(message("group.window.options")) {
twoColumnsRow(
{ checkBox(cdShowToolWindowBars) },
{ checkBox(cdShowToolWindowNumbers) }
)
twoColumnsRow(
{ checkBox(cdLeftToolWindowLayout) },
{ checkBox(cdRightToolWindowLayout) }
)
twoColumnsRow(
{
checkBox(cdWidescreenToolWindowLayout)
.gap(RightGap.SMALL)
contextHelp(message("checkbox.widescreen.tool.window.layout.description"))
})
}
group(message("group.presentation.mode")) {
row(message("presentation.mode.fon.size")) {
fontSizeComboBox({ settings.presentationModeFontSize },
{ settings.presentationModeFontSize = it },
settings.presentationModeFontSize)
.shouldUpdateLaF()
}
}
}
}
override fun apply() {
val uiSettingsChanged = isModified
shouldUpdateLaF = false
super.apply()
if (shouldUpdateLaF) {
LafManager.getInstance().updateUI()
}
if (uiSettingsChanged) {
UISettings.instance.fireUISettingsChanged()
EditorFactory.getInstance().refreshAllEditors()
}
}
private fun <T : JComponent> Cell<T>.shouldUpdateLaF(): Cell<T> = onApply { shouldUpdateLaF = true }
}
internal fun Row.fontSizeComboBox(getter: () -> Int, setter: (Int) -> Unit, defaultValue: Int): Cell<ComboBox<String>> {
val model = DefaultComboBoxModel(UIUtil.getStandardFontSizes())
val modelBinding: PropertyBinding<String?> = PropertyBinding({ getter().toString() }, { setter(getIntValue(it, defaultValue)) })
return comboBox(model)
.accessibleName(message("presentation.mode.fon.size"))
.applyToComponent {
isEditable = true
renderer = SimpleListCellRenderer.create("") { it.toString() }
selectedItem = modelBinding.get()
}
.bind(
{ component -> component.editor.item as String? },
{ component, value -> component.setSelectedItem(value) },
modelBinding
)
}
private fun getIntValue(text: String?, defaultValue: Int): Int {
if (text != null && text.isNotBlank()) {
val value = text.toIntOrNull()
if (value != null && value > 0) return value
}
return defaultValue
}
private class AAListCellRenderer(private val myUseEditorFont: Boolean) : SimpleListCellRenderer<AntialiasingType>() {
private val SUBPIXEL_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
private val GREYSCALE_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
override fun customize(list: JList<out AntialiasingType>, value: AntialiasingType, index: Int, selected: Boolean, hasFocus: Boolean) {
val aaType = when (value) {
AntialiasingType.SUBPIXEL -> SUBPIXEL_HINT
AntialiasingType.GREYSCALE -> GREYSCALE_HINT
AntialiasingType.OFF -> null
}
GraphicsUtil.setAntialiasingType(this, aaType)
if (myUseEditorFont) {
val scheme = EditorColorsManager.getInstance().globalScheme
font = UIUtil.getFontWithFallback(scheme.getFont(EditorFontType.PLAIN))
}
text = value.presentableName
}
}
| apache-2.0 | 72de3d2a6966aa261aebac62e789672f | 45.462054 | 158 | 0.674033 | 4.916155 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/HideAllToolWindowsAction.kt | 1 | 2791 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.impl.EditorWindow
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.impl.ToolWindowEventSource
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import org.jetbrains.annotations.ApiStatus
internal class HideAllToolWindowsAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
e.project?.let { ToolWindowManager.getInstance(it) as? ToolWindowManagerImpl }?.let {
val idsToHide = getIDsToHide(it)
val window = e.getData(EditorWindow.DATA_KEY)
if (window != null && window.owner.isFloating) return
if (idsToHide.isNotEmpty()) {
val layout = it.layout.copy()
it.clearSideStack()
//it.activateEditorComponent();
for (id in idsToHide) {
it.hideToolWindow(id, false, true, ToolWindowEventSource.HideAllWindowsAction)
}
it.layoutToRestoreLater = layout
it.activateEditorComponent()
}
else {
val restoredLayout = it.layoutToRestoreLater
if (restoredLayout != null) {
it.layoutToRestoreLater = null
it.setLayout(restoredLayout)
}
}
}
}
companion object {
@JvmStatic
@ApiStatus.Internal
fun getIDsToHide(toolWindowManager: ToolWindowManagerEx): Set<String> {
val set = HashSet<String>()
toolWindowManager.toolWindowIds.forEach {
if (HideToolWindowAction.shouldBeHiddenByShortCut(toolWindowManager, it)) {
set.add(it)
}
}
return set
}
}
override fun update(event: AnActionEvent) {
with(event.presentation) {
isEnabled = false
event.project?.let { ToolWindowManager.getInstance(it) as? ToolWindowManagerEx }?.let {
val window = event.getData(EditorWindow.DATA_KEY)
if (window == null || !window.owner.isFloating) {
if (getIDsToHide(it).isNotEmpty()) {
isEnabled = true
putClientProperty(MaximizeEditorInSplitAction.CURRENT_STATE_IS_MAXIMIZED_KEY, false)
text = IdeBundle.message("action.hide.all.windows")
return
}
if (it.layoutToRestoreLater != null) {
isEnabled = true
text = IdeBundle.message("action.restore.windows")
putClientProperty(MaximizeEditorInSplitAction.CURRENT_STATE_IS_MAXIMIZED_KEY, true)
return
}
}
}
}
}
} | apache-2.0 | 1c31cd9fbcb3fab8425074f8931a29bc | 34.341772 | 120 | 0.677535 | 4.590461 | false | false | false | false |
webianks/BlueChat | app/src/main/java/com/webianks/bluechat/MainActivity.kt | 1 | 19224 | package com.webianks.bluechat
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.*
class MainActivity : AppCompatActivity(), DevicesRecyclerViewAdapter.ItemClickListener,
ChatFragment.CommunicationListener {
private val REQUEST_ENABLE_BT = 123
private val TAG = javaClass.simpleName
private lateinit var progressBar: ProgressBar
private lateinit var recyclerView: RecyclerView
private lateinit var recyclerViewPaired: RecyclerView
private val mDeviceList = arrayListOf<DeviceData>()
private lateinit var devicesAdapter: DevicesRecyclerViewAdapter
private var mBtAdapter: BluetoothAdapter? = null
private val PERMISSION_REQUEST_LOCATION = 123
private val PERMISSION_REQUEST_LOCATION_KEY = "PERMISSION_REQUEST_LOCATION"
private var alreadyAskedForPermission = false
private lateinit var headerLabel: TextView
private lateinit var headerLabelPaired: TextView
private lateinit var headerLabelContainer: LinearLayout
private lateinit var status: TextView
private lateinit var connectionDot: ImageView
private lateinit var mConnectedDeviceName: String
private var connected: Boolean = false
private var mChatService: BluetoothChatService? = null
private lateinit var chatFragment: ChatFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbarTitle = findViewById<TextView>(R.id.toolbarTitle)
val typeFace = Typeface.createFromAsset(assets, "fonts/product_sans.ttf")
toolbarTitle.typeface = typeFace
progressBar = findViewById(R.id.progressBar)
recyclerView = findViewById(R.id.recyclerView)
recyclerViewPaired = findViewById(R.id.recyclerViewPaired)
headerLabel = findViewById(R.id.headerLabel)
headerLabelPaired = findViewById(R.id.headerLabelPaired)
headerLabelContainer = findViewById(R.id.headerLabelContainer)
status = findViewById(R.id.status)
connectionDot = findViewById(R.id.connectionDot)
status.text = getString(R.string.bluetooth_not_enabled)
headerLabelContainer.visibility = View.INVISIBLE
if (savedInstanceState != null)
alreadyAskedForPermission = savedInstanceState.getBoolean(PERMISSION_REQUEST_LOCATION_KEY, false)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerViewPaired.layoutManager = LinearLayoutManager(this)
recyclerView.isNestedScrollingEnabled = false
recyclerViewPaired.isNestedScrollingEnabled = false
findViewById<Button>(R.id.search_devices).setOnClickListener {
findDevices()
}
findViewById<Button>(R.id.make_visible).setOnClickListener {
makeVisible()
}
devicesAdapter = DevicesRecyclerViewAdapter(context = this, mDeviceList = mDeviceList)
recyclerView.adapter = devicesAdapter
devicesAdapter.setItemClickListener(this)
// Register for broadcasts when a device is discovered.
var filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(mReceiver, filter)
// Register for broadcasts when discovery has finished
filter = IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
this.registerReceiver(mReceiver, filter)
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter()
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = BluetoothChatService(this, mHandler)
if (mBtAdapter == null)
showAlertAndExit()
else {
if (mBtAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
} else {
status.text = getString(R.string.not_connected)
}
// Get a set of currently paired devices
val pairedDevices = mBtAdapter?.bondedDevices
val mPairedDeviceList = arrayListOf<DeviceData>()
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices?.size ?: 0 > 0) {
// There are paired devices. Get the name and address of each paired device.
for (device in pairedDevices!!) {
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
mPairedDeviceList.add(DeviceData(deviceName,deviceHardwareAddress))
}
val devicesAdapter = DevicesRecyclerViewAdapter(context = this, mDeviceList = mPairedDeviceList)
recyclerViewPaired.adapter = devicesAdapter
devicesAdapter.setItemClickListener(this)
headerLabelPaired.visibility = View.VISIBLE
}
}
//showChatFragment()
}
private fun makeVisible() {
val discoverableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE)
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300)
startActivity(discoverableIntent)
}
private fun checkPermissions() {
if (alreadyAskedForPermission) {
// don't check again because the dialog is still open
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
val builder = AlertDialog.Builder(this)
builder.setTitle(getString(R.string.need_loc_access))
builder.setMessage(getString(R.string.please_grant_loc_access))
builder.setPositiveButton(android.R.string.ok, null)
builder.setOnDismissListener {
// the dialog will be opened so we have to save that
alreadyAskedForPermission = true
requestPermissions(arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
), PERMISSION_REQUEST_LOCATION)
}
builder.show()
} else {
startDiscovery()
}
} else {
startDiscovery()
alreadyAskedForPermission = true
}
}
private fun showAlertAndExit() {
AlertDialog.Builder(this)
.setTitle(getString(R.string.not_compatible))
.setMessage(getString(R.string.no_support))
.setPositiveButton("Exit", { _, _ -> System.exit(0) })
.show()
}
private fun findDevices() {
checkPermissions()
}
private fun startDiscovery() {
headerLabelContainer.visibility = View.VISIBLE
progressBar.visibility = View.VISIBLE
headerLabel.text = getString(R.string.searching)
mDeviceList.clear()
// If we're already discovering, stop it
if (mBtAdapter?.isDiscovering ?: false)
mBtAdapter?.cancelDiscovery()
// Request discover from BluetoothAdapter
mBtAdapter?.startDiscovery()
}
// Create a BroadcastReceiver for ACTION_FOUND.
private val mReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (BluetoothDevice.ACTION_FOUND == action) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
val deviceData = DeviceData(deviceName, deviceHardwareAddress)
mDeviceList.add(deviceData)
val setList = HashSet<DeviceData>(mDeviceList)
mDeviceList.clear()
mDeviceList.addAll(setList)
devicesAdapter.notifyDataSetChanged()
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
progressBar.visibility = View.INVISIBLE
headerLabel.text = getString(R.string.found)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
progressBar.visibility = View.INVISIBLE
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
//Bluetooth is now connected.
status.text = getString(R.string.not_connected)
// Get a set of currently paired devices
val pairedDevices = mBtAdapter?.bondedDevices
val mPairedDeviceList = arrayListOf<DeviceData>()
mPairedDeviceList.clear()
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices?.size ?: 0 > 0) {
// There are paired devices. Get the name and address of each paired device.
for (device in pairedDevices!!) {
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
mPairedDeviceList.add(DeviceData(deviceName,deviceHardwareAddress))
}
val devicesAdapter = DevicesRecyclerViewAdapter(context = this, mDeviceList = mPairedDeviceList)
recyclerViewPaired.adapter = devicesAdapter
devicesAdapter.setItemClickListener(this)
headerLabelPaired.visibility = View.VISIBLE
}
}
//label.setText("Bluetooth is now enabled.")
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(PERMISSION_REQUEST_LOCATION_KEY, alreadyAskedForPermission)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
grantResults: IntArray) {
when (requestCode) {
PERMISSION_REQUEST_LOCATION -> {
// the request returned a result so the dialog is closed
alreadyAskedForPermission = false
if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//Log.d(TAG, "Coarse and fine location permissions granted")
startDiscovery()
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val builder = AlertDialog.Builder(this)
builder.setTitle(getString(R.string.fun_limted))
builder.setMessage(getString(R.string.since_perm_not_granted))
builder.setPositiveButton(android.R.string.ok, null)
builder.show()
}
}
}
}
}
override fun itemClicked(deviceData: DeviceData) {
connectDevice(deviceData)
}
private fun connectDevice(deviceData: DeviceData) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter?.cancelDiscovery()
val deviceAddress = deviceData.deviceHardwareAddress
val device = mBtAdapter?.getRemoteDevice(deviceAddress)
status.text = getString(R.string.connecting)
connectionDot.setImageDrawable(getDrawable(R.drawable.ic_circle_connecting))
// Attempt to connect to the device
mChatService?.connect(device, true)
}
override fun onResume() {
super.onResume()
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService?.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService?.start()
}
}
if(connected)
showChatFragment()
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(mReceiver)
}
/**
* The Handler that gets information back from the BluetoothChatService
*/
private val mHandler = @SuppressLint("HandlerLeak")
object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
Constants.MESSAGE_STATE_CHANGE -> {
when (msg.arg1) {
BluetoothChatService.STATE_CONNECTED -> {
status.text = getString(R.string.connected_to) + " "+ mConnectedDeviceName
connectionDot.setImageDrawable(getDrawable(R.drawable.ic_circle_connected))
Snackbar.make(findViewById(R.id.mainScreen),"Connected to " + mConnectedDeviceName,Snackbar.LENGTH_SHORT).show()
//mConversationArrayAdapter.clear()
connected = true
}
BluetoothChatService.STATE_CONNECTING -> {
status.text = getString(R.string.connecting)
connectionDot.setImageDrawable(getDrawable(R.drawable.ic_circle_connecting))
connected = false
}
BluetoothChatService.STATE_LISTEN, BluetoothChatService.STATE_NONE -> {
status.text = getString(R.string.not_connected)
connectionDot.setImageDrawable(getDrawable(R.drawable.ic_circle_red))
Snackbar.make(findViewById(R.id.mainScreen),getString(R.string.not_connected),Snackbar.LENGTH_SHORT).show()
connected = false
}
}
}
Constants.MESSAGE_WRITE -> {
val writeBuf = msg.obj as ByteArray
// construct a string from the buffer
val writeMessage = String(writeBuf)
//Toast.makeText(this@MainActivity,"Me: $writeMessage",Toast.LENGTH_SHORT).show()
//mConversationArrayAdapter.add("Me: " + writeMessage)
val milliSecondsTime = System.currentTimeMillis()
chatFragment.communicate(com.webianks.bluechat.Message(writeMessage,milliSecondsTime,Constants.MESSAGE_TYPE_SENT))
}
Constants.MESSAGE_READ -> {
val readBuf = msg.obj as ByteArray
// construct a string from the valid bytes in the buffer
val readMessage = String(readBuf, 0, msg.arg1)
val milliSecondsTime = System.currentTimeMillis()
//Toast.makeText(this@MainActivity,"$mConnectedDeviceName : $readMessage",Toast.LENGTH_SHORT).show()
//mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage)
chatFragment.communicate(com.webianks.bluechat.Message(readMessage,milliSecondsTime,Constants.MESSAGE_TYPE_RECEIVED))
}
Constants.MESSAGE_DEVICE_NAME -> {
// save the connected device's name
mConnectedDeviceName = msg.data.getString(Constants.DEVICE_NAME)
status.text = getString(R.string.connected_to) + " " +mConnectedDeviceName
connectionDot.setImageDrawable(getDrawable(R.drawable.ic_circle_connected))
Snackbar.make(findViewById(R.id.mainScreen),"Connected to " + mConnectedDeviceName,Snackbar.LENGTH_SHORT).show()
connected = true
showChatFragment()
}
Constants.MESSAGE_TOAST -> {
status.text = getString(R.string.not_connected)
connectionDot.setImageDrawable(getDrawable(R.drawable.ic_circle_red))
Snackbar.make(findViewById(R.id.mainScreen),msg.data.getString(Constants.TOAST),Snackbar.LENGTH_SHORT).show()
connected = false
}
}
}
}
private fun sendMessage(message: String) {
// Check that we're actually connected before trying anything
if (mChatService?.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return
}
// Check that there's actually something to send
if (message.isNotEmpty()) {
// Get the message bytes and tell the BluetoothChatService to write
val send = message.toByteArray()
mChatService?.write(send)
// Reset out string buffer to zero and clear the edit text field
//mOutStringBuffer.setLength(0)
//mOutEditText.setText(mOutStringBuffer)
}
}
private fun showChatFragment() {
if(!isFinishing) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
chatFragment = ChatFragment.newInstance()
chatFragment.setCommunicationListener(this)
fragmentTransaction.replace(R.id.mainScreen, chatFragment, "ChatFragment")
fragmentTransaction.addToBackStack("ChatFragment")
fragmentTransaction.commit()
}
}
override fun onCommunication(message: String) {
sendMessage(message)
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount == 0)
super.onBackPressed()
else
supportFragmentManager.popBackStack()
}
}
| mit | 61baf24c076f367534433ff20829bfe2 | 39.297694 | 140 | 0.624493 | 5.403992 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/TriggerTaskerTaskActionType.kt | 1 | 726 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class TriggerTaskerTaskActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = TriggerTaskerTaskAction(
taskName = actionDTO.getString(0) ?: "",
variableValuesJson = actionDTO.getString(1) ?: "{}",
)
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
parameters = 2,
)
companion object {
private const val TYPE = "trigger_tasker_task"
private const val FUNCTION_NAME = "triggerTaskerTask"
}
}
| mit | d9b36c0623587f375916217f02d711ae | 28.04 | 73 | 0.699725 | 4.196532 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/KtMain.kt | 1 | 670 | package glorantq.ramszesz
import ch.qos.logback.classic.Level
import com.cloudinary.Cloudinary
import org.opencv.core.Core
import org.slf4j.Logger
import org.slf4j.LoggerFactory
val inviteUrl: String = "https://discordapp.com/oauth2/authorize?client_id=338377690002489344&permissions=356936710&scope=bot"
val discordToken: String = System.getenv("DISCORD_TOKEN")
val cloudinary: Cloudinary = Cloudinary()
val osuKey: String = System.getenv("OSU_TOKEN")
fun main(args: Array<String>) {
(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as ch.qos.logback.classic.Logger).level = Level.DEBUG
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Ramszesz.instance
} | gpl-3.0 | 44cef9d25f382ad0698dd45478f85c5a | 34.315789 | 126 | 0.791045 | 3.366834 | false | false | false | false |
monarezio/PathFinder | app/src/main/java/net/zdendukmonarezio/pathfinder/domain/game/model/utils/Coordinate.kt | 1 | 881 | package net.zdendukmonarezio.pathfinder.domain.game.model.utils
/**
* Created by monarezio on 23/04/2017.
*/
data class Coordinate(val x: Int, val y: Int) {
fun north(): Coordinate = Coordinate(x, y - 1)
fun south(): Coordinate = Coordinate(x, y + 1)
fun east(): Coordinate = Coordinate(x + 1, y)
fun west(): Coordinate = Coordinate(x - 1, y)
fun getNextCoordinate(direction: Direction): Coordinate {
if(direction == Direction.NORTH)
return north();
else if(direction == Direction.EAST)
return east();
else if(direction == Direction.SOUTH)
return south();
else
return west();
}
fun getNextCoordinates(directions: Set<Direction>): Set<Coordinate>
= directions.map { i -> getNextCoordinate(i) }.toSet()
fun isEmpty(): Boolean = x == -1 || y == - 1
} | apache-2.0 | 02b8cb935e4e428fbe8c0c8db373bff6 | 27.451613 | 71 | 0.600454 | 4.078704 | false | false | false | false |
dmgburg/AlfaPlugin | src/main/kotlin/com/dmgburg/alfa/stubs/AttributeStubElementType.kt | 1 | 2858 | package com.dmgburg.alfa.stubs
import com.dmgburg.alfa.AlfaLanguage
import com.dmgburg.alfa.psi.AlfaAttributeDeclaration
import com.dmgburg.alfa.psi.AlfaTypes
import com.dmgburg.alfa.psi.impl.AlfaAttributeDeclarationImpl
import com.intellij.lang.LighterAST
import com.intellij.lang.LighterASTNode
import com.intellij.lang.LighterASTTokenNode
import com.intellij.openapi.project.Project
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.*
import com.intellij.util.CharTable
class AlfaAttributeStubElementType(debugName: String) : ILightStubElementType<AttributeDeclarationStub, AlfaAttributeDeclaration>(debugName, AlfaLanguage.INSTANCE) {
override fun createPsi(stub: AttributeDeclarationStub): AlfaAttributeDeclaration {
return AlfaAttributeDeclarationImpl(stub, this)
}
override fun serialize(stub: AttributeDeclarationStub, dataStream: StubOutputStream) {
dataStream.writeName(stub.name)
}
override fun createStub(psi: AlfaAttributeDeclaration, parentStub: StubElement<*>?): AttributeDeclarationStub {
return AttributeDeclarationStub(parentStub, psi.name)
}
override fun createStub(tree: LighterAST, node: LighterASTNode?, parentStub: StubElement<*>?): AttributeDeclarationStub {
val keyNode = LightTreeUtil.firstChildOfType(tree, node, AlfaTypes.ATTRIBUTE_NAME) ?: throw IllegalStateException("Attribute without name!")
val key = intern(tree.getCharTable(), keyNode)
return AttributeDeclarationStub(parentStub, key)
}
override fun indexStub(stub: AttributeDeclarationStub, sink: IndexSink) {
sink.occurrence(AttributeKeyIndex.key, stub.name);
}
override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): AttributeDeclarationStub {
val ref = dataStream.readName()
return AttributeDeclarationStub(parentStub, ref!!.string)
}
override fun getExternalId(): String {
return "alfa.attribute"
}
fun intern(table: CharTable, node: LighterASTNode): String {
assert(node is LighterASTTokenNode) { node }
return table.intern((node as LighterASTTokenNode).text).toString()
}
}
object AttributeKeyIndex : StringStubIndexExtension<AlfaAttributeDeclaration>() {
var KEY : StubIndexKey<String, AlfaAttributeDeclaration>? = null
init{
if(KEY == null){
KEY = StubIndexKey.createIndexKey("alfa.attribute.index")
}
}
override fun getKey(): StubIndexKey<String, AlfaAttributeDeclaration> {
return KEY!!
}
override fun get(key: String, project: Project, scope: GlobalSearchScope): Collection<AlfaAttributeDeclaration> {
return StubIndex.getElements(getKey(), key, project, scope, AlfaAttributeDeclaration::class.java)
}
} | apache-2.0 | 20bfee0876c8ed8f4164155b75337dcb | 39.842857 | 165 | 0.752274 | 4.550955 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKPermanentStoreItemTable.kt | 1 | 4769 | /*
* Copyright 2019 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.store.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.store.bukkit.RPKStoresBukkit
import com.rpkit.store.bukkit.storeitem.RPKPermanentStoreItem
import com.rpkit.store.bukkit.storeitem.RPKPermanentStoreItemImpl
import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_PERMANENT_STORE_ITEM
import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_STORE_ITEM
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
class RPKPermanentStoreItemTable(database: Database, private val plugin: RPKStoresBukkit): Table<RPKPermanentStoreItem>(database, RPKPermanentStoreItem::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_permanent_store_item.id.enabled")) {
database.cacheManager.createCache("rpkit-stores-bukkit.rpkit_permanent_store_item.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKPermanentStoreItem::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_permanent_store_item.id.size"))).build())
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_PERMANENT_STORE_ITEM)
.column(RPKIT_PERMANENT_STORE_ITEM.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID, SQLDataType.INTEGER)
.constraints(
constraint("pk_rpkit_permanent_store_item").primaryKey(RPKIT_PERMANENT_STORE_ITEM.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.6.0")
}
}
override fun insert(entity: RPKPermanentStoreItem): Int {
val id = database.getTable(RPKStoreItemTable::class).insert(entity)
database.create
.insertInto(
RPKIT_PERMANENT_STORE_ITEM,
RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID
)
.values(
id
)
.execute()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKPermanentStoreItem) {
database.getTable(RPKStoreItemTable::class).update(entity)
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKPermanentStoreItem? {
if (cache?.containsKey(id) == true) {
return cache[id]
} else {
val result = database.create
.select(
RPKIT_STORE_ITEM.PLUGIN,
RPKIT_STORE_ITEM.IDENTIFIER,
RPKIT_STORE_ITEM.DESCRIPTION,
RPKIT_STORE_ITEM.COST
)
.from(
RPKIT_STORE_ITEM,
RPKIT_PERMANENT_STORE_ITEM
)
.where(RPKIT_STORE_ITEM.ID.eq(id))
.and(RPKIT_STORE_ITEM.ID.eq(RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID))
.fetchOne() ?: return null
val storeItem = RPKPermanentStoreItemImpl(
id,
result[RPKIT_STORE_ITEM.PLUGIN],
result[RPKIT_STORE_ITEM.IDENTIFIER],
result[RPKIT_STORE_ITEM.DESCRIPTION],
result[RPKIT_STORE_ITEM.COST]
)
cache?.put(id, storeItem)
return storeItem
}
}
override fun delete(entity: RPKPermanentStoreItem) {
database.getTable(RPKStoreItemTable::class).delete(entity)
database.create
.deleteFrom(RPKIT_PERMANENT_STORE_ITEM)
.where(RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | apache-2.0 | fe331f5b906d364e8b961145693a41da | 38.75 | 161 | 0.615852 | 4.648148 | false | true | false | false |
diareuse/mCache | app/src/main/java/wiki/depasquale/mcachepreview/Github.kt | 1 | 2278 | package wiki.depasquale.mcachepreview
import android.annotation.SuppressLint
import android.util.Log
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import wiki.depasquale.mcache.Cache
import java.util.concurrent.TimeUnit
/**
* diareuse on 26.03.2017
*/
object Github {
private var retrofit: Retrofit? = null
private var service: Service? = null
@SuppressLint("LogConditional")
fun user(username: String): Observable<User> {
return Cache.obtain(User::class.java)
.ofIndex(username)
.build()
.getLaterConcat(
getRetrofit()
.user(username)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
)
}
private fun getRetrofit(): Service {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.client(client())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
if (service == null) {
service = retrofit!!.create(Service::class.java)
}
return service!!
}
private fun client(): OkHttpClient {
val client = OkHttpClient.Builder()
client.connectTimeout(200, TimeUnit.SECONDS)
client.readTimeout(200, TimeUnit.SECONDS)
client.interceptors().add(Interceptor { chain ->
val request = chain.request()
val response: Response? = chain.proceed(request)
Log.i("ServiceInfo", response?.request()?.url()?.url().toString())
response
})
return client.build()
}
private interface Service {
@GET("/users/{user}")
fun user(@Path("user") user: String): Observable<User>
}
}
| apache-2.0 | 0a2ad126f1132c439fd5be5c93c31f07 | 29.373333 | 78 | 0.633889 | 4.735967 | false | false | false | false |
jmiecz/YelpBusinessExample | app/src/main/java/net/mieczkowski/yelpbusinessexample/controllers/LocationController.kt | 1 | 2150 | package net.mieczkowski.yelpbusinessexample.controllers
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.view.View
import com.bluelinelabs.conductor.RouterTransaction
import kotlinx.android.synthetic.main.controller_location.view.*
import net.mieczkowski.yelpbusinessexample.R
import net.mieczkowski.yelpbusinessexample.controllers.base.BaseController
import net.mieczkowski.yelpbusinessexample.controllers.search.SearchController
/**
* Created by Josh Mieczkowski on 10/21/2017.
*/
class LocationController : BaseController() {
private val REQUEST_CODE = 938543
override fun getLayoutID(): Int = R.layout.controller_location
override fun onViewBound(view: View, savedViewState: Bundle?) {
setTitle(resources?.getString(R.string.location_permission))
requestForLocation()
view.btnLocation.setOnClickListener {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity!!, Manifest.permission.ACCESS_COARSE_LOCATION)) {
requestForLocation()
} else {
openPermissionPage()
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_CODE -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
router.setRoot(RouterTransaction.with(SearchController()))
}
}
}
private fun requestForLocation() {
requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), REQUEST_CODE)
}
private fun openPermissionPage() {
val intent = Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", activity?.packageName, null)
}
startActivity(intent)
}
}
| apache-2.0 | 7eebeae30675990e7649083907c96e32 | 33.677419 | 126 | 0.71907 | 5.070755 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/MapDetailFragment.kt | 1 | 5713 | package org.eurofurence.connavigator.ui.fragments
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.github.chrisbanes.photoview.PhotoView
import io.reactivex.disposables.Disposables
import io.swagger.client.model.MapEntryRecord
import io.swagger.client.model.MapRecord
import nl.komponents.kovenant.ui.failUi
import nl.komponents.kovenant.ui.successUi
import org.eurofurence.connavigator.R
import org.eurofurence.connavigator.database.HasDb
import org.eurofurence.connavigator.database.findLinkFragment
import org.eurofurence.connavigator.database.lazyLocateDb
import org.eurofurence.connavigator.services.ImageService
import org.eurofurence.connavigator.util.extensions.photoView
import org.eurofurence.connavigator.util.v2.compatAppearance
import org.eurofurence.connavigator.util.v2.plus
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.px2dip
import java.util.*
class MapDetailFragment : DisposingFragment(), HasDb, AnkoLogger {
override val db by lazyLocateDb()
val ui by lazy { MapDetailUi() }
val id get() = arguments?.getString("id") ?: ""
val showTitle get() = arguments!!.getBoolean("showTitle")
private var linkFound = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
UI { ui.createView(this) }.view
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
db.subscribe {
ui.title.visibility = if (showTitle) View.VISIBLE else View.GONE
findLinkFragment()
}
.collectOnDestroyView()
}
fun withArguments(id: UUID?, showTitle: Boolean = false) = apply {
arguments = Bundle().apply {
id?.let { putString("id", it.toString()) }
putBoolean("showTitle", showTitle)
}
}
private fun findLinkFragment() {
info { "Finding map link in mapEntries. ID: $id" }
val entryMap = db.findLinkFragment(id)
val map = entryMap["map"] as MapRecord?
val entry = entryMap["entry"] as MapEntryRecord?
if (map == null) {
info { "No maps or deviations. Hiding location and availability" }
ui.layout.visibility = View.GONE
return
}
// Setup map
if (map != null && entry != null) {
info { "Found maps and entries, ${map.description} at (${entry.x}, ${entry.y})" }
linkFound = true
val mapImage = db.toImage(map)!!
val radius = 300
val circle = entry.tapRadius
val x = maxOf(0, (entry.x ?: 0) - radius)
val y = maxOf(0, (entry.y ?: 0) - radius)
val w = minOf((mapImage.width ?: 0) - x - 1, radius + radius)
val h = minOf((mapImage.height ?: 0) - y - 1, radius + radius)
val ox = (entry.x ?: 0) - x
val oy = (entry.y ?: 0) - y
ImageService.preload(mapImage) successUi {
if (it == null || activity == null)
ui.layout.visibility = View.GONE
else {
try {
val bitmap = Bitmap.createBitmap(it, x, y, w, h)
Canvas(bitmap).apply {
drawCircle(ox.toFloat(), oy.toFloat(), (circle
?: 0).toFloat(), Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = px2dip(5)
})
}
ui.map.image = BitmapDrawable(resources, bitmap)
ui.layout.visibility = View.VISIBLE
} catch (ex: IllegalArgumentException) {
ui.layout.visibility = View.GONE
}
}
} failUi {
ui.layout.visibility = View.GONE
}
} else {
warn { "No map or entry found!" }
ui.layout.visibility = View.GONE
}
}
}
class MapDetailUi : AnkoComponent<Fragment> {
lateinit var map: PhotoView
lateinit var layout: LinearLayout
lateinit var title: TextView
override fun createView(ui: AnkoContext<Fragment>) = with(ui) {
relativeLayout {
lparams(matchParent, wrapContent)
layout = verticalLayout {
backgroundResource = R.color.lightBackground
title = textView {
textResource = R.string.misc_location
compatAppearance = android.R.style.TextAppearance_Small
padding = dip(20)
}
map = photoView {
backgroundResource = R.color.darkBackground
minimumScale = 1F
mediumScale = 2.5F
maximumScale = 5F
scaleType = ImageView.ScaleType.CENTER_INSIDE
imageResource = R.drawable.placeholder_event
}.lparams(matchParent, wrapContent)
}.lparams(matchParent, wrapContent) {
topMargin = dip(10)
}
}
}
} | mit | db425c03163181e3c1d4c95e723470a5 | 36.103896 | 109 | 0.591108 | 4.698191 | false | false | false | false |
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Update.kt | 1 | 5450 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.lists
import jp.nephy.penicillin.core.request.action.EmptyApiAction
import jp.nephy.penicillin.core.request.formBody
import jp.nephy.penicillin.core.session.post
import jp.nephy.penicillin.endpoints.Lists
import jp.nephy.penicillin.endpoints.Option
/**
* Updates the specified list. The authenticated user must own the list to be able to update it.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update)
*
* @param listId The numerical id of the list.
* @param name The name for the list.
* @param mode Whether your list is public or private. Values can be public or private . If no mode is specified the list will be public.
* @param description The description to give the list.
* @param options Optional. Custom parameters of this request.
* @receiver [Lists] endpoint instance.
* @return [EmptyApiAction].
*/
private fun Lists.update(
listId: Long,
name: String? = null,
mode: ListVisibilityMode = ListVisibilityMode.Default,
description: String? = null,
vararg options: Option
) = update(listId, null, null, null, name, mode, description, *options)
/**
* Updates the specified list. The authenticated user must own the list to be able to update it.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update)
*
* @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters.
* @param ownerScreenName The screen name of the user who owns the list being requested by a slug.
* @param name The name for the list.
* @param mode Whether your list is public or private. Values can be public or private . If no mode is specified the list will be public.
* @param description The description to give the list.
* @param options Optional. Custom parameters of this request.
* @receiver [Lists] endpoint instance.
* @return [EmptyApiAction].
*/
fun Lists.updateByOwnerScreenName(
slug: String,
ownerScreenName: String,
name: String? = null,
mode: ListVisibilityMode = ListVisibilityMode.Default,
description: String? = null,
vararg options: Option
) = update(null, slug, ownerScreenName, null, name, mode, description, *options)
/**
* Updates the specified list. The authenticated user must own the list to be able to update it.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update)
*
* @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters.
* @param ownerId The user ID of the user who owns the list being requested by a slug.
* @param name The name for the list.
* @param mode Whether your list is public or private. Values can be public or private . If no mode is specified the list will be public.
* @param description The description to give the list.
* @param options Optional. Custom parameters of this request.
* @receiver [Lists] endpoint instance.
* @return [EmptyApiAction].
*/
fun Lists.updateByOwnerId(
slug: String,
ownerId: Long,
name: String? = null,
mode: ListVisibilityMode = ListVisibilityMode.Default,
description: String? = null,
vararg options: Option
) = update(null, slug, null, ownerId, name, mode, description, *options)
private fun Lists.update(
listId: Long? = null,
slug: String? = null,
ownerScreenName: String? = null,
ownerId: Long? = null,
name: String? = null,
mode: ListVisibilityMode = ListVisibilityMode.Default,
description: String? = null,
vararg options: Option
) = client.session.post("/1.1/lists/update.json") {
formBody(
"list_id" to listId,
"slug" to slug,
"owner_screen_name" to ownerScreenName,
"owner_id" to ownerId,
"name" to name,
"mode" to mode,
"description" to description,
*options
)
}.empty()
| mit | 5fb31e31e3b0033bdac7eb78339bce12 | 43.672131 | 208 | 0.731743 | 4.025111 | false | false | false | false |
rharter/windy-city-devcon-android | core/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/sessiondetail/SessionDetailPresenter.kt | 1 | 1333 | package com.gdgchicagowest.windycitydevcon.features.sessiondetail
import com.gdgchicagowest.windycitydevcon.data.SessionProvider
import com.gdgchicagowest.windycitydevcon.data.SpeakerProvider
import com.gdgchicagowest.windycitydevcon.model.Session
import com.gdgchicagowest.windycitydevcon.model.Speaker
class SessionDetailPresenter(private val sessionProvider: SessionProvider, private val speakerProvider: SpeakerProvider) : SessionDetailMvp.Presenter {
private var view: SessionDetailMvp.View? = null
private var session: Session? = null
private var speakers: MutableSet<Speaker> = mutableSetOf()
override fun onAttach(view: SessionDetailMvp.View) {
this.view = view
}
override fun onDetach() {
this.view = null
}
override fun setSessionId(sessionId: String) {
sessionProvider.addSessionListener(sessionId, { session: Session? ->
if (session != null) {
view?.showSessionDetail(session)
session.speakers?.map {
speakerProvider.addSpeakerListener(it, onSpeakerReceived)
}
}
})
}
private val onSpeakerReceived = { speaker: Speaker? ->
if (speaker != null) {
speakers.add(speaker)
view?.showSpeakerInfo(speakers)
}
}
} | apache-2.0 | a3ab4cbc7ce7dc9cd46d3804408394de | 32.35 | 151 | 0.68192 | 4.918819 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-drinks-bukkit/src/main/kotlin/com/rpkit/drinks/bukkit/listener/PlayerItemConsumeListener.kt | 1 | 2266 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.drinks.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.drink.bukkit.drink.RPKDrinkService
import com.rpkit.drink.bukkit.event.drink.RPKBukkitDrinkEvent
import com.rpkit.drinks.bukkit.RPKDrinksBukkit
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerItemConsumeEvent
class PlayerItemConsumeListener(private val plugin: RPKDrinksBukkit) : Listener {
@EventHandler
fun onPlayerItemConsume(event: PlayerItemConsumeEvent) {
val drinkService = Services[RPKDrinkService::class.java] ?: return
val drink = drinkService.getDrink(event.item) ?: return
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return
val drinkEvent = RPKBukkitDrinkEvent(character, drink, event.isAsynchronous)
plugin.server.pluginManager.callEvent(drinkEvent)
if (drinkEvent.isCancelled) {
event.isCancelled = true
return
}
drinkService.getDrunkenness(drinkEvent.character).thenAccept { characterDrunkenness ->
drinkService.setDrunkenness(drinkEvent.character, characterDrunkenness + drinkEvent.drink.drunkenness)
}
}
} | apache-2.0 | 7df69aa8689327054fcb22a8607fac37 | 43.45098 | 114 | 0.763901 | 4.605691 | false | false | false | false |
pchrysa/Memento-Calendar | android_mobile/src/main/java/com/alexstyl/specialdates/ui/base/ThemedMementoActivity.kt | 1 | 1827 | package com.alexstyl.specialdates.ui.base
import android.content.res.ColorStateList
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.annotation.MenuRes
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v7.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.Menu
import com.alexstyl.specialdates.theming.AttributeExtractor
import com.alexstyl.specialdates.theming.MementoTheme
import com.alexstyl.specialdates.theming.Themer
open class ThemedMementoActivity : MementoActivity() {
private var themer: Themer? = null
private var attributeExtractor: AttributeExtractor? = null
override fun onCreate(savedInstanceState: Bundle?) {
themer = Themer.get(this)
attributeExtractor = AttributeExtractor()
themer!!.initialiseActivity(this)
super.onCreate(savedInstanceState)
}
fun setContentView(@LayoutRes layoutResID: Int, theme: MementoTheme) {
val wrapper = ContextThemeWrapper(this, theme.androidTheme())
val inflate = LayoutInflater.from(wrapper).inflate(layoutResID, null, false)
setContentView(inflate)
}
fun reapplyTheme() {
val intent = intent
startActivity(intent)
finish()
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}
protected fun inflateThemedMenu(@MenuRes menuResId: Int, menu: Menu) {
menuInflater.inflate(menuResId, menu)
for (i in 0..menu.size() - 1) {
val item = menu.getItem(i)
val wrappedDrawable = DrawableCompat.wrap(item.icon)
val color = attributeExtractor!!.extractToolbarIconColors(this)
DrawableCompat.setTintList(wrappedDrawable, ColorStateList.valueOf(color))
}
}
}
| mit | b739f9933253031522536dd93197d5d1 | 35.54 | 86 | 0.730706 | 4.55611 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/sound/SoundManager.kt | 1 | 2621 | /*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.sound
import org.lwjgl.openal.AL
import org.lwjgl.openal.ALC
import org.lwjgl.openal.ALC10
import org.lwjgl.openal.ALCCapabilities
import org.lwjgl.system.MemoryUtil.NULL
import java.nio.ByteBuffer
import java.nio.IntBuffer
object SoundManager {
private var _device: Long = 0L
private var _capabilities: ALCCapabilities? = null
private var _context: Long = 0L
val device: Long
get() = _device
val capabilities: ALCCapabilities
get() = _capabilities!!
val context: Long
get() = _context
private val MAX_SOUNDS = 10
private val sources = mutableListOf<SoundSource>()
fun initialise() {
if (_device != 0L) {
System.err.println("WARNING. SoundManager has already been initialised.")
return
}
_device = ALC10.alcOpenDevice(null as ByteBuffer?)
if (_device == NULL) {
throw IllegalStateException("Failed to open the default OpenAL device.")
}
_capabilities = ALC.createCapabilities(_device)
_context = ALC10.alcCreateContext(_device, null as IntBuffer?)
if (_context == NULL) {
throw IllegalStateException("Failed to create OpenAL context.")
}
ALC10.alcMakeContextCurrent(_context)
AL.createCapabilities(_capabilities)
for (i in 0..MAX_SOUNDS) {
sources.add(SoundSource())
}
}
fun ensureInitialised() {
if (_device == 0L) {
initialise()
}
}
private fun findFreeSource(): SoundSource? = sources.firstOrNull { !it.isPlaying() }
fun play(sound: Sound) {
findFreeSource()?.play(sound)
}
fun cleanUp() {
if (_context != 0L) {
ALC10.alcDestroyContext(_context)
_context = 0L
}
if (_device != 0L) {
ALC10.alcCloseDevice(_device)
_device = 0L
}
}
}
| gpl-3.0 | 81c059062f99f6dea98c94f525d881d8 | 25.744898 | 88 | 0.647081 | 4.25487 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/FixedSizeCardLayout.kt | 1 | 1171 | package cn.yiiguxing.plugin.translate.ui
import java.awt.CardLayout
import java.awt.Component
import java.awt.Container
import java.awt.Dimension
/**
* FixedSizeCardLayout
*/
class FixedSizeCardLayout : CardLayout() {
override fun preferredLayoutSize(parent: Container): Dimension = parent.getSize { preferredSize }
override fun minimumLayoutSize(parent: Container): Dimension = parent.getSize { minimumSize }
override fun maximumLayoutSize(parent: Container): Dimension = parent.getSize { maximumSize }
private inline fun Container.getSize(targetSize: Component.() -> Dimension): Dimension {
synchronized(treeLock) {
var w = 0
var h = 0
for (i in 0 until componentCount) {
val comp = getComponent(i)
if (comp.isVisible) {
comp.targetSize().let { (tw, th) ->
w = tw
h = th
}
break
}
}
return with(insets) {
Dimension(left + right + w + hgap * 2, top + bottom + h + vgap * 2)
}
}
}
} | mit | 78994bb5e118e4c354f49d676e50be29 | 29.051282 | 101 | 0.560205 | 4.940928 | false | false | false | false |
lunabox/leetcode | kotlin/problems/src/Main.kt | 1 | 4022 | import case.print
import data.structure.BrowserHistory
import solution.*
fun main() {
val linkNode = LinkProblems()
// val t = solution.TreeProblems()
// val tree = t.createTree(arrayListOf(1, 2, 3, null, 4, null, 5))
// t.levelOrder(tree).forEach {
// printArray(it.toIntArray())
// }
// println(t.isCousins(tree, 4, 5))
val g = GraphProblems()
// println(g.checkOverlap(1, 1, 1, 1, -3, 2, -1))
val sp = StringProblems()
// println(sp.buddyStrings("ab", "ab"))
// sp.restoreIpAddresses("0279245587303").forEach {
// println(it)
// }
// println(sp.longestDiverseString(4, 42, 11))
// println(sp.countCharacters(arrayOf("cat", "bt", "hat", "tree"), "atach"))
// println(sp.nextGreatestLetter(charArrayOf('a', 'b'), 'z'))
// println(sp.rotateString("abcde", "cdeab"))
// sp.letterCombinations("22").forEach {
// println(it)
// }
// sp.generateParenthesis(4).forEach {
// println(it)
// }
// println(sp.letterCasePermutation("s"))
// println(sp.validPalindrome("abcaa"))
// sp.largeGroupPositions("abc").forEach {
// printArray(it.toIntArray())
// }
// println(sp.validIPAddress("1081:db8:85a3:01:-0:8A2E:0370:7334"))
// println(sp.reverseWords(""))
// println(sp.validIPAddress("00.0.0.0"))
val np = NumberProblems()
// np.maxSlidingWindow(intArrayOf(1, 3, -1, -3, 5, 3, 6, 7), 3).print()
// np.searchRange(intArrayOf(5, 7, 7, 7, 8, 8, 10), 7).print()
// println(np.multiply("123", "456"))
// println(np.numSteps("1"))
// println(np.myAtoi("20000000000000000000"))
// println(np.findErrorNums(intArrayOf(2, 2)).toList())
// np.selfDividingNumbers(1, 100).forEach {
// println(it)
// }
// println(np.subsets(intArrayOf(2, 4, 9)))
// NumberCase.loadIntArray().forEachCase { _, case ->
// println(np.findShortestSubArray(case))
// }
// println(np.findMaxAverage(intArrayOf(1, 12, -5, -6, 50, 3), 4))
// println(np.getHint("1123", "0111"))
// repeat(100) {
// print("$it ${Integer.toBinaryString(it)} ")
// println(np.hasAlternatingBits(it))
// }
// val arr = intArrayOf(1, 2, 3)
// val arr = intArrayOf(1, 5, 8, 4, 7, 6, 5, 3, 1)
// np.nextPermutation(arr)
// println(arr.toList())
// np.permute(arr).forEach {
// println(it)
// }
// val arr = intArrayOf(1, 5, 1)
// val arr = intArrayOf(1, 5, 8, 4, 7, 6, 5, 3, 1)
// np.nextPermutation(arr)
// println(arr.toList())
// var obj = SnapshotArray(5)
// obj.set(2, 15)
// var snap1 = obj.snap()
// var param_3 = obj.get(2, snap1)
// println(param_3)
//
// obj.set(2, 10)
// val snap2 = obj.snap()
// println(obj.get(2, snap2))
// var obj = RangeModule()
// obj.addRange(left, right)
// var param_2 = obj.queryRange(left, right)
// obj.removeRange(left, right)
// val simulatedProgram = solution.SimulatedProgram()
// println(simulatedProgram.judgeCircle("UDRL"))
val sim = SimulatedProgram()
// sim.findDiagonalOrder(arrayListOf(arrayListOf(1,2,3), arrayListOf(4,5,6), arrayListOf(7,8,9))).forEach { println(it) }
// println(sim.maxDistToClosest(intArrayOf(1, 0, 0, 0, 1, 0, 1)))
// NumberCase.randomIntArray(0, 10, 10, 5).forEachCase { i, ints ->
// println(sim.search(ints, ints[0]))
// }
// println(sim.coinChange(intArrayOf(2,6), 7))
val week = WeeklyContest()
println(week.modifyString("?a?ub???w?b"))
// println(week.getWinner(intArrayOf(2, 1, 3, 5, 4, 6, 7), 2))
// val dfs = DFSPrograms()
// println(dfs.canPartition(intArrayOf(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,100)))
}
fun printArray(array: IntArray) {
(array.indices).forEach {
print(array[it])
if (it == array.size - 1) {
println()
} else {
print(", ")
}
}
} | apache-2.0 | 6093562a00f59946137012e929da2b33 | 31.97541 | 244 | 0.585032 | 2.651285 | false | false | false | false |
alibaba/fastjson | src/test/java/com/alibaba/json/bvt/issue_3200/TestIssue3223.kt | 1 | 3461 | package com.alibaba.json.bvt.issue_3200;
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.parser.ParserConfig
import com.alibaba.fastjson.serializer.SerializerFeature
import org.junit.Assert
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
import kotlin.properties.Delegates
/**
* kotlin集合测试
* @author 佐井
* @since 2020-06-05 20:35
*/
class TestIssue3223 {
@Test
fun test() {
val cfg = ParserConfig.getGlobalInstance()
cfg.addAccept("com.")
cfg.addAccept("net.")
cfg.addAccept("java.")
cfg.addAccept("kotlin.")
cfg.addAccept("org.")
val n = NullableKotlin()
//nullable
n.nullableList = listOf("nullableList")
n.nullableMap = mapOf("nullableMap" to "nullableMap")
n.nullableSet = setOf("nullableSet")
//empty
n.emptyList = listOf("emptyList")
n.emptyMap = mapOf("emptyMap" to "emptyMap")
n.emptySet = setOf("emptySet")
//delegate
n.delegateList = listOf("delegateList")
n.delegateMap = mapOf("delegateMap" to "delegateMap")
n.delegateSet = setOf("delegateSet")
//basic
n.atomicInt = AtomicInteger(10)
n.longValue = 1
n.json = JSON.parseObject(JSON.toJSONString(mapOf("a" to "b")))
val raw = JSON.toJSONString(n, SerializerFeature.WriteClassName)
val d = JSON.parseObject(raw, NullableKotlin::class.java)
Assert.assertTrue(n == d)
}
}
class NullableKotlin {
//map
var nullableMap: Map<String, String>? = null
var emptyMap: Map<String, String> = emptyMap()
var delegateMap by Delegates.notNull<Map<String, String>>()
//set
var nullableSet: Set<String>? = null
var emptySet: Set<String> = emptySet()
var delegateSet by Delegates.notNull<Set<String>>()
//list
var nullableList: List<String>? = null
var emptyList: List<String> = emptyList()
var delegateList by Delegates.notNull<List<String>>()
//basic
var atomicInt: AtomicInteger? = null
var longValue: Long? = null
var json: JSONObject? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NullableKotlin
if (nullableMap != other.nullableMap) return false
if (emptyMap != other.emptyMap) return false
if (nullableSet != other.nullableSet) return false
if (emptySet != other.emptySet) return false
if (nullableList != other.nullableList) return false
if (emptyList != other.emptyList) return false
if (atomicInt?.get() != other.atomicInt?.get()) return false
if (longValue != other.longValue) return false
if (json != other.json) return false
return true
}
override fun hashCode(): Int {
var result = nullableMap?.hashCode() ?: 0
result = 31 * result + emptyMap.hashCode()
result = 31 * result + (nullableSet?.hashCode() ?: 0)
result = 31 * result + emptySet.hashCode()
result = 31 * result + (nullableList?.hashCode() ?: 0)
result = 31 * result + emptyList.hashCode()
result = 31 * result + (atomicInt?.hashCode() ?: 0)
result = 31 * result + (longValue?.hashCode() ?: 0)
result = 31 * result + (json?.hashCode() ?: 0)
return result
}
} | apache-2.0 | 8dbfca30d054cb616f9d66659a906f0b | 30.944444 | 72 | 0.632067 | 4.115752 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/discord/webhook/WebhookCommandUtils.kt | 1 | 15023 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.webhook
import dev.kord.common.entity.DiscordMessage
import dev.kord.common.entity.Snowflake
import dev.kord.common.entity.optional.Optional
import dev.kord.rest.json.request.EmbedRequest
import dev.kord.rest.json.request.WebhookEditMessageRequest
import dev.kord.rest.json.request.WebhookExecuteRequest
import dev.kord.rest.request.RestRequestException
import dev.kord.rest.service.ChannelService
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.putJsonArray
import net.perfectdreams.i18nhelper.core.keydata.StringI18nData
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.common.utils.URLUtils
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.declarations.WebhookCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.utils.DiscordResourceLimits
import net.perfectdreams.loritta.cinnamon.discord.utils.WebhookUtils
object WebhookCommandUtils {
suspend fun sendMessageViaWebhook(
context: ApplicationCommandContext,
webhookUrl: String,
requestBuilder: () -> (WebhookExecuteRequest)
) {
val matchResult = WebhookUtils.webhookRegex.find(webhookUrl) ?: context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.InvalidWebhookUrl
)
)
val webhookId = Snowflake(matchResult.groupValues[1].toULong())
val webhookToken = matchResult.groupValues[2]
// Can we workaround this by using horrible hacks?
// Yes we can!
val request = requestBuilder.invoke()
// Validations before sending the message
// Message Length
validateMessageLength(context, request.content)
// Avatar URL
validateURLAsHttpOrHttps(context, request.avatar.value, WebhookCommand.I18N_PREFIX.InvalidAvatarUrl)
// Embeds
validateEmbeds(context, request.embeds)
val sentMessage = try {
WebhookUtils.executeWebhook(
webhookId,
webhookToken,
true,
request = request
)
} catch (e: RestRequestException) {
if (e.status.code == 401) {
// The webhook doesn't exist!
context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.WebhookDoesNotExist))
}
// I don't know what happened so let's just leave!
throw e
}
// I think these are always present, but who knows
// The guild ID is always NOT present
val messageId = sentMessage?.id?.value
sendWebhookSuccessMessage(context, messageId?.toLong(), WebhookCommand.I18N_PREFIX.Send.Success)
}
suspend fun editMessageViaWebhook(
context: ApplicationCommandContext,
webhookUrl: String,
messageId: Long,
requestBuilder: () -> (WebhookEditMessageRequest)
) {
val matchResult = WebhookUtils.webhookRegex.find(webhookUrl) ?: context.failEphemerally(context.i18nContext.get(
WebhookCommand.I18N_PREFIX.InvalidWebhookUrl))
val webhookId = Snowflake(matchResult.groupValues[1].toULong())
val webhookToken = matchResult.groupValues[2]
// Can we workaround this by using horrible hacks?
// Yes we can!
val request = requestBuilder.invoke()
// Validations before sending the message
// Message Length
validateMessageLength(context, request.content)
// Embeds
validateEmbeds(context, request.embeds)
val sentMessage = try {
WebhookUtils.editWebhookMessage(
webhookId,
webhookToken,
Snowflake(messageId),
request = request
)
} catch (e: RestRequestException) {
if (e.status.code == 401) {
// The webhook doesn't exist!
context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.WebhookDoesNotExist))
} else if (e.status.code == 404) {
// The message doesn't exist or wasn't sent via this webhook!
context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.MessageDoesNotExistOrWasntSentByThisWebhook))
}
// I don't know what happened so let's just leave!
throw e
}
// The guild ID is always NOT present so don't bother trying to get it
sendWebhookSuccessMessage(context, messageId, WebhookCommand.I18N_PREFIX.Edit.Success)
}
val messageUrlRegex = Regex("/channels/([0-9]+)/([0-9]+)/([0-9]+)")
/**
* Cleans up the retrieved message, removing Loritta's "Message sent by" tag
*/
fun cleanUpRetrievedMessageContent(input: DiscordMessage): String {
var content = input.content
if (input.author.id == Snowflake(297153970613387264)) {
// Message sent by Loritta via "+say", clean up the message by automatically drop all lines starting with "Message sent by"
content.lines()
.filterNot {
it.startsWith("<:lori_coffee:727631176432484473> *Mensagem enviada por ") || it.startsWith("<:lori_coffee:727631176432484473> *Message sent by ")
}
.joinToString("\n")
.also { content = it }
}
return content
}
/**
* Gets a Message ID from the [input].
*
* * The input is parsed as a Long, if it fails...
* * The input is parsed as Message URL and the Message ID is extracted from the message, if it fails...
* * The command fails ephemerally
*/
fun getRawMessageIdOrFromURLOrFail(context: ApplicationCommandContext, input: String): Long {
return input.toLongOrNull() ?: messageUrlRegex.find(input)?.groupValues?.get(3)?.toLongOrNull() ?: context.failEphemerally("a")
}
/**
* Gets a message or, if it doesn't exists, fails ephemerally
*/
suspend fun getMessageOrFail(context: ApplicationCommandContext, service: ChannelService, channelId: Snowflake, messageId: Snowflake) = try {
service.getMessage(channelId, messageId)
} catch (e: RestRequestException) {
if (e.status.code == 404)
context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.MessageToBeRepostedDoesNotExist))
throw e
}
inline fun <reified T> decodeRequestFromString(context: ApplicationCommandContext, input: String): T {
try {
val parsedToJsonElement = Json.parseToJsonElement(input).jsonObject
val rebuiltJson = buildJsonObject {
for (entry in parsedToJsonElement.entries) {
if (entry.key == "embed") {
putJsonArray("embeds") {
add(entry.value)
}
} else {
put(entry.key, entry.value)
}
}
}
return Json.decodeFromJsonElement(rebuiltJson)
} catch (e: Exception) {
// Invalid message
if (!input.startsWith("{")) // Doesn't seem to be a valid JSON, maybe they would prefer using "/webhook send simple"?
context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.InvalidJsonMessageNoCurlyBraces(context.loritta.commandMentions.webhookSendSimple, context.loritta.commandMentions.webhookSendRepost)))
else
context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.InvalidJsonMessage))
}
}
private fun validateMessageLength(context: ApplicationCommandContext, optionalContent: Optional<String?>) {
optionalContent.value?.length?.let {
if (it > DiscordResourceLimits.Message.Length)
context.failEphemerally(context.i18nContext.get(
WebhookCommand.I18N_PREFIX.MessageTooBig(
DiscordResourceLimits.Message.Length
)))
}
}
private fun validateEmbeds(context: ApplicationCommandContext, optionalEmbeds: Optional<List<EmbedRequest>>) {
// Embeds
val embeds = optionalEmbeds.value
embeds?.size?.let {
if (it > DiscordResourceLimits.Message.EmbedsPerMessage)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.TooManyEmbeds(
DiscordResourceLimits.Message.EmbedsPerMessage
)
)
)
}
if (embeds != null) {
var totalEmbedLength = 0
for (embed in embeds) {
val titleLength = embed.title.value?.length
if (titleLength != null && titleLength > DiscordResourceLimits.Embed.Title)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedTitleTooBig(
DiscordResourceLimits.Embed.Title
)
)
)
totalEmbedLength += titleLength ?: 0
val descriptionLength = embed.description.value?.length
if (descriptionLength != null && descriptionLength > DiscordResourceLimits.Embed.Description)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedDescriptionTooBig(
DiscordResourceLimits.Embed.Description
)
)
)
totalEmbedLength += descriptionLength ?: 0
val fields = embed.fields.value
val fieldsSize = fields?.size
if (fieldsSize != null && fieldsSize > DiscordResourceLimits.Embed.FieldsPerEmbed)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.TooManyEmbedFields(
DiscordResourceLimits.Embed.FieldsPerEmbed
)
)
)
if (fields != null) {
for (field in fields) {
val fieldName = field.name
val fieldValue = field.value
val fieldNameLength = fieldName.length
val fieldValueLength = fieldValue.length
if (fieldNameLength > DiscordResourceLimits.Embed.Field.Name)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedFieldNameTooBig(
DiscordResourceLimits.Embed.Field.Name
)
)
)
if (fieldValueLength > DiscordResourceLimits.Embed.Field.Value)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedFieldValueTooBig(
DiscordResourceLimits.Embed.Field.Value
)
)
)
totalEmbedLength += fieldNameLength
totalEmbedLength += fieldValueLength
}
}
val footerLength = embed.footer.value?.text?.length
if (footerLength != null && footerLength > DiscordResourceLimits.Embed.Footer.Text)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedFooterTooBig(
DiscordResourceLimits.Embed.Footer.Text
)
)
)
totalEmbedLength += footerLength ?: 0
val authorLength = embed.author.value?.name?.value?.length
if (authorLength != null && authorLength > DiscordResourceLimits.Embed.Author.Name)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedAuthorNameTooBig(
DiscordResourceLimits.Embed.Author.Name
)
)
)
// Images
validateURLAsHttpOrHttps(context, embed.image.value?.url, WebhookCommand.I18N_PREFIX.InvalidEmbedImageUrl)
validateURLAsHttpOrHttps(context, embed.thumbnail.value?.url, WebhookCommand.I18N_PREFIX.InvalidEmbedThumbnailUrl)
totalEmbedLength += authorLength ?: 0
}
if (totalEmbedLength > DiscordResourceLimits.Embed.TotalCharacters)
context.failEphemerally(
context.i18nContext.get(
WebhookCommand.I18N_PREFIX.EmbedTooBig(
DiscordResourceLimits.Embed.TotalCharacters
)
)
)
}
}
/**
* Validates if the [url] is a valid HTTP or HTTPS URL via [URLUtils.isValidHttpOrHttpsURL], if it isn't, the command will fail ephemerally with the [message]
*/
private fun validateURLAsHttpOrHttps(context: ApplicationCommandContext, url: String?, message: StringI18nData) {
if (url != null && !URLUtils.isValidHttpOrHttpsURL(url))
context.failEphemerally(context.i18nContext.get(message))
}
private suspend fun sendWebhookSuccessMessage(context: ApplicationCommandContext, messageId: Long?, message: StringI18nData) = context.sendEphemeralMessage {
styled(
"**${context.i18nContext.get(message)}**",
Emotes.LoriYay
)
if (messageId != null) {
styled(
context.i18nContext.get(WebhookCommand.I18N_PREFIX.MessageId(messageId.toString()))
)
}
styled(
"*${context.i18nContext.get(WebhookCommand.I18N_PREFIX.WatchOutDontSendTheWebhookUrlToOtherUsers)}*"
)
}
} | agpl-3.0 | 3241f39f5b4fbeb8042254fe8272c23c | 42.29683 | 226 | 0.58903 | 5.169649 | false | false | false | false |
chRyNaN/GuitarChords | sample/src/main/java/com/chrynan/sample/model/DiatonicScaleMode.kt | 1 | 1324 | package com.chrynan.sample.model
import com.chrynan.sample.model.ScaleStep.Companion.HALF
import com.chrynan.sample.model.ScaleStep.Companion.WHOLE
enum class DiatonicScaleMode(
val modeName: String,
val numeralName: String,
val relativeStartingNote: Int,
val steps: Set<ScaleStep>
) {
IONIAN(modeName = "Ionian", numeralName = "I", relativeStartingNote = 1, steps = setOf(WHOLE, WHOLE, HALF, WHOLE, WHOLE, WHOLE, HALF)),
DORIAN(modeName = "Dorian", numeralName = "II", relativeStartingNote = 2, steps = setOf(WHOLE, HALF, WHOLE, WHOLE, WHOLE, HALF, WHOLE)),
PHRYGIAN(modeName = "Phyrgian", numeralName = "III", relativeStartingNote = 3, steps = setOf(HALF, WHOLE, WHOLE, WHOLE, HALF, WHOLE, WHOLE)),
LYDIAN(modeName = "Lydian", numeralName = "IV", relativeStartingNote = 4, steps = setOf(WHOLE, WHOLE, WHOLE, HALF, WHOLE, WHOLE, HALF)),
MIXOLYDIAN(modeName = "Mixolydian", numeralName = "V", relativeStartingNote = 5, steps = setOf(WHOLE, WHOLE, HALF, WHOLE, WHOLE, HALF, WHOLE)),
AEOLIAN(modeName = "Aeolian", numeralName = "VI", relativeStartingNote = 6, steps = setOf(WHOLE, HALF, WHOLE, WHOLE, HALF, WHOLE, WHOLE)),
LOCRIAN(modeName = "Locrian", numeralName = "VII", relativeStartingNote = 7, steps = setOf(HALF, WHOLE, WHOLE, HALF, WHOLE, WHOLE, WHOLE))
} | apache-2.0 | d778b7de3a2fd0ab769bbc7e88c32d64 | 65.25 | 147 | 0.703172 | 2.853448 | false | false | false | false |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/views/main/HomeRecyclerAdapter.kt | 1 | 6499 | package com.sampsonjoliver.firestarter.views.main
import android.location.Location
import android.support.v7.widget.RecyclerView
import android.text.format.DateUtils
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.model.LatLng
import com.sampsonjoliver.firestarter.R
import com.sampsonjoliver.firestarter.models.Session
import com.sampsonjoliver.firestarter.utils.DistanceUtils
import com.sampsonjoliver.firestarter.utils.appear
import com.sampsonjoliver.firestarter.utils.inflate
import com.sampsonjoliver.firestarter.views.RecyclerEmptyViewHolder
import com.sampsonjoliver.firestarter.views.RecyclerHeaderViewHolder
import kotlinx.android.synthetic.main.row_session.view.*
import java.util.*
class HomeRecyclerAdapter(val listener: OnSessionClickedListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
val TYPE_SUBSCRIBED_HEADER = 0
val TYPE_NEARBY_HEADER = 1
val TYPE_SUBSCRIBED_SESSION = 2
val TYPE_NEARBY_SESSION = 3
val TYPE_EMPTY = 4
}
var location: Location? = null
set(value) {
field = value
notifyItemRangeChanged(0, itemCount)
}
interface OnSessionClickedListener {
fun onSessionClicked(session: Session)
}
var filter: List<String> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
val _subscribedSessions: MutableList<Session> = mutableListOf()
val _nearbySessions: MutableList<Session> = mutableListOf()
val subscribedSessions: List<Session>
get() {
return _subscribedSessions.filter { filter.isEmpty() || it.tags.any { it.value && filter.contains(it.key) } }
}
val nearbySessions: List<Session>
get() {
return _nearbySessions.filter { filter.isEmpty() || it.tags.any { it.value && filter.contains(it.key) } }
}
fun hasSubscriptions() = subscribedSessions.isNotEmpty()
fun hasNearbySessions() = nearbySessions.isNotEmpty()
fun nearbySessionIndexToAdapterIndex(dataIndex: Int): Int {
return (if (hasSubscriptions()) 1 + subscribedSessions.size else 0) + 1 + dataIndex
}
fun subscribedSessionIndexToAdapterIndex(dataIndex: Int): Int {
return 1 + dataIndex
}
fun getSubscribedHeaderIndex() = 0
fun getNearbyHeaderIndex() = if (hasSubscriptions()) 1 + subscribedSessions.size else 0
fun getSession(position: Int): Session {
if (getItemViewType(position) != TYPE_SUBSCRIBED_SESSION && getItemViewType(position) != TYPE_NEARBY_SESSION)
throw IndexOutOfBoundsException()
if (hasSubscriptions() && position < subscribedSessions.size + 1)
return subscribedSessions[position - 1]
else if (hasNearbySessions() && position < nearbySessions.size + 1 + (if (hasSubscriptions()) subscribedSessions.size + 1 else 0))
return nearbySessions[position - 1 - (if (hasSubscriptions()) subscribedSessions.size + 1 else 0)]
else
throw IndexOutOfBoundsException()
}
override fun getItemViewType(position: Int): Int {
if (position == 0) {
if (hasSubscriptions())
return TYPE_SUBSCRIBED_HEADER
else if (hasNearbySessions())
return TYPE_NEARBY_HEADER
else
return TYPE_EMPTY
} else {
if (hasSubscriptions() && position < subscribedSessions.size + 1)
return TYPE_SUBSCRIBED_SESSION
else if (hasSubscriptions() && position == subscribedSessions.size + 1)
return TYPE_NEARBY_HEADER
else if (hasNearbySessions() && position < nearbySessions.size + 1 + if (hasSubscriptions()) subscribedSessions.size + 1 else 0)
return TYPE_NEARBY_SESSION
}
return TYPE_EMPTY
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is SessionViewHolder)
holder.bindView(getSession(position), listener)
else if (holder is RecyclerHeaderViewHolder) {
if (getItemViewType(position) == TYPE_NEARBY_HEADER)
holder.bind(holder.itemView.context.resources.getString(R.string.home_nearby_sessions))
else if (getItemViewType(position) == TYPE_SUBSCRIBED_HEADER)
holder.bind(holder.itemView.context.resources.getString(R.string.home_my_sessions))
}
else if (holder is RecyclerEmptyViewHolder)
holder.bind(holder.itemView.context.resources.getString(R.string.home_no_sessions))
}
override fun getItemCount(): Int = (subscribedSessions.size + if (subscribedSessions.isNotEmpty()) 1 else 0) +
(nearbySessions.size + if (nearbySessions.isNotEmpty()) 1 else 0)
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder? {
return when (viewType) {
TYPE_SUBSCRIBED_HEADER -> RecyclerHeaderViewHolder(RecyclerHeaderViewHolder.inflate(parent))
TYPE_NEARBY_HEADER -> RecyclerHeaderViewHolder(RecyclerHeaderViewHolder.inflate(parent))
TYPE_SUBSCRIBED_SESSION -> SessionViewHolder(parent?.inflate(R.layout.row_session, false))
TYPE_NEARBY_SESSION -> SessionViewHolder(parent?.inflate(R.layout.row_session, false))
TYPE_EMPTY -> RecyclerEmptyViewHolder(RecyclerEmptyViewHolder.inflate(parent))
else -> null
}
}
inner class SessionViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
fun bindView(session: Session, listener: OnSessionClickedListener) {
itemView.title.text = session.topic
itemView.subtitle.text = session.username
itemView.image.setImageURI(session.bannerUrl)
itemView.distance.appear = location != null
if (location != null) {
itemView.distance.text = DistanceUtils.formatDistance(LatLng(location?.latitude ?: 0.0, location?.longitude ?: 0.0), session.getLocation())
}
itemView.time.text = DateUtils.getRelativeTimeSpanString(
session.startDateAsDate.time ?: Date().time,
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE)
itemView.setOnClickListener { listener.onSessionClicked(session) }
}
}
} | apache-2.0 | 33913ef9760277681227d916e28d853b | 42.333333 | 155 | 0.670103 | 4.814074 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ideaInterop/fileTypes/asmref/jsonSchema/AsmRefJsonSchemaProviderFactory.kt | 1 | 1298 | package com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.asmref.jsonSchema
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider
import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory
import com.jetbrains.jsonSchema.extension.SchemaType
import com.jetbrains.rider.plugins.unity.UnityBundle
import com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.asmref.AsmRefFileType
class AsmRefJsonSchemaProviderFactory : JsonSchemaProviderFactory {
override fun getProviders(project: Project): MutableList<JsonSchemaFileProvider> {
return mutableListOf(
object : JsonSchemaFileProvider {
private val schemaFile = JsonSchemaProviderFactory.getResourceFile(this::class.java, "/schemas/unity/asmref.json")
override fun isAvailable(file: VirtualFile) = file.fileType == AsmRefFileType
override fun getName() = UnityBundle.message("unity.assembly.definition.reference")
override fun getSchemaFile() = schemaFile
override fun getSchemaType() = SchemaType.embeddedSchema
override fun getRemoteSource() = "https://json.schemastore.org/asmref.json"
})
}
}
| apache-2.0 | d3725598b2098da57d306167e5c2b58f | 55.434783 | 130 | 0.756549 | 4.807407 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/firstrun/FirstrunPagerAdapter.kt | 1 | 3597 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.firstrun
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import org.mozilla.focus.R
class FirstrunPagerAdapter(
private val context: Context,
private val listener: View.OnClickListener,
) : PagerAdapter() {
private data class FirstrunPage(val title: String, val text: String, val imageResource: Int) {
val contentDescription = title + text
}
private val pages: Array<FirstrunPage>
init {
val appName = context.getString(R.string.app_name)
pages = arrayOf(
FirstrunPage(
context.getString(R.string.firstrun_defaultbrowser_title),
context.getString(R.string.firstrun_defaultbrowser_text2),
R.drawable.onboarding_img1,
),
FirstrunPage(
context.getString(R.string.firstrun_search_title),
context.getString(R.string.firstrun_search_text),
R.drawable.onboarding_img4,
),
FirstrunPage(
context.getString(R.string.firstrun_shortcut_title),
context.getString(R.string.firstrun_shortcut_text, appName),
R.drawable.onboarding_img3,
),
FirstrunPage(
context.getString(R.string.firstrun_privacy_title),
context.getString(R.string.firstrun_privacy_text, appName),
R.drawable.onboarding_img2,
),
)
}
private fun getView(position: Int, pager: ViewPager): View {
val view = LayoutInflater.from(context).inflate(R.layout.firstrun_page, pager, false)
val page = pages[position]
val titleView: TextView = view.findViewById(R.id.title)
titleView.text = page.title
val textView: TextView = view.findViewById(R.id.text)
textView.text = page.text
val imageView: ImageView = view.findViewById(R.id.image)
imageView.setImageResource(page.imageResource)
val buttonView: Button = view.findViewById(R.id.button)
buttonView.setOnClickListener(listener)
if (position == pages.size - 1) {
buttonView.setText(R.string.firstrun_close_button)
buttonView.id = R.id.finish
buttonView.contentDescription = buttonView.text.toString().lowercase()
} else {
buttonView.setText(R.string.firstrun_next_button)
buttonView.id = R.id.next
}
return view
}
fun getPageAccessibilityDescription(position: Int): String =
pages[position].contentDescription
override fun isViewFromObject(view: View, any: Any) = view === any
override fun getCount() = pages.size
override fun instantiateItem(container: ViewGroup, position: Int): Any {
container as ViewPager
val view = getView(position, container)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, view: Any) {
view as View
container.removeView(view)
}
}
| mpl-2.0 | c553ff4b94adb6e1117a7489b50ef934 | 33.586538 | 98 | 0.651098 | 4.338963 | false | false | false | false |
charbgr/CliffHanger | cliffhanger/arch/src/test/kotlin/com/github/charbgr/arch/RxPresenterTest.kt | 1 | 889 | package com.github.charbgr.arch
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class RxPresenterTest {
@Test
fun test_init_view() {
val presenter = TestPresenter()
presenter.init(TestView)
assertTrue(presenter.hasDisposableZeroSize())
}
@Test
fun test_destroy_view() {
val presenter = TestPresenter()
presenter.init(TestView)
presenter.addDummyUseCase()
assertFalse(presenter.hasDisposableZeroSize())
presenter.destroy()
assertTrue(presenter.hasDisposableZeroSize())
}
private object TestView : View
private class TestPresenter : RxPresenter<TestView>() {
fun addDummyUseCase() {
val useCase = object : UseCase<Unit, Unit>() {
override fun build(params: Unit) {
}
}
register(useCase)
}
fun hasDisposableZeroSize() = disposable.size() == 0
}
}
| mit | 74ba88a4f0a173bae11d2bc165012e3d | 20.166667 | 57 | 0.686164 | 4.134884 | false | true | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/annotator/RsCargoCheckAnnotator.kt | 1 | 9217 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.google.gson.JsonParser
import com.intellij.execution.ExecutionException
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.lang.annotation.ProblemGroup
import com.intellij.openapi.application.Result
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.PathUtil
import org.apache.commons.lang.StringEscapeUtils.escapeHtml
import org.rust.cargo.project.settings.rustSettings
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.cargo.toolchain.*
import org.rust.ide.RsConstants
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.cargoWorkspace
import org.rust.lang.core.psi.ext.containingCargoPackage
import java.nio.file.Path
import java.util.*
data class CargoCheckAnnotationInfo(
val file: VirtualFile,
val toolchain: RustToolchain,
val projectPath: Path,
val module: Module
)
class CargoCheckAnnotationResult(commandOutput: List<String>) {
companion object {
private val parser = JsonParser()
private val messageRegex = """\s*\{\s*"message".*""".toRegex()
}
val messages: List<CargoTopMessage> =
commandOutput
.filter { messageRegex.matches(it) }
.map { parser.parse(it) }
.filter { it.isJsonObject }
.mapNotNull { CargoTopMessage.fromJson(it.asJsonObject) }
}
class RsCargoCheckAnnotator : ExternalAnnotator<CargoCheckAnnotationInfo, CargoCheckAnnotationResult>() {
override fun collectInformation(file: PsiFile, editor: Editor, hasErrors: Boolean): CargoCheckAnnotationInfo? {
if (file !is RsFile) return null
if (!file.project.rustSettings.useCargoCheckAnnotator) return null
val ws = file.cargoWorkspace ?: return null
val module = ModuleUtil.findModuleForFile(file.virtualFile, file.project) ?: return null
val toolchain = module.project.toolchain ?: return null
return CargoCheckAnnotationInfo(file.virtualFile, toolchain, ws.contentRoot, module)
}
override fun doAnnotate(info: CargoCheckAnnotationInfo): CargoCheckAnnotationResult? =
CachedValuesManager.getManager(info.module.project)
.getCachedValue(info.module, {
CachedValueProvider.Result.create(
checkProject(info),
PsiModificationTracker.MODIFICATION_COUNT)
})
override fun apply(file: PsiFile, annotationResult: CargoCheckAnnotationResult?, holder: AnnotationHolder) {
if (annotationResult == null) return
val fileOrigin = (file as? RsElement)?.containingCargoPackage?.origin
if (fileOrigin != PackageOrigin.WORKSPACE) return
val doc = file.viewProvider.document
?: error("Can't find document for $file in Cargo check annotator")
for ((topMessage) in annotationResult.messages) {
val message = filterMessage(file, doc, topMessage) ?: continue
holder.createAnnotation(message.severity, message.textRange, message.message, message.htmlTooltip)
.apply {
problemGroup = ProblemGroup { message.message }
setNeedsUpdateOnTyping(true)
}
}
}
}
// NB: executed asynchronously off EDT, so care must be taken not to access
// disposed objects
private fun checkProject(info: CargoCheckAnnotationInfo): CargoCheckAnnotationResult? {
// We have to save the file to disk to give cargo a chance to check fresh file content.
object : WriteAction<Unit>() {
override fun run(result: Result<Unit>) {
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getDocument(info.file)
if (document == null) {
fileDocumentManager.saveAllDocuments()
} else if (fileDocumentManager.isDocumentUnsaved(document)) {
fileDocumentManager.saveDocument(document)
}
}
}.execute()
val output = try {
info.toolchain.cargoOrWrapper(info.projectPath).checkProject(info.module, info.projectPath)
} catch (e: ExecutionException) {
return null
}
if (output.isCancelled) return null
return CargoCheckAnnotationResult(output.stdoutLines)
}
private data class FilteredMessage(
val severity: HighlightSeverity,
val textRange: TextRange,
val message: String,
val htmlTooltip: String
)
private fun filterMessage(file: PsiFile, document: Document, message: RustcMessage): FilteredMessage? {
if (message.message.startsWith("aborting due to") || message.message.startsWith("cannot continue")) {
return null
}
val severity = when (message.level) {
"error" -> HighlightSeverity.ERROR
"warning" -> HighlightSeverity.WEAK_WARNING
else -> HighlightSeverity.INFORMATION
}
val span = message.spans
.firstOrNull { it.is_primary && it.isValid() }
// Some error messages are global, and we *could* show then atop of the editor,
// but they look rather ugly, so just skip them.
?: return null
val syntaxErrors = listOf("expected pattern", "unexpected token")
if (syntaxErrors.any { it in span.label.orEmpty() || it in message.message }) {
return null
}
val spanFilePath = PathUtil.toSystemIndependentName(span.file_name)
if (!file.virtualFile.path.endsWith(spanFilePath)) return null
@Suppress("NAME_SHADOWING")
fun toOffset(line: Int, column: Int): Int? {
val line = line - 1
val column = column - 1
if (line >= document.lineCount) return null
return (document.getLineStartOffset(line) + column)
.takeIf { it <= document.textLength }
}
// The compiler message lines and columns are 1 based while intellij idea are 0 based
val startOffset = toOffset(span.line_start, span.column_start)
val endOffset = toOffset(span.line_end, span.column_end)
val textRange = if (startOffset != null && endOffset != null && startOffset < endOffset) {
TextRange(startOffset, endOffset)
} else {
return null
}
val tooltip = with(ArrayList<String>()) {
val code = message.code.formatAsLink()
add(escapeHtml(message.message) + if (code == null) "" else " $code")
if (span.label != null && !message.message.startsWith(span.label)) {
add(escapeHtml(span.label))
}
message.children
.filter { !it.message.isBlank() }
.map { "${it.level.capitalize()}: ${escapeHtml(it.message)}" }
.forEach { add(it) }
joinToString("<br>") { formatMessage(it) }
}
return FilteredMessage(severity, textRange, message.message, tooltip)
}
private fun RustcSpan.isValid() =
line_end > line_start || (line_end == line_start && column_end >= column_start)
private fun ErrorCode?.formatAsLink() =
if (this?.code.isNullOrBlank()) null
else "<a href=\"${RsConstants.ERROR_INDEX_URL}#${this?.code}\">${this?.code}</a>"
private fun formatMessage(message: String): String {
data class Group(val isList: Boolean, val lines: ArrayList<String>)
val (lastGroup, groups) =
message.split("\n").fold(
Pair(null as Group?, ArrayList<Group>()),
{ (group: Group?, acc: ArrayList<Group>), lineWithPrefix ->
val (isListItem, line) = if (lineWithPrefix.startsWith("-")) {
true to lineWithPrefix.substring(2)
} else {
false to lineWithPrefix
}
when {
group == null -> Pair(Group(isListItem, arrayListOf(line)), acc)
group.isList == isListItem -> {
group.lines.add(line)
Pair(group, acc)
}
else -> {
acc.add(group)
Pair(Group(isListItem, arrayListOf(line)), acc)
}
}
})
if (lastGroup != null && lastGroup.lines.isNotEmpty()) groups.add(lastGroup)
return groups.joinToString {
if (it.isList) "<ul>${it.lines.joinToString("<li>", "<li>")}</ul>"
else it.lines.joinToString("<br>")
}
}
| mit | 349ab083ddc739f788916da0268aa726 | 37.564854 | 115 | 0.66616 | 4.50709 | false | false | false | false |
square/leakcanary | shark-graph/src/test/java/shark/HprofDeobfuscatorTest.kt | 2 | 5651 | package shark
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import shark.ValueHolder.IntHolder
import java.io.File
class HprofDeobfuscatorTest {
@get:Rule
var testFolder = TemporaryFolder()
private lateinit var hprofFile: File
@Before
fun setUp() {
hprofFile = testFolder.newFile("temp.hprof")
}
@Test
fun deobfuscateHprofClassName() {
val proguardMapping = ProguardMapping().create {
clazz("Foo" to "a")
}
hprofFile.dump {
"a" clazz {}
}
val deobfuscator = HprofDeobfuscator()
val deobfuscatedFile = deobfuscator.deobfuscate(proguardMapping, hprofFile)
deobfuscatedFile.readHprof { graph ->
val fooClass = graph.findClassByName("Foo")
assertThat(fooClass).isNotNull
}
}
@Test
fun deobfuscateHprofStaticFieldName() {
val proguardMapping = ProguardMapping().create {
clazz("Foo" to "a") {
field { "staticField" to "b" }
}
}
hprofFile.dump {
"a" clazz {
staticField["b"] = IntHolder(42)
}
}
val deobfuscator = HprofDeobfuscator()
val deobfuscatedFile = deobfuscator.deobfuscate(proguardMapping, hprofFile)
deobfuscatedFile.readHprof { graph ->
val fooClass = graph.findClassByName("Foo")!!
assertThat(
fooClass.readStaticFields()
.map { it.name }
.toList()
).contains("staticField")
}
}
@Test
fun deobfuscateHprofMemberFieldName() {
val proguardMapping = ProguardMapping().create {
clazz("Foo" to "a") {
field { "instanceField" to "b" }
}
}
hprofFile.dump {
val classId = clazz(
className = "a",
fields = listOf("b" to IntHolder::class)
)
instance(classId, listOf(IntHolder(0)))
}
val deobfuscator = HprofDeobfuscator()
val deobfuscatedFile = deobfuscator.deobfuscate(proguardMapping, hprofFile)
deobfuscatedFile.readHprof { graph ->
val instance = graph.instances.find { heapInstance ->
heapInstance.instanceClassName == "Foo"
}!!
assertThat(
instance.readFields()
.map { it.name }
.toList()
).contains("instanceField")
}
}
@Test
fun deobfuscateHprofClassNameUsedAsFieldName() {
val proguardMapping = ProguardMapping().create {
clazz("Foo" to "a") {
field { "instanceField" to "a" }
}
}
hprofFile.dump {
val classNameRecord = stringRecord("a")
val classId = clazz(
classNameRecord = classNameRecord,
fields = listOf(classNameRecord.id to IntHolder::class)
)
instance(classId, listOf(IntHolder(0)))
}
val deobfuscator = HprofDeobfuscator()
val deobfuscatedFile = deobfuscator.deobfuscate(proguardMapping, hprofFile)
deobfuscatedFile.readHprof { graph ->
val instance = graph.instances.find { heapInstance ->
heapInstance.instanceClassName == "Foo"
}!!
assertThat(
instance.readFields()
.map { it.name }
.toList()
).contains("instanceField")
}
}
@Test
fun deobfuscateHprofClassNameUsedAsStaticFieldName() {
val proguardMapping = ProguardMapping().create {
clazz("Foo" to "a") {
field { "staticField" to "a" }
}
}
hprofFile.dump {
val classNameRecord = stringRecord("a")
clazz(
classNameRecord = classNameRecord,
staticFields = listOf(classNameRecord.id to IntHolder(42))
)
}
val deobfuscator = HprofDeobfuscator()
val deobfuscatedFile = deobfuscator.deobfuscate(proguardMapping, hprofFile)
deobfuscatedFile.readHprof { graph ->
val fooClass = graph.findClassByName("Foo")!!
assertThat(
fooClass.readStaticFields()
.map { it.name }
.toList()
).contains("staticField")
}
}
@Test
fun deobfuscateHprofTwoFieldsWithSameName() {
val proguardMapping = ProguardMapping().create {
clazz("Foo" to "a") {
field { "instanceField1" to "c" }
}
clazz("Bar" to "b") {
field { "instanceField2" to "c" }
}
}
hprofFile.dump {
val fooClassNameRecord = stringRecord("a")
val barClassNameRecord = stringRecord("b")
val fieldNameRecord = stringRecord("c")
val fooClassId = clazz(
classNameRecord = fooClassNameRecord,
fields = listOf(fieldNameRecord.id to IntHolder::class)
)
instance(fooClassId, listOf(IntHolder(0)))
val barClassId = clazz(
classNameRecord = barClassNameRecord,
fields = listOf(fieldNameRecord.id to IntHolder::class)
)
instance(barClassId, listOf(IntHolder(0)))
}
val deobfuscator = HprofDeobfuscator()
val deobfuscatedFile = deobfuscator.deobfuscate(proguardMapping, hprofFile)
deobfuscatedFile.readHprof { graph ->
val fooInstance = graph.instances.find { heapInstance ->
heapInstance.instanceClassName == "Foo"
}!!
assertThat(
fooInstance.readFields()
.map { it.name }
.toList()
).contains("instanceField1")
val barInstance = graph.instances.find { heapInstance ->
heapInstance.instanceClassName == "Bar"
}!!
assertThat(
barInstance.readFields()
.map { it.name }
.toList()
).contains("instanceField2")
}
}
private fun File.readHprof(block: (HeapGraph) -> Unit) {
Hprof.open(this)
.use { hprof ->
block(HprofHeapGraph.indexHprof(hprof))
}
}
} | apache-2.0 | fa1715065f30868ab0c584a0016fae84 | 23.898678 | 79 | 0.625376 | 4.136896 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/highlight/RsHighlightExitPointsHandlerFactory.kt | 2 | 2491 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.highlight
import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerBase
import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerFactoryBase
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.Consumer
import org.rust.lang.core.ExitPoint
import org.rust.lang.core.psi.RsElementTypes.Q
import org.rust.lang.core.psi.RsElementTypes.RETURN
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsLambdaExpr
import org.rust.lang.core.psi.RsTryExpr
import org.rust.lang.core.psi.ext.ancestors
import org.rust.lang.core.psi.ext.elementType
class RsHighlightExitPointsHandlerFactory : HighlightUsagesHandlerFactoryBase() {
override fun createHighlightUsagesHandler(editor: Editor, file: PsiFile, target: PsiElement): HighlightUsagesHandlerBase<*>? {
if (file !is RsFile) return null
val elementType = target.elementType
if (elementType == RETURN || elementType == Q) {
return RsHighlightExitPointsHandler(editor, file, target)
}
return null
}
}
private class RsHighlightExitPointsHandler(editor: Editor, file: PsiFile, var target: PsiElement) : HighlightUsagesHandlerBase<PsiElement>(editor, file) {
override fun getTargets() = listOf(target)
override fun selectTargets(targets: List<PsiElement>, selectionConsumer: Consumer<List<PsiElement>>) {
selectionConsumer.consume(targets)
}
override fun computeUsages(targets: MutableList<PsiElement>?) {
val sink: (ExitPoint) -> Unit = { exitPoint ->
when (exitPoint) {
is ExitPoint.Return -> addOccurrence(exitPoint.e)
is ExitPoint.TryExpr -> if (exitPoint.e is RsTryExpr) addOccurrence(exitPoint.e.q) else addOccurrence(exitPoint.e)
is ExitPoint.DivergingExpr -> addOccurrence(exitPoint.e)
is ExitPoint.TailExpr -> addOccurrence(exitPoint.e)
is ExitPoint.TailStatement -> Unit
}
}
val fnOrLambda = target.ancestors.firstOrNull { it is RsFunction || it is RsLambdaExpr }
when (fnOrLambda) {
is RsFunction -> ExitPoint.process(fnOrLambda, sink)
is RsLambdaExpr -> ExitPoint.process(fnOrLambda, sink)
}
}
}
| mit | d1cceb7775ce1d9f2c9d3e194dd096df | 39.836066 | 154 | 0.71939 | 4.165552 | false | false | false | false |
ffgiraldez/rx-mvvm-android | app/src/main/java/es/ffgiraldez/comicsearch/query/search/data/SearchDataSources.kt | 1 | 1682 | package es.ffgiraldez.comicsearch.query.search.data
import es.ffgiraldez.comicsearch.comics.data.SuspendComicLocalDataSource
import es.ffgiraldez.comicsearch.comics.data.SuspendComicRemoteDataSource
import es.ffgiraldez.comicsearch.comics.data.network.SuspendComicVineApi
import es.ffgiraldez.comicsearch.comics.data.storage.ComicDatabase
import es.ffgiraldez.comicsearch.comics.domain.Query
import es.ffgiraldez.comicsearch.comics.domain.Volume
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class SuspendSearchRemoteDataSource(
private val api: SuspendComicVineApi
) : SuspendComicRemoteDataSource<Volume> {
override suspend fun findByTerm(searchTerm: String): List<Volume> =
api.fetchVolumes(searchTerm).run {
results.filter { it.apiPublisher != null && it.apiImage != null }
.map { Volume(it.name, it.apiPublisher!!.name, it.apiImage!!.url) }
}
}
class SuspendSearchLocalDataSource(
private val database: ComicDatabase
) : SuspendComicLocalDataSource<Volume> {
override suspend fun insert(query: String, titles: List<Volume>) =
database.suspendingVolumeDao().insert(query, titles)
override fun findQueryByTerm(searchTerm: String): Flow<Query?> =
database.suspendingVolumeDao().findQueryByTerm(searchTerm)
.map { queries -> queries?.let { Query(it.queryId, it.searchTerm) } }
override fun findByQuery(query: Query): Flow<List<Volume>> =
database.suspendingVolumeDao().findVolumeByQuery(query.identifier)
.map { results -> results.map { Volume(it.title, it.author, it.url) } }
} | apache-2.0 | 94de4a8b475c4169c1710fe2f0ca9c71 | 45.75 | 91 | 0.725922 | 4.312821 | false | false | false | false |
SUPERCILEX/Robot-Scouter | app/server/functions/src/main/kotlin/com/supercilex/robotscouter/server/Index.kt | 1 | 3555 | package com.supercilex.robotscouter.server
import com.supercilex.robotscouter.common.FIRESTORE_DELETION_QUEUE
import com.supercilex.robotscouter.common.FIRESTORE_DUPLICATE_TEAMS
import com.supercilex.robotscouter.common.FIRESTORE_TEAMS
import com.supercilex.robotscouter.server.functions.deleteUnusedData
import com.supercilex.robotscouter.server.functions.emptyTrash
import com.supercilex.robotscouter.server.functions.initUser
import com.supercilex.robotscouter.server.functions.logUserData
import com.supercilex.robotscouter.server.functions.mergeDuplicateTeams
import com.supercilex.robotscouter.server.functions.populateTeam
import com.supercilex.robotscouter.server.functions.processClientRequest
import com.supercilex.robotscouter.server.functions.sanitizeDeletionRequest
import com.supercilex.robotscouter.server.functions.transferUserData
import com.supercilex.robotscouter.server.functions.updateDefaultTemplates
import com.supercilex.robotscouter.server.functions.updateOwners
import com.supercilex.robotscouter.server.utils.types.functions
import kotlin.js.Json
import kotlin.js.json
external val exports: dynamic
@Suppress("unused") // Used by Cloud Functions
fun main() {
createManualTriggerFunctions()
createCronJobFunctions()
createClientApiFunctions()
createReactiveFunctions()
createAuthFunctions()
}
private fun createManualTriggerFunctions() {
val pubsub = functions.pubsub
// Trigger: `gcloud beta pubsub topics publish log-user-data '{"uid":"..."}'`
exports.logUserData = pubsub.topic("log-user-data")
.onPublish { message, _ -> logUserData(message) }
exports.updateDefaultTemplates = pubsub.topic("update-default-templates")
.onPublish { _, _ -> updateDefaultTemplates() }
}
private fun createCronJobFunctions() {
val pubsub = functions.runWith(json(
"timeoutSeconds" to 540,
"memory" to "512MB"
)).pubsub
exports.cleanup = pubsub.topic("daily-tick")
.onPublish { _, _ -> emptyTrash() }
exports.deleteUnusedData = pubsub.topic("daily-tick")
.onPublish { _, _ -> deleteUnusedData() }
}
private fun createClientApiFunctions() {
val https = functions.runWith(json(
"timeoutSeconds" to 540,
"memory" to "2GB"
)).https
// TODO remove once we stop getting API requests
exports.emptyTrash = https
.onCall { data: Array<String>?, context -> emptyTrash(json("ids" to data), context) }
exports.transferUserData = https
.onCall { data: Json, context -> transferUserData(data, context) }
exports.updateOwners = https
.onCall { data: Json, context -> updateOwners(data, context) }
exports.clientApi = https
.onCall { data: Json, context -> processClientRequest(data, context) }
}
private fun createReactiveFunctions() {
val firestore = functions.runWith(json(
"timeoutSeconds" to 540,
"memory" to "1GB"
)).firestore
exports.sanitizeDeletionQueue = firestore.document("$FIRESTORE_DELETION_QUEUE/{uid}")
.onWrite { event, _ -> sanitizeDeletionRequest(event) }
exports.mergeDuplicateTeams = firestore.document("$FIRESTORE_DUPLICATE_TEAMS/{uid}")
.onWrite { event, _ -> mergeDuplicateTeams(event) }
exports.populateTeam = firestore.document("$FIRESTORE_TEAMS/{id}")
.onWrite { event, _ -> populateTeam(event) }
}
private fun createAuthFunctions() {
exports.initUser = functions.auth.user().onCreate { user -> initUser(user) }
}
| gpl-3.0 | 06135ad060d15b2141fffb64a1a12674 | 39.397727 | 97 | 0.723769 | 4.303874 | false | false | false | false |
mayuki/AgqrPlayer4Tv | AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/component/fragment/guidedstep/StreamingSettingGuidedStepFragment.kt | 1 | 2043 | package org.misuzilla.agqrplayer4tv.component.fragment.guidedstep
import android.os.Bundle
import android.support.v17.leanback.app.GuidedStepSupportFragment
import android.support.v17.leanback.widget.GuidanceStylist
import android.support.v17.leanback.widget.GuidedAction
import org.misuzilla.agqrplayer4tv.R
import org.misuzilla.agqrplayer4tv.infrastracture.extension.addCheckAction
import org.misuzilla.agqrplayer4tv.model.preference.ApplicationPreference
import org.misuzilla.agqrplayer4tv.model.preference.StreamingType
/**
* 設定: 配信形式設定のGuidedStepクラスです。
*/
class StreamingSettingGuidedStepFragment : GuidedStepSupportFragment() {
override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
return GuidanceStylist.Guidance(context!!.getString(R.string.guidedstep_streaming_title), context!!.getString(R.string.guidedstep_streaming_description_long), context!!.getString(R.string.guidedstep_settings_title), null)
}
override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
with (actions) {
addCheckAction(context!!, StreamingType.RTMP.value,
context!!.getString(R.string.guidedstep_streaming_type_rtmp),
context!!.getString(R.string.guidedstep_streaming_type_rtmp_description),
ApplicationPreference.streamingType.get() == StreamingType.RTMP)
addCheckAction(context!!, StreamingType.HLS.value,
context!!.getString(R.string.guidedstep_streaming_type_hls),
context!!.getString(R.string.guidedstep_streaming_type_hls_description),
ApplicationPreference.streamingType.get() == StreamingType.HLS)
}
}
override fun onGuidedActionClicked(action: GuidedAction) {
actions.forEach { it.isChecked = it == action }
ApplicationPreference.streamingType.set(StreamingType.fromInt(action.id.toInt()))
fragmentManager!!.popBackStack()
}
} | mit | a521dd7d74eed39fc69615aae9ee5ba8 | 49.35 | 229 | 0.742176 | 4.616972 | false | false | false | false |
JimSeker/ui | Navigation/NavDrawerFragDemo_kt/app/src/main/java/edu/cs4730/navdrawerfragdemo_kt/titlefrag.kt | 1 | 2589 | package edu.cs4730.navdrawerfragdemo_kt
import edu.cs4730.navdrawerfragdemo_kt.titlefrag.OnFragmentInteractionListener
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import edu.cs4730.navdrawerfragdemo_kt.R
import android.widget.ArrayAdapter
import edu.cs4730.navdrawerfragdemo_kt.Shakespeare
import android.app.Activity
import android.content.Context
import android.view.View
import android.widget.ListView
import androidx.fragment.app.ListFragment
import java.lang.ClassCastException
/**
* this ia listfragment. All we need to do is setlistadapter in onCreateView (there is no layout)
* and override onListItemClick. Since we also have callbacks, also deal with those.
*/
class titlefrag : ListFragment() {
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private var mListener: OnFragmentInteractionListener? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.listfragment_layout, container, false)
val adapter =
ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, Shakespeare.TITLES)
listAdapter = adapter
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
val activity: Activity = requireActivity()
mListener = try {
activity as OnFragmentInteractionListener
} catch (e: ClassCastException) {
throw ClassCastException(
activity.toString()
+ " must implement OnFragmentInteractionListener"
)
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
override fun onListItemClick(listView: ListView, view: View, position: Int, id: Long) {
super.onListItemClick(listView, view, position, id)
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
if (mListener != null) mListener!!.onItemSelected(position)
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
interface OnFragmentInteractionListener {
/**
* Callback for when an item has been selected.
*/
fun onItemSelected(id: Int)
}
} | apache-2.0 | 079e1f318b8308235bee037aa95aac63 | 32.636364 | 100 | 0.685593 | 4.839252 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/feature/scheduled/ScheduledActivity.kt | 3 | 3661 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.scheduled
import android.graphics.Typeface
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.moez.QKSMS.common.QkDialog
import com.moez.QKSMS.common.base.QkThemedActivity
import com.moez.QKSMS.common.util.FontProvider
import com.moez.QKSMS.common.util.extensions.setBackgroundTint
import com.moez.QKSMS.common.util.extensions.setTint
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.collapsing_toolbar.*
import kotlinx.android.synthetic.main.scheduled_activity.*
import javax.inject.Inject
class ScheduledActivity : QkThemedActivity(), ScheduledView {
@Inject lateinit var dialog: QkDialog
@Inject lateinit var fontProvider: FontProvider
@Inject lateinit var messageAdapter: ScheduledMessageAdapter
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
override val messageClickIntent by lazy { messageAdapter.clicks }
override val messageMenuIntent by lazy { dialog.adapter.menuItemClicks }
override val composeIntent by lazy { compose.clicks() }
override val upgradeIntent by lazy { upgrade.clicks() }
private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory)[ScheduledViewModel::class.java] }
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.scheduled_activity)
setTitle(R.string.scheduled_title)
showBackButton(true)
viewModel.bindView(this)
if (!prefs.systemFont.get()) {
fontProvider.getLato { lato ->
val typeface = Typeface.create(lato, Typeface.BOLD)
collapsingToolbar.setCollapsedTitleTypeface(typeface)
collapsingToolbar.setExpandedTitleTypeface(typeface)
}
}
dialog.title = getString(R.string.scheduled_options_title)
dialog.adapter.setData(R.array.scheduled_options)
messageAdapter.emptyView = empty
messages.adapter = messageAdapter
colors.theme().let { theme ->
sampleMessage.setBackgroundTint(theme.theme)
sampleMessage.setTextColor(theme.textPrimary)
compose.setTint(theme.textPrimary)
compose.setBackgroundTint(theme.theme)
upgrade.setBackgroundTint(theme.theme)
upgradeIcon.setTint(theme.textPrimary)
upgradeLabel.setTextColor(theme.textPrimary)
}
}
override fun render(state: ScheduledState) {
messageAdapter.updateData(state.scheduledMessages)
compose.isVisible = state.upgraded
upgrade.isVisible = !state.upgraded
}
override fun showMessageOptions() {
dialog.show(this)
}
} | gpl-3.0 | d2d12b667d4640abd54851d30700e184 | 36.752577 | 115 | 0.73204 | 4.581977 | false | false | false | false |
MyDogTom/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/LoopWithTooManyJumpStatements.kt | 1 | 1889 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.psi.KtBreakExpression
import org.jetbrains.kotlin.psi.KtContinueExpression
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtLoopExpression
class LoopWithTooManyJumpStatements(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName, Severity.Style,
"The loop contains more than one break or continue statement. " +
"The code should be refactored to increase readability.", Debt.TEN_MINS)
private val maxJumpCount = valueOrDefault(MAX_JUMP_COUNT, 1)
override fun visitLoopExpression(loopExpression: KtLoopExpression) {
if (countBreakAndReturnStatements(loopExpression.body) > maxJumpCount) {
report(CodeSmell(issue, Entity.from(loopExpression)))
}
super.visitLoopExpression(loopExpression)
}
private fun countBreakAndReturnStatements(body: KtExpression?): Int {
return body?.countBreakAndReturnStatementsInLoop() ?: 0
}
private fun KtElement.countBreakAndReturnStatementsInLoop(): Int {
var count = 0
this.accept(object : DetektVisitor() {
override fun visitKtElement(element: KtElement) {
if (element is KtLoopExpression) {
return
}
if (element is KtBreakExpression || element is KtContinueExpression) {
count++
}
element.children.forEach { it.accept(this) }
}
})
return count
}
companion object {
const val MAX_JUMP_COUNT = "maxJumpCount"
}
}
| apache-2.0 | 10952822a2bf25fbadd62e53ad50deb0 | 33.345455 | 83 | 0.780836 | 3.87885 | false | true | false | false |
jpmoreto/play-with-robots | android/lib/src/main/java/jpm/lib/math/Rectangle2D.kt | 1 | 25723 | package jpm.lib.math
import it.unimi.dsi.fastutil.doubles.Double2ReferenceAVLTreeMap
import it.unimi.dsi.fastutil.objects.ObjectAVLTreeSet
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet
//import it.unimi.dsi.fastutil.objects.ReferenceArraySet
/**
* Created by jm on 25/03/17.
*
*/
val epsilon = 1E-30
/**
* @p1 left bottom
* @p2 right top
*/
open class DoubleRectangle2D(val p1: DoubleVector2D, val p2: DoubleVector2D) {
override fun toString() = "(p1=$p1, p2=$p2)"
fun height() = p2.y - p1.y
fun width() = p2.x - p1.x
override fun equals(other: Any?): Boolean {
if(other is DoubleRectangle2D) {
return p1.x == other.p1.x && p1.y == other.p1.y && p2.x == other.p2.x && p2.y == other.p2.y
}
return false
}
override fun hashCode(): Int
= p1.hashCode().xor(p2.hashCode())
}
/*
object CompareDoubleRectangle2DXY : Comparator<DoubleRectangle2D> {
override fun compare(r0: DoubleRectangle2D, r1: DoubleRectangle2D): Int {
if(r0.p1.x < r1.p1.x) return -1
if(r0.p1.x > r1.p1.x) return 1
if(r0.p2.x < r1.p2.x) return -1
if(r0.p2.x > r1.p2.x) return 1
if(r0.p1.y < r1.p1.y) return -1
if(r0.p1.y > r1.p1.y) return 1
if(r0.p2.y < r1.p2.y) return -1
if(r0.p2.y > r1.p2.y) return 1
return 0
}
}
object CompareDoubleRectangle2DYX : Comparator<DoubleRectangle2D> {
override fun compare(r0: DoubleRectangle2D, r1: DoubleRectangle2D): Int {
if(r0.p1.y < r1.p1.y) return -1
if(r0.p1.y > r1.p1.y) return 1
if(r0.p2.y < r1.p2.y) return -1
if(r0.p2.y > r1.p2.y) return 1
if(r0.p1.x < r1.p1.x) return -1
if(r0.p1.x > r1.p1.x) return 1
if(r0.p2.x < r1.p2.x) return -1
if(r0.p2.x > r1.p2.x) return 1
return 0
}
}
*/
object SimpleCompareDoubleRectangle2DXY : Comparator<DoubleRectangle2D> {
override fun compare(r0: DoubleRectangle2D, r1: DoubleRectangle2D): Int {
if(r0.p1.x < r1.p1.x) return -1
if(r0.p1.x > r1.p1.x) return 1
if(r0.p2.x < r1.p2.x) return -1
if(r0.p2.x > r1.p2.x) return 1
return 0
}
}
object SimpleCompareDoubleRectangle2DYX : Comparator<DoubleRectangle2D> {
override fun compare(r0: DoubleRectangle2D, r1: DoubleRectangle2D): Int {
if(r0.p1.y < r1.p1.y) return -1
if(r0.p1.y > r1.p1.y) return 1
if(r0.p2.y < r1.p2.y) return -1
if(r0.p2.y > r1.p2.y) return 1
return 0
}
}
fun intersectsY(b: DoubleRectangle2D, a: DoubleRectangle2D)
= a.p1.y - epsilon <= b.p1.y && b.p2.y <= a.p2.y - epsilon ||
b.p1.y - epsilon <= a.p1.y && a.p1.y < b.p2.y - epsilon ||
b.p1.y + epsilon < a.p2.y && a.p2.y <= b.p2.y + epsilon
fun intersectsX(b: DoubleRectangle2D, a: DoubleRectangle2D)
= a.p1.x - epsilon <= b.p1.x && b.p2.x <= a.p2.x - epsilon ||
b.p1.x - epsilon <= a.p1.x && a.p1.x < b.p2.x - epsilon ||
b.p1.x + epsilon < a.p2.x && a.p2.x <= b.p2.x + epsilon
enum class Side(val dir: Int, val oppositeDir: Int) {
TOP(0,1), BOTTOM(1,0), RIGHT(2,3), LEFT (3,2)
}
class RectangleContext(p1: DoubleVector2D, p2: DoubleVector2D): DoubleRectangle2D(p1,p2) {
val dirs = arrayOf(
ReferenceOpenHashSet<RectangleContext>(23),
ReferenceOpenHashSet<RectangleContext>(23),
ReferenceOpenHashSet<RectangleContext>(23),
ReferenceOpenHashSet<RectangleContext>(23)
)
/*
val dirs = arrayOf(
mutableSetOf<RectangleContext>(),
mutableSetOf<RectangleContext>(),
mutableSetOf<RectangleContext>(),
mutableSetOf<RectangleContext>()
)
*/
operator fun get(side: Side) = dirs[side.dir]
fun contains(p: DoubleVector2D): Boolean
= p1.x <= p.x && p.x < p2.x && p1.y <= p.y && p.y < p2.y
fun add(other: RectangleContext, toDir: Side) {
//println("${toStringLess()} add ${other.toStringLess()} toDir $toDir")
dirs[toDir.dir].add(other)
other.dirs[toDir.oppositeDir].add(this)
}
override fun toString()
= "RC(${super.toString()}\n top=${dirs[Side.TOP.dir].map {it.toStringLess()}}\n bottom=${dirs[Side.BOTTOM.dir].map {it.toStringLess()}}\n left=${dirs[Side.LEFT.dir].map {it.toStringLess()}}\n right=${dirs[Side.RIGHT.dir].map {it.toStringLess()}})"
fun toStringLess()
= super.toString()
}
fun compactRectangles(rectContexts: Collection<RectangleContext>, minDiff: Int = 30, maxIterations: Int= 5): Collection<RectangleContext> {
var size = 0
val rectContextsByBottom = Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>()
val rectContextsByTop = Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>()
val rectContextsByLeft = Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>()
val rectContextsByRight = Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>()
fun addTo(xOrY: Double, context: RectangleContext, map: Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>, cmp: Comparator<DoubleRectangle2D>) {
val nodes = map.get(xOrY)
if(nodes == null) {
val newTree = ObjectAVLTreeSet<RectangleContext>(cmp)
newTree.add(context)
map.put(xOrY,newTree)
} else
nodes.add(context)
}
fun mergeRectangles(leftMatchRectangles: MutableList<RectangleContext>, rightMatchRectangles: MutableList<RectangleContext>): RectangleContext {
// left rectangles are to the right of the merge
// right rectangles are to the left of the merge
//
return RectangleContext(rightMatchRectangles.first().p1, leftMatchRectangles.last().p2)
}
fun mergeNeighborsLeftAndRight(
leftRectangles: ObjectAVLTreeSet<RectangleContext>,
rightRectangles: ObjectAVLTreeSet<RectangleContext>,
rectangleContextsToAdd: MutableList<RectangleContext>,
rectangleContextsToDelete: MutableList<RectangleContext>) {
fun normalizeLeftRectangles(matchRectangles: MutableList<RectangleContext>,contextMin: Double, contextMax: Double): MutableList<RectangleContext> {
// left rectangles are to the right of the merge
//
if(nearZero(contextMin - contextMax,epsilon)) // all contexts with same width
return matchRectangles
val newMatchRectangles = mutableListOf<RectangleContext>() // stores the central rectangles
for(rectangle in matchRectangles) {
if(nearZero(rectangle.p2.x - contextMin,epsilon)) {
newMatchRectangles.add(rectangle)
} else { // split in 2
newMatchRectangles.add(RectangleContext(rectangle.p1, DoubleVector2D(contextMin,rectangle.p2.y)))
rectangleContextsToAdd.add(RectangleContext(DoubleVector2D(contextMin,rectangle.p1.y), rectangle.p2))
}
}
return newMatchRectangles
}
fun normalizeRightRectangles(rightMatchRectangles: MutableList<RectangleContext>,contextMin: Double, contextMax: Double): MutableList<RectangleContext> {
// right rectangles are to the left of the merge
//
if(nearZero(contextMin - contextMax,epsilon)) // all contexts with same width
return rightMatchRectangles
val newMatchRectangles = mutableListOf<RectangleContext>() // stores the central rectangles
for(rectangle in rightMatchRectangles) {
if(nearZero(rectangle.p1.x - contextMin,epsilon)) {
newMatchRectangles.add(rectangle)
} else { // split in 2
newMatchRectangles.add(RectangleContext(DoubleVector2D(contextMin,rectangle.p1.y), rectangle.p2))
rectangleContextsToAdd.add(RectangleContext(rectangle.p1, DoubleVector2D(contextMin,rectangle.p2.y)))
}
}
return newMatchRectangles
}
val iterLeft = leftRectangles.iterator()
val iterRight = rightRectangles.iterator()
var left: RectangleContext = iterLeft.next()
var right: RectangleContext = iterRight.next()
val leftMatchRectangles = mutableListOf<RectangleContext>()
val rightMatchRectangles = mutableListOf<RectangleContext>()
while (true) {
while (left.p1.y < right.p1.y - epsilon && iterLeft.hasNext()) left = iterLeft.next()
while (right.p1.y < left.p1.y - epsilon && iterRight.hasNext()) right = iterRight.next()
if(nearZero(left.p1.y - right.p1.y,epsilon)) {
leftMatchRectangles.add(left)
rightMatchRectangles.add(right)
while (left.p2.y < right.p2.y - epsilon && iterLeft.hasNext()) {
val leftPrevious = left
left = iterLeft.next()
if (!nearZero(leftPrevious.p2.y - left.p1.y, epsilon)) break
leftMatchRectangles.add(left)
}
while (right.p2.y < left.p2.y - epsilon && iterRight.hasNext()) {
val rightPrevious = right
right = iterRight.next()
if (!nearZero(rightPrevious.p2.y - right.p1.y, epsilon)) break
rightMatchRectangles.add(right)
}
if(nearZero(leftMatchRectangles.last().p2.y - rightMatchRectangles.last().p2.y,epsilon)) {
var contextMinLeft = Double.MIN_VALUE
var contextMaxLeft = Double.MAX_VALUE
for(leftRectangle in rightMatchRectangles) {
if (leftRectangle.p1.x > contextMinLeft) contextMinLeft = leftRectangle.p1.x
if (leftRectangle.p1.x < contextMaxLeft) contextMaxLeft = leftRectangle.p1.x
}
var contextMinRight = Double.MAX_VALUE
var contextMaxRight = Double.MIN_VALUE
for(rightRectangle in leftMatchRectangles) {
if (rightRectangle.p2.x < contextMinRight) contextMinRight = rightRectangle.p2.x
if (rightRectangle.p2.x > contextMaxRight) contextMaxRight = rightRectangle.p2.x
}
rectangleContextsToDelete.addAll(leftMatchRectangles)
rectangleContextsToDelete.addAll(rightMatchRectangles)
rectangleContextsToAdd.add(mergeRectangles(
normalizeLeftRectangles(leftMatchRectangles, contextMinRight, contextMaxRight), // leftRectangles are in the right side of the merge
normalizeRightRectangles(rightMatchRectangles, contextMinLeft, contextMaxLeft))) // rightRectangles are in the left side of the merge
}
if(iterLeft.hasNext()) {
if(left == leftMatchRectangles.last()) left = iterLeft.next()
} else
break
if(iterRight.hasNext()) {
if(right == rightMatchRectangles.last()) right = iterRight.next()
} else
break
} else if(left.p1.y < right.p1.y) {
if(iterLeft.hasNext()) left = iterLeft.next() else break
} else {
if(iterRight.hasNext()) right = iterRight.next() else break
}
leftMatchRectangles.clear()
rightMatchRectangles.clear()
}
}
fun mergeNeighborsBottomAndTop(
bottomRectangles: ObjectAVLTreeSet<RectangleContext>,
topRectangles: ObjectAVLTreeSet<RectangleContext>,
rectangleContextsToAdd: MutableList<RectangleContext>,
rectangleContextsToDelete: MutableList<RectangleContext>) {
fun normalizeBottomRectangles(matchRectangles: MutableList<RectangleContext>,contextMin: Double, contextMax: Double): MutableList<RectangleContext> {
// bottom rectangles are to the top of the merge
//
if(nearZero(contextMin - contextMax,epsilon)) // all contexts with same width
return matchRectangles
val newMatchRectangles = mutableListOf<RectangleContext>() // stores the central rectangles
for(rectangle in matchRectangles) {
if(nearZero(rectangle.p2.y - contextMin,epsilon)) {
newMatchRectangles.add(rectangle)
} else { // split in 2
newMatchRectangles.add(RectangleContext(rectangle.p1, DoubleVector2D(rectangle.p2.x, contextMin)))
rectangleContextsToAdd.add(RectangleContext(DoubleVector2D(rectangle.p1.x, contextMin), rectangle.p2))
}
}
return newMatchRectangles
}
fun normalizeTopRectangles(topMatchRectangles: MutableList<RectangleContext>,contextMin: Double, contextMax: Double): MutableList<RectangleContext> {
// top rectangles are to the bottom of the merge
//
if(nearZero(contextMin - contextMax,epsilon)) // all contexts with same width
return topMatchRectangles
val newMatchRectangles = mutableListOf<RectangleContext>() // stores the central rectangles
for(rectangle in topMatchRectangles) {
if(nearZero(rectangle.p1.y - contextMin,epsilon)) {
newMatchRectangles.add(rectangle)
} else { // split in 2
newMatchRectangles.add(RectangleContext(DoubleVector2D(rectangle.p1.x,contextMin), rectangle.p2))
rectangleContextsToAdd.add(RectangleContext(rectangle.p1, DoubleVector2D(rectangle.p2.x,contextMin)))
}
}
return newMatchRectangles
}
val iterBottom = bottomRectangles.iterator()
val iterTop = topRectangles.iterator()
var bottom: RectangleContext = iterBottom.next()
var top: RectangleContext = iterTop.next()
val bottomMatchRectangles = mutableListOf<RectangleContext>()
val topMatchRectangles = mutableListOf<RectangleContext>()
while (true) {
while (bottom.p1.x < top.p1.x - epsilon && iterBottom.hasNext()) bottom = iterBottom.next()
while (top.p1.x < bottom.p1.x - epsilon && iterTop.hasNext()) top = iterTop.next()
if(nearZero(bottom.p1.x - top.p1.x,epsilon)) {
bottomMatchRectangles.add(bottom)
topMatchRectangles.add(top)
while (bottom.p2.x < top.p2.x - epsilon && iterBottom.hasNext()) {
val bottomPrevious = bottom
bottom = iterBottom.next()
if (!nearZero(bottomPrevious.p2.x - bottom.p1.x, epsilon)) break
bottomMatchRectangles.add(bottom)
}
while (top.p2.x < bottom.p2.x - epsilon && iterTop.hasNext()) {
val topPrevious = top
top = iterTop.next()
if (!nearZero(topPrevious.p2.x - top.p1.x, epsilon)) break
topMatchRectangles.add(top)
}
if(nearZero(bottomMatchRectangles.last().p2.x - topMatchRectangles.last().p2.x,epsilon)) {
var contextMinBottom = Double.MIN_VALUE
var contextMaxBottom = Double.MAX_VALUE
for(bottomRectangle in topMatchRectangles) {
if (bottomRectangle.p1.y > contextMinBottom) contextMinBottom = bottomRectangle.p1.y
if (bottomRectangle.p1.y < contextMaxBottom) contextMaxBottom = bottomRectangle.p1.y
}
var contextMinTop = Double.MAX_VALUE
var contextMaxTop = Double.MIN_VALUE
for(topRectangle in bottomMatchRectangles) {
if (topRectangle.p2.y < contextMinTop) contextMinTop = topRectangle.p2.y
if (topRectangle.p2.y > contextMaxTop) contextMaxTop = topRectangle.p2.y
}
rectangleContextsToDelete.addAll(bottomMatchRectangles)
rectangleContextsToDelete.addAll(topMatchRectangles)
rectangleContextsToAdd.add(mergeRectangles(
normalizeBottomRectangles(bottomMatchRectangles, contextMinTop, contextMaxTop), // bottomRectangles are in the top side of the merge
normalizeTopRectangles(topMatchRectangles, contextMinBottom, contextMaxBottom))) // topRectangles are in the bottom side of the merge
}
if(iterBottom.hasNext()) {
if(bottom == bottomMatchRectangles.last()) bottom = iterBottom.next()
} else
break
if(iterTop.hasNext()) {
if(top == topMatchRectangles.last()) top = iterTop.next()
} else
break
} else if(bottom.p1.x < top.p1.x) {
if(iterBottom.hasNext()) bottom = iterBottom.next() else break
} else {
if(iterTop.hasNext()) top = iterTop.next() else break
}
bottomMatchRectangles.clear()
topMatchRectangles.clear()
}
}
fun mergeNeighbors(rectContextsByLow: Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>,
rectContextsByHigh: Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>,
mergeNeighborsLowHigh: (lowRectangles: ObjectAVLTreeSet<RectangleContext>,
highRectangles: ObjectAVLTreeSet<RectangleContext>,
rectangleContextsToAdd: MutableList<RectangleContext>,
rectangleContextsToDelete: MutableList<RectangleContext>) -> Unit) {
val iterLow = rectContextsByLow.double2ReferenceEntrySet().iterator()
val iterHigh = rectContextsByHigh.double2ReferenceEntrySet().iterator()
var low: Map.Entry<Double,ObjectAVLTreeSet<RectangleContext>>
var high: Map.Entry<Double,ObjectAVLTreeSet<RectangleContext>>
val rectangleContextsToAdd = mutableListOf<RectangleContext>()
val rectangleContextsToDelete = mutableListOf<RectangleContext>()
while (iterLow.hasNext() && iterHigh.hasNext()) {
low = iterLow.next()
high = iterHigh.next()
while ((low.value.isEmpty() || low.key < high.key - epsilon) && iterLow.hasNext()) low = iterLow.next()
while ((high.value.isEmpty() || high.key < low.key - epsilon) && iterHigh.hasNext()) high = iterHigh.next()
if (!low.value.isEmpty() && !high.value.isEmpty() && nearZero(low.key - high.key, epsilon))
mergeNeighborsLowHigh(low.value, high.value, rectangleContextsToAdd, rectangleContextsToDelete)
for (rect in rectangleContextsToDelete) {
rectContextsByBottom.get(rect.p1.y)?.remove(rect)
rectContextsByTop.get(rect.p2.y)?.remove(rect)
rectContextsByLeft.get(rect.p1.x)?.remove(rect)
rectContextsByRight.get(rect.p2.x)?.remove(rect)
}
size -= rectangleContextsToDelete.size
rectangleContextsToDelete.clear()
}
size += rectangleContextsToAdd.size
for (rect in rectangleContextsToAdd) {
addTo(rect.p1.y, rect, rectContextsByBottom, SimpleCompareDoubleRectangle2DXY)
addTo(rect.p2.y, rect, rectContextsByTop, SimpleCompareDoubleRectangle2DXY)
addTo(rect.p1.x, rect, rectContextsByLeft, SimpleCompareDoubleRectangle2DYX)
addTo(rect.p2.x, rect, rectContextsByRight, SimpleCompareDoubleRectangle2DYX)
}
}
fun setNeighbors(
rectContextsByLow: Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>,
rectContextsByHigh: Double2ReferenceAVLTreeMap<ObjectAVLTreeSet<RectangleContext>>,
xOrY: Int,
side: Side,
intersects: (b: RectangleContext, a: RectangleContext) -> Boolean) {
fun setNeighbors(
lowRectangles: ObjectAVLTreeSet<RectangleContext>,
highRectangles: ObjectAVLTreeSet<RectangleContext>) {
val iterLow = lowRectangles.iterator()
val iterHigh = highRectangles.iterator()
var low: RectangleContext = iterLow.next()
var high: RectangleContext = iterHigh.next()
while (true) {
//println("setNeighbors $side inner low = ${low.toStringLess()} high = ${high.toStringLess()}")
while (low.p2[xOrY] < high.p1[xOrY] - epsilon && iterLow.hasNext()) {
low = iterLow.next()
//println("setNeighbors $side inner (low.p2[$xOrY] < high.p1[$xOrY]) low = $${low.toStringLess()} high = ${high.toStringLess()}")
}
while (high.p2[xOrY] < low.p1[xOrY] - epsilon && iterHigh.hasNext()) {
high = iterHigh.next()
//println("setNeighbors $side inner (high.p2[$xOrY] < low.p1[$xOrY]) low = $${low.toStringLess()} high = ${high.toStringLess()}")
}
if(intersects(high,low)) low.add(high,side)
if(low.p2[xOrY] < high.p2[xOrY] - epsilon) {
if(iterLow.hasNext()) {
low = iterLow.next()
//println("setNeighbors $side inner (low.p2[$xOrY] < high.p2[$xOrY]) low = $${low.toStringLess()} high = ${high.toStringLess()}")
} else break
}
else if(high.p2[xOrY] < low.p2[xOrY] - epsilon){
if(iterHigh.hasNext()) {
high = iterHigh.next()
//println("setNeighbors $side inner (high.p2[$xOrY] < low.p2[$xOrY]) low = $${low.toStringLess()} high = ${high.toStringLess()}")
} else break
} else {
if(iterLow.hasNext()) {
low = iterLow.next()
//println("setNeighbors $side inner (else) low = $${low.toStringLess()} high = ${high.toStringLess()}")
} else break
if(iterHigh.hasNext()) {
high = iterHigh.next()
//println("setNeighbors $side inner (else) low = $${low.toStringLess()} high = ${high.toStringLess()}")
} else break
}
}
}
val iterLow = rectContextsByLow.iterator()
val iterHigh = rectContextsByHigh.iterator()
var low = iterLow.next()
var high = iterHigh.next()
//println("setNeighbors $side low.first.key = ${rectContextsByLow.keys.firstDouble()} low.last.key = ${rectContextsByLow.keys.lastDouble()}")
//println("setNeighbors $side high.first.key = ${rectContextsByHigh.keys.firstDouble()} high.last.key = ${rectContextsByHigh.keys.lastDouble()}")
while (true) {
//println("setNeighbors $side low.key = ${low.key} high.key = ${high.key}")
while (low.key < high.key - epsilon) {
if(iterLow.hasNext()) low = iterLow.next() else break
//println("setNeighbors $side (low.key < high.key) low.key = ${low.key} high.key = ${high.key}")
}
while (high.key < low.key - epsilon) {
if(iterHigh.hasNext()) high = iterHigh.next() else break
//println("setNeighbors $side (high.key < low.key) low.key = ${low.key} high.key = ${high.key}")
}
if(nearZero(low.key - high.key, epsilon)) {
if (!low.value.isEmpty() && !high.value.isEmpty()) setNeighbors(low.value, high.value)
if(iterLow.hasNext()) low = iterLow.next() else break
if(iterHigh.hasNext()) high = iterHigh.next() else break
} else if(low.key < high.key) {
if(iterLow.hasNext()) low = iterLow.next() else break
} else {
if(iterHigh.hasNext()) high = iterHigh.next() else break
}
}
}
for(rect in rectContexts) {
addTo(rect.p1.y, rect,rectContextsByBottom,SimpleCompareDoubleRectangle2DXY)
addTo(rect.p2.y, rect,rectContextsByTop,SimpleCompareDoubleRectangle2DXY)
addTo(rect.p1.x, rect,rectContextsByLeft,SimpleCompareDoubleRectangle2DYX)
addTo(rect.p2.x, rect,rectContextsByRight,SimpleCompareDoubleRectangle2DYX)
size += 1
}
println("result begin size = $size")
var previousSize: Int
var iterations = 0
do {
//println("result size = ${rectContextsByLeft.flatMap { it.value }.size} iterations = $iterations")
previousSize = size
mergeNeighbors(rectContextsByLeft,rectContextsByRight,::mergeNeighborsLeftAndRight)
mergeNeighbors(rectContextsByBottom,rectContextsByTop,::mergeNeighborsBottomAndTop)
//println("result end size = ${result.size}\n ${result.map { it.toStringLess() }}")
//println("result end size = $size")
iterations += 1
} while (previousSize > size + minDiff && iterations < maxIterations)
println("result end size = $size iterations = $iterations")
setNeighbors(rectContextsByLeft,rectContextsByRight,1,Side.LEFT,::intersectsY)
setNeighbors(rectContextsByBottom,rectContextsByTop,0,Side.BOTTOM,::intersectsX)
return rectContextsByLeft.flatMap { it.value }
}
| mit | ac632d8f699512fa9303b7a649f9829e | 44.446996 | 267 | 0.60199 | 4.00545 | false | false | false | false |
msebire/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/reportUtils.kt | 1 | 12178 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images.sync
import java.io.File
import java.util.*
import java.util.stream.Collectors
import java.util.stream.Stream
import kotlin.streams.toList
internal fun report(context: Context, skipped: Int): String {
val (devIcons, icons) = context.devIcons.size to context.icons.size
log("Skipped $skipped dirs")
fun Collection<String>.logIcons(description: String) = "$size $description${if (size < 100) ": ${joinToString()}" else ""}"
@Suppress("Duplicates")
var report = when {
context.iconsCommitHashesToSync.isNotEmpty() -> """
|${context.iconsRepoName} commits ${context.iconsCommitHashesToSync.joinToString()} are synced into ${context.devRepoName}:
| ${context.byDesigners.added.logIcons("added")}
| ${context.byDesigners.removed.logIcons("removed")}
| ${context.byDesigners.modified.logIcons("modified")}
""".trimMargin()
context.devIconsCommitHashesToSync.isNotEmpty() -> """
|${context.devRepoName} commits ${context.devIconsCommitHashesToSync.joinToString()} are synced into ${context.iconsRepoName}:
| ${context.byDev.added.logIcons("added")}
| ${context.byDev.removed.logIcons("removed")}
| ${context.byDev.modified.logIcons("modified")}
""".trimMargin()
else -> """
|$devIcons icons are found in ${context.devRepoName}:
| ${context.byDev.added.logIcons("added")}
| ${context.byDev.removed.logIcons("removed")}
| ${context.byDev.modified.logIcons("modified")}
|$icons icons are found in ${context.iconsRepoName}:
| ${context.byDesigners.added.logIcons("added")}
| ${context.byDesigners.removed.logIcons("removed")}
| ${context.byDesigners.modified.logIcons("modified")}
|${context.consistent.size} consistent icons in both repos
""".trimMargin()
}
if (context.createdReviews.isNotEmpty()) {
report += "\nCreated reviews: ${context.createdReviews.joinToString { it.url }}"
}
return report
}
internal fun findCommitsToSync(context: Context) {
if (context.doSyncDevRepo && context.devSyncRequired()) {
context.iconsCommitsToSync = findCommitsByRepo(context, UPSOURCE_DEV_PROJECT_ID, context.iconsRepoDir, context.byDesigners)
}
if (context.doSyncIconsRepo && context.iconsSyncRequired()) {
context.devCommitsToSync = findCommitsByRepo(context, UPSOURCE_ICONS_PROJECT_ID, context.devRepoDir, context.byDev)
}
}
private fun Map<File, Collection<CommitInfo>>.commitMessage() = "Synchronization of changed icons from ${entries.joinToString { entry ->
"${getOriginUrl(entry.key)}: ${entry.value.joinToString { it.hash }}"
}}"
private fun withTmpBranch(repos: Collection<File>, master: String, action: (String) -> Review?): Review? {
val branch = "icons-sync/${UUID.randomUUID()}"
return try {
action(branch)
}
catch (e: Throwable) {
repos.parallelStream().forEach {
deleteBranch(it, branch)
}
throw e
}
finally {
repos.parallelStream().forEach {
callSafely {
checkout(it, master)
}
}
}
}
private fun createReviewForDev(context: Context, user: String, email: String): Review? {
if (context.iconsCommitsToSync.isEmpty()) return null
val repos = context.iconsChanges().map {
findRepo(context.devRepoRoot.resolve(it))
}.distinct()
verifyDevIcons(context, repos)
if (repos.all { gitStage(it).isEmpty() }) {
log("Nothing to commit")
context.byDesigners.clear()
return null
}
val master = repos.parallelStream().map(::head).collect(Collectors.toSet()).single()
return withTmpBranch(repos, master) { branch ->
val commitsForReview = commitAndPush(branch, user, email, context.iconsCommitsToSync.commitMessage(), repos)
val projectId = UPSOURCE_DEV_PROJECT_ID
if (projectId.isNullOrEmpty()) {
log("WARNING: unable to create Upsource review for ${context.devRepoName}, just plain old branch review")
PlainOldReview(branch, projectId)
}
else {
val review = createReview(projectId, branch, master, commitsForReview)
try {
addReviewer(projectId, review, triggeredBy() ?: DEFAULT_INVESTIGATOR)
postVerificationResultToReview(review)
review
}
catch (e: Exception) {
closeReview(projectId, review)
throw e
}
}
}
}
private fun verifyDevIcons(context: Context, repos: Collection<File>) {
callSafely {
context.verifyDevIcons(repos)
}
repos.forEach { repo ->
val status = gitStatus(repo)
if (status.isNotEmpty()) {
log("Staging ${status.joinToString("," + System.lineSeparator()) {
repo.resolve(it).toString()
}}")
status.forEach {
stageFiles(listOf(it), repo)
}
log("Staged: " + gitStage(repo))
}
}
}
private fun postVerificationResultToReview(review: Review) {
val runConfigurations = System.getProperty("sync.dev.icons.checks")?.splitNotBlank(";") ?: return
postComment(UPSOURCE_DEV_PROJECT_ID, review,
"Following configurations were run: ${runConfigurations.joinToString()}, see build ${thisBuildReportableLink()}")
}
private fun createReviewForIcons(context: Context, user: String, email: String): Collection<Review> {
if (context.devCommitsToSync.isEmpty()) return emptyList()
val repos = listOf(context.iconsRepo)
val master = head(context.iconsRepo)
return context.devCommitsToSync.values.flatten()
.groupBy(CommitInfo::committerEmail)
.entries.map {
val (committer, commits) = it
withTmpBranch(repos, master) { branch ->
commits.forEach { commit ->
val change = context.byCommit[commit.hash] ?: error("Unable to find changes for commit ${commit.hash} by $committer")
log("[$committer] syncing ${commit.hash} in ${context.iconsRepoName}")
syncIconsRepo(context, change)
}
if (gitStage(context.iconsRepo).isEmpty()) {
log("Nothing to commit")
context.byDev.clear()
null
}
else {
val commitsForReview = commitAndPush(branch, user, email, commits.groupBy(CommitInfo::repo).commitMessage(), repos)
val review = createReview(UPSOURCE_ICONS_PROJECT_ID, branch, master, commitsForReview)
addReviewer(UPSOURCE_ICONS_PROJECT_ID, review, committer)
review
}
}
}.filter(Objects::nonNull).map { it as Review }.toList()
}
internal fun createReviews(context: Context) = callSafely {
val (user, email) = System.getProperty("upsource.user.name") to System.getProperty("upsource.user.email")
context.createdReviews = Stream.of(
{ createReviewForDev(context, user, email)?.let { listOf(it) } ?: emptyList() },
{ createReviewForIcons(context, user, email) }
).parallel().flatMap { it().stream() }
.filter(Objects::nonNull)
.map { it as Review }
.toList()
}
internal fun assignInvestigation(context: Context): Investigator? =
callSafely {
var (investigator, commits) = if (context.iconsSyncRequired()) {
context.devCommitsToSync.flatMap { it.value }.maxBy(CommitInfo::timestamp)?.let { latest ->
log("Assigning investigation to ${latest.committerEmail} as author of latest change ${latest.hash}")
latest.committerEmail
} to context.devCommitsToSync
}
else triggeredBy() to context.iconsCommitsToSync
var reviews = emptyList<String>()
if (commits.isEmpty()) {
if (context.commitsAlreadyInReview.isEmpty()) {
log("No commits, no investigation")
return@callSafely null
}
context.commitsAlreadyInReview.keys.maxBy(CommitInfo::timestamp)?.let { latest ->
val review = context.commitsAlreadyInReview[latest]!!
log("Assigning investigation to ${latest.committerEmail} as author of latest change ${latest.hash} under review $review")
investigator = latest.committerEmail
commits = context.commitsAlreadyInReview.keys
.filter { context.commitsAlreadyInReview[it] == review }
.groupBy(CommitInfo::repo)
reviews += review
}
}
if (context.iconsSyncRequired() && context.iconsReviews().isNotEmpty()) {
reviews += context.iconsReviews().map(Review::url)
}
if (context.devReviews().isNotEmpty()) {
reviews += context.devReviews().map(Review::url)
}
assignInvestigation(Investigator(investigator ?: DEFAULT_INVESTIGATOR, commits), context, reviews)
}
private fun findCommitsByRepo(context: Context, projectId: String?, root: File, changes: Changes
): Map<File, Collection<CommitInfo>> {
var changesAlreadyInReview = emptyList<String>()
var commits = findCommits(context, root, changes)
if (commits.isEmpty()) return emptyMap()
val reviewTitles = if (!projectId.isNullOrEmpty()) {
getOpenIconsReviewTitles(projectId)
}
else emptyMap()
val before = commits.size
commits = commits.filter { entry ->
val (commit, change) = entry
reviewTitles.entries.firstOrNull {
// review with commit
it.value.contains(commit.hash)
}?.also {
changesAlreadyInReview += change
context.commitsAlreadyInReview += commit to it.key
} == null
}
log("$projectId: ${before - commits.size} commits already in review")
changesAlreadyInReview
.map(root::resolve)
.map {
val repo = findRepo(it)
repo to it.toRelativeString(repo)
}
.groupBy({ it.first }, { it.second })
.forEach {
val (repo, skipped) = it
log("Already in review, skipping: $skipped")
unStageFiles(skipped, repo)
}
log("$projectId: ${commits.size} commits found")
return commits.map { it.key }.groupBy(CommitInfo::repo)
}
@Volatile
private var reposMap = emptyMap<File, File>()
private val reposMapGuard = Any()
internal fun findRepo(file: File): File {
if (!reposMap.containsKey(file)) synchronized(reposMapGuard) {
if (!reposMap.containsKey(file)) {
reposMap += file to findGitRepoRoot(file, silent = true)
}
}
return reposMap[file]!!
}
private fun findCommits(context: Context, root: File, changes: Changes) = changes.all()
.mapNotNull { change ->
val absoluteFile = root.resolve(change)
val repo = findRepo(absoluteFile)
val commit = latestChangeCommit(absoluteFile.toRelativeString(repo), repo)
if (commit != null) commit to change else null
}.onEach {
val commit = it.first.hash
val change = it.second
if (!context.byCommit.containsKey(commit)) context.byCommit[commit] = Changes(changes.includeRemoved)
val commitChange = context.byCommit[commit]!!
when {
changes.added.contains(change) -> commitChange.added += change
changes.modified.contains(change) -> commitChange.modified += change
changes.removed.contains(change) -> commitChange.removed += change
}
}.groupBy({ it.first }, { it.second })
private fun commitAndPush(branch: String,
user: String,
email: String,
message: String,
repos: Collection<File>) = repos.parallelStream().map {
withUser(it, user, email) {
commitAndPush(it, branch, message)
}
}.toList()
internal fun sendNotification(investigator: Investigator?, context: Context) {
callSafely {
if (isNotificationRequired(context)) {
notifySlackChannel(investigator, context)
}
}
}
private val CHANNEL_WEB_HOOK = System.getProperty("intellij.icons.slack.channel")
private fun notifySlackChannel(investigator: Investigator?, context: Context) {
val investigation = when {
investigator == null -> ""
investigator.isAssigned -> "Investigation is assigned to ${investigator.email}\n"
else -> "Unable to assign investigation to ${investigator.email}\n"
}
val reaction = if (context.isFail()) ":scream:" else ":white_check_mark:"
val build = "See <${thisBuildReportableLink()}|build log>"
val text = "*${context.devRepoName}* $reaction\n" + investigation + build
val response = post(CHANNEL_WEB_HOOK, """{ "text": "$text" }""")
if (response != "ok") error("$CHANNEL_WEB_HOOK responded with $response")
} | apache-2.0 | d79036a801bd22e9799936298a373418 | 38.414239 | 140 | 0.68205 | 4.064753 | false | false | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/db/AccountManager.kt | 1 | 6100 | /* Copyright 2018 Conny Duck
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky.db
import android.util.Log
import com.keylesspalace.tusky.entity.Account
import com.keylesspalace.tusky.entity.Status
/**
* This class caches the account database and handles all account related operations
* @author ConnyDuck
*/
private const val TAG = "AccountManager"
class AccountManager(db: AppDatabase) {
@Volatile
var activeAccount: AccountEntity? = null
private var accounts: MutableList<AccountEntity> = mutableListOf()
private val accountDao: AccountDao = db.accountDao()
init {
accounts = accountDao.loadAll().toMutableList()
activeAccount = accounts.find { acc ->
acc.isActive
}
}
/**
* Adds a new empty account and makes it the active account.
* More account information has to be added later with [updateActiveAccount]
* or the account wont be saved to the database.
* @param accessToken the access token for the new account
* @param domain the domain of the accounts Mastodon instance
*/
fun addAccount(accessToken: String, domain: String) {
activeAccount?.let {
it.isActive = false
Log.d(TAG, "addAccount: saving account with id " + it.id)
accountDao.insertOrReplace(it)
}
val maxAccountId = accounts.maxBy { it.id }?.id ?: 0
val newAccountId = maxAccountId + 1
activeAccount = AccountEntity(id = newAccountId, domain = domain.toLowerCase(), accessToken = accessToken, isActive = true)
}
/**
* Saves an already known account to the database.
* New accounts must be created with [addAccount]
* @param account the account to save
*/
fun saveAccount(account: AccountEntity) {
if (account.id != 0L) {
Log.d(TAG, "saveAccount: saving account with id " + account.id)
accountDao.insertOrReplace(account)
}
}
/**
* Logs the current account out by deleting all data of the account.
* @return the new active account, or null if no other account was found
*/
fun logActiveAccountOut(): AccountEntity? {
if (activeAccount == null) {
return null
} else {
accounts.remove(activeAccount!!)
accountDao.delete(activeAccount!!)
if (accounts.size > 0) {
accounts[0].isActive = true
activeAccount = accounts[0]
Log.d(TAG, "logActiveAccountOut: saving account with id " + accounts[0].id)
accountDao.insertOrReplace(accounts[0])
} else {
activeAccount = null
}
return activeAccount
}
}
/**
* updates the current account with new information from the mastodon api
* and saves it in the database
* @param account the [Account] object returned from the api
*/
fun updateActiveAccount(account: Account) {
activeAccount?.let {
it.accountId = account.id
it.username = account.username
it.displayName = account.name
it.profilePictureUrl = account.avatar
it.defaultPostPrivacy = account.source?.privacy ?: Status.Visibility.PUBLIC
it.defaultMediaSensitivity = account.source?.sensitive ?: false
it.emojis = account.emojis ?: emptyList()
Log.d(TAG, "updateActiveAccount: saving account with id " + it.id)
it.id = accountDao.insertOrReplace(it)
val accountIndex = accounts.indexOf(it)
if (accountIndex != -1) {
//in case the user was already logged in with this account, remove the old information
accounts.removeAt(accountIndex)
accounts.add(accountIndex, it)
} else {
accounts.add(it)
}
}
}
/**
* changes the active account
* @param accountId the database id of the new active account
*/
fun setActiveAccount(accountId: Long) {
activeAccount?.let {
Log.d(TAG, "setActiveAccount: saving account with id " + it.id)
it.isActive = false
saveAccount(it)
}
activeAccount = accounts.find { acc ->
acc.id == accountId
}
activeAccount?.let {
it.isActive = true
accountDao.insertOrReplace(it)
}
}
/**
* @return an immutable list of all accounts in the database with the active account first
*/
fun getAllAccountsOrderedByActive(): List<AccountEntity> {
val accountsCopy = accounts.toMutableList()
accountsCopy.sortWith(Comparator { l, r ->
when {
l.isActive && !r.isActive -> -1
r.isActive && !l.isActive -> 1
else -> 0
}
})
return accountsCopy
}
/**
* @return true if at least one account has notifications enabled
*/
fun areNotificationsEnabled(): Boolean {
return accounts.any { it.notificationsEnabled }
}
/**
* Finds an account by its database id
* @param accountId the id of the account
* @return the requested account or null if it was not found
*/
fun getAccountById(accountId: Long): AccountEntity? {
return accounts.find { acc ->
acc.id == accountId
}
}
} | gpl-3.0 | 77c256a272dbe1e7e2f10b15a0490003 | 30.611399 | 131 | 0.614754 | 4.710425 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/usb/HoneyCombMr1Communication.kt | 2 | 2761 | package me.jahnen.libaums.core.usb
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import java.io.IOException
import java.nio.ByteBuffer
/**
* On Android API level lower 18 (Jelly Bean MR2) we cannot specify a start
* offset in the source/destination array. Because of that we have to use
* this workaround, where we have to copy the data every time offset is non
* zero.
*
* @author mjahnen
*/
internal class HoneyCombMr1Communication(
usbManager: UsbManager,
usbDevice: UsbDevice,
usbInterface: UsbInterface,
outEndpoint: UsbEndpoint,
inEndpoint: UsbEndpoint
) : AndroidUsbCommunication(usbManager, usbDevice, usbInterface, outEndpoint, inEndpoint) {
@Throws(IOException::class)
override fun bulkOutTransfer(src: ByteBuffer): Int {
val offset = src.position()
if (offset == 0) {
val result = deviceConnection!!.bulkTransfer(outEndpoint,
src.array(), src.remaining(), UsbCommunication.TRANSFER_TIMEOUT)
if (result == -1) {
throw IOException("Could not write to device, result == -1")
}
src.position(src.position() + result)
return result
}
val tmpBuffer = ByteArray(src.remaining())
System.arraycopy(src.array(), offset, tmpBuffer, 0, src.remaining())
val result = deviceConnection!!.bulkTransfer(outEndpoint,
tmpBuffer, src.remaining(), UsbCommunication.TRANSFER_TIMEOUT)
if (result == -1) {
throw IOException("Could not write to device, result == -1")
}
src.position(src.position() + result)
return result
}
@Throws(IOException::class)
override fun bulkInTransfer(dest: ByteBuffer): Int {
val offset = dest.position()
if (offset == 0) {
val result = deviceConnection!!.bulkTransfer(inEndpoint,
dest.array(), dest.remaining(), UsbCommunication.TRANSFER_TIMEOUT)
if (result == -1) {
throw IOException("Could read from to device, result == -1")
}
dest.position(dest.position() + result)
return result
}
val tmpBuffer = ByteArray(dest.remaining())
val result = deviceConnection!!.bulkTransfer(inEndpoint, tmpBuffer, dest.remaining(), UsbCommunication.TRANSFER_TIMEOUT)
if (result == -1) {
throw IOException("Could not read from device, result == -1")
}
System.arraycopy(tmpBuffer, 0, dest.array(), offset, result)
dest.position(dest.position() + result)
return result
}
}
| apache-2.0 | 4b290fd70814adc699ebd03cb08a2a5c | 32.26506 | 128 | 0.632742 | 4.474878 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/MessageActivityBase.kt | 1 | 4117 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel
import nl.adaptivity.process.util.Identifiable
abstract class MessageActivityBase(
builder: MessageActivity.Builder,
newOwner: ProcessModel<*>,
otherNodes: Iterable<ProcessNode.Builder>
) : ActivityBase(builder, newOwner, otherNodes), MessageActivity {
private var _message: XmlMessage?
final override var message: IXmlMessage?
get() = _message
private set(value) {
_message = XmlMessage.from(value)
}
init {
_message = XmlMessage.from(builder.message)
}
override fun builder(): MessageActivity.Builder = Builder(this)
override fun <R> visit(visitor: ProcessNode.Visitor<R>): R = visitor.visitActivity(this)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
if (!super.equals(other)) return false
other as MessageActivityBase
if (_message != other._message) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (_message?.hashCode() ?: 0)
return result
}
open class Builder : BaseBuilder, MessageActivity.Builder {
final override var message: IXmlMessage?
constructor(): this(
null,
null,
null,
null,
null,
null,
null,
null,
null,
Double.NaN,
Double.NaN,
false
)
constructor(
id: String?,
predecessor: Identifiable?,
successor: Identifiable?,
label: String?,
defines: Collection<IXmlDefineType>?,
results: Collection<IXmlResultType>?,
message: XmlMessage?,
condition: Condition?,
name: String?,
x: Double,
y: Double,
isMultiInstance: Boolean
) : super(
id,
predecessor,
successor,
label,
defines,
results,
condition,
name,
x,
y,
isMultiInstance
) {
this.message = message
}
// @Suppress("DEPRECATION")
constructor(activity: MessageActivity) : this(
activity.id,
activity.predecessor,
activity.successor,
activity.label,
activity.defines,
activity.results,
XmlMessage.from(activity.message),
activity.condition,
activity.name,
activity.x,
activity.y,
activity.isMultiInstance
)
constructor(serialDelegate: SerialDelegate) : this(
id = serialDelegate.id,
predecessor = serialDelegate.predecessor,
successor = null,
label = serialDelegate.label,
defines = serialDelegate.defines,
results = serialDelegate.results,
message = XmlMessage.from(serialDelegate.message),
condition = serialDelegate.elementCondition,
name = serialDelegate.name,
x = serialDelegate.x,
y = serialDelegate.y,
isMultiInstance = serialDelegate.isMultiInstance
)
}
}
| lgpl-3.0 | 59c471e9909ba03109fe4ce1d82991ac | 27.992958 | 112 | 0.580277 | 5.063961 | false | false | false | false |
PrivacyStreams/PrivacyStreams | privacystreams-app/src/main/java/io/github/privacystreams/app/db/TableBgAudio.kt | 2 | 4014 | package io.github.privacystreams.app.db
import android.Manifest
import android.content.ContentValues
import android.util.Log
import io.github.privacystreams.app.Config
import io.github.privacystreams.app.R
import io.github.privacystreams.audio.Audio
import io.github.privacystreams.audio.AudioOperators
import io.github.privacystreams.core.Callback
import io.github.privacystreams.core.Item
import io.github.privacystreams.core.exceptions.PSException
import io.github.privacystreams.utils.StorageUtils
import io.github.privacystreams.utils.TimeUtils
import java.io.File
class TableBgAudio(dbHelper: PStreamDBHelper) : PStreamTable(dbHelper) {
companion object {
val TABLE_NAME = "BgAudio"
val ICON_RES_ID = R.drawable.microphone;
/* Fields */
val _ID = "_id" // Long
val TIME_CREATED = Audio.TIME_CREATED // Long
val AUDIO_PATH = "audio_path" // Long
}
override val tableName: String = TABLE_NAME
override val iconResId: Int = ICON_RES_ID
override val sqlCreateEntries = listOf<String>(
"CREATE TABLE $TABLE_NAME (" +
"$_ID INTEGER PRIMARY KEY," +
"$TIME_CREATED INTEGER," +
"$AUDIO_PATH TEXT)",
"CREATE INDEX ${TABLE_NAME}_time_created_index on $TABLE_NAME ($TIME_CREATED)"
)
override val sqlDeleteEntries = listOf<String>(
"DROP TABLE IF EXISTS $TABLE_NAME"
)
override fun collectStreamToTable() {
val db = dbHelper.writableDatabase
this.uqi.getData(Audio.recordPeriodic(Config.COLLECT_AUDIO_DURATION, Config.COLLECT_AUDIO_INTERVAL), this.purpose)
.setField("tempPath", AudioOperators.getFilepath(Audio.AUDIO_DATA))
.logAs(this.tableName)
.forEach(object : Callback<Item>() {
init {
addRequiredPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
override fun onInput(input: Item) {
val values = ContentValues()
try {
val tempPath : String = input.getValueByField("tempPath")
val tempFile = File(tempPath)
val audioPath = Config.DATA_DIR + "/audio_" + TimeUtils.getTimeTag() + ".amr"
val audioFile : File = StorageUtils.getValidFile(uqi.context, audioPath, true)
tempFile.copyTo(audioFile, true)
tempFile.delete()
values.put(AUDIO_PATH, audioFile.absolutePath)
} catch (e: Exception) {
Log.e(TABLE_NAME, "fail to write audio")
e.printStackTrace()
}
values.put(TIME_CREATED, input.getAsLong(Audio.TIME_CREATED))
db.insert(tableName, null, values)
increaseNumItems()
}
override fun onFail(exception: PSException) {
stopCollectService()
if (exception.isPermissionDenied) {
message.set("Denied")
}
}
})
}
class PROVIDER(): PStreamTableProvider() {
override fun provide() {
val dbHelper = PStreamDBHelper.getInstance(context)
val db = dbHelper.readableDatabase
val cur = db.query(TABLE_NAME, null, null, null, null, null, null)
while (cur.moveToNext()) {
val item = Item()
item.setFieldValue(TIME_CREATED, cur.getLong(cur.getColumnIndex(TIME_CREATED)))
item.setFieldValue(AUDIO_PATH, cur.getString(cur.getColumnIndex(AUDIO_PATH)))
output(item)
}
cur.close()
}
}
} | apache-2.0 | db631a77fe9f0a28065b17f2a3df1d4f | 39.969388 | 122 | 0.554808 | 4.744681 | false | false | false | false |
OpenWeen/OpenWeen.Droid | app/src/main/java/moe/tlaster/openween/core/model/user/UserModel.kt | 1 | 3056 | package moe.tlaster.openween.core.model.user
import android.os.Parcel
import android.os.Parcelable
import com.fasterxml.jackson.annotation.JsonProperty
import org.ocpsoft.prettytime.PrettyTime
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import moe.tlaster.openween.common.helpers.TimeHelper
/**
* Created by Tlaster on 2016/9/2.
*/
class UserModel : UserBaseModel() {
@field:JsonProperty("screen_name")
var screenName: String? = null
@field:JsonProperty("name")
var name: String? = null
@field:JsonProperty("remark")
var remark: String? = null
@field:JsonProperty("province")
var province: String? = null
@field:JsonProperty("city")
var city: String? = null
@field:JsonProperty("location")
var location: String? = null
@field:JsonProperty("description")
var description: String? = null
@field:JsonProperty("url")
var url: String? = null
@field:JsonProperty("profile_image_url")
var profileImageUrl: String? = null
@field:JsonProperty("domain")
var domain: String? = null
@field:JsonProperty("gender")
var gender: String? = null
@field:JsonProperty("favourites_count")
var favouritesCount = 0
@field:JsonProperty("verified_type")
var verifiedType: Int = 0
@field:JsonProperty("created_at")
var createdAt: String? = null
@field:JsonProperty("following")
var isFollowing = false
@field:JsonProperty("allow_all_act_msg")
var isAllowAllActMsg = false
@field:JsonProperty("geo_enabled")
var isGeoEnabled = false
@field:JsonProperty("verified")
var isVerified = false
@field:JsonProperty("allow_all_comment")
var isAllowAllComment = false
@field:JsonProperty("avatar_large")
var avatarLarge: String? = null
@field:JsonProperty("verified_reason")
var verifiedReason: String? = null
@field:JsonProperty("follow_me")
var isFollowMe = false
@field:JsonProperty("online_status")
var onlineStatus = 0
@field:JsonProperty("bi_followers_count")
var biFollowersCount = 0
@field:JsonProperty("cover_image")
var coverimage = ""
@field:JsonProperty("cover_image_phone")
var coverImagePhone: String? = null
@field:JsonProperty("avatar_hd")
var avatarHD: String? = null
@field:JsonProperty("weihao")
var weihao: String? = null
@field:JsonProperty("lang")
var lang: String? = null
@field:JsonProperty("level")
var level: Int = 0
val createdAtDiffForHuman: String
get() {
try {
return TimeHelper.prettyTime.format(TimeHelper.simpleDateFormat.parse(createdAt))
} catch (e: ParseException) {
e.printStackTrace()
}
return createdAt!!
}
val createdDate: Date?
get() {
try {
return TimeHelper.simpleDateFormat.parse(createdAt)
} catch (e: ParseException) {
return null
}
}
}
| mit | 29f5165b771a23fcc50223c9316bf4af | 28.669903 | 97 | 0.660013 | 4.124157 | false | false | false | false |
jcam3ron/cassandra-migration | src/test/java/com/builtamont/cassandra/migration/internal/command/BaselineKIT.kt | 1 | 14044 | /**
* File : BaselineKIT.kt
* License :
* Original - Copyright (c) 2015 - 2016 Contrast Security
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* 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.builtamont.cassandra.migration.internal.command
import com.builtamont.cassandra.migration.BaseKIT
import com.builtamont.cassandra.migration.CassandraMigration
import com.builtamont.cassandra.migration.api.CassandraMigrationException
import com.builtamont.cassandra.migration.api.MigrationVersion
import com.builtamont.cassandra.migration.internal.dbsupport.SchemaVersionDAO
/**
* Baseline command unit tests.
*/
class BaselineKIT : BaseKIT() {
init {
"Baseline command API" - {
"should mark at first migration script" - {
"with default table prefix" - {
"for session and keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.baseline()
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("1")
}
"for session and keyspace, version and description setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.baselineVersion = MigrationVersion.fromVersion("0.0.1")
cm.baselineDescription = "Baseline test"
cm.baseline()
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("0.0.1")
}
"for external session, but keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession()
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.baseline(session)
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("1")
}
"for external session and defaulted keyspace" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession(getKeyspace())
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.baseline(session)
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("1")
}
}
"with user-defined table prefix" - {
"for session and keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.baseline()
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), cm.tablePrefix + MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("1")
}
"for session and keyspace, version and description setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.baselineVersion = MigrationVersion.fromVersion("0.0.1")
cm.baselineDescription = "Baseline test"
cm.baseline()
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), cm.tablePrefix + MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("0.0.1")
}
"for external session, but keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession()
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.baseline(session)
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), cm.tablePrefix + MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("1")
}
"for external session and defaulted keyspace" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession(getKeyspace())
val cm = CassandraMigration()
cm.locations = scriptsLocations
cm.tablePrefix = "test1_"
cm.baseline(session)
val schemaVersionDAO = SchemaVersionDAO(getSession(), getKeyspace(), cm.tablePrefix + MigrationVersion.CURRENT.table)
val baselineMarker = schemaVersionDAO.baselineMarker
baselineMarker.version shouldBe MigrationVersion.fromVersion("1")
}
}
}
"should throw exception when baselining after successful migration" - {
"with default table prefix" - {
"for session and keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.migrate()
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
shouldThrow<CassandraMigrationException> { cm.baseline() }
}
"for session and keyspace, version and description setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.migrate()
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.baselineVersion = MigrationVersion.fromVersion("0.0.1")
cm.baselineDescription = "Baseline test"
shouldThrow<CassandraMigrationException> { cm.baseline() }
}
"for external session, but keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession()
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.migrate(session)
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
shouldThrow<CassandraMigrationException> { cm.baseline(session) }
}
"for external session and defaulted keyspace" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession()
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.migrate(session)
cm = CassandraMigration()
cm.locations = scriptsLocations
shouldThrow<CassandraMigrationException> { cm.baseline(session) }
}
}
"with user-defined table prefix" - {
"for session and keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.migrate()
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
shouldThrow<CassandraMigrationException> { cm.baseline() }
}
"for session and keyspace, version and description setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.migrate()
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.baselineVersion = MigrationVersion.fromVersion("0.0.1")
cm.baselineDescription = "Baseline test"
shouldThrow<CassandraMigrationException> { cm.baseline() }
}
"for external session, but keyspace setup via configuration" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession()
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
cm.migrate(session)
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.keyspaceConfig = getKeyspace()
cm.tablePrefix = "test1_"
shouldThrow<CassandraMigrationException> { cm.baseline(session) }
}
"for external session and defaulted keyspace" {
val scriptsLocations = arrayOf("migration/integ", "migration/integ/java")
val session = getSession()
var cm = CassandraMigration()
cm.locations = scriptsLocations
cm.tablePrefix = "test1_"
cm.migrate(session)
cm = CassandraMigration()
cm.locations = scriptsLocations
cm.tablePrefix = "test1_"
shouldThrow<CassandraMigrationException> { cm.baseline(session) }
}
}
}
}
}
}
| apache-2.0 | 714dd65bfcd6cc34b7c583e57fe23323 | 45.503311 | 141 | 0.526773 | 6.495837 | false | true | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RAlert.kt | 1 | 6306 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
import android.widget.Toast
import pyxis.uzuki.live.richutilskt.impl.F1
import pyxis.uzuki.live.richutilskt.impl.F3
/**
* Display Toast Message
*
* @param[message] to display
* @param[length] Length of display time of Toast, Default is Toast.LENGTH_SHORT
*/
@JvmOverloads
fun Context.toast(message: String, length: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, message, length).show()
/**
* Display Toast Message
*
* @param[message] to display
* @param[length] Length of display time of Toast, Default is Toast.LENGTH_SHORT
*/
@JvmOverloads
fun Context.toast(message: Int, length: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, message, length).show()
/**
* Display AlertDialog instantly
*
* @param[title] optional, title
* @param[message] to display
* @param[positiveButton] optional, button text
* @param[cancelable] able to cancel
* @param[callback] callback of click ok button
*/
@JvmOverloads
fun Context.alert(message: String, title: String = "", positiveButton: String? = null, cancelable: Boolean = true, callback: (DialogInterface) -> Unit = {}) =
AlertDialog.Builder(this).apply {
if (title.isEmpty().not())
setTitle(title)
setMessage(message)
setPositiveButton(positiveButton ?: getString(android.R.string.ok), { dialog, _ -> callback(dialog) })
setCancelable(cancelable)
show()
}
/**
* Display AlertDialog instantly
* for SAM Conversion
*
* @param[title] optional, title
* @param[message] to display
* @param[positiveButton] optional, button text
* @param[cancelable] able to cancel
* @param[callback] callback of click ok button
*/
@JvmOverloads
fun Context.alert(message: String, title: String = "", positiveButton: String? = null, cancelable: Boolean = true, callback: F1<DialogInterface>?) =
AlertDialog.Builder(this).apply {
if (title.isEmpty().not())
setTitle(title)
setMessage(message)
setPositiveButton(positiveButton ?: getString(android.R.string.ok), { dialog, _ -> callback?.invoke(dialog) })
setCancelable(cancelable)
show()
}
/**
* Display SelectorDialog instantly
*
* @param[title] optional, title
* @param[items] list of display item, working with generic. it will display item.toString()
* @param[cancelable] able to cancel
* @param[callback] callback of click ok button
*/
@JvmOverloads
fun <T> Context.selector(items: List<T>, callback: (DialogInterface, item: T, Int) -> Unit, title: String = "", cancelable: Boolean = true) =
AlertDialog.Builder(this).apply {
if (title.isEmpty().not())
setTitle(title)
setItems(Array(items.size) { i -> items[i].toString() }) { dialog, which ->
callback(dialog, items[which], which)
}
setCancelable(cancelable)
show()
}
/**
* Display SelectorDialog instantly
* for SAM Conversion
*
* @param[title] optional, title
* @param[items] list of display item, working with generic. it will display item.toString()
* @param[cancelable] able to cancel
* @param[callback] callback of click ok button
*/
@JvmOverloads
fun <T> Context.selector(items: List<T>, callback: F3<DialogInterface, T, Int>?, title: String = "", cancelable: Boolean = true) =
AlertDialog.Builder(this).apply {
if (title.isEmpty().not())
setTitle(title)
setItems(Array(items.size) { i -> items[i].toString() }) { dialog, which ->
callback?.invoke(dialog, items[which], which)
}
setCancelable(cancelable)
show()
}
/**
* Display AlertDialog instantly with confirm
*
* @param[title] optional, title
* @param[message] to display
* @param[positiveButton] optional, button text
* @param[negativeButton] optional, button text
* @param[cancelable] able to cancel
* @param[callback] callback of click ok button
*/
@JvmOverloads
fun Context.confirm(message: String, callback: DialogInterface.() -> Unit, title: String = "", positiveButton: String? = null, negativeButton: String? = null, cancelable: Boolean = true) =
AlertDialog.Builder(this).apply {
if (title.isEmpty().not())
setTitle(title)
setMessage(message)
setPositiveButton(positiveButton ?: getString(android.R.string.ok), { dialog, _ -> dialog.callback() })
setNegativeButton(negativeButton ?: getString(android.R.string.no), { _, _ -> })
setCancelable(cancelable)
show()
}
/**
* Display AlertDialog instantly with confirm
* for SAM Conversion
*
* @param[title] optional, title
* @param[message] to display
* @param[positiveButton] optional, button text
* @param[negativeButton] optional, button text
* @param[cancelable] able to cancel
* @param[callback] callback of click ok button
*/
@JvmOverloads
fun Context.confirm(message: String, callback: F1<DialogInterface>?, title: String = "", positiveButton: String? = null, negativeButton: String? = null, cancelable: Boolean = true) =
AlertDialog.Builder(this).apply {
if (title.isEmpty().not())
setTitle(title)
setMessage(message)
setPositiveButton(positiveButton ?: getString(android.R.string.ok), { dialog, _ -> callback?.invoke(dialog) })
setNegativeButton(negativeButton ?: getString(android.R.string.no), { _, _ -> })
setCancelable(cancelable)
show()
}
/**
* Display ProgressDialog
*
* @param[title] optional, title
* @param[cancelable]
* @param[message] message
* @return DialogInterface
*/
@JvmOverloads
fun Context.progress(message: String, cancelable: Boolean = true, title: String = ""): DialogInterface {
return ProgressDialog(this).apply {
setProgressStyle(ProgressDialog.STYLE_SPINNER)
setMessage(message)
if (title.isEmpty().not())
setTitle(title)
setCancelable(cancelable)
show()
}
} | apache-2.0 | 862026a91e1239dec758f2f41bff245d | 34.632768 | 188 | 0.6562 | 4.243607 | false | false | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/ui/search/users/SearchUsersPresenter.kt | 1 | 2303 | package com.andreapivetta.blu.ui.search.users
import com.andreapivetta.blu.data.twitter.TwitterAPI
import com.andreapivetta.blu.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import twitter4j.Paging
/**
* Created by andrea on 25/07/16.
*/
class SearchUsersPresenter(private val textQuery: String) : BasePresenter<SearchUsersMvpView>() {
var page: Int = 1
private var isLoading: Boolean = false
private val disposables = CompositeDisposable()
override fun detachView() {
super.detachView()
disposables.clear()
}
fun getUsers() {
checkViewAttached()
mvpView?.showLoading()
isLoading = true
disposables.add(TwitterAPI.searchUsers(textQuery, Paging(page, 50))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
mvpView?.hideLoading()
when {
it == null -> mvpView?.showError()
it.isEmpty() -> mvpView?.showEmpty()
else -> {
mvpView?.showUsers(it)
page++
}
}
isLoading = false
}, {
Timber.e(it)
mvpView?.hideLoading()
mvpView?.showError()
isLoading = false
}))
}
fun getMoreUsers() {
if (isLoading)
return
checkViewAttached()
isLoading = true
disposables.add(TwitterAPI.searchUsers(textQuery, Paging(page, 50))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
if (it != null) {
if (it.isNotEmpty())
mvpView?.showMoreUsers(it)
page++
}
isLoading = false
}, {
Timber.e(it)
isLoading = false
}))
}
} | apache-2.0 | c83a44920c0b8f97e9e12bce4ca99678 | 28.922078 | 97 | 0.505428 | 5.630807 | false | false | false | false |
budioktaviyan/kotlin-mvp | app/src/main/kotlin/com/baculsoft/sample/kotlinmvp/views/main/MainActivity.kt | 1 | 1970 | package com.baculsoft.sample.kotlinmvp.views.main
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.baculsoft.sample.kotlinmvp.R
import com.baculsoft.sample.kotlinmvp.model.Data
import com.baculsoft.sample.kotlinmvp.views.next.NextFragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), MainView {
lateinit var presenter: MainPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initPresenter()
onAttach()
}
override fun onAttach() {
presenter.onAttach(this)
initToolbar()
addButtonListener()
}
override fun onDetach() {
presenter.onDetach()
}
override fun onShowFragment(data: Data) {
// Get Data
val bundle: Bundle = Bundle()
bundle.putString("data", data.text)
// Show Fragment with Data
val tag: String = NextFragment::class.java.simpleName
val fragment: Fragment = NextFragment().newInstance()
fragment.arguments = bundle
// Begin Fragment Transaction
val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fl_main, fragment, tag)
fragmentTransaction.commit()
}
override fun onDestroy() {
onDetach()
super.onDestroy()
}
private fun initPresenter() {
presenter = MainPresenter()
}
private fun initToolbar() {
toolbar_main.title = title
setSupportActionBar(toolbar_main)
}
private fun addButtonListener() {
btn_main.setOnClickListener { view ->
btn_main.visibility = View.GONE
presenter.showFragment()
}
}
} | apache-2.0 | c08322367ea585023dabd6fe17699b4b | 27.565217 | 96 | 0.67868 | 4.888337 | false | false | false | false |
ntlv/BasicLauncher2 | app/src/main/java/se/ntlv/basiclauncher/packagehandling/AppChangeLoggerService.kt | 1 | 6634 | package se.ntlv.basiclauncher.packagehandling
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import se.ntlv.basiclauncher.BasicLauncherApplication
import se.ntlv.basiclauncher.database.AppDetail
import se.ntlv.basiclauncher.database.AppDetailDB
import se.ntlv.basiclauncher.database.GlobalConfig
import se.ntlv.basiclauncher.tag
import javax.inject.Inject
class AppChangeLoggerService : IntentService("AppChangeLoggerService") {
val TAG = tag()
@Inject lateinit var db: AppDetailDB
@Inject lateinit var pM: PackageManager
@Inject lateinit var config: GlobalConfig
companion object {
private val EXTRA_PACKAGE_NAME = "extra_package_name"
private enum class Action {
ONE_TIME_INIT,
LOG_PACKAGE_INSTALLED,
LOG_PACKAGE_REMOVED,
LOG_PACKAGE_CHANGED
}
fun logPackageInstall(context: Context, packageName: String) {
startLogPackageAction(context, packageName, Action.LOG_PACKAGE_INSTALLED)
}
fun logPackageRemove(context: Context, packageName: String) {
startLogPackageAction(context, packageName, Action.LOG_PACKAGE_REMOVED)
}
fun logPackageChanged(context: Context, packageName: String) {
startLogPackageAction(context, packageName, Action.LOG_PACKAGE_CHANGED)
}
private fun startLogPackageAction(context: Context, packageName: String, action: Action) {
val intent = Intent(context, AppChangeLoggerService::class.java)
intent.putExtra(EXTRA_PACKAGE_NAME, packageName)
intent.action = action.name
if (context.startService(intent) == null) {
throw IllegalStateException("Unable to start data service")
}
}
fun oneTimeInit(context: Context) {
val i = Intent(context, AppChangeLoggerService::class.java)
i.action = Action.ONE_TIME_INIT.name
if (context.startService(i) == null) {
throw IllegalStateException("Unable to start data service")
}
}
}
private val specification = Intent(Intent.ACTION_MAIN, null)
.addCategory(Intent.CATEGORY_LAUNCHER)
override fun onCreate() {
super.onCreate()
BasicLauncherApplication.applicationComponent().inject(this)
}
override fun onHandleIntent(intent: Intent?) {
if (intent == null) return
val action = Action.valueOf(intent.action)
val packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME)
when (action) {
Action.LOG_PACKAGE_INSTALLED -> doLogPackageInstall(packageName)
Action.LOG_PACKAGE_REMOVED -> doLogPackageRemove(packageName)
Action.LOG_PACKAGE_CHANGED -> doLogPackageChange(packageName)
Action.ONE_TIME_INIT -> doOneTimeInit()
}
}
private fun doLogPackageChange(pName: String) {
Log.d(TAG, "Log change of $pName")
val isEnabled = pM.getApplicationEnabledSetting(pName)
when (isEnabled) {
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT -> doLogPackageInstall(pName)
PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> doLogPackageInstall(pName)
else -> doLogPackageRemove(pName)
}
}
private fun doOneTimeInit() {
val dimens = config.pageDimens
val rowsPerPage = dimens.rowCount
val columnsPerPage = dimens.columnCount
val pageSize = rowsPerPage * columnsPerPage
val launchIntents = pM.queryIntentActivities(specification, 0)
.filter {
val pName = it.activityInfo.packageName
pM.getLaunchIntentForPackage(pName) != null
}
.distinctBy { it.activityInfo.packageName }
val minRequiredPageCount = Math.ceil(launchIntents.size / pageSize.toDouble()).toInt()
val collector: MutableList<AppDetail> = mutableListOf()
var rest = launchIntents
for (page in 0..minRequiredPageCount - 1) {
val take = rest.take(pageSize)
for (row in 0..rowsPerPage - 1) {
for (column in 0..columnsPerPage - 1) {
val index = row * columnsPerPage + column
val info = take.getOrNull(index)
if (info != null) {
val label = info.loadLabel(pM).toString()
val packageName = info.activityInfo.packageName
val meta = AppDetail(label, packageName, false, false, page, row, column)
Log.v(TAG, "Adding at page: ${meta.page}, row: ${meta.row}, col: ${meta.column}, ${meta.packageName} ")
collector.add(meta)
}
}
}
rest = rest.drop(pageSize)
}
val insertions = collector.toTypedArray()
db.insert(*insertions, overwrite = false)
/*
launchIntents.map {
val label = it.loadLabel(pM).toString()
val packageName = it.activityInfo.packageName
val res = AppDetail(label, packageName, false, false, currentPage, currentRow, currentColumn)
currentColumn = (currentColumn + 1) % columnsPerPage
if (currentColumn == 0) {
currentRow = (currentRow + 1) % rowsPerPage
}
res
}.let {
val insertions = it.toTypedArray()
db.insert(*insertions, overwrite = false)
}*/
}
private fun doLogPackageInstall(pName: String) {
Log.d(TAG, "Log installation of $pName")
val launchable = pM.getLaunchIntentForPackage(pName)
if (launchable == null) {
Log.v(TAG, "Skipping logging of package install, unable to find launchable activity for $pName")
return
}
val info = pM.getApplicationInfo(pName, 0)
val label = info.loadLabel(pM).toString()
val (page, row, column) = db.getFirstFreeSpace()
val (maxRow, maxColumn) = config.pageDimens
val appColumn = (column + 1) % maxColumn
val appRow = (row + 1) % maxRow
val appPage = page + if (appRow == 0) 1 else 0
val appDetails = AppDetail(label, pName, false, false, appPage, appRow, appColumn)
db.insert(appDetails, overwrite = false)
}
private fun doLogPackageRemove(pName: String) {
Log.d(TAG, "Log removal of $pName")
db.delete(pName)
}
}
| mit | 406b01ebe529ebab7e33bb4ba1d1f612 | 36.269663 | 127 | 0.619686 | 4.616562 | false | false | false | false |
alphafoobar/intellij-community | platform/testFramework/testSrc/com/intellij/testFramework/TemporaryDirectory.kt | 4 | 4941 | /*
* 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 com.intellij.testFramework
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import org.junit.rules.ExternalResource
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.File
import java.io.IOException
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
public class TemporaryDirectory : ExternalResource() {
private val paths = SmartList<Path>()
private var sanitizedName: String? = null
override fun apply(base: Statement, description: Description): Statement {
sanitizedName = FileUtil.sanitizeFileName(description.getMethodName(), false)
return super.apply(base, description)
}
override fun after() {
for (path in paths) {
path.deleteRecursively()
}
paths.clear()
}
/**
* Directory is not created.
*/
public fun newDirectory(directoryName: String? = null): File = generatePath(directoryName).toFile()
public fun newPath(directoryName: String? = null, refreshVfs: Boolean = true): Path {
val path = generatePath(directoryName)
if (refreshVfs) {
path.refreshVfs()
}
return path
}
private fun generatePath(suffix: String?): Path {
var fileName = sanitizedName!!
if (suffix != null) {
fileName += "_$suffix"
}
var path = generateTemporaryPath(fileName)
paths.add(path)
return path
}
public fun newVirtualDirectory(directoryName: String? = null): VirtualFile {
val path = generatePath(directoryName)
path.createDirectories()
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.systemIndependentPath)
VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile)
return virtualFile!!
}
}
public fun generateTemporaryPath(fileName: String?): Path {
val tempDirectory = Paths.get(FileUtilRt.getTempDirectory())
var path = tempDirectory.resolve(fileName)
var i = 0
while (path.exists() && i < 9) {
path = tempDirectory.resolve("${fileName}_$i")
i++
}
if (path.exists()) {
throw IOException("Cannot generate unique random path")
}
return path
}
public fun Path.exists(): Boolean = Files.exists(this)
public fun Path.createDirectories(): Path = Files.createDirectories(this)
public fun Path.deleteRecursively(): Path = if (exists()) Files.walkFileTree(this, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
Files.delete(dir)
return FileVisitResult.CONTINUE
}
}) else this
public val Path.systemIndependentPath: String
get() = toString().replace(File.separatorChar, '/')
public val Path.parentSystemIndependentPath: String
get() = getParent()!!.toString().replace(File.separatorChar, '/')
public fun Path.readText(): String = Files.readAllBytes(this).toString(Charsets.UTF_8)
public fun VirtualFile.writeChild(relativePath: String, data: String): VirtualFile = VfsTestUtil.createFile(this, relativePath, data)
public fun Path.writeChild(relativePath: String, data: String): Path = writeChild(relativePath, data.toByteArray())
public fun Path.writeChild(relativePath: String, data: ByteArray): Path {
val path = resolve(relativePath)
path.getParent().createDirectories()
return Files.write(path, data)
}
public fun Path.isDirectory(): Boolean = Files.isDirectory(this)
public fun Path.isFile(): Boolean = Files.isRegularFile(this)
/**
* Opposite to ugly Java, parent directories will be created
*/
public fun Path.createFile() {
getParent()?.createDirectories()
Files.createFile(this)
}
public fun Path.refreshVfs() {
LocalFileSystem.getInstance()?.let { fs ->
// If a temp directory is reused from some previous test run, there might be cached children in its VFS. Ensure they're removed.
val virtualFile = fs.findFileByPath(systemIndependentPath)
if (virtualFile != null) {
VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile)
}
}
}
val VirtualFile.path: String
get() = getPath() | apache-2.0 | b44959675e18eafa771ebe70132b5adf | 31.090909 | 133 | 0.737098 | 4.384206 | false | false | false | false |
meteochu/DecisionKitchen | Android/app/src/main/java/com/decisionkitchen/decisionkitchen/GroupActivity.kt | 1 | 16303 | package com.decisionkitchen.decisionkitchen
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.opengl.Visibility
import android.os.Bundle
import android.support.v4.app.ShareCompat
import android.support.v7.widget.Toolbar
import android.text.Layout
import android.util.Log
import android.view.*
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.ValueEventListener
import android.widget.*
import com.facebook.drawee.view.SimpleDraweeView
import com.google.firebase.auth.FirebaseAuth
import com.facebook.drawee.generic.RoundingParams
import com.github.kevinsawicki.timeago.TimeAgo
import com.usebutton.sdk.ButtonContext
import com.usebutton.sdk.ButtonDropin
import com.usebutton.sdk.context.Location
import com.usebutton.sdk.util.LocationProvider
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import org.joda.time.format.ISODateTimeFormat
import java.net.URLEncoder
class GroupActivity : Activity() {
private fun getContext(): Context {
return this
}
private var mShareActionProvider: ShareActionProvider? = null
private var group: Group? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
com.usebutton.sdk.Button.getButton(this).start();
setContentView(R.layout.activity_group)
val database = FirebaseDatabase.getInstance()
val groupRef = database.getReference("groups/" + intent.getStringExtra("GROUP_ID"))
val toolbar : Toolbar = findViewById(R.id.toolbar) as Toolbar
toolbar.title = "Loading..."
val groupListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
group = dataSnapshot.getValue<Group>(Group::class.java)!!
val memberScrollView : HorizontalScrollView = findViewById(R.id.members) as HorizontalScrollView
memberScrollView.removeAllViews()
toolbar.title = group!!.name
var loadCount : Int = 0
val auth: FirebaseAuth = FirebaseAuth.getInstance()
val roundingParams = RoundingParams.fromCornersRadius(5f)
roundingParams.roundAsCircle = true
val membersLayout = LinearLayout(getContext())
val membersLayoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
membersLayout.layoutParams = membersLayoutParams
membersLayout.orientation = LinearLayout.HORIZONTAL
for (member_id in group!!.members!!) {
database.getReference("users/" + member_id).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(memberSnapshot: DataSnapshot) {
val userLayout = LinearLayout(membersLayout.context)
userLayout.orientation = LinearLayout.VERTICAL
userLayout.gravity = Gravity.CENTER_HORIZONTAL
userLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
val member : User = memberSnapshot.getValue<User>(User::class.java)!!
val profile = SimpleDraweeView(userLayout.context)
profile.setImageURI(member.img)
profile.hierarchy.roundingParams = roundingParams
val params = ViewGroup.LayoutParams(120, 120)
profile.layoutParams = params;
val marginParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(profile.layoutParams);
marginParams.setMargins(50, 30, 50, 20)
profile.layoutParams = marginParams
userLayout.addView(profile)
val name = TextView(userLayout.context)
name.text = member.first_name
name.textSize = 11.0F
name.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
name.setPadding(0, 0, 0, 30)
userLayout.addView(name)
membersLayout.addView(userLayout)
loadCount ++
if (loadCount == group!!.members!!.size) {
findViewById(R.id.loader).visibility = View.INVISIBLE
findViewById(R.id.content).visibility = View.VISIBLE
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
memberScrollView.addView(membersLayout)
val mainContent : LinearLayout = findViewById(R.id.group_content) as LinearLayout
mainContent.removeAllViews()
if (group!!.games != null) {
for (game in group!!.games!!) {
Log.w("test", game.toString())
if (game.meta!!.end == null) {
if (game.responses != null && game.responses.containsKey(FirebaseAuth.getInstance().currentUser!!.uid)) {
findViewById(R.id.create_game).visibility = View.GONE
findViewById(R.id.voted).visibility = View.VISIBLE
} else {
(findViewById(R.id.create_game) as TextView).setText(R.string.join_vote)
(findViewById(R.id.textView) as TextView).setText("Enter your vote!")
}
continue
}
val cardWrapper = LinearLayout(mainContent.context)
cardWrapper.orientation = LinearLayout.VERTICAL
cardWrapper.gravity = Gravity.TOP
cardWrapper.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val startDate = TextView(cardWrapper.context)
startDate.text = DateTime(game.meta!!.end).toString(DateTimeFormat.shortDateTime())
startDate.textSize = 13.0F
startDate.typeface = Typeface.create("sans-serif", Typeface.BOLD)
startDate.setTextColor(Color.rgb(0, 0, 0))
val startDateParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
startDateParams.setMargins(50, 50, 50, 0)
startDate.layoutParams = startDateParams
cardWrapper.addView(startDate)
val cardScrollWrapper = HorizontalScrollView(cardWrapper.context)
val cardScrollWrapperInner = LinearLayout(mainContent.context)
cardScrollWrapperInner.orientation = LinearLayout.HORIZONTAL
cardScrollWrapperInner.gravity = Gravity.TOP
cardScrollWrapperInner.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
for (j in (game.result!!).size - 1 downTo 0) {
val restaurant = group!!.restaurants!![game.result!![j][0]]!!
val cardLayout = LinearLayout(mainContent.context)
cardLayout.orientation = LinearLayout.HORIZONTAL
cardLayout.gravity = Gravity.TOP
cardLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val profile = SimpleDraweeView(cardLayout.context)
profile.setImageURI(if (restaurant.image != null) restaurant.image else "https://unsplash.it/200")
profile.hierarchy.roundingParams = roundingParams
val params = ViewGroup.LayoutParams(230, 230)
profile.layoutParams = params;
val marginParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(profile.layoutParams);
marginParams.setMargins(50, 50, 50, 50)
profile.layoutParams = marginParams
cardLayout.addView(profile)
val cardContentLayout = LinearLayout(mainContent.context)
cardContentLayout.orientation = LinearLayout.VERTICAL
cardContentLayout.gravity = Gravity.TOP
cardContentLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
(cardContentLayout.layoutParams as LinearLayout.LayoutParams).setMargins(0, 50, 50, 50)
val name = TextView(cardContentLayout.context)
name.text = restaurant.name
name.textSize = 20.0F
name.typeface = Typeface.DEFAULT_BOLD
name.setTextColor(Color.BLACK)
name.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
name.setPadding(0, 0, 0, 10)
cardContentLayout.addView(name)
val address = TextView(cardContentLayout.context)
address.text = restaurant.address
address.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
address.setPadding(0, 0, 0, 20)
cardContentLayout.addView(address)
/*
val date = TextView(cardContentLayout.context)
date.text = DateTime(game.meta!!.end).toString(DateTimeFormat.shortDateTime())
date.textSize = 15.0F
date.typeface = Typeface.create("sans-serif-light", Typeface.NORMAL)
date.setTextColor(Color.rgb(150, 150, 150))
date.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
cardContentLayout.addView(date)*/
val butt = ButtonDropin(cardContentLayout.context)
butt.setButtonId("btn-749e2bd5d9e4a4c3")
// Set Button Context
val location : com.usebutton.sdk.context.Location = com.usebutton.sdk.context.Location(restaurant.name)
location.setAddress(restaurant.address)
location.setCity(restaurant.city)
location.setState(restaurant.state)
location.setZip(restaurant.zip)
location.setName(restaurant.name)
location.setCountry("USA")
val context = ButtonContext.withSubjectLocation(location)
// Provide the user's location if we have the permission to
try {
@SuppressLint("MissingPermission")
val userLocation: android.location.Location? = com.usebutton.sdk.util.LocationProvider(applicationContext).bestLocation
if (userLocation != null) {
context.setUserLocation(userLocation as com.usebutton.sdk.context.Location);
}
} catch (e: Exception) {
}
// Prepare the Button for display with our Context
butt.prepareForDisplay(context);
cardContentLayout.addView(butt)
cardLayout.addView(cardContentLayout)
cardScrollWrapperInner.addView(cardLayout)
}
cardScrollWrapper.addView(cardScrollWrapperInner)
cardWrapper.addView(cardScrollWrapper)
mainContent.addView(cardWrapper)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.w("dk", "loadPost:onCancelled", databaseError.toException())
// ...
}
}
toolbar.setNavigationOnClickListener {
groupRef.removeEventListener(groupListener)
val intent: Intent = Intent(applicationContext, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
applicationContext.startActivity(intent)
}
groupRef.addValueEventListener(groupListener)
}
public fun createGame(view: View) {
val intent:Intent = Intent(getBaseContext(), RestaurantActivity::class.java)
intent.putExtra("GROUP_ID", getIntent().getStringExtra("GROUP_ID"))
startActivity(intent)
val ref = FirebaseDatabase.getInstance().getReference("groups/" + getIntent().getStringExtra("GROUP_ID"))
ref.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
Log.e("error", p0.toString())
}
override fun onDataChange(snapshot: DataSnapshot) {
val group = snapshot.getValue(Group::class.java)!!
if (group.games != null) {
for (game in group.games!!) {
if (game.meta!!.end == null) {
return
}
}
val game = Game(GameMeta(null, ISODateTimeFormat.dateTimeNoMillis().print(DateTime())))
group.games!!.add(game)
ref.setValue(group)
return
}
val al = ArrayList<Game>()
al.add(Game(GameMeta(null, ISODateTimeFormat.dateTimeNoMillis().print(DateTime()))))
val newGroup = Group(group.password, group.members, group.name, group.restaurants, group.id, al)
ref.setValue(newGroup)
}
})
}
override public fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate menu resource file.
menuInflater.inflate(R.menu.group_activity_actions, menu);
val item = menu.findItem(R.id.share);
mShareActionProvider = item.actionProvider as ShareActionProvider;
// Create the share Intent
val url = "https://decisionkitchen.app/group?name=" + URLEncoder.encode(group!!.name) + "&pass=" + URLEncoder.encode(group!!.password)
val shareText = "Join my DecisionKitchen group at " + url;
val shareIntent = ShareCompat.IntentBuilder.from(this).setType("text/plain").setText(shareText).getIntent();
// Set the share Intent
(mShareActionProvider as ShareActionProvider).setShareIntent(shareIntent);
return true;
}
} | apache-2.0 | 04278a307cf3f09cafcf4d990553048a | 49.166154 | 178 | 0.579648 | 5.724368 | false | false | false | false |
sandjelkovic/dispatchd | content-service/src/test/kotlin/com/sandjelkovic/dispatchd/content/data/repository/EpisodeRepositoryTest.kt | 1 | 6534 | package com.sandjelkovic.dispatchd.content.data.repository
import com.sandjelkovic.dispatchd.content.data.entity.Episode
import com.sandjelkovic.dispatchd.content.data.entity.Season
import com.sandjelkovic.dispatchd.content.data.entity.Show
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.data.domain.PageRequest
import org.springframework.test.context.junit4.SpringRunner
import java.time.ZonedDateTime
/**
* @author sandjelkovic
* @date 27.1.18.
*/
@RunWith(SpringRunner::class)
@DataJpaTest
class EpisodeRepositoryTest {
@Autowired
lateinit var repository: EpisodeRepository
@Autowired
lateinit var showRepository: ShowRepository
@Autowired
lateinit var seasonRepository: SeasonRepository
@Test
fun saveEpisode() {
val episode = exampleEpisode()
val saved = repository.save(episode.copy())
assertThat(saved)
.isEqualToIgnoringNullFields(episode)
assertThat(saved.id)
.isNotNull()
.isGreaterThan(0)
val foundOptional = repository.findById(saved.id!!)
assertThat(foundOptional)
.isPresent
assertThat(foundOptional.get())
.isEqualToIgnoringNullFields(episode)
assertThat(foundOptional.get().id)
.isNotNull()
.isGreaterThan(0)
}
@Test
fun saveEmptyEpisode() {
val episode = Episode()
val saved = repository.save(episode.copy())
assertThat(saved)
.isEqualToIgnoringNullFields(episode)
assertThat(saved.id)
.isNotNull()
.isGreaterThan(0)
val foundOptional = repository.findById(saved.id!!)
assertThat(foundOptional)
.isPresent
assertThat(foundOptional.get())
.isEqualToIgnoringNullFields(episode)
assertThat(foundOptional.get().id)
.isNotNull()
.isGreaterThan(0)
}
@Test
fun saveEpisodeWithNewShow() {
val episode = Episode(show = Show())
val saved = repository.save(episode.copy())
assertThat(saved)
.isEqualToIgnoringNullFields(episode)
assertThat(saved.id)
.isNotNull()
.isGreaterThan(0)
val foundOptional = repository.findById(saved.id!!)
assertThat(foundOptional)
.isPresent
assertThat(foundOptional.get())
.isEqualToIgnoringNullFields(episode)
assertThat(foundOptional.get().id)
.isNotNull()
.isGreaterThan(0)
}
@Test
fun findByShow() {
val show = showRepository.save(Show())
val episode = repository.save(Episode(show = show))
val episodeByShow = repository.findByShow(show)
assertThat(episodeByShow)
.isNotNull
.isNotEmpty
.hasSize(1)
.first()
.isEqualTo(episode)
}
@Test
fun findByShowMultipleEpisodes() {
val show = showRepository.save(Show())
val episodes = repository.saveAll(listOf(
Episode(show = show),
Episode(show = show),
Episode(show = show)
))
val episodeByShow = repository.findByShow(show)
assertThat(episodeByShow)
.isNotNull
.isNotEmpty
.hasSize(3)
.doesNotHaveDuplicates()
.containsAll(episodes)
}
@Test
fun findByShowPageable() {
val show = showRepository.save(Show())
val episodes = repository.saveAll(listOf(
Episode(show = show),
Episode(show = show),
Episode(show = show),
Episode(show = show),
Episode(show = show)
))
val pageable = PageRequest.of(1, 2) // second Page, pages start from 0
val page = repository.findByShow(show, pageable)
assertThat(page)
.isNotNull
.isNotEmpty
.hasSize(2)
.doesNotHaveDuplicates()
assertThat(page.totalElements).isEqualTo(episodes.count().toLong())
assertThat(page.totalPages).isEqualTo(3)
}
@Test
fun findBySeason() {
val season = seasonRepository.save(Season())
val episode = repository.save(Episode(season = season))
val episodeBySeason = repository.findBySeason(season)
assertThat(episodeBySeason)
.isNotNull
.isNotEmpty
.hasSize(1)
.first()
.isEqualTo(episode)
}
@Test
fun findBySeasonMultipleEpisodes() {
val season = seasonRepository.save(Season())
val episodes = repository.saveAll(listOf(
Episode(season = season),
Episode(season = season),
Episode(season = season)
))
val episodeByShow = repository.findBySeason(season)
assertThat(episodeByShow)
.isNotNull
.isNotEmpty
.hasSize(3)
.doesNotHaveDuplicates()
.containsAll(episodes)
}
@Test
fun findBySeasonPageable() {
val season = seasonRepository.save(Season())
val episodes = repository.saveAll(listOf(
Episode(season = season),
Episode(season = season),
Episode(season = season),
Episode(season = season),
Episode(season = season)
))
val pageable = PageRequest.of(1, 2) // second Page, pages start from 0
val page = repository.findBySeason(season, pageable)
assertThat(page)
.isNotNull
.isNotEmpty
.hasSize(2)
.doesNotHaveDuplicates()
assertThat(page.totalElements).isEqualTo(episodes.count().toLong())
assertThat(page.totalPages).isEqualTo(3)
}
private fun exampleEpisode(): Episode {
return Episode(airDate = ZonedDateTime.now().plusDays(1),
number = 5,
traktId = "123456",
title = "Episode Title",
description = "Episode Description")
}
}
| apache-2.0 | ad4029ee7ab1edb17f72e7d8ffbe908b | 29.110599 | 78 | 0.57989 | 5.037779 | false | true | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/n73xs.kt | 1 | 3484 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.base.jar.ownLinesString
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstThreeIntPattern
/**
* Created by AoEiuV020 on 2018.06.04-17:23:51.
*/
class N73xs : DslJsoupNovelContext() {init {
reason = "超时,网站可能快凉了,"
upkeep = false
site {
name = "73文学"
baseUrl = "http://www.73wxw.com"
logo = "https://imgsa.baidu.com/forum/w%3D580/sign=d8f0b6300f3b5bb5bed720f606d2d523/958c4b160924ab1867ef56ac39fae6cd79890b9f.jpg"
}
search {
get {
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchkey" to it
}
}
document {
if (root.ownerDocument().location().endsWith("/")) {
single {
name(".zhuyan > ul:nth-child(1) > li:nth-child(1)", block = pickString("书名:(\\S*)"))
author(".zhuyan > ul:nth-child(1) > li:nth-child(2)", block = pickString("作\\s*者:(\\S*)"))
}
} else {
items("#content > table > tbody > tr:not(:nth-child(1)):not(:nth-last-child(1))") {
name("> td.odd > a")
author("> td.odd", block = pickString(" / (\\S*)"))
}
}
}
}
// http://www.73wx.com/book/32252/
// http://www.73wx.com/32/32252/
// http://www.73wx.com/32/32252/8967417.html
bookIdRegex = "/((book)|(\\d+))/(\\d+)"
bookIdIndex = 3
// 详情页连简介都没有,直接用章节列表页,
// 但是搜索结果可能跳到详情页,bookId不得不支持,
detailDivision = 1000
detailPageTemplate = "/%d/%s/"
detail {
document {
val div = element("#info")
val title = element("> div.infotitle", parent = div)
novel {
name("> h1", parent = title)
author("> i:nth-child(2)", parent = title, block = pickString("作\\s*者:(\\S*)"))
}
image("#fmimg img")
introduction("> div.intro", parent = div) {
it.textNodes().first {
// TextNode不可避免的有空的,
!it.isBlank
&& !it.wholeText.let {
// 后面几个TextNode广告包含这些文字,
it.startsWith("各位书友要是觉得《${novel?.name}》还不错的话请不要忘记向您QQ群和微博里的朋友推荐哦!")
|| it.startsWith("${novel?.name}最新章节,${novel?.name}无弹窗,${novel?.name}全文阅读.")
}
}.ownLinesString()
}
// 这网站详情页更新时间是js另外拿的,
// http://www.73wx.com/modules/article/pd_uptime.php?id=32252
}
}
// http://www.73wx.com/32/32252/
chapters {
document {
items("#list > dl > dd > a")
}
}
// http://www.73wx.com/32/32252/8967417.html
bookIdWithChapterIdRegex = firstThreeIntPattern
contentPageTemplate = "/%s.html"
content {
document {
items("#content > p")
}
}
cookieFilter {
removeAll {
// 删除cookie绕开搜索时间间隔限制,
it.name() == "jieqiVisitTime"
}
}
}
}
| gpl-3.0 | 1925ba82175a62683a57dea973c25446 | 32.020833 | 137 | 0.495268 | 3.456925 | false | false | false | false |
robertwb/incubator-beam | examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/WindowedWordCount.kt | 6 | 8584 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.kotlin
import org.apache.beam.examples.kotlin.common.ExampleBigQueryTableOptions
import org.apache.beam.examples.kotlin.common.ExampleOptions
import org.apache.beam.examples.kotlin.common.WriteOneFilePerWindow
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.io.TextIO
import org.apache.beam.sdk.options.*
import org.apache.beam.sdk.transforms.DoFn
import org.apache.beam.sdk.transforms.MapElements
import org.apache.beam.sdk.transforms.ParDo
import org.apache.beam.sdk.transforms.windowing.FixedWindows
import org.apache.beam.sdk.transforms.windowing.Window
import org.apache.beam.sdk.values.PDone
import org.joda.time.Duration
import org.joda.time.Instant
import java.io.IOException
import java.util.concurrent.ThreadLocalRandom
/**
* An example that counts words in text, and can run over either unbounded or bounded input
* collections.
*
*
* This class, [WindowedWordCount], is the last in a series of four successively more
* detailed 'word count' examples. First take a look at [MinimalWordCount], [WordCount],
* and [DebuggingWordCount].
*
*
* Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples:
* Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally and
* using a selected runner; defining DoFns; user-defined PTransforms; defining PipelineOptions.
*
*
* New Concepts:
*
* <pre>
* 1. Unbounded and bounded pipeline input modes
* 2. Adding timestamps to data
* 3. Windowing
* 4. Re-using PTransforms over windowed PCollections
* 5. Accessing the window of an element
* 6. Writing data to per-window text files
</pre> *
*
*
* By default, the examples will run with the `DirectRunner`. To change the runner,
* specify:
*
* <pre>`--runner=YOUR_SELECTED_RUNNER
`</pre> *
*
* See examples/kotlin/README.md for instructions about how to configure different runners.
*
*
* To execute this pipeline locally, specify a local output file (if using the `DirectRunner`) or output prefix on a supported distributed file system.
*
* <pre>`--output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX]
`</pre> *
*
*
* The input file defaults to a public data set containing the text of of King Lear, by William
* Shakespeare. You can override it and choose your own input with `--inputFile`.
*
*
* By default, the pipeline will do fixed windowing, on 10-minute windows. You can change this
* interval by setting the `--windowSize` parameter, e.g. `--windowSize=15` for
* 15-minute windows.
*
*
* The example will try to cancel the pipeline on the signal to terminate the process (CTRL-C).
*/
public object WindowedWordCount {
const val WINDOW_SIZE = 10 // Default window duration in minutes
/**
* Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for this
* example, for the bounded data case.
*
*
* Imagine that many ghosts of Shakespeare are all typing madly at the same time to recreate
* his masterworks. Each line of the corpus will get a random associated timestamp somewhere in a
* 2-hour period.
*/
public class AddTimestampFn(private val minTimestamp: Instant, private val maxTimestamp: Instant) : DoFn<String, String>() {
@ProcessElement
fun processElement(@Element element: String, receiver: DoFn.OutputReceiver<String>) {
val randomTimestamp = Instant(
ThreadLocalRandom.current()
.nextLong(minTimestamp.millis, maxTimestamp.millis))
/*
* Concept #2: Set the data element with that timestamp.
*/
receiver.outputWithTimestamp(element, Instant(randomTimestamp))
}
}
/** A [DefaultValueFactory] that returns the current system time. */
public class DefaultToCurrentSystemTime : DefaultValueFactory<Long> {
override fun create(options: PipelineOptions) = System.currentTimeMillis()
}
/** A [DefaultValueFactory] that returns the minimum timestamp plus one hour. */
public class DefaultToMinTimestampPlusOneHour : DefaultValueFactory<Long> {
override fun create(options: PipelineOptions) = (options as Options).minTimestampMillis!! + Duration.standardHours(1).millis
}
/**
* Options for [WindowedWordCount].
*
*
* Inherits standard example configuration options, which allow specification of the runner, as
* well as the [WordCount.WordCountOptions] support for specification of the input and
* output files.
*/
public interface Options : WordCount.WordCountOptions, ExampleOptions, ExampleBigQueryTableOptions {
@get:Description("Fixed window duration, in minutes")
@get:Default.Integer(WINDOW_SIZE)
var windowSize: Int?
@get:Description("Minimum randomly assigned timestamp, in milliseconds-since-epoch")
@get:Default.InstanceFactory(DefaultToCurrentSystemTime::class)
var minTimestampMillis: Long?
@get:Description("Maximum randomly assigned timestamp, in milliseconds-since-epoch")
@get:Default.InstanceFactory(DefaultToMinTimestampPlusOneHour::class)
var maxTimestampMillis: Long?
@get:Description("Fixed number of shards to produce per window")
var numShards: Int?
}
@Throws(IOException::class)
@JvmStatic
fun runWindowedWordCount(options: Options) {
val output = options.output
val minTimestamp = Instant(options.minTimestampMillis)
val maxTimestamp = Instant(options.maxTimestampMillis)
val pipeline = Pipeline.create(options)
/*
* Concept #1: the Beam SDK lets us run the same pipeline with either a bounded or
* unbounded input source.
*/
val input = pipeline
/* Read from the GCS file. */
.apply(TextIO.read().from(options.inputFile))
// Concept #2: Add an element timestamp, using an artificial time just to show
// windowing.
// See AddTimestampFn for more detail on this.
.apply(ParDo.of(AddTimestampFn(minTimestamp, maxTimestamp)))
/*
* Concept #3: Window into fixed windows. The fixed window size for this example defaults to 1
* minute (you can change this with a command-line option). See the documentation for more
* information on how fixed windows work, and for information on the other types of windowing
* available (e.g., sliding windows).
*/
val windowedWords = input.apply(
Window.into<String>(FixedWindows.of(Duration.standardMinutes(options.windowSize!!.toLong()))))
/*
* Concept #4: Re-use our existing CountWords transform that does not have knowledge of
* windows over a PCollection containing windowed values.
*/
val wordCounts = windowedWords.apply(WordCount.CountWords())
/*
* Concept #5: Format the results and write to a sharded file partitioned by window, using a
* simple ParDo operation. Because there may be failures followed by retries, the
* writes must be idempotent, but the details of writing to files is elided here.
*/
wordCounts
.apply(MapElements.via(WordCount.FormatAsTextFn()))
.apply<PDone>(WriteOneFilePerWindow(output, options.numShards))
val result = pipeline.run()
try {
result.waitUntilFinish()
} catch (exc: Exception) {
result.cancel()
}
}
@Throws(IOException::class)
@JvmStatic
fun main(args: Array<String>) {
val options = (PipelineOptionsFactory.fromArgs(*args).withValidation() as Options)
runWindowedWordCount(options)
}
}
| apache-2.0 | 0cdc044332f09e584e9ce7f5bcf997c4 | 39.490566 | 151 | 0.70247 | 4.294147 | false | false | false | false |
soniccat/android-taskmanager | app_demo/src/main/java/com/rssclient/model/RssFeedXmlParser.kt | 1 | 6324 | package com.rssclient.model
import android.util.Xml
import com.aglushkov.taskmanager_http.image.Image
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import java.io.IOException
import java.io.StringReader
import java.net.MalformedURLException
import java.net.URL
import java.nio.charset.Charset
// TODO: rewrite this legacy
class RssFeedXmlParser(val url: URL) {
fun parse(data: ByteArray): RssFeed {
val ch = Charset.forName("UTF-8")
val str = String(data, ch)
var reader: StringReader? = null
return try {
val parser = Xml.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
reader = StringReader(str)
parser.setInput(reader)
parser.nextTag()
parse(parser)!!
} finally {
reader!!.close()
}
}
internal fun parse(parser: XmlPullParser): RssFeed? {
val name: String?
parser.nextTag()
name = parser.name
return if (name != null && parser.name == "channel") {
try {
val feed = RssFeed(name, url, null)
this.parse(parser, feed)
feed
} catch (e: java.lang.Exception) {
e.printStackTrace()
throw e
}
} else
null
}
internal fun parse(parser: XmlPullParser, feed: RssFeed) {
val items = mutableListOf<RssItem>()
while (parser.next() != XmlPullParser.END_TAG) {
val name = parser.name
var startedTag = parser.eventType == XmlPullParser.START_TAG
if (name != null) {
if (name == "image") {
feed.image = this.readImage(parser)
} else if (name == "item") {
val item = readItem(parser)
if (item != null) {
items.add(item)
}
}
}
if (startedTag) {
skip(parser)
startedTag = false
}
}
feed.items = items
}
internal fun readItem(parser: XmlPullParser): RssItem? {
var title: String? = null
var link: String? = null
var description: String? = null
var image: Image? = null
try {
while (parser.next() != XmlPullParser.END_TAG) {
var startedTag = parser.eventType == XmlPullParser.START_TAG
val name = parser.name
if (name != null) {
if (name == "title") {
parser.next()
title = parser.text
} else if (name == "description") {
parser.next()
description = parser.text
} else if (name == "link") {
parser.next()
link = parser.text
} else {
if (image == null) {
image = tryToFindImageInAttributes(parser)
}
}
}
if (startedTag) {
skip(parser)
startedTag = false
}
}
} catch (e: Exception) {
return null
}
return if (title != null && link != null) {
RssItem(title, link, description, image)
} else {
null
}
}
internal fun tryToFindImageInAttributes(parser: XmlPullParser): Image? {
var image: Image? = null
var byteSize = 0
val attrCount = parser.attributeCount
for (i in 0 until attrCount) {
val str = parser.getAttributeValue(i)
if (stringIsImageUrl(str)) {
var url: URL? = null
try {
url = URL(str)
image = Image()
image.url = url
} catch (e: MalformedURLException) {
}
}
if (parser.getAttributeName(i) == "length") {
byteSize = parser.getAttributeValue(i).toInt()
}
}
if (image != null) {
image.byteSize = byteSize
}
return image
}
internal fun stringIsImageUrl(string: String): Boolean {
return if (string.endsWith(".png") || string.endsWith(".jpg")) {
true
} else false
}
internal fun readImage(parser: XmlPullParser): Image? {
val item = Image()
try {
while (parser.next() != XmlPullParser.END_TAG) {
var startedTag = parser.eventType == XmlPullParser.START_TAG
val name = parser.name
if (name != null) {
if (name == "url") {
parser.next()
try {
val url = URL(parser.text)
item.url = url
} catch (e: Exception) {
e.printStackTrace()
}
} else if (name == "length") {
item.byteSize = parser.text.toInt()
} else if (name == "width") {
parser.next()
item.width = parser.text.toInt()
} else if (name == "height") {
parser.next()
item.height = parser.text.toInt()
}
}
if (startedTag) {
skip(parser)
startedTag = false
}
}
} catch (e: Exception) {
return null
}
return item
}
@Throws(XmlPullParserException::class, IOException::class)
private fun skip(parser: XmlPullParser) {
if (parser.eventType == XmlPullParser.END_TAG) {
parser.next()
return
}
var depth = 1
while (depth != 0) {
when (parser.next()) {
XmlPullParser.END_TAG -> depth--
XmlPullParser.START_TAG -> depth++
}
}
}
} | mit | 587a903ef0af2bee31ad585c82726145 | 30.944444 | 78 | 0.451297 | 5.031026 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-git/src/test/java/net/nemerosa/ontrack/extension/git/AbstractGitTestJUnit4Support.kt | 1 | 15376 | package net.nemerosa.ontrack.extension.git
import net.nemerosa.ontrack.extension.git.mocking.GitMockingConfigurationProperty
import net.nemerosa.ontrack.extension.git.mocking.GitMockingConfigurationPropertyType
import net.nemerosa.ontrack.extension.git.model.BasicGitConfiguration
import net.nemerosa.ontrack.extension.git.model.BranchInfo
import net.nemerosa.ontrack.extension.git.model.ConfiguredBuildGitCommitLink
import net.nemerosa.ontrack.extension.git.model.OntrackGitCommitInfo
import net.nemerosa.ontrack.extension.git.property.*
import net.nemerosa.ontrack.extension.git.service.GitConfigurationService
import net.nemerosa.ontrack.extension.git.service.GitService
import net.nemerosa.ontrack.extension.git.support.*
import net.nemerosa.ontrack.extension.issues.model.toIdentifier
import net.nemerosa.ontrack.extension.issues.support.MockIssueServiceConfiguration
import net.nemerosa.ontrack.extension.scm.support.TagPattern
import net.nemerosa.ontrack.git.GitRepositoryClientFactory
import net.nemerosa.ontrack.git.support.GitRepo
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import net.nemerosa.ontrack.job.JobRunListener
import net.nemerosa.ontrack.job.orchestrator.JobOrchestrator
import net.nemerosa.ontrack.model.security.GlobalSettings
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.model.support.NoConfig
import net.nemerosa.ontrack.test.TestUtils
import org.springframework.beans.factory.annotation.Autowired
import java.lang.Thread.sleep
import java.util.function.Consumer
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@Deprecated(message = "JUnit 4 is deprecated", replaceWith = ReplaceWith("AbstractGitTestSupport"))
abstract class AbstractGitTestJUnit4Support : AbstractQLKTITJUnit4Support() {
@Autowired
protected lateinit var gitConfigProperties: GitConfigProperties
@Autowired
private lateinit var commitBuildNameGitCommitLink: CommitBuildNameGitCommitLink
@Autowired
private lateinit var gitCommitPropertyCommitLink: GitCommitPropertyCommitLink
@Autowired
private lateinit var tagBuildNameGitCommitLink: TagBuildNameGitCommitLink
@Autowired
private lateinit var tagPatternBuildNameGitCommitLink: TagPatternBuildNameGitCommitLink
@Autowired
private lateinit var gitConfigurationService: GitConfigurationService
@Autowired
private lateinit var gitRepositoryClientFactory: GitRepositoryClientFactory
@Autowired
protected lateinit var gitService: GitService
@Autowired
private lateinit var jobOrchestrator: JobOrchestrator
/**
* Working with the PR cache disabled
*/
protected fun <T> withPRCacheDisabled(code: () -> T): T {
val old = gitConfigProperties.pullRequests.cache.enabled
return try {
gitConfigProperties.pullRequests.cache.enabled = false
code()
} finally {
gitConfigProperties.pullRequests.cache.enabled = old
}
}
/**
* Working with PR feature disabled
*/
protected fun <T> withPRDisabled(code: () -> T): T {
val old = gitConfigProperties.pullRequests.enabled
return try {
gitConfigProperties.pullRequests.enabled = false
code()
} finally {
gitConfigProperties.pullRequests.enabled = old
}
}
/**
* Working with PR cleanup feature disabled
*/
protected fun <T> withPRCleanupDisabled(code: () -> T): T {
val old = gitConfigProperties.pullRequests.cleanup.enabled
return try {
gitConfigProperties.pullRequests.cleanup.enabled = false
code()
} finally {
gitConfigProperties.pullRequests.cleanup.enabled = old
}
}
/**
* Working with custom PR cleanup properties
*/
protected fun <T> withPRCleanupProperties(disabling: Int? = null, deleting: Int? = null, code: () -> T): T {
val oldDisabling = gitConfigProperties.pullRequests.cleanup.disabling
val oldDeleting = gitConfigProperties.pullRequests.cleanup.deleting
return try {
disabling?.apply { gitConfigProperties.pullRequests.cleanup.disabling = this }
deleting?.apply { gitConfigProperties.pullRequests.cleanup.deleting = this }
code()
} finally {
gitConfigProperties.pullRequests.cleanup.disabling = oldDisabling
gitConfigProperties.pullRequests.cleanup.deleting = oldDeleting
}
}
/**
* Creates and saves a Git configuration
*/
protected fun createGitConfiguration(repo: GitRepo, sync: Boolean = true): BasicGitConfiguration {
val gitConfigurationName = TestUtils.uid("C")
val gitConfiguration = asUser().with(GlobalSettings::class.java).call {
gitConfigurationService.newConfiguration(
BasicGitConfiguration.empty()
.withName(gitConfigurationName)
.withIssueServiceConfigurationIdentifier(MockIssueServiceConfiguration.INSTANCE.toIdentifier().format())
.withRemote("file://${repo.dir.absolutePath}")
)
}
if (sync) {
gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository).sync(Consumer { println(it) })
}
return gitConfiguration
}
/**
* Configures a project for Git.
*/
protected fun Project.gitProject(repo: GitRepo, sync: Boolean = true) {
// Create a Git configuration
val gitConfiguration = createGitConfiguration(repo, sync)
// Configures the project
setProperty(
this,
GitProjectConfigurationPropertyType::class.java,
GitProjectConfigurationProperty(gitConfiguration)
)
// Makes sure to register the project
if (sync) {
asAdmin().execute {
jobOrchestrator.orchestrate(JobRunListener.out())
}
}
}
/**
* Configures a project for Git, with compatibility with pull requests (mocking)
*/
protected fun Project.prGitProject(repo: GitRepo, sync: Boolean = true) {
// Create a Git configuration
val gitConfiguration = createGitConfiguration(repo, sync)
// Configures the project
setProperty(
this,
GitMockingConfigurationPropertyType::class.java,
GitMockingConfigurationProperty(gitConfiguration, null)
)
// Makes sure to register the project
if (sync) {
asAdmin().execute {
jobOrchestrator.orchestrate(JobRunListener.out())
}
}
}
/**
* Configures a branch for Git.
*
* @receiver Branch to configure
* @param branchName Git branch to associate with the branch
* @param commitLinkConfiguration Returns the build commit link, defaults to [buildNameAsCommit]
*/
protected fun Branch.gitBranch(
branchName: String = "main",
commitLinkConfiguration: () -> ConfiguredBuildGitCommitLink<*> = { buildNameAsCommit() }
) {
asAdmin().execute {
propertyService.editProperty(
this,
GitBranchConfigurationPropertyType::class.java,
GitBranchConfigurationProperty(
branchName,
commitLinkConfiguration().toServiceConfiguration(),
false, 0
)
)
}
}
/**
* Configuration of a build commit link based on build name being a commit
*/
protected fun buildNameAsCommit(abbreviated: Boolean = true): ConfiguredBuildGitCommitLink<CommitLinkConfig> {
return ConfiguredBuildGitCommitLink(
commitBuildNameGitCommitLink,
CommitLinkConfig(abbreviated)
)
}
/**
* Configuration of a build commit link based on a commit property.
*/
protected fun commitAsProperty() = ConfiguredBuildGitCommitLink(
gitCommitPropertyCommitLink,
NoConfig.INSTANCE
)
/**
* Configuration of a build commit link based on tag as build name.
*/
protected fun tagBuildName() = ConfiguredBuildGitCommitLink(
tagBuildNameGitCommitLink,
NoConfig.INSTANCE
)
/**
* Configuration of a build commit link based on tag pattern as build name.
*/
protected fun tagPatternBuildName(pattern: String) = ConfiguredBuildGitCommitLink(
tagPatternBuildNameGitCommitLink,
TagPattern(pattern)
)
/**
* Sets the Git commit property on a build
*/
protected fun Build.gitCommitProperty(commit: String) {
setProperty(
this,
GitCommitPropertyType::class.java,
GitCommitProperty(commit)
)
}
/**
* Creates [n] commits, from 1 to [n], with message being "Commit `i`" by default.
*
* @param n Number of commits to create
* @param pauses `true` if we must pause ~ 1 second between each commit (default to `false`)
* @param shortId `true` if we must return the short commit hash, not the long ones (default to `false`)
* @return A map where the key in the index, and the value is the commit hash.
*/
protected fun GitRepo.commits(n: Int, pauses: Boolean = false, shortId: Boolean = false) =
(1..n).associate {
val message = "Commit $it"
commit(it, message)
val hash = commitLookup(message, shortId)
if (pauses) sleep(1010)
it to hash
}
/**
* Creates a sequence of commits on different branches.
*/
protected fun GitRepo.sequence(vararg commands: Any): Map<Int, String> =
runSequence(commands.toList(), false)
/**
* Creates a sequence of commits on different branches, pausing after each commit
*/
protected fun GitRepo.sequenceWithPauses(vararg commands: Any): Map<Int, String> =
runSequence(commands.toList(), true)
/**
* Creates a sequence of commits on different branches.
*/
private fun GitRepo.runSequence(commands: List<*>, pauses: Boolean): Map<Int, String> {
val index = mutableMapOf<Int, String>()
val branches = mutableSetOf("main")
commands.forEach { command ->
when (command) {
// Branch
is String -> branch(command, branches)
// Single commit
is Int -> {
index[command] = commit(command)
if (pauses) sleep(1010)
}
// Range of commit
is IntRange -> command.forEach {
index[it] = commit(it)
if (pauses) sleep(1010)
}
// Commit to tag
is Pair<*, *> -> {
val commit = command.first as Int
val tag = command.second as String
index[commit] = commit(commit)
tag(tag)
if (pauses) sleep(1010)
}
// Any other item
else -> throw IllegalArgumentException("Unknown type: $command")
}
}
return index
}
private fun GitRepo.branch(branch: String, branches: MutableSet<String>) {
if (branches.contains(branch)) {
git("checkout", branch)
} else {
branches += branch
git("checkout", "-b", branch)
}
}
protected fun withRepo(code: (GitRepo) -> Unit) {
createRepo { commits(1) } and { repo, _ -> code(repo) }
}
protected fun <T> createRepo(init: GitRepo.() -> T) = RepoTestActions(init)
protected class RepoTestActions<T>(
private val init: GitRepo.() -> T
) {
infix fun and(code: (GitRepo, T) -> Unit) {
var value: T? = null
GitRepo.prepare {
gitInit()
value = init()
log()
} and { _, repo ->
repo.use {
code(it, value!!)
}
}
}
}
protected fun commitInfoTest(
project: Project,
commits: Map<Int, String>,
no: Int,
tests: OntrackGitCommitInfo.() -> Unit
) {
val commit = commits.getValue(no)
val info = gitService.getCommitProjectInfo(project.id, commit)
// Commit message & hash
assertEquals(commit, info.uiCommit.id)
assertEquals("Commit $no", info.uiCommit.annotatedMessage)
// Tests
info.tests()
}
protected fun OntrackGitCommitInfo.assertBranchInfos(
vararg tests: Pair<String, List<BranchInfoTest>>
) {
assertEquals(tests.size, branchInfos.size, "Number of tests must match the number of collected branch infos")
// Test per test
tests.forEach { (type, branchInfoTests) ->
val branchInfoList = branchInfos[type]
assertNotNull(branchInfoList) { it ->
assertEquals(branchInfoTests.size, it.size, "Number of tests for type $type must match the number of collect branch infos")
// Group by pair
it.zip(branchInfoTests).forEach { (branchInfo, branchInfoTest) ->
branchInfoTest(branchInfo)
}
}
}
}
protected class BranchInfoTest(
private val branch: String,
private val firstBuild: String?,
private val promotions: List<Pair<String, String>> = emptyList()
) {
operator fun invoke(branchInfo: BranchInfo) {
// Branch
assertEquals(branch, branchInfo.branch.name)
// First build test
if (firstBuild != null) {
assertNotNull(branchInfo.firstBuild, "First build expected") {
assertEquals(firstBuild, it.name)
}
} else {
assertNull(branchInfo.firstBuild, "No first build")
}
// Promotion tests
assertEquals(promotions.size, branchInfo.promotions.size)
branchInfo.promotions.zip(promotions).forEach { (run, promotionTest) ->
val promotion = promotionTest.first
val name = promotionTest.second
assertEquals(promotion, run.promotionLevel.name)
assertEquals(name, run.build.name)
}
}
}
protected fun Branch.build(
no: Int,
commits: Map<Int, String>,
validations: List<ValidationStamp> = emptyList(),
promotions: List<PromotionLevel> = emptyList()
) {
build(no.toString()) {
gitCommitProperty(commits.getValue(no))
validations.forEach { validate(it) }
promotions.forEach { promote(it) }
gitService.getCommitForBuild(this)?.let {
println("build=$entityDisplayName,commit=${it.commit.shortId},time=${it.commit.commitTime},timestamp=${it.timestamp}")
}
}
}
} | mit | 65f5e75682eca021ee29538c5d11dec9 | 35.963942 | 139 | 0.616545 | 5.047932 | false | true | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/language/ArrayValue.kt | 1 | 508 | package graphql.language
class ArrayValue() : AbstractNode(), Value {
val values: MutableList<Value> = mutableListOf()
constructor(values: List<Value>) : this() {
this.values.addAll(values)
}
override val children: List<Node>
get() = values
fun add(value: Value) {
values += value
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
return true
}
}
| mit | f13cdc98442d4f9006183f179df4ea75 | 21.086957 | 53 | 0.604331 | 4.34188 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/errorhandling/ExceptionHandler.kt | 1 | 4654 | /*
* Nextcloud Android client application
*
* @author LukeOwncloud
* @author AndyScherzinger
* @author Tobias Kaminsky
* @author Chris Narkiewicz
*
* Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2016 LukeOwncloud
* Copyright (C) 2019 Andy Scherzinger
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.errorhandling
import android.content.Context
import android.content.Intent
import android.os.Build
import com.owncloud.android.BuildConfig
import com.owncloud.android.R
class ExceptionHandler(
private val context: Context,
private val defaultExceptionHandler: Thread.UncaughtExceptionHandler
) : Thread.UncaughtExceptionHandler {
companion object {
private const val LINE_SEPARATOR = "\n"
private const val EXCEPTION_FORMAT_MAX_RECURSIVITY = 10
}
override fun uncaughtException(thread: Thread, exception: Throwable) {
@Suppress("TooGenericExceptionCaught") // this is exactly what we want here
try {
val errorReport = generateErrorReport(formatException(thread, exception))
val intent = Intent(context, ShowErrorActivity::class.java)
intent.putExtra(ShowErrorActivity.EXTRA_ERROR_TEXT, errorReport)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
// Pass exception to OS for graceful handling - OS will report it via ADB
// and close all activities and services.
defaultExceptionHandler.uncaughtException(thread, exception)
} catch (fatalException: Exception) {
// do not recurse into custom handler if exception is thrown during
// exception handling. Pass this ultimate fatal exception to OS
defaultExceptionHandler.uncaughtException(thread, fatalException)
}
}
private fun formatException(thread: Thread, exception: Throwable): String {
fun formatExceptionRecursive(thread: Thread, exception: Throwable, count: Int = 0): String {
if (count > EXCEPTION_FORMAT_MAX_RECURSIVITY) {
return "Max number of recursive exception causes exceeded!"
}
// print exception
val stringBuilder = StringBuilder()
val stackTrace = exception.stackTrace
stringBuilder.appendLine("Exception in thread \"${thread.name}\" $exception")
// print available stacktrace
for (element in stackTrace) {
stringBuilder.appendLine(" at $element")
}
// print cause recursively
exception.cause?.let {
stringBuilder.append("Caused by: ")
stringBuilder.append(formatExceptionRecursive(thread, it, count + 1))
}
return stringBuilder.toString()
}
return formatExceptionRecursive(thread, exception, 0)
}
private fun generateErrorReport(stackTrace: String): String {
val buildNumber = context.resources.getString(R.string.buildNumber)
val buildNumberString = when {
buildNumber.isNotEmpty() -> " (build #$buildNumber)"
else -> ""
}
return """
|### Cause of error
|```java
${stackTrace.prependIndent("|")}
|```
|
|### App information
|* ID: `${BuildConfig.APPLICATION_ID}`
|* Version: `${BuildConfig.VERSION_CODE}$buildNumberString`
|* Build flavor: `${BuildConfig.FLAVOR}`
|
|### Device information
|* Brand: `${Build.BRAND}`
|* Device: `${Build.DEVICE}`
|* Model: `${Build.MODEL}`
|* Id: `${Build.ID}`
|* Product: `${Build.PRODUCT}`
|
|### Firmware
|* SDK: `${Build.VERSION.SDK_INT}`
|* Release: `${Build.VERSION.RELEASE}`
|* Incremental: `${Build.VERSION.INCREMENTAL}`
""".trimMargin("|")
}
}
| gpl-2.0 | 03d861dee689a3083fc3822db79fddd8 | 38.440678 | 100 | 0.625483 | 4.924868 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | buildSrc/src/main/kotlin/com/engineer/plugin/transforms/cat/CatTransform.kt | 1 | 5986 | package com.engineer.plugin.transforms.cat
import com.android.build.api.transform.Format
import com.android.build.api.transform.QualifiedContent
import com.android.build.api.transform.Transform
import com.android.build.api.transform.TransformInvocation
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import org.gradle.api.Project
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import java.io.File
import java.io.FileOutputStream
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry
/**
* @author rookie
* @since 11-29-2019
*/
class CatTransform(private val project: Project) : Transform() {
override fun getName(): String {
return "cat"
}
override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> {
return TransformManager.CONTENT_CLASS
}
override fun isIncremental(): Boolean {
return false
}
override fun getScopes(): MutableSet<in QualifiedContent.Scope> {
return TransformManager.SCOPE_FULL_PROJECT
}
override fun transform(transformInvocation: TransformInvocation?) {
super.transform(transformInvocation)
val outputProvider = transformInvocation?.outputProvider
if (!isIncremental) {
outputProvider?.deleteAll()
}
transformInvocation?.inputs?.forEach { input ->
input.directoryInputs.forEach { directoryInput ->
if (directoryInput.file.isDirectory) {
FileUtils.getAllFiles(directoryInput.file).forEach {
val file = it
val name = file.name
if (name.endsWith(".class") && name != ("R.class")
&& !name.startsWith("R\$") && name != ("BuildConfig.class")
) {
val reader = ClassReader(file.readBytes())
val writer = ClassWriter(reader, ClassWriter.COMPUTE_MAXS)
val visitor = CatClassVisitor(project, writer)
reader.accept(visitor, ClassReader.EXPAND_FRAMES)
val code = writer.toByteArray()
val classPath = file.parentFile.absolutePath + File.separator + name
val fos = FileOutputStream(classPath)
fos.write(code)
fos.close()
}
}
}
val dest = transformInvocation.outputProvider?.getContentLocation(
directoryInput.name,
directoryInput.contentTypes,
directoryInput.scopes,
Format.DIRECTORY
)
FileUtils.copyDirectoryToDirectory(directoryInput.file, dest)
}
input.jarInputs.forEach { jarInput ->
val src = jarInput.file
val dest = transformInvocation.outputProvider?.getContentLocation(
jarInput.name,
jarInput.contentTypes, jarInput.scopes, Format.JAR
)
// println()
// println("jar Name "+jarInput.name)
// println("dest "+dest?.absolutePath)
// println("jar path "+src.absolutePath)
// println("jar name "+src.name)
// println()
if (jarInput.name == "include") {
println("jar Name " + jarInput.name)
println("dest " + dest?.absolutePath)
println("jar path " + src.absolutePath)
println("jar name " + src.name)
val temp =
src.absolutePath.substring(0, src.absolutePath.length - 4) + "_cat.jar"
val tempFile = File(temp)
if (tempFile.exists()) {
tempFile.delete()
}
val outputStream = JarOutputStream(FileOutputStream(tempFile))
val jarFile = JarFile(src)
val entries = jarFile.entries()
while (entries.hasMoreElements()) {
val jarEntry = entries.nextElement()
val jarName = jarEntry.name
println("jarName==$jarName")
val inputStream = jarFile.getInputStream(jarEntry)
val zipEntry = ZipEntry(jarName)
outputStream.putNextEntry(zipEntry)
if (jarName.endsWith(".class") && jarName.startsWith("home")) {
val reader = ClassReader(inputStream)
val writer = ClassWriter(reader, ClassWriter.COMPUTE_MAXS)
val visitor = CatClassVisitor(project, writer)
reader.accept(visitor, ClassReader.EXPAND_FRAMES)
val code = writer.toByteArray()
outputStream.write(code)
} else {
println("unsupported jarName==$jarName")
var len = inputStream.read()
while (len != -1) {
outputStream.write(len)
len = inputStream.read()
}
}
inputStream.close()
}
outputStream.flush()
outputStream.close()
FileUtils.copyFile(tempFile, dest)
tempFile.delete()
// tempFile.renameTo(src)
} else {
FileUtils.copyFile(src, dest)
}
}
}
}
} | apache-2.0 | c959a9e615f0f9508ce920323730a33b | 37.378205 | 96 | 0.51136 | 5.739214 | false | false | false | false |
MrBIMC/RunInBackgroundPermissionSetter | app/src/main/java/com/pavelsikun/runinbackgroundpermissionsetter/ShellUtil.kt | 1 | 1266 | package com.pavelsikun.runinbackgroundpermissionsetter
import eu.chainfire.libsuperuser.Shell
import java.util.concurrent.CompletableFuture
/**
* Created by Pavel Sikun on 16.07.17.
*/
typealias Callback = (isSuccess: Boolean) -> Unit
private val shell by lazy { Shell.Builder()
.setShell("su")
.open()
}
fun checkRunInBackgroundPermission(pkg: String): CompletableFuture<Boolean> {
val future = CompletableFuture<Boolean>()
shell.addCommand("cmd appops get $pkg RUN_IN_BACKGROUND", 1) { _, _, output: MutableList<String> ->
val outputString = output.joinToString()
val runInBackgroundEnabled = outputString.contains("allow")
future.complete(runInBackgroundEnabled)
}
return future
}
fun setRunInBackgroundPermission(pkg: String, setEnabled: Boolean, callback: Callback): CompletableFuture<Boolean> {
val future = CompletableFuture<Boolean>()
val cmd = if (setEnabled) "allow" else "ignore"
shell.addCommand("cmd appops set $pkg RUN_IN_BACKGROUND $cmd", 1) { _, _, output: MutableList<String> ->
val outputString = output.joinToString()
val isSuccess = outputString.trim().isEmpty()
callback(isSuccess)
future.complete(isSuccess)
}
return future
} | gpl-3.0 | ef9d1de56b5abdd6fe535a0bf6eb8a55 | 30.675 | 116 | 0.703791 | 4.20598 | false | false | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/TownEntity.kt | 1 | 2173 | /*
* Copyright (c) 2017 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.entity
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Table
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* @author nmaerchy
* @version 0.0.1
*/
@Entity
@Table(name = "TOWN")
data class TownEntity(
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null,
@NotNull
@Size(min = 4, max = 4)
var zip: String = "",
@NotNull
@Size(min = 1, max = 50)
var name: String = ""
)
| gpl-3.0 | 6e8181a013f5acd689d169cc33f3789d | 31.283582 | 77 | 0.739251 | 4.183752 | false | false | false | false |
AromaTech/banana-data-operations | src/test/java/tech/aroma/data/AromaGenerators.kt | 3 | 3610 | /*
* Copyright 2017 RedRoma, 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 tech.aroma.data
import tech.aroma.thrift.Application
import tech.aroma.thrift.Image
import tech.aroma.thrift.Message
import tech.aroma.thrift.ProgrammingLanguage
import tech.aroma.thrift.Tier
import tech.aroma.thrift.authentication.AuthenticationToken
import tech.aroma.thrift.generators.ApplicationGenerators
import tech.aroma.thrift.generators.ChannelGenerators.mobileDevices
import tech.aroma.thrift.generators.ImageGenerators
import tech.aroma.thrift.generators.MessageGenerators.messages
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.EnumGenerators
import tech.sirwellington.alchemy.generator.ObjectGenerators.pojos
import tech.sirwellington.alchemy.generator.StringGenerators
import tech.sirwellington.alchemy.generator.TimeGenerators
import tech.sirwellington.alchemy.generator.one
/**
*
* @author SirWellington
*/
class AromaGenerators
{
companion object
{
val id: String get() = StringGenerators.uuids.get()
val name: String get() = StringGenerators.alphabeticStrings().get()
}
object Times
{
val pastTimes: Long
get() = TimeGenerators.pastInstants().get().toEpochMilli()
val futureTimes: Long
get() = TimeGenerators.futureInstants().get().toEpochMilli()
val currentTimes: Long
get() = TimeGenerators.presentInstants().get().toEpochMilli()
}
object Applications
{
val programmingLanguage: ProgrammingLanguage get() = EnumGenerators.enumValueOf(ProgrammingLanguage::class.java).get()
val tier: Tier get() = EnumGenerators.enumValueOf(Tier::class.java).get()
val owner: String get() = StringGenerators.uuids.get()
val owners: Set<String> get() = CollectionGenerators.listOf(StringGenerators.uuids, 5).toSet()
val application: Application get() = ApplicationGenerators.applications().get()
}
object Devices
{
val device get() = one(mobileDevices())!!
val devices get() = CollectionGenerators.listOf(mobileDevices(), 10).toMutableSet()!!
}
object Messages
{
val message: Message get() = one(messages()).setTimeOfCreation(Times.currentTimes)
val messages get() = CollectionGenerators.listOf(messages(), 10)!!
}
object Tokens
{
val token: AuthenticationToken
get()
{
val token = one(pojos(AuthenticationToken::class.java))
token.unsetOrganizationName()
return token
.setTokenId(id)
.setOrganizationId(id)
.setOwnerId(id)
.setTimeOfCreation(Times.currentTimes)
.setTimeOfExpiration(Times.futureTimes)
}
}
object Images
{
val icon: Image get() = ImageGenerators.appIcons().get()
val profileImage: Image get() = ImageGenerators.profileImages().get()
}
} | apache-2.0 | 9ed12a0ae3b6ccbce6b392eb1e4f8fad | 30.12931 | 126 | 0.685873 | 4.670116 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/billing/ign/Billing.kt | 1 | 8233 | package com.peterlaurence.trekme.billing.ign
import android.app.Activity
import android.content.Context
import android.util.Log
import com.android.billingclient.api.*
import com.android.billingclient.api.BillingClient.BillingResponseCode.*
import com.peterlaurence.trekme.viewmodel.mapcreate.IgnLicenseDetails
import com.peterlaurence.trekme.viewmodel.mapcreate.NotSupportedException
import com.peterlaurence.trekme.viewmodel.mapcreate.ProductNotFoundException
import kotlinx.coroutines.delay
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
const val IGN_LICENSE_SKU = "ign_license"
typealias PurchaseAcknowledgedCallback = () -> Unit
typealias PurchasePendingCallback = () -> Unit
class Billing(val context: Context, val activity: Activity) : PurchasesUpdatedListener, AcknowledgePurchaseResponseListener {
private val billingClient = BillingClient.newBuilder(context).setListener(this).enablePendingPurchases().build()
private lateinit var purchaseAcknowledgedCallback: PurchaseAcknowledgedCallback
private lateinit var purchasePendingCallback: PurchasePendingCallback
/**
* This function returns when we're connected to the billing service.
*/
private suspend fun connectClient() = suspendCoroutine<Boolean> {
if (billingClient.isReady) {
it.resume(true)
return@suspendCoroutine
}
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
/* It already happened that this continuation was called twice, resulting in IllegalStateException */
try {
if (billingResult.responseCode == OK) {
it.resume(true)
} else {
it.resume(false)
}
} catch (e: Exception) {
}
}
override fun onBillingServiceDisconnected() {
}
})
}
override fun onPurchasesUpdated(billingResult: BillingResult?, purchases: MutableList<Purchase>?) {
fun acknowledge() {
purchases?.forEach {
if (it.sku == IGN_LICENSE_SKU) {
if (it.purchaseState == Purchase.PurchaseState.PURCHASED && !it.isAcknowledged) {
acknowledgeIgnLicense(it)
} else if (it.purchaseState == Purchase.PurchaseState.PENDING) {
if (this::purchasePendingCallback.isInitialized) {
purchasePendingCallback()
}
}
}
}
}
if (billingResult != null && purchases != null) {
if (billingResult.responseCode == OK) {
acknowledge()
}
}
}
private fun acknowledgeIgnLicense(purchase: Purchase) {
/* Approve the payment */
val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
billingClient.acknowledgePurchase(acknowledgePurchaseParams, this)
}
private fun shouldAcknowledgeIgnLicense(purchase: Purchase): Boolean {
return purchase.sku == IGN_LICENSE_SKU && purchase.purchaseState == Purchase.PurchaseState.PURCHASED && !purchase.isAcknowledged
}
/**
* This is the callback of the [BillingClient.acknowledgePurchase] call.
* The [purchaseAcknowledgedCallback] is called only if the purchase is successfully acknowledged.
*/
override fun onAcknowledgePurchaseResponse(billingResult: BillingResult?) {
/* Then notify registered PurchaseListener that it completed normally */
billingResult?.also {
if (it.responseCode == OK && this::purchaseAcknowledgedCallback.isInitialized) {
purchaseAcknowledgedCallback()
} else {
Log.e(TAG, "Payment couldn't be acknowledged (code ${it.responseCode}): ${it.debugMessage}")
}
}
}
/**
* This is one of the first things to do. If the IGN license is among the purchases, check if it
* should be acknowledged. This call is required when the acknowledgement wasn't done right after
* a billing flow (typically when the payment method is slow and the user didn't wait the end of
* the procedure with the [onPurchasesUpdated] call). So we can end up with a purchase which is
* in [Purchase.PurchaseState.PURCHASED] state but not acknowledged.
* This is why the acknowledgement is also made here.
*/
suspend fun acknowledgeIgnLicense(purchaseAcknowledgedCallback: PurchaseAcknowledgedCallback): Boolean {
runCatching { connectWithRetry() }.onFailure { return false }
val purchases = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
return purchases.purchasesList?.getIgnLicense()?.let {
this.purchaseAcknowledgedCallback = purchaseAcknowledgedCallback
if (shouldAcknowledgeIgnLicense(it)) {
acknowledgeIgnLicense(it)
true
} else false
} ?: false
}
suspend fun getIgnLicensePurchase(): Purchase? {
runCatching { connectWithRetry() }.onFailure { return null }
val purchases = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
return purchases.purchasesList.getValidIgnLicense()?.let {
if (checkTime(it.purchaseTime) !is AccessGranted) {
it.consumeIgnLicense()
null
} else it
}
}
private fun List<Purchase>.getIgnLicense(): Purchase? {
return firstOrNull { it.sku == IGN_LICENSE_SKU }
}
private fun List<Purchase>.getValidIgnLicense(): Purchase? {
return firstOrNull { it.sku == IGN_LICENSE_SKU && it.isAcknowledged }
}
private fun Purchase.consumeIgnLicense() {
if (sku == IGN_LICENSE_SKU) {
consume(purchaseToken)
}
}
private fun consume(token: String) {
val consumeParams = ConsumeParams.newBuilder().setPurchaseToken(token).build()
billingClient.consumeAsync(consumeParams) { _, _ ->
Log.i(TAG, "Consumed the purchase. It can now be bought again.")
}
}
suspend fun getIgnLicenseDetails(): IgnLicenseDetails {
connectWithRetry()
val (billingResult, skuDetailsList) = queryIgnLicenseSku()
return when (billingResult.responseCode) {
OK -> skuDetailsList.find { it.sku == IGN_LICENSE_SKU }?.let {
IgnLicenseDetails(it)
} ?: throw ProductNotFoundException()
FEATURE_NOT_SUPPORTED -> throw NotSupportedException()
SERVICE_DISCONNECTED -> error("should retry")
else -> error("other error")
}
}
private suspend fun connectWithRetry() {
var retryCnt = 0
while (!connectClient()) {
retryCnt++
delay(1000)
if (retryCnt > 5) error("Couldn't connect to billing client")
}
}
private suspend fun queryIgnLicenseSku() = suspendCoroutine<SkuQueryResult> {
val skuList = ArrayList<String>()
skuList.add(IGN_LICENSE_SKU)
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)
billingClient.querySkuDetailsAsync(params.build()) { billingResult, skuDetailsList ->
it.resume(SkuQueryResult(billingResult, skuDetailsList))
}
}
data class SkuQueryResult(val billingResult: BillingResult, val skuDetailsList: List<SkuDetails>)
fun launchBilling(skuDetails: SkuDetails, purchaseAcknowledgedCb: PurchaseAcknowledgedCallback, purchasePendingCb: PurchasePendingCallback) {
val flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build()
this.purchaseAcknowledgedCallback = purchaseAcknowledgedCb
this.purchasePendingCallback = purchasePendingCb
billingClient.launchBillingFlow(activity, flowParams)
}
}
const val TAG = "ign.Billing.kt"
| gpl-3.0 | a480056809a2eabf61aa3e51e04bd4ad | 39.960199 | 145 | 0.652253 | 5.223985 | false | false | false | false |
AndroidX/androidx | navigation/navigation-ui/src/androidTest/java/androidx/navigation/ui/NavigationUITest.kt | 3 | 8121 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.ui
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import androidx.core.content.res.TypedArrayUtils.getString
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.createGraph
import androidx.navigation.ui.test.R
import androidx.test.annotation.UiThreadTest
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.TestNavigator
import androidx.testutils.test
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class NavigationUITest {
@UiThreadTest
@Test
fun navigateWithSingleStringReferenceArg() {
val context = ApplicationProvider.getApplicationContext<Context>()
val navController = NavHostController(context)
navController.navigatorProvider.addNavigator(TestNavigator())
val startDestination = "start_destination"
val endDestination = "end_destination"
navController.graph = navController.createGraph(startDestination = startDestination) {
test(startDestination)
test("$endDestination/{test}") {
label = "{test}"
argument(name = "test") {
type = NavType.ReferenceType
}
}
}
val toolbar = Toolbar(context).apply { setupWithNavController(navController) }
navController.navigate(
endDestination + "/${R.string.dest_title}"
)
val expected = "${context.resources.getString(R.string.dest_title)}"
assertThat(toolbar.title.toString()).isEqualTo(expected)
}
@UiThreadTest
@Test
fun navigateWithMultiStringReferenceArgs() {
val context = ApplicationProvider.getApplicationContext<Context>()
val navController = NavHostController(context)
navController.navigatorProvider.addNavigator(TestNavigator())
val startDestination = "start_destination"
val endDestination = "end_destination"
navController.graph = navController.createGraph(startDestination = startDestination) {
test(startDestination)
test("$endDestination/{test}") {
label = "start/{test}/end/{test}"
argument(name = "test") {
type = NavType.ReferenceType
}
}
}
val toolbar = Toolbar(context).apply { setupWithNavController(navController) }
navController.navigate(
endDestination + "/${R.string.dest_title}"
)
val argString = context.resources.getString(R.string.dest_title)
val expected = "start/$argString/end/$argString"
assertThat(toolbar.title.toString()).isEqualTo(expected)
}
@UiThreadTest
@Test(expected = IllegalArgumentException::class)
fun navigateWithArg_NotFoundInBundleThrows() {
val context = ApplicationProvider.getApplicationContext<Context>()
val navController = NavHostController(context)
navController.navigatorProvider.addNavigator(TestNavigator())
val startDestination = "start_destination"
val endDestination = "end_destination"
val labelString = "end/{test}"
navController.graph = navController.createGraph(startDestination = startDestination) {
test(startDestination)
test(endDestination) {
label = labelString
}
}
val toolbar = Toolbar(context).apply { setupWithNavController(navController) }
// empty bundle
val testListener = createToolbarOnDestinationChangedListener(
toolbar = toolbar, bundle = Bundle(), context = context, navController = navController
)
// navigate to destination. Since the argument {test} is not present in the bundle,
// this should throw an IllegalArgumentException
navController.apply {
addOnDestinationChangedListener(testListener)
navigate(route = endDestination)
}
}
@UiThreadTest
@Test(expected = IllegalArgumentException::class)
fun navigateWithArg_NullBundleThrows() {
val context = ApplicationProvider.getApplicationContext<Context>()
val navController = NavHostController(context)
navController.navigatorProvider.addNavigator(TestNavigator())
val startDestination = "start_destination"
val endDestination = "end_destination"
val labelString = "end/{test}"
navController.graph = navController.createGraph(startDestination = startDestination) {
test(startDestination)
test("$endDestination/{test}") {
label = labelString
argument(name = "test") {
type = NavType.ReferenceType
}
}
}
val toolbar = Toolbar(context).apply { setupWithNavController(navController) }
// null Bundle
val testListener = createToolbarOnDestinationChangedListener(
toolbar = toolbar, bundle = null, context = context, navController = navController
)
// navigate to destination, should throw due to template found but null bundle
navController.apply {
addOnDestinationChangedListener(testListener)
navigate(route = endDestination + "/${R.string.dest_title}")
}
}
@UiThreadTest
@Test
fun navigateWithStaticLabel() {
val context = ApplicationProvider.getApplicationContext<Context>()
val navController = NavHostController(context)
navController.navigatorProvider.addNavigator(TestNavigator())
val startDestination = "start_destination"
val endDestination = "end_destination"
val labelString = "end/test"
navController.graph = navController.createGraph(startDestination = startDestination) {
test(startDestination)
test(endDestination) {
label = labelString
}
}
val toolbar = Toolbar(context).apply { setupWithNavController(navController) }
// navigate to destination, static label should be returned directly
navController.navigate(route = endDestination)
assertThat(toolbar.title.toString()).isEqualTo(labelString)
}
private fun createToolbarOnDestinationChangedListener(
toolbar: Toolbar,
bundle: Bundle?,
context: Context,
navController: NavController
): NavController.OnDestinationChangedListener {
return object : AbstractAppBarOnDestinationChangedListener(
context, AppBarConfiguration.Builder(navController.graph).build()
) {
override fun setTitle(title: CharSequence?) {
toolbar.title = title
}
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
super.onDestinationChanged(controller, destination, bundle)
}
override fun setNavigationIcon(icon: Drawable?, contentDescription: Int) {}
}
}
}
| apache-2.0 | a38fa7a12e4eedacd12e49ee0d09728d | 35.913636 | 98 | 0.67073 | 5.505763 | false | true | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/SubscriptionInteraction.kt | 1 | 1270 | @file:JvmName("SubscriptionInteractionUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
import com.vimeo.networking2.enums.StreamAccessType
import com.vimeo.networking2.enums.asEnum
import java.util.Date
/**
* Information on the subscription video action.
*
* @param drm Whether the video has DRM.
* @param expiresTime The time in ISO 8601 format when the subscription expires.
* @param purchaseTime The time in ISO 8601 format when the subscription was purchased.
* @param streamAccess The stream type. See [SubscriptionInteraction.streamAccessType].
*/
@Internal
@JsonClass(generateAdapter = true)
data class SubscriptionInteraction(
@Internal
@Json(name = "drm")
val drm: Boolean? = null,
@Internal
@Json(name = "expires_time")
val expiresTime: Date? = null,
@Internal
@Json(name = "purchase_time")
val purchaseTime: Date? = null,
@Internal
@Json(name = "stream")
val streamAccess: String? = null
)
/**
* @see SubscriptionInteraction.streamAccess
* @see StreamAccessType
*/
val SubscriptionInteraction.streamAccessType: StreamAccessType
get() = streamAccess.asEnum(StreamAccessType.UNKNOWN)
| mit | 561879914f1c28b604e400e969b84017 | 26.021277 | 87 | 0.748031 | 4.018987 | false | false | false | false |
config4k/config4k | src/test/kotlin/io/github/config4k/TestToConfigForArbitraryType.kt | 1 | 2808 | package io.github.config4k
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
import java.net.URL
import java.time.Duration
import java.util.*
class TestToConfigForArbitraryType : WordSpec({
"Person.toConfig" should {
"return Config having Person" {
val person = Person("foo", 20).toConfig("person")
person.extract<Person>("person") shouldBe Person("foo", 20)
}
}
"Nest.toConfig" should {
"return Config having Nest" {
val nest = Nest(1, Person("foo", 20)).toConfig("nest")
nest.extract<Nest>("nest") shouldBe
Nest(1, Person("foo", 20))
}
}
"NullableName.toConfig" should {
"return Config having name" {
val person = NullableName("foo").toConfig("nullable")
person.extract<NullableName>("nullable") shouldBe
NullableName("foo")
}
"return Config having null" {
val person = NullableName(null).toConfig("nullable")
person.extract<NullableName>("nullable") shouldBe
NullableName(null)
}
}
"Size.toConfig" should {
"return Config having Size" {
val person = Size.SMALL.toConfig("size")
person.extract<Size>("size") shouldBe Size.SMALL
}
}
"PrivatePerson.toConfig" should {
"return Config having Person" {
val person = PrivatePerson("foo", 20).toConfig("person")
person.extract<PrivatePerson>("person") shouldBe PrivatePerson("foo", 20)
}
}
"DataWithUUID.toConfig" should {
"return Config having DataWithUUID" {
val data = DataWithUUID(UUID.fromString("3f5f1d2f-38b7-4a14-9e67-c618d8f83189"))
val config = data.toConfig("data")
config.extract<DataWithUUID>("data") shouldBe data
}
}
"DataWithURL.toConfig" should {
"return Config having DataWithURL" {
val data = DataWithURL(URL("https://config4k.github.io/config4k/"))
val config = data.toConfig("data")
config.extract<DataWithURL>("data") shouldBe data
}
}
"DataWithDuration.toConfig" should {
"return Config having DataWithDuration" {
val data = DataWithDuration(Duration.ofMinutes(15))
val config = data.toConfig("data")
config.extract<DataWithDuration>("data") shouldBe data
val dataNanos = DataWithDuration(Duration.ofHours(8).plusNanos(123))
val configNanos = dataNanos.toConfig("data")
configNanos.extract<DataWithDuration>("data") shouldBe dataNanos
}
}
})
data class NullableName(val name: String?)
private data class PrivatePerson(val name: String, val age: Int? = 10)
| apache-2.0 | c506699cee3d4ddee8ef646bb6ba2a99 | 32.428571 | 92 | 0.608262 | 4.216216 | false | true | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/anime/NoWifiDialog.kt | 1 | 1581 | package me.proxer.app.anime
import android.app.Dialog
import android.os.Bundle
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseDialog
import me.proxer.app.util.extension.getSafeString
/**
* @author Ruben Gees
*/
class NoWifiDialog : BaseDialog() {
companion object {
private const val STREAM_ID_ARGUMENT = "stream_id"
fun show(activity: AppCompatActivity, fragment: Fragment, streamId: String) = NoWifiDialog()
.apply { arguments = bundleOf(STREAM_ID_ARGUMENT to streamId) }
.apply { setTargetFragment(fragment, 0) }
.show(activity.supportFragmentManager, "no_wifi_dialog")
}
private val remember by bindView<CheckBox>(R.id.remember)
private val streamId: String
get() = requireArguments().getSafeString(STREAM_ID_ARGUMENT)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = MaterialDialog(requireContext())
.customView(R.layout.dialog_no_wifi, scrollable = true)
.positiveButton(R.string.dialog_no_wifi_positive) {
if (remember.isChecked) {
preferenceHelper.shouldCheckCellular = false
}
(requireTargetFragment() as AnimeFragment).onConfirmNoWifi(streamId)
}
.negativeButton(R.string.cancel)
}
| gpl-3.0 | 6d11e7765bb39813811852dad5bcbd0e | 34.133333 | 103 | 0.722328 | 4.416201 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/WikiPrototype.kt | 1 | 2340 | package me.proxer.app.ui.view.bbcode.prototype
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import com.uber.autodispose.android.ViewScopeProvider
import com.uber.autodispose.autoDisposable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.proxer.app.base.CustomTabsAware
import me.proxer.app.ui.view.ProxerWebView
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.util.extension.buildSingle
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.library.ProxerApi
import org.koin.core.KoinComponent
import org.koin.core.get
object WikiPrototype : AutoClosingPrototype, KoinComponent {
override val startRegex = Regex(" *wiki( .*?)?", BBPrototype.REGEX_OPTIONS)
override val endRegex = Regex("/ *wiki *", BBPrototype.REGEX_OPTIONS)
override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> {
val link = children.firstOrNull()?.args?.text?.toString() ?: ""
if (link.isNotBlank()) {
@Suppress("UNCHECKED_CAST")
val heightMap = args[ImagePrototype.HEIGHT_MAP_ARGUMENT] as MutableMap<String, Int>?
val height = heightMap?.get(link) ?: WRAP_CONTENT
val view = ProxerWebView(parent.context)
view.showPageSubject
.autoDisposable(ViewScopeProvider.from(parent))
.subscribe { (parent.context as? CustomTabsAware)?.showPage(it) }
view.loadingFinishedSubject
.autoDisposable(ViewScopeProvider.from(parent))
.subscribe { heightMap?.put(link, view.height) }
view.layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, height)
get<ProxerApi>().wiki.content(link).buildSingle()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(ViewScopeProvider.from(parent))
.subscribeAndLogErrors { view.loadHtml(it.content) }
return listOf(view)
} else {
return emptyList()
}
}
}
| gpl-3.0 | b4ec6fe5f0f7e60cff71c4f8ff564e59 | 39.344828 | 98 | 0.701282 | 4.40678 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/action/GenerateSoftImplementsAction.kt | 1 | 3447 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.platform.mixin.util.findSoftImplements
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.findMatchingMethod
import com.demonwav.mcdev.util.ifEmpty
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.util.MemberChooser
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiModifier
import java.util.IdentityHashMap
class GenerateSoftImplementsAction : MixinCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return
val implements = psiClass.findSoftImplements() ?: return
if (implements.isEmpty()) {
return
}
val methods = IdentityHashMap<PsiMethodMember, String>()
for ((prefix, iface) in implements) {
for (signature in iface.visibleSignatures) {
val method = signature.method
if (method.isConstructor || method.hasModifierProperty(PsiModifier.STATIC)) {
continue
}
// Include only methods from interfaces
val containingClass = method.containingClass
if (containingClass == null || !containingClass.isInterface) {
continue
}
// Check if not already implemented
if (psiClass.findMatchingMethod(method, false, prefix + method.name) == null) {
methods[PsiMethodMember(method)] = prefix
}
}
}
if (methods.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No methods to soft-implement have been found")
return
}
val chooser = MemberChooser<PsiMethodMember>(methods.keys.toTypedArray(), false, true, project)
chooser.title = "Select Methods to Soft-implement"
chooser.show()
val elements = (chooser.selectedElements ?: return).ifEmpty { return }
runWriteAction {
GenerateMembersUtil.insertMembersAtOffset(
file,
offset,
elements.flatMap {
val method = it.element
val prefix = methods[it]
OverrideImplementUtil.overrideOrImplementMethod(
psiClass,
method,
it.substitutor,
chooser.isCopyJavadoc,
false
)
.map { m ->
// Apply prefix
m.name = prefix + m.name
OverrideImplementUtil.createGenerationInfo(m)
}
}
).firstOrNull()?.positionCaret(editor, true)
}
}
}
| mit | b49aa1d6b97d443a5fcdd3d117f63eae | 34.536082 | 107 | 0.603133 | 5.360809 | false | false | false | false |
robohorse/RoboPOJOGenerator | app/src/main/kotlin/com/robohorse/robopojogenerator/persistense/ViewStateService.kt | 1 | 725 | package com.robohorse.robopojogenerator.persistense
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.util.xmlb.XmlSerializerUtil
import com.robohorse.robopojogenerator.models.GenerationModel
@State(
name = "RoboPojoState"
)
internal class ViewStateService : PersistentStateComponent<PluginState> {
private var state = PluginState()
override fun getState() = state
fun persistModel(model: GenerationModel) {
this.state = PluginState(model)
}
override fun loadState(state: PluginState) {
XmlSerializerUtil.copyBean(state, this)
}
}
data class PluginState(
val model: GenerationModel? = null
)
| mit | 8165453371ad6010c7c94d408a9372bb | 25.851852 | 73 | 0.765517 | 4.447853 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-recyclerview/src/test/kotlin/org/ccci/gto/android/common/androidx/recyclerview/decorator/MarginItemDecorationTest.kt | 2 | 6455 | package org.ccci.gto.android.common.androidx.recyclerview.decorator
import android.graphics.Rect
import android.view.View
import android.view.View.LAYOUT_DIRECTION_LTR
import android.view.View.LAYOUT_DIRECTION_RTL
import junitparams.JUnitParamsRunner
import junitparams.Parameters
import junitparams.converters.ConversionFailedException
import junitparams.converters.Converter
import junitparams.converters.Param
import kotlin.random.Random
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
@RunWith(JUnitParamsRunner::class)
class MarginItemDecorationTest {
private val all = Random.nextInt(0, 10)
private val horizontal = Random.nextInt(10, 20)
private val vertical = Random.nextInt(20, 30)
private val left = Random.nextInt(30, 40)
private val top = Random.nextInt(40, 50)
private val right = Random.nextInt(50, 60)
private val bottom = Random.nextInt(60, 70)
private val start = Random.nextInt(70, 80)
private val end = Random.nextInt(80, 90)
@Test
@Parameters("ltr", "rtl")
fun `MarginItemDecoration()`(@Param(converter = LayoutDirectionConverter::class) dir: Int) {
MarginItemDecoration().testDecoration(dir) {
assertEquals(0, it.left)
assertEquals(0, it.top)
assertEquals(0, it.right)
assertEquals(0, it.bottom)
}
}
@Test
@Parameters("ltr", "rtl")
fun `MarginItemDecoration(margins=all)`(@Param(converter = LayoutDirectionConverter::class) dir: Int) {
MarginItemDecoration(margins = all).testDecoration(dir) {
assertEquals(all, it.left)
assertEquals(all, it.top)
assertEquals(all, it.right)
assertEquals(all, it.bottom)
}
}
@Test
@Parameters("ltr", "rtl")
fun `MarginItemDecoration(margins=all) - overrides`(@Param(converter = LayoutDirectionConverter::class) dir: Int) {
MarginItemDecoration(margins = all, horizontalMargins = horizontal).testDecoration(dir) {
assertEquals(horizontal, it.left)
assertEquals(all, it.top)
assertEquals(horizontal, it.right)
assertEquals(all, it.bottom)
}
MarginItemDecoration(margins = all, horizontalMargins = horizontal, rightMargin = right).testDecoration(dir) {
assertEquals(horizontal, it.left)
assertEquals(all, it.top)
assertEquals(right, it.right)
assertEquals(all, it.bottom)
}
MarginItemDecoration(margins = all, verticalMargins = vertical).testDecoration(dir) {
assertEquals(all, it.left)
assertEquals(vertical, it.top)
assertEquals(all, it.right)
assertEquals(vertical, it.bottom)
}
MarginItemDecoration(margins = all, verticalMargins = vertical, bottomMargin = bottom).testDecoration(dir) {
assertEquals(all, it.left)
assertEquals(vertical, it.top)
assertEquals(all, it.right)
assertEquals(bottom, it.bottom)
}
}
@Test
@Parameters("ltr", "rtl")
fun `MarginItemDecoration() - absolute`(@Param(converter = LayoutDirectionConverter::class) dir: Int) {
MarginItemDecoration(
leftMargin = left,
topMargin = top,
rightMargin = right,
bottomMargin = bottom
).testDecoration(dir) {
assertEquals(left, it.left)
assertEquals(top, it.top)
assertEquals(right, it.right)
assertEquals(bottom, it.bottom)
}
}
@Test
@Parameters("ltr", "rtl")
fun `MarginItemDecoration() - relative`(@Param(converter = LayoutDirectionConverter::class) dir: Int) {
MarginItemDecoration(
leftMargin = left,
rightMargin = right,
startMargin = start,
endMargin = end
).testDecoration(dir) {
assertNotEquals(left, it.left)
assertNotEquals(right, it.right)
when (dir) {
LAYOUT_DIRECTION_LTR -> {
assertEquals(start, it.left)
assertEquals(end, it.right)
}
LAYOUT_DIRECTION_RTL -> {
assertEquals(end, it.left)
assertEquals(start, it.right)
}
else -> fail()
}
}
}
@Test
fun `MarginItemDecoration() - relative - startMargin fallbacks`() {
val decoration = MarginItemDecoration(
leftMargin = left,
rightMargin = right,
startMargin = start
)
decoration.testDecoration(LAYOUT_DIRECTION_LTR) {
assertEquals(start, it.left)
assertNotEquals(left, it.left)
assertEquals(right, it.right)
}
decoration.testDecoration(LAYOUT_DIRECTION_RTL) {
assertEquals(left, it.left)
assertEquals(start, it.right)
assertNotEquals(right, it.right)
}
}
@Test
fun `MarginItemDecoration() - relative - endMargin fallbacks`() {
val decoration = MarginItemDecoration(
leftMargin = left,
rightMargin = right,
endMargin = end
)
decoration.testDecoration(LAYOUT_DIRECTION_LTR) {
assertEquals(left, it.left)
assertEquals(end, it.right)
assertNotEquals(right, it.right)
}
decoration.testDecoration(LAYOUT_DIRECTION_RTL) {
assertEquals(end, it.left)
assertNotEquals(left, it.left)
assertEquals(right, it.right)
}
}
private fun MarginItemDecoration.testDecoration(dir: Int, block: (Rect) -> Unit) {
val outRect = Rect()
val view = mock<View> { on { layoutDirection } doReturn dir }
getItemOffsets(outRect, view, mock(), mock())
block(outRect)
}
class LayoutDirectionConverter : Converter<Param, Int> {
override fun initialize(annotation: Param?) = Unit
override fun convert(param: Any) = when (param) {
"ltr" -> LAYOUT_DIRECTION_LTR
"rtl" -> LAYOUT_DIRECTION_RTL
else -> throw ConversionFailedException("Invalid layout direction: $param")
}
}
}
| mit | 032e4d08c774b35f7badd8709ac1520b | 33.891892 | 119 | 0.614872 | 4.600855 | false | true | false | false |
inorichi/tachiyomi-extensions | src/id/maidmanga/src/eu/kanade/tachiyomi/extension/id/maidmanga/MaidManga.kt | 1 | 10397 | package eu.kanade.tachiyomi.extension.id.maidmanga
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Locale
class MaidManga : ParsedHttpSource() {
override val name = "Maid - Manga"
override val baseUrl = "https://www.maid.my.id"
override val lang = "id"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
private fun pagePathSegment(page: Int): String = if (page > 1) "page/$page/" else ""
override fun latestUpdatesSelector() = searchMangaSelector()
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/advanced-search/${pagePathSegment(page)}?order=update")
}
override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = searchMangaNextPageSelector()
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/advanced-search/${pagePathSegment(page)}?order=popular")
}
override fun popularMangaSelector() = searchMangaSelector()
override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun popularMangaNextPageSelector() = searchMangaNextPageSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var url = "$baseUrl/advanced-search/${pagePathSegment(page)}".toHttpUrlOrNull()!!.newBuilder()
url.addQueryParameter("title", query)
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is AuthorFilter -> {
url.addQueryParameter("author", filter.state)
}
is YearFilter -> {
url.addQueryParameter("yearx", filter.state)
}
is StatusFilter -> {
val status = when (filter.state) {
Filter.TriState.STATE_INCLUDE -> "completed"
Filter.TriState.STATE_EXCLUDE -> "ongoing"
else -> ""
}
url.addQueryParameter("status", status)
}
is TypeFilter -> {
url.addQueryParameter("type", filter.toUriPart())
}
is OrderByFilter -> {
url.addQueryParameter("order", filter.toUriPart())
}
is GenreList -> {
filter.state
.filter { it.state }
.forEach { url.addQueryParameter("genre[]", it.id) }
}
is ProjectFilter -> {
if (filter.toUriPart() == "project-filter-on") {
url = "$baseUrl/project-list/page/$page".toHttpUrlOrNull()!!.newBuilder()
}
}
}
}
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = "div.flexbox2-item"
override fun searchMangaFromElement(element: Element): SManga {
return SManga.create().apply {
setUrlWithoutDomain(element.select("div.flexbox2-content a").attr("href"))
title = element.select("div.flexbox2-title > span").first().text()
thumbnail_url = element.select("img").attr("abs:src")
}
}
override fun searchMangaNextPageSelector() = "div.pagination span.current + a"
override fun mangaDetailsParse(document: Document): SManga {
return SManga.create().apply {
genre = document.select("div.series-genres a").joinToString { it.text() }
description = document.select("div.series-synops").text()
thumbnail_url = document.select("div.series-thumb img").attr("abs:src")
status = parseStatus(document.select("div.block span.status").text())
author = document.select("ul.series-infolist li b:contains(Author) + span").text()
// add series type(manga/manhwa/manhua/other) thinggy to genre
document.select("div.block span.type").firstOrNull()?.ownText()?.let {
if (it.isEmpty().not() && it != "-" && genre!!.contains(it, true).not()) {
genre += if (genre!!.isEmpty()) it else ", $it"
}
}
// add alternative name to manga description
val altName = "Alternative Name: "
document.select(".series-title span").firstOrNull()?.ownText()?.let {
if (it.isEmpty().not()) {
description += when {
description!!.isEmpty() -> altName + it
else -> "\n\n$altName" + it
}
}
}
}
}
private fun parseStatus(status: String?) = when {
status == null -> SManga.UNKNOWN
status.contains("Ongoing") -> SManga.ONGOING
status.contains("Completed") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
private fun parseDate(date: String): Long {
return SimpleDateFormat("MMM d, yyyy", Locale("id")).parse(date)?.time ?: 0L
}
// careful not to include download links
override fun chapterListSelector() = "ul.series-chapterlist div.flexch-infoz > a"
override fun chapterFromElement(element: Element): SChapter {
return SChapter.create().apply {
setUrlWithoutDomain(element.attr("href"))
name = element.select("span").first().ownText()
date_upload = parseDate(element.select("span.date").text())
}
}
override fun pageListParse(document: Document): List<Page> {
return document.select("div.reader-area img").mapIndexed { i, img ->
Page(i, "", img.attr("abs:src"))
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
override fun getFilterList() = FilterList(
Filter.Header("You can combine filter."),
Filter.Separator(),
AuthorFilter(),
YearFilter(),
StatusFilter(),
TypeFilter(),
OrderByFilter(),
GenreList(getGenreList()),
Filter.Separator(),
Filter.Header("NOTE: cant be used with other filter!"),
Filter.Header("$name Project List page"),
ProjectFilter(),
)
private class ProjectFilter : UriPartFilter(
"Filter Project",
arrayOf(
Pair("Show all manga", ""),
Pair("Show only project manga", "project-filter-on")
)
)
private class AuthorFilter : Filter.Text("Author")
private class YearFilter : Filter.Text("Year")
private class StatusFilter : Filter.TriState("Completed")
private class TypeFilter : UriPartFilter(
"Type",
arrayOf(
Pair("All", ""),
Pair("Manga", "Manga"),
Pair("Manhua", "Manhua"),
Pair("Manhwa", "Manhwa"),
Pair("One-Shot", "One-Shot"),
Pair("Doujin", "Doujin")
)
)
private class OrderByFilter : UriPartFilter(
"Order By",
arrayOf(
Pair("<select>", ""),
Pair("A-Z", "title"),
Pair("Z-A", "titlereverse"),
Pair("Latest Update", "update"),
Pair("Latest Added", "latest"),
Pair("Popular", "popular"),
Pair("Rating", "rating")
)
)
private fun getGenreList() = listOf(
Tag("4-koma", "4-Koma"),
Tag("4-koma-comedy", "4-Koma Comedy"),
Tag("action", "Action"),
Tag("adult", "Adult"),
Tag("adventure", "Adventure"),
Tag("comedy", "Comedy"),
Tag("demons", "Demons"),
Tag("drama", "Drama"),
Tag("ecchi", "Ecchi"),
Tag("fantasy", "Fantasy"),
Tag("game", "Game"),
Tag("gender-bender", "Gender bender"),
Tag("gore", "Gore"),
Tag("harem", "Harem"),
Tag("historical", "Historical"),
Tag("horror", "Horror"),
Tag("isekai", "Isekai"),
Tag("josei", "Josei"),
Tag("loli", "Loli"),
Tag("magic", "Magic"),
Tag("manga", "Manga"),
Tag("manhua", "Manhua"),
Tag("manhwa", "Manhwa"),
Tag("martial-arts", "Martial Arts"),
Tag("mature", "Mature"),
Tag("mecha", "Mecha"),
Tag("military", "Military"),
Tag("monster-girls", "Monster Girls"),
Tag("music", "Music"),
Tag("mystery", "Mystery"),
Tag("one-shot", "One Shot"),
Tag("parody", "Parody"),
Tag("police", "Police"),
Tag("psychological", "Psychological"),
Tag("romance", "Romance"),
Tag("school", "School"),
Tag("school-life", "School Life"),
Tag("sci-fi", "Sci-Fi"),
Tag("socks", "Socks"),
Tag("seinen", "Seinen"),
Tag("shoujo", "Shoujo"),
Tag("shoujo-ai", "Shoujo Ai"),
Tag("shounen", "Shounen"),
Tag("shounen-ai", "Shounen Ai"),
Tag("slice-of-life", "Slice of Life"),
Tag("smut", "Smut"),
Tag("sports", "Sports"),
Tag("super-power", "Super Power"),
Tag("supernatural", "Supernatural"),
Tag("survival", "Survival"),
Tag("thriller", "Thriller"),
Tag("tragedy", "Tragedy"),
Tag("vampire", "Vampire"),
Tag("webtoons", "Webtoons"),
Tag("yuri", "Yuri")
)
private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) :
Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) {
fun toUriPart() = vals[state].second
}
private class Tag(val id: String, name: String) : Filter.CheckBox(name)
private class GenreList(genres: List<Tag>) : Filter.Group<Tag>("Genres", genres)
}
| apache-2.0 | 9cb583d00ff10dda707c8b134920d52b | 36 | 108 | 0.56901 | 4.606557 | false | false | false | false |
mobapptuts/kotlin-webview | app/src/main/java/com/mobapptuts/kotlinwebview/HistoryDialogFragment.kt | 2 | 2116 | package com.mobapptuts.kotlinwebview
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.webkit.WebView
import android.widget.Toast
/**
* Created by nigelhenshaw on 2017/08/28.
*/
class HistoryDialogFragment : DialogFragment(){
val selectBackAdapter = "SELECT_BACK_ADAPTER"
interface WebHistory {
fun getWebView(): WebView
}
lateinit var webHistory: WebHistory
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
webHistory = context as WebHistory
} catch (e: ClassCastException) {
e.printStackTrace()
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
super.onCreateDialog(savedInstanceState)
val backAdapter = arguments.getBoolean(selectBackAdapter)
val recyclerView = RecyclerView(activity)
if (backAdapter) {
recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, true)
recyclerView.adapter = BackHistoryAdapter(this, webHistory.getWebView())
} else {
recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = ForwardHistoryAdapter(this, webHistory.getWebView())
}
val itemDecoration = DividerItemDecoration(activity, LinearLayoutManager.VERTICAL)
itemDecoration.setDrawable(ColorDrawable(Color.RED))
recyclerView.addItemDecoration(itemDecoration)
recyclerView.background = ColorDrawable(Color.LTGRAY)
val alertDialogBuilder = AlertDialog.Builder(activity)
.setView(recyclerView)
return alertDialogBuilder.create()
}
} | mit | 81df48104d0ce33814a7ffcbeb674fa5 | 34.283333 | 107 | 0.732987 | 5.135922 | false | false | false | false |
CoEValencia/fwk | src/main/java/body/core/commandDispatcher/CommandDispatcherAsyncImpl.kt | 1 | 6612 | package body.core.commandDispatcher
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executor
/**
* Created by vicboma on 08/02/17.
*/
class CommandDispatcherAsyncImpl<T> internal constructor() : CommandDispatcherAsync<T> {
private val map by lazy { ConcurrentHashMap<String, MutableList<CompletableFuture<T>>>() }
init {
}
companion object {
fun <J> create(): CommandDispatcherAsync<J> = CommandDispatcherAsyncImpl()
}
override fun add(command: String, completableList: List<CompletableFuture<T>>): CommandDispatcherAsync<T> {
completableList
.filter { it -> it != null }
.forEach { it -> add(command, it) }
return this
}
override fun add(command: String, completable: CompletableFuture<T>): CommandDispatcherAsync<T> {
val listFun = map.get(command)
when (listFun) {
null -> map.put(command, arrayListOf(completable))
else -> {
if (!listFun.contains(completable))
listFun.add(completable)
}
}
return this
}
override fun contains(command: String) = map.containsKey(command)
override fun remove(command: String, completable: CompletableFuture<T>): CommandDispatcherAsync<T> {
val listFun = map.get(command)
when (listFun) {
null -> {
}
else -> {
val index = listFun.indexOf(completable)
if (listFun.indexOf(completable) != -1) {
val completableFuture = listFun?.removeAt(index)
completableFuture?.cancel(true)
if (listFun?.size == 0)
listFun?.clear()
}
}
}
return this
}
override fun remove(command: String): CommandDispatcherAsync<T> {
map.remove(command)
return this
}
override fun dispatch(command: String): CommandDispatcherAsync<T> {
val listFun = map.get(command)
if (null != listFun) {
for (i in listFun!!.indices) {
val res = intArrayOf(i)
executeRunnable(completable(listFun, res))
}
}
return this
}
override fun dispatch(command: String, executor: Executor): CommandDispatcherAsync<T> {
val listFun = map.get(command)
if (null != listFun) {
for (i in listFun!!.indices) {
val res = intArrayOf(i)
executeRunnable(completable(listFun, res),executor)
}
}
return this
}
override fun dispatchOnce(command: String): CommandDispatcherAsync<T> {
val listFun = map.get(command)
if (null != listFun) {
for (i in listFun!!.indices) {
val res = intArrayOf(i)
executeRunnable(completable(listFun, res))
}
remove(command)
}
return this
}
override fun dispatchOnce(command: String,executor: Executor): CommandDispatcherAsync<T> {
val listFun = map.get(command)
if (null != listFun) {
for (i in listFun!!.indices) {
val res = intArrayOf(i)
executeRunnable(completable(listFun, res),executor)
}
remove(command)
}
return this
}
private fun completable(listFun: MutableList<CompletableFuture<T>>?, res: IntArray): Runnable {
return Runnable {
listFun!!.get(res[0])
}
}
override fun dispatchAll(command: String): CompletableFuture<Void> {
val child = map.get(command)
val toArray = child?.toTypedArray()
if(toArray?.size!! <= 0)
return CompletableFuture.completedFuture(null)
val res = hashSetOf<CompletableFuture<T>>()
return executeRunnable(this.all(res, toArray))
}
override fun dispatchAll(command: String, executor:Executor): CompletableFuture<Void> {
val child = map.get(command)
val toArray = child?.toTypedArray()
if(toArray?.size!! <= 0)
return CompletableFuture.completedFuture(null)
val res = hashSetOf<CompletableFuture<T>>()
return executeRunnable(this.all(res, toArray),executor)
}
private fun all(res: HashSet<CompletableFuture<T>>, toArray: Array<CompletableFuture<T>>?): Runnable {
return Runnable {
logger.debug("Start dispatchAll ")
while (res.size != toArray?.size) {
toArray?.
filter { it.isDone }?.
forEach {
res.add(it)
}
}
res.forEach { logger.debug("${it.toString()}") }
logger.debug("End dispatchAll ")
}
}
override fun <H> dispatchAny(command: String) : CompletableFuture<H> {
val child = map.get(command)
val toArray = child?.toTypedArray()
if(toArray?.size!! <= 0)
return CompletableFuture.completedFuture(null)
val res = CompletableFuture<H>()
executeRunnable(this.any(res, toArray))
return res
}
override fun <H> dispatchAny(command: String, executor: Executor) : CompletableFuture<H> {
val child = map.get(command)
val toArray = child?.toTypedArray()
if(toArray?.size!! <= 0)
return CompletableFuture.completedFuture(null)
val res = CompletableFuture<H>()
executeRunnable(this.any(res, toArray),executor)
return res
}
private fun <H> any(res: CompletableFuture<H>, toArray: Array<CompletableFuture<T>>?) : Runnable {
return Runnable {
logger.debug("Start dispatchAny ")
while (!res.isDone) {
toArray?.
filter { it.isDone }?.
forEach {
when (!res.isDone) {
true -> {
logger.debug("${res.toString()}")
res.complete(it.get() as (H))
logger.debug("${res.toString()}")
}
else -> {
}
}
}
}
logger.debug("End dispatchAny ")
}
}
override fun size() = this.map.size
}
| gpl-3.0 | 76d66d45c8488a0c105575641c1a1fe7 | 30.336493 | 111 | 0.537356 | 4.941704 | false | false | false | false |
moallemi/gradle-advanced-build-version | src/main/kotlin/me/moallemi/gradle/advancedbuildversion/gradleextensions/FileOutputConfig.kt | 1 | 2496 | /*
* Copyright 2020 Reza Moallemi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.moallemi.gradle.advancedbuildversion.gradleextensions
import com.android.build.gradle.api.ApplicationVariant
import com.android.build.gradle.internal.api.BaseVariantOutputImpl
import groovy.text.SimpleTemplateEngine
import org.gradle.api.DomainObjectSet
import org.gradle.api.Project
class FileOutputConfig(private val project: Project) {
private var nameFormat: String? = null
private var renameOutput = false
private val templateEngine: SimpleTemplateEngine = SimpleTemplateEngine()
fun nameFormat(format: String) {
nameFormat = format
}
fun renameOutput(b: Boolean) {
renameOutput = b
}
fun renameOutputApkIfPossible(variants: DomainObjectSet<ApplicationVariant>) {
if (renameOutput) {
variants.all { variant ->
generateOutputName(variant)
}
}
}
private fun generateOutputName(variant: ApplicationVariant) {
val map = linkedMapOf(
"appName" to project.name,
"projectName" to project.rootProject.name,
"flavorName" to variant.flavorName,
"buildType" to variant.buildType.name,
"versionName" to (variant.versionName ?: ""),
"versionCode" to variant.versionCode.toString()
)
val template = nameFormat ?: variant.flavorName
?.takeIf { it.isNotBlank() }
?.let {
"\$appName-\$flavorName-\$buildType-\$versionName"
} ?: "\$appName-\$buildType-\$versionName"
val fileName = templateEngine
.createTemplate(template)
.make(map)
.toString()
variant.outputs.all { output ->
val outputImpl = output as BaseVariantOutputImpl
outputImpl.outputFileName = "$fileName.apk"
println("outputFileName renamed to $fileName.apk")
}
}
}
| apache-2.0 | ad6d298607389a99201f66220da11999 | 31.842105 | 82 | 0.661458 | 4.630798 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/codegen/bridges/test15.kt | 1 | 549 | // non-generic interface, generic impl, vtable call + interface call
open class A<T> {
open var size: T = 56 as T
}
interface C {
var size: Int
}
open class B : C, A<Int>()
open class D: B() {
override var size: Int = 117
}
fun <T> foo(a: A<T>) {
a.size = 42 as T
}
fun box(): String {
val b = B()
foo(b)
if (b.size != 42) return "fail 1"
val d = D()
if (d.size != 117) return "fail 2"
foo(d)
if (d.size != 42) return "fail 3"
return "OK"
}
fun main(args: Array<String>) {
println(box())
} | apache-2.0 | 3618d3d0fbd2935b1799ac6d9447d5af | 14.714286 | 68 | 0.544627 | 2.758794 | false | false | false | false |
InsertKoinIO/koin | core/koin-core/src/commonTest/kotlin/org/koin/core/ParametersInjectionTest.kt | 1 | 7050 | package org.koin.core
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.test.runTest
import org.koin.Simple
import org.koin.core.logger.Level
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class ParametersInjectionTest {
@Test
fun `can create a single with parameters`() {
val app = koinApplication {
modules(
module {
single { (i: Int) -> Simple.MySingle(i) }
})
}
val koin = app.koin
val a: Simple.MySingle = koin.get { parametersOf(42) }
assertEquals(42, a.id)
}
@Test
fun nullable_injection_param() {
val app = koinApplication {
modules(
module {
single { p -> Simple.MySingleWithNull(p.getOrNull()) }
})
}
val koin = app.koin
val a: Simple.MySingleWithNull = koin.get()
assertNull(a.id)
}
internal class MyOptionalSingle(val i: Int, val o: String? = null)
@Test
fun nullable_injection_param_in_graph() {
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { p -> MyOptionalSingle(p.get(), getOrNull()) }
})
}
val koin = app.koin
val value = 42
val a: MyOptionalSingle = koin.get { parametersOf(value) }
assertEquals(value, a.i)
assertNull(a.o)
}
@Test
fun `can create a single with parameters - using param object resolution`() {
val app = koinApplication {
modules(
module {
single { params -> Simple.MySingle(params.get()) }
})
}
val koin = app.koin
val a: Simple.MySingle = koin.get { parametersOf(42) }
assertEquals(42, a.id)
}
@Test
fun `can create a single with parameters - using graph resolution`() {
val app = koinApplication {
modules(
module {
single { Simple.MySingle(get()) }
})
}
val koin = app.koin
val a: Simple.MySingle = koin.get { parametersOf(42) }
assertEquals(42, a.id)
}
@Test
fun `can create a single with parameters - using double graph resolution`() {
val app = koinApplication {
modules(
module {
single { Simple.MySingle(get()) }
single(named("2")) { Simple.MySingle(get()) }
})
}
val koin = app.koin
assertEquals(42, koin.get<Simple.MySingle> { parametersOf(42) }.id)
assertEquals(24, koin.get<Simple.MySingle>(named("2")) { parametersOf(24) }.id)
}
@Test
fun `can create a single with nullable parameters`() {
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (i: Int?) -> Simple.MySingleWithNull(i) }
})
}
val koin = app.koin
val a: Simple.MySingleWithNull = koin.get { parametersOf(null) }
assertEquals(null, a.id)
}
@Test
fun `can get a single created with parameters - no need of give it again`() {
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (i: Int) -> Simple.MySingle(i) }
})
}
val koin = app.koin
val a: Simple.MySingle = koin.get { parametersOf(42) }
assertEquals(42, a.id)
val a2: Simple.MySingle = koin.get()
assertEquals(42, a2.id)
}
@Test
fun `can create factories with params`() {
val app = koinApplication {
modules(
module {
factory { (i: Int) -> Simple.MyIntFactory(i) }
})
}
val koin = app.koin
val a: Simple.MyIntFactory = koin.get { parametersOf(42) }
val a2: Simple.MyIntFactory = koin.get { parametersOf(43) }
assertEquals(42, a.id)
assertEquals(43, a2.id)
}
@Test
fun `chained factory injection`() {
val koin = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
factory { (i: Int) -> Simple.MyIntFactory(i) }
factory { (s: String) -> Simple.MyStringFactory(s) }
factory { (i: Int, s: String) ->
Simple.AllFactory(
get { parametersOf(i) },
get { parametersOf(s) })
}
})
}.koin
val f = koin.get<Simple.AllFactory> { parametersOf(42, "42") }
assertEquals(42, f.ints.id)
assertEquals("42", f.strings.s)
}
@Test
fun `inject in graph`() {
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.MySingle(it.get()) }
})
}
val koin = app.koin
val a: Simple.MySingle = koin.get { parametersOf(42) }
assertEquals(42, a.id)
}
@Test
fun `chained factory injection - graph`() {
val koin = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
factory { p -> Simple.MyIntFactory(p.get()) }
factory { Simple.MyStringFactory(it.get()) }
factory { (i: Int, s: String) ->
Simple.AllFactory(
get { parametersOf(i) },
get { parametersOf(s) })
}
})
}.koin
val f = koin.get<Simple.AllFactory> { parametersOf(42, "42") }
assertEquals(42, f.ints.id)
assertEquals("42", f.strings.s)
}
@Test
@OptIn(ExperimentalCoroutinesApi::class)
fun `inject across multiple threads`() = runTest {
val app = koinApplication {
modules(
module {
factory { (i: Int) -> Simple.MyIntFactory(i) }
})
}
val koin = app.koin
repeat(1000) {
val range = (0 until 1000)
val deferreds = range.map {
async(Dispatchers.Default) {
koin.get<Simple.MyIntFactory> { parametersOf(it) }
}
}
val values = awaitAll(*deferreds.toTypedArray())
assertEquals(range.map { it }, values.map { it.id })
}
}
} | apache-2.0 | ce8b06a6198d3e8038b97306a6c9becf | 26.223938 | 87 | 0.504397 | 4.499043 | false | true | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectFileReader/app/src/main/java/me/liuqingwen/android/projectfilereader/MainActivity.kt | 1 | 3496 | package me.liuqingwen.android.projectfilereader
import android.app.Activity
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.layout_activity_main.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.toast
import java.io.IOException
class MainActivity : AppCompatActivity(), AnkoLogger
{
companion object
{
const val REQUEST_CODE = 1001
const val DATA_NAME = "name"
const val FILE_NAME = "project_file_reader"
}
private val dataList by lazy(LazyThreadSafetyMode.NONE) { ArrayList<MyContact>() }
private val adapter by lazy(LazyThreadSafetyMode.NONE) { MyAdapter(this, this.dataList, null) }
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
this.readData()
this.init()
}
private fun readData()
{
try
{
val stream = this.openFileInput(MainActivity.FILE_NAME)
val reader = stream.bufferedReader()
var id = this.dataList.size + 1
reader.readLines().forEach { this.dataList.add(MyContact(id ++, it)) }
this.adapter.notifyDataSetChanged()
}
catch (e: IOException)
{
e.printStackTrace()
}
}
private fun saveData(contact: MyContact)
{
try
{
val stream = this.openFileOutput(MainActivity.FILE_NAME, android.content.Context.MODE_APPEND)
val writer = stream.bufferedWriter()
writer.write(contact.name)
writer.write("\n")
writer.flush()
}
catch (e: IOException)
{
e.printStackTrace()
}
}
private fun init()
{
this.recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
this.recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
this.recyclerView.adapter = this.adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
this.menuInflater.inflate(R.menu.menu_toolbar, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean
{
when(item?.itemId)
{
R.id.menuAdd -> {
val intent = Intent(this, AddItemActivity::class.java)
this.startActivityForResult(intent, MainActivity.REQUEST_CODE)
}
else -> { toast("Not implement yet!") }
}
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
if (requestCode == MainActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
val name = data?.getStringExtra(MainActivity.DATA_NAME)
name?.let {
val contact = MyContact(this.dataList.size + 1, it)
this.dataList.add(contact)
this.adapter.notifyDataSetChanged()
this.saveData(contact)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
}
| mit | 3c2b9405d40603a540bbe4ba1e377fa0 | 30.495495 | 105 | 0.622712 | 4.79561 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectBetterPracticeFragment/app/src/main/java/me/liuqingwen/android/projectbetterpracticefragment/MainFragment.kt | 1 | 3319 | package me.liuqingwen.android.projectbetterpracticefragment
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import kotlinx.android.synthetic.main.layout_fragment_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
class MainFragment : Fragment()
{
companion object
{
fun newInstance(): MainFragment = MainFragment()
}
private val dataList by lazy(LazyThreadSafetyMode.NONE) { arrayListOf<Contact>() }
private val adapter by lazy(LazyThreadSafetyMode.NONE) { MyAdapter(this.activityContext!!, this.dataList, {
val index = this.recyclerView.getChildAdapterPosition(it)
this.activityContext?.let { this.startActivity(DetailActivity.getDetailIntent(it, this.dataList, index)) }
}) }
private val layoutAnimation by lazy(LazyThreadSafetyMode.NONE) { AnimationUtils.loadLayoutAnimation(this.activityContext, R.anim.anim_item_layout) }
private var activityContext : Context? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
return inflater.inflate(R.layout.layout_fragment_main, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?)
{
super.onActivityCreated(savedInstanceState)
this.labelNoData.visibility = View.INVISIBLE
this.layoutSwipRefresh.setOnRefreshListener {
this.loadData()
}
this.recyclerView.adapter = this.adapter
this.recyclerView.layoutManager = LinearLayoutManager(this.activityContext, LinearLayoutManager.VERTICAL, false)
this.recyclerView.addItemDecoration(DividerItemDecoration(this.activityContext, DividerItemDecoration.VERTICAL))
[email protected] = this.layoutAnimation
this.layoutSwipRefresh.isRefreshing = true
this.loadData()
}
private fun loadData()
{
this.labelNoData.visibility = View.INVISIBLE
doAsync {
val data = [email protected]?.let { DatabaseHelper.getInstance(it).getAllContacts() }
[email protected]()
data?.let { [email protected](it) }
uiThread {
[email protected] = false
if ([email protected] <= 0)
{
[email protected] = View.VISIBLE
}
[email protected]()
[email protected]()
}
}
}
override fun onAttach(context: Context?)
{
this.activityContext = context!!
super.onAttach(context)
}
override fun onDetach()
{
this.activityContext = null
super.onDetach()
}
}
| mit | 81b88ac6fb2270f2ff5d36de8c9dadca | 36.292135 | 152 | 0.699307 | 5.106154 | false | false | false | false |
apollostack/apollo-android | apollo-runtime/src/main/java/com/apollographql/apollo3/internal/RealApolloCall.kt | 1 | 20671 | package com.apollographql.apollo3.internal
import com.apollographql.apollo3.ApolloCall
import com.apollographql.apollo3.ApolloMutationCall
import com.apollographql.apollo3.ApolloQueryCall
import com.apollographql.apollo3.api.ResponseAdapterCache
import com.apollographql.apollo3.api.Mutation
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.Query
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.cache.http.HttpCache
import com.apollographql.apollo3.api.cache.http.HttpCachePolicy
import com.apollographql.apollo3.api.internal.Action
import com.apollographql.apollo3.api.internal.ApolloLogger
import com.apollographql.apollo3.api.internal.Optional
import com.apollographql.apollo3.cache.CacheHeaders
import com.apollographql.apollo3.cache.normalized.ApolloStore
import com.apollographql.apollo3.exception.ApolloCanceledException
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.exception.ApolloHttpException
import com.apollographql.apollo3.exception.ApolloNetworkException
import com.apollographql.apollo3.exception.ApolloParseException
import com.apollographql.apollo3.fetcher.ApolloResponseFetchers
import com.apollographql.apollo3.fetcher.ResponseFetcher
import com.apollographql.apollo3.interceptor.ApolloAutoPersistedOperationInterceptor
import com.apollographql.apollo3.interceptor.ApolloInterceptor
import com.apollographql.apollo3.interceptor.ApolloInterceptor.CallBack
import com.apollographql.apollo3.interceptor.ApolloInterceptor.FetchSourceType
import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorRequest
import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorResponse
import com.apollographql.apollo3.interceptor.ApolloInterceptorChain
import com.apollographql.apollo3.interceptor.ApolloInterceptorFactory
import com.apollographql.apollo3.internal.interceptor.ApolloCacheInterceptor
import com.apollographql.apollo3.internal.interceptor.ApolloParseInterceptor
import com.apollographql.apollo3.internal.interceptor.ApolloServerInterceptor
import com.apollographql.apollo3.internal.interceptor.RealApolloInterceptorChain
import com.apollographql.apollo3.request.RequestHeaders
import okhttp3.Call
import okhttp3.HttpUrl
import java.lang.IllegalArgumentException
import java.util.ArrayList
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicReference
class RealApolloCall<D : Operation.Data> internal constructor(builder: Builder<D>) : ApolloQueryCall<D>, ApolloMutationCall<D> {
val operation: Operation<D>
val serverUrl: HttpUrl?
val httpCallFactory: Call.Factory?
val httpCache: HttpCache?
val httpCachePolicy: HttpCachePolicy.Policy?
val responseAdapterCache: ResponseAdapterCache
val apolloStore: ApolloStore?
val cacheHeaders: CacheHeaders?
val requestHeaders: RequestHeaders
val responseFetcher: ResponseFetcher?
val interceptorChain: ApolloInterceptorChain
val dispatcher: Executor?
val logger: ApolloLogger?
val tracker: ApolloCallTracker?
val applicationInterceptors: List<ApolloInterceptor>?
val applicationInterceptorFactories: List<ApolloInterceptorFactory>?
val autoPersistedOperationsInterceptorFactory: ApolloInterceptorFactory?
val refetchQueryNames: List<String>
val refetchQueries: List<Query<*>>
var queryReFetcher: Optional<QueryReFetcher>? = null
val enableAutoPersistedQueries: Boolean
val state = AtomicReference(CallState.IDLE)
val originalCallback = AtomicReference<ApolloCall.Callback<D>?>()
val optimisticUpdates: Optional<Operation.Data>
val useHttpGetMethodForQueries: Boolean
val useHttpGetMethodForPersistedQueries: Boolean
val writeToNormalizedCacheAsynchronously: Boolean
override fun enqueue(responseCallback: ApolloCall.Callback<D>?) {
try {
activate(Optional.fromNullable(responseCallback))
} catch (e: ApolloCanceledException) {
if (responseCallback != null) {
responseCallback.onCanceledError(e)
} else {
logger!!.e(e, "Operation: %s was canceled", operation().name())
}
return
}
val request = InterceptorRequest.builder(operation)
.cacheHeaders(cacheHeaders!!)
.requestHeaders(requestHeaders)
.fetchFromCache(false)
.optimisticUpdates(optimisticUpdates)
.useHttpGetMethodForQueries(useHttpGetMethodForQueries)
.build()
interceptorChain.proceedAsync(request, dispatcher!!, interceptorCallbackProxy())
}
override fun watcher(): RealApolloQueryWatcher<D> {
return RealApolloQueryWatcher(clone(), apolloStore!!, responseAdapterCache!!, logger!!, tracker!!, ApolloResponseFetchers.CACHE_FIRST)
}
override fun httpCachePolicy(httpCachePolicy: HttpCachePolicy.Policy): RealApolloCall<D> {
check(state.get() == CallState.IDLE) { "Already Executed" }
return toBuilder()
.httpCachePolicy(httpCachePolicy)
.build()
}
override fun responseFetcher(fetcher: ResponseFetcher): RealApolloCall<D> {
check(state.get() == CallState.IDLE) { "Already Executed" }
return toBuilder()
.responseFetcher(fetcher)
.build()
}
override fun cacheHeaders(cacheHeaders: CacheHeaders): RealApolloCall<D> {
check(state.get() == CallState.IDLE) { "Already Executed" }
return toBuilder()
.cacheHeaders(cacheHeaders)
.build()
}
override fun requestHeaders(requestHeaders: RequestHeaders): RealApolloCall<D> {
check(state.get() == CallState.IDLE) { "Already Executed" }
return toBuilder()
.requestHeaders(requestHeaders)
.build()
}
@Synchronized
override fun cancel() {
when (state.get()) {
CallState.ACTIVE -> {
state.set(CallState.CANCELED)
try {
interceptorChain.dispose()
if (queryReFetcher!!.isPresent) {
queryReFetcher!!.get().cancel()
}
} finally {
tracker!!.unregisterCall(this)
originalCallback.set(null)
}
}
CallState.IDLE -> state.set(CallState.CANCELED)
CallState.CANCELED, CallState.TERMINATED -> {
}
else -> throw IllegalStateException("Unknown state")
}
}
override val isCanceled: Boolean
get() = state.get() == CallState.CANCELED
override fun clone(): RealApolloCall<D> {
return toBuilder().build()
}
override fun refetchQueries(vararg operationNames: String): ApolloMutationCall<D> {
check(state.get() == CallState.IDLE) { "Already Executed" }
return toBuilder()
.refetchQueryNames(operationNames.toList())
.build()
}
override fun refetchQueries(vararg queries: Query<*>): ApolloMutationCall<D> {
check(state.get() == CallState.IDLE) { "Already Executed" }
return toBuilder()
.refetchQueries(queries.toList())
.build()
}
override fun operation(): Operation<D> {
return operation
}
private fun interceptorCallbackProxy(): CallBack {
return object : CallBack {
override fun onResponse(response: InterceptorResponse) {
val callback = responseCallback()
if (!callback.isPresent) {
logger!!.d("onResponse for operation: %s. No callback present.", operation().name())
return
}
callback.get().onResponse(response.parsedResponse.get() as ApolloResponse<D>)
}
override fun onFailure(e: ApolloException) {
val callback = terminate()
if (!callback.isPresent) {
logger!!.d(e, "onFailure for operation: %s. No callback present.", operation().name())
return
}
if (e is ApolloHttpException) {
callback.get().onHttpError(e)
} else if (e is ApolloParseException) {
callback.get().onParseError(e)
} else if (e is ApolloNetworkException) {
callback.get().onNetworkError(e)
} else {
callback.get().onFailure(e)
}
}
override fun onCompleted() {
val callback = terminate()
if (queryReFetcher!!.isPresent) {
queryReFetcher!!.get().refetch()
}
if (!callback.isPresent) {
logger!!.d("onCompleted for operation: %s. No callback present.", operation().name())
return
}
callback.get().onStatusEvent(ApolloCall.StatusEvent.COMPLETED)
}
override fun onFetch(sourceType: FetchSourceType) {
responseCallback().apply(object : Action<ApolloCall.Callback<D>> {
override fun apply(t: ApolloCall.Callback<D>) {
when (sourceType) {
FetchSourceType.CACHE -> t.onStatusEvent(ApolloCall.StatusEvent.FETCH_CACHE)
FetchSourceType.NETWORK -> t.onStatusEvent(ApolloCall.StatusEvent.FETCH_NETWORK)
}
}
})
}
}
}
override fun toBuilder(): Builder<D> {
return builder<D>()
.operation(operation)
.serverUrl(serverUrl)
.httpCallFactory(httpCallFactory)
.httpCache(httpCache)
.httpCachePolicy(httpCachePolicy!!)
.scalarTypeAdapters(responseAdapterCache)
.apolloStore(apolloStore)
.cacheHeaders(cacheHeaders!!)
.requestHeaders(requestHeaders)
.responseFetcher(responseFetcher!!)
.dispatcher(dispatcher)
.logger(logger)
.applicationInterceptors(applicationInterceptors)
.applicationInterceptorFactories(applicationInterceptorFactories)
.autoPersistedOperationsInterceptorFactory(autoPersistedOperationsInterceptorFactory)
.tracker(tracker)
.refetchQueryNames(refetchQueryNames)
.refetchQueries(refetchQueries)
.enableAutoPersistedQueries(enableAutoPersistedQueries)
.useHttpGetMethodForQueries(useHttpGetMethodForQueries)
.useHttpGetMethodForPersistedQueries(useHttpGetMethodForPersistedQueries)
.optimisticUpdates(optimisticUpdates)
.writeToNormalizedCacheAsynchronously(writeToNormalizedCacheAsynchronously)
}
@Synchronized
private fun activate(callback: Optional<ApolloCall.Callback<D>>) {
when (state.get()) {
CallState.IDLE -> {
originalCallback.set(callback.orNull())
tracker!!.registerCall(this)
callback.apply(object : Action<ApolloCall.Callback<D>> {
override fun apply(t: ApolloCall.Callback<D>) {
t.onStatusEvent(ApolloCall.StatusEvent.SCHEDULED)
}
})
}
CallState.CANCELED -> throw ApolloCanceledException()
CallState.TERMINATED, CallState.ACTIVE -> throw IllegalStateException("Already Executed")
else -> throw IllegalStateException("Unknown state")
}
state.set(CallState.ACTIVE)
}
@Synchronized
fun responseCallback(): Optional<ApolloCall.Callback<D>> {
return when (state.get()) {
CallState.ACTIVE, CallState.CANCELED -> Optional.fromNullable(originalCallback.get())
CallState.IDLE, CallState.TERMINATED -> throw IllegalStateException(
CallState.IllegalStateMessage.forCurrentState(state.get()).expected(CallState.ACTIVE, CallState.CANCELED))
else -> throw IllegalStateException("Unknown state")
}
}
@Synchronized
fun terminate(): Optional<ApolloCall.Callback<D>> {
return when (state.get()) {
CallState.ACTIVE -> {
tracker!!.unregisterCall(this)
state.set(CallState.TERMINATED)
Optional.fromNullable(originalCallback.getAndSet(null))
}
CallState.CANCELED -> Optional.fromNullable(originalCallback.getAndSet(null))
CallState.IDLE, CallState.TERMINATED -> throw IllegalStateException(
CallState.IllegalStateMessage.forCurrentState(state.get()).expected(CallState.ACTIVE, CallState.CANCELED))
else -> throw IllegalStateException("Unknown state")
}
}
private fun prepareInterceptorChain(operation: Operation<*>): ApolloInterceptorChain {
val httpCachePolicy = if (operation is Query<*>) httpCachePolicy else null
val interceptors: MutableList<ApolloInterceptor> = ArrayList()
for (factory in applicationInterceptorFactories!!) {
val interceptor = factory.newInterceptor(logger!!, operation)
if (interceptor != null) {
interceptors.add(interceptor)
}
}
interceptors.addAll(applicationInterceptors!!)
interceptors.add(responseFetcher!!.provideInterceptor(logger))
interceptors.add(ApolloCacheInterceptor(
apolloStore!!,
dispatcher!!,
logger!!,
originalCallback,
writeToNormalizedCacheAsynchronously,
responseAdapterCache
))
if (autoPersistedOperationsInterceptorFactory != null) {
val interceptor = autoPersistedOperationsInterceptorFactory.newInterceptor(logger, operation)
if (interceptor != null) {
interceptors.add(interceptor)
}
} else {
if (enableAutoPersistedQueries && (operation is Query<*> || operation is Mutation<*>)) {
interceptors.add(ApolloAutoPersistedOperationInterceptor(
logger,
useHttpGetMethodForPersistedQueries && operation !is Mutation<*>))
}
}
interceptors.add(ApolloParseInterceptor(
httpCache,
responseAdapterCache,
logger))
interceptors.add(ApolloServerInterceptor(serverUrl!!, httpCallFactory!!, httpCachePolicy, false, responseAdapterCache,
logger))
return RealApolloInterceptorChain(interceptors)
}
class Builder<D : Operation.Data> internal constructor() : ApolloQueryCall.Builder<D>, ApolloMutationCall.Builder<D> {
var operation: Operation<*>? = null
var serverUrl: HttpUrl? = null
var httpCallFactory: Call.Factory? = null
var httpCache: HttpCache? = null
var httpCachePolicy: HttpCachePolicy.Policy? = null
var responseAdapterCache: ResponseAdapterCache? = null
var apolloStore: ApolloStore? = null
var responseFetcher: ResponseFetcher? = null
var cacheHeaders: CacheHeaders? = null
var requestHeaders = RequestHeaders.NONE
var dispatcher: Executor? = null
var logger: ApolloLogger? = null
var applicationInterceptors: List<ApolloInterceptor>? = null
var applicationInterceptorFactories: List<ApolloInterceptorFactory>? = null
var autoPersistedOperationsInterceptorFactory: ApolloInterceptorFactory? = null
var refetchQueryNames: List<String> = emptyList()
var refetchQueries: List<Query<*>> = emptyList()
var tracker: ApolloCallTracker? = null
var enableAutoPersistedQueries = false
var optimisticUpdates = Optional.absent<Operation.Data>()
var useHttpGetMethodForQueries = false
var useHttpGetMethodForPersistedQueries = false
var writeToNormalizedCacheAsynchronously = false
fun operation(operation: Operation<*>?): Builder<D> {
this.operation = operation
return this
}
fun serverUrl(serverUrl: HttpUrl?): Builder<D> {
this.serverUrl = serverUrl
return this
}
fun httpCallFactory(httpCallFactory: Call.Factory?): Builder<D> {
this.httpCallFactory = httpCallFactory
return this
}
fun httpCache(httpCache: HttpCache?): Builder<D> {
this.httpCache = httpCache
return this
}
fun scalarTypeAdapters(responseAdapterCache: ResponseAdapterCache?): Builder<D> {
this.responseAdapterCache = responseAdapterCache
return this
}
fun apolloStore(apolloStore: ApolloStore?): Builder<D> {
this.apolloStore = apolloStore
return this
}
override fun cacheHeaders(cacheHeaders: CacheHeaders): Builder<D> {
this.cacheHeaders = cacheHeaders
return this
}
override fun httpCachePolicy(httpCachePolicy: HttpCachePolicy.Policy): Builder<D> {
this.httpCachePolicy = httpCachePolicy
return this
}
override fun responseFetcher(responseFetcher: ResponseFetcher): Builder<D> {
this.responseFetcher = responseFetcher
return this
}
override fun requestHeaders(requestHeaders: RequestHeaders): Builder<D> {
this.requestHeaders = requestHeaders
return this
}
override fun refetchQueryNames(refetchQueryNames: List<String>): Builder<D> {
this.refetchQueryNames = ArrayList(refetchQueryNames)
return this
}
override fun refetchQueries(refetchQueries: List<Query<*>>): Builder<D> {
this.refetchQueries = ArrayList(refetchQueries)
return this
}
fun dispatcher(dispatcher: Executor?): Builder<D> {
this.dispatcher = dispatcher
return this
}
fun logger(logger: ApolloLogger?): Builder<D> {
this.logger = logger
return this
}
fun tracker(tracker: ApolloCallTracker?): Builder<D> {
this.tracker = tracker
return this
}
fun applicationInterceptors(applicationInterceptors: List<ApolloInterceptor>?): Builder<D> {
this.applicationInterceptors = applicationInterceptors
return this
}
fun applicationInterceptorFactories(applicationInterceptorFactories: List<ApolloInterceptorFactory>?): Builder<D> {
this.applicationInterceptorFactories = applicationInterceptorFactories
return this
}
fun autoPersistedOperationsInterceptorFactory(interceptorFactory: ApolloInterceptorFactory?): Builder<D> {
autoPersistedOperationsInterceptorFactory = interceptorFactory
return this
}
fun enableAutoPersistedQueries(enableAutoPersistedQueries: Boolean): Builder<D> {
this.enableAutoPersistedQueries = enableAutoPersistedQueries
return this
}
fun optimisticUpdates(optimisticUpdates: Optional<Operation.Data>): Builder<D> {
this.optimisticUpdates = optimisticUpdates
return this
}
fun useHttpGetMethodForQueries(useHttpGetMethodForQueries: Boolean): Builder<D> {
this.useHttpGetMethodForQueries = useHttpGetMethodForQueries
return this
}
fun useHttpGetMethodForPersistedQueries(useHttpGetMethodForPersistedQueries: Boolean): Builder<D> {
this.useHttpGetMethodForPersistedQueries = useHttpGetMethodForPersistedQueries
return this
}
fun writeToNormalizedCacheAsynchronously(writeToNormalizedCacheAsynchronously: Boolean): Builder<D> {
this.writeToNormalizedCacheAsynchronously = writeToNormalizedCacheAsynchronously
return this
}
override fun build(): RealApolloCall<D> {
return RealApolloCall(this)
}
}
companion object {
@JvmStatic
fun <D : Operation.Data> builder(): Builder<D> {
return Builder()
}
}
init {
operation = builder.operation as Operation<D>
serverUrl = builder.serverUrl
httpCallFactory = builder.httpCallFactory
httpCache = builder.httpCache
httpCachePolicy = builder.httpCachePolicy
responseAdapterCache = builder.responseAdapterCache ?: throw IllegalArgumentException()
apolloStore = builder.apolloStore
responseFetcher = builder.responseFetcher
cacheHeaders = builder.cacheHeaders
requestHeaders = builder.requestHeaders
dispatcher = builder.dispatcher
logger = builder.logger
applicationInterceptors = builder.applicationInterceptors
applicationInterceptorFactories = builder.applicationInterceptorFactories
autoPersistedOperationsInterceptorFactory = builder.autoPersistedOperationsInterceptorFactory
refetchQueryNames = builder.refetchQueryNames
refetchQueries = builder.refetchQueries
tracker = builder.tracker
queryReFetcher = if (refetchQueries.isEmpty() && refetchQueryNames.isEmpty() || builder.apolloStore == null) {
Optional.absent()
} else {
Optional.of(QueryReFetcher.builder()
.queries(builder.refetchQueries)
.queryWatchers(refetchQueryNames)
.serverUrl(builder.serverUrl)
.httpCallFactory(builder.httpCallFactory)
.scalarTypeAdapters(builder.responseAdapterCache)
.apolloStore(builder.apolloStore)
.dispatcher(builder.dispatcher)
.logger(builder.logger)
.applicationInterceptors(builder.applicationInterceptors)
.applicationInterceptorFactories(builder.applicationInterceptorFactories)
.autoPersistedOperationsInterceptorFactory(builder.autoPersistedOperationsInterceptorFactory)
.callTracker(builder.tracker)
.build())
}
useHttpGetMethodForQueries = builder.useHttpGetMethodForQueries
enableAutoPersistedQueries = builder.enableAutoPersistedQueries
useHttpGetMethodForPersistedQueries = builder.useHttpGetMethodForPersistedQueries
optimisticUpdates = builder.optimisticUpdates
writeToNormalizedCacheAsynchronously = builder.writeToNormalizedCacheAsynchronously
interceptorChain = prepareInterceptorChain(operation)
}
}
| mit | 5e743935d2a0cffca0b6dfabed56211b | 37.855263 | 138 | 0.728605 | 4.898341 | false | false | false | false |
Asqatasun/Asqatasun | server/server-model/src/main/kotlin/org/asqatasun/model/Reference.kt | 1 | 1642 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.model
import io.swagger.v3.oas.annotations.media.Schema
@Schema(
description = "Referential against which the audit is ran.",
example = "RGAA_4_0",
)
enum class Referential(val code: String) {
RGAA_4_0("Rgaa40"),
RGAA_3_0("Rgaa30"),
ACCESSIWEB_2_2("Aw22"),
SEO("Seo");
companion object {
private val map = values().associateBy(Referential::code)
fun fromCode(code: String): Referential? = map[code]
}
}
@Schema(
description = "Referential level",
example = "AA",
)
enum class Level(val code: String) {
AAA("Or"),
AA("Ar"),
A("Bz");
companion object {
private val map = values().associateBy(Level::code)
fun fromCode(code: String): Level? = map[code]
}
}
| agpl-3.0 | d1baf2362e74f8ec92343a12406872b0 | 28.854545 | 76 | 0.676614 | 3.624724 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/storage/ProxyInterface.kt | 1 | 3670 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtOperation
/** A [ProxyMessage] of any data type. */
typealias UntypedProxyMessage = ProxyMessage<CrdtData, CrdtOperation, Any?>
/** A message coming from the storage proxy into one of the [IStore] implementations. */
sealed class ProxyMessage<Data : CrdtData, Op : CrdtOperation, ConsumerData>(
/** Identifier for the sender of the [ProxyMessage]. */
open val id: Int?,
/** [Type] of the message. */
internal open val type: Type
) {
fun withId(id: Int): ProxyMessage<Data, Op, ConsumerData> = when (this) {
is SyncRequest -> copy(id = id)
is ModelUpdate -> copy(id = id)
is Operations -> copy(id = id)
}
/** A request to sync data with the store. */
data class SyncRequest<Data : CrdtData, Op : CrdtOperation, ConsumerData>(
override val id: Int?,
override val type: Type = Type.SyncRequest
) : ProxyMessage<Data, Op, ConsumerData>(id, type)
/**
* A message requesting an update of the backing data in the store using a state-based CRDT
* update.
*/
data class ModelUpdate<Data : CrdtData, Op : CrdtOperation, ConsumerData>(
/** The new model data. */
val model: Data,
override val id: Int?,
override val type: Type = Type.ModelUpdate
) : ProxyMessage<Data, Op, ConsumerData>(id, type)
/** A message requesting an update of the backing data in the store using [CrdtOperation]s. */
data class Operations<Data : CrdtData, Op : CrdtOperation, ConsumerData>(
/** Operations required to update the backing data. */
val operations: List<Op>,
override val id: Int?,
override val type: Type = Type.Operations
) : ProxyMessage<Data, Op, ConsumerData>(id, type)
/** Type of message coming from the Storage Proxy. */
enum class Type {
SyncRequest,
ModelUpdate,
Operations,
}
}
/**
* A callback for listening to [ProxyMessage]s.
*
* Usage:
*
* ```kotlin
* val myCallback = ProxyCallback<FooData, FooOperation, RawFoo> { message ->
* when (message) {
* is ProxyMessage.SyncRequest -> handleSync()
* is ProxyMessage.ModelUpdate -> handleModelUpdate(message.model)
* is ProxyMessage.Operations -> handleOperations(message.operations)
* }
* }
* ```
*/
typealias ProxyCallback<Data, Op, ConsumerData> =
suspend (ProxyMessage<Data, Op, ConsumerData>) -> Unit
/**
* A combination of a [ProxyMessage] and a [muxId], which is typically the reference ID that
* uniquely identifies the entity store that has generated the message.
*/
data class MuxedProxyMessage<Data : CrdtData, Op : CrdtOperation, T>(
val muxId: String,
val message: ProxyMessage<Data, Op, T>
)
/** A convenience for a [CallbackManager] callback that uses a [MuxedProxyMessage] parameter. */
typealias MuxedProxyCallback<Data, Op, T> = suspend (MuxedProxyMessage<Data, Op, T>) -> Unit
/** Interface common to an [ActiveStore] and the PEC, used by the Storage Proxy. */
interface StorageEndpoint<Data : CrdtData, Op : CrdtOperation, ConsumerData> {
/**
* Suspends until the endpoint has become idle (typically: when it is finished flushing data to
* storage media.
*/
suspend fun idle()
/**
* Sends the storage layer a message from a [StorageProxy].
*/
suspend fun onProxyMessage(message: ProxyMessage<Data, Op, ConsumerData>)
suspend fun close()
}
| bsd-3-clause | c9a2d2f34cfb5b8684938c973be7a8cb | 32.063063 | 97 | 0.697275 | 3.971861 | false | false | false | false |
abigpotostew/easypolitics | rest/src/main/kotlin/bz/stewart/bracken/rest/data/bills/BillDelegated.kt | 1 | 5976 | package bz.stewart.bracken.rest.data.bills
import bz.stewart.bracken.db.bill.data.Bill
import bz.stewart.bracken.db.bill.data.parse.DbDateSerializer
import bz.stewart.bracken.db.leglislators.data.LegislatorData
import bz.stewart.bracken.rest.data.legislators.DelegatedLegislator
import bz.stewart.bracken.shared.data.EnactedAs
import bz.stewart.bracken.shared.data.FixedStatus
import bz.stewart.bracken.shared.data.PublicAction
import bz.stewart.bracken.shared.data.PublicBill
import bz.stewart.bracken.shared.data.PublicBillHistory
import bz.stewart.bracken.shared.data.PublicRelatedBill
import bz.stewart.bracken.shared.data.PublicSummary
import bz.stewart.bracken.shared.data.PublicTitle
import bz.stewart.bracken.shared.data.person.PublicLegislator
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonPropertyOrder
/**
* THIS IS THE DATA THAT WILL BE VISIBLE TO REST API
* Transforms a database bill to a public bill.
* Created by stew on 3/30/17.
*/
@JsonPropertyOrder("billId", "number", "congress", "resolutionType", "billType",
"shortTitle", "billName", "officialTitle", "currentStatus",
"currentStatusAt", "introducedAt", "updatedAt", "sponsor", "subjects")
@JsonInclude(JsonInclude.Include.NON_NULL)
class BillDelegated(private val bill: Bill,
private val peopleMap: Map<String, LegislatorData> = emptyMap()) : PublicBill {
override fun getCurrentStatusLabel(): String { //todo not working??
return getCurrentStatusDescription()
}
override fun getCurrentStatusDescription(): String {
return bill.billSummary?.text ?: ""
}
override fun getResolutionType(): String {
return when (bill.bill_type.isBill) {
true -> "bill"
false -> "resolution"
}
}
//NEW minimal data
override fun getBillName(): String {
return "${this.getBillId()} ${this.getOfficialTitle()}"
}
override fun id(): Int {
return 1
}
//old data
override fun getBillId(): String {
return "${bill.bill_type.shortLabel()} ${bill.billNumber}"
}
//@JsonIgnore
//todo this is output as actionsArr :(
override fun getActions(): Array<PublicAction>? {
return toPublicActionCollection(bill.actionsArr).toTypedArray()
}
override fun getBillType(): String {
return bill.bill_type.shortCode() //shortCode, todo need to make this a string
}
override fun getByRequest(): String? {
return bill.by_request
}
override fun getCommitteeReports(): Array<String>? {
return bill.committee_reports
}
//@JsonIgnore
override fun getCongress(): Int {
return bill.congressNum
}
//@JsonIgnore
override fun getCosponsors(): Array<PublicLegislator>? {
val cosponsorData: List<DelegatedLegislator> = bill.cosponsorsArr
.map { peopleMap[it.bioguide_id] }
.filterNotNull()
.map { DelegatedLegislator(it) }
return cosponsorData.toTypedArray()
}
//@JsonIgnore
override fun getSponsor(): PublicLegislator? {
val p: LegislatorData = peopleMap.get(bill.billSponsor.bioguide_id) ?: return null
return DelegatedLegislator(p)
}
override fun getEnactedAs(): EnactedAs? {
return bill.enacted_as
}
@JsonIgnore
override fun getHistory(): PublicBillHistory? {
return null//bill.billHistory
}
//@JsonSerialize(using = DbDateSerializer::class)
override fun getIntroducedAt(): String { //TODO make this return type Any
return DbDateSerializer().serializeDate(bill.introduced_at)
}
//@JsonIgnore
override fun getNumber(): String? {
return bill.billNumber
}
//@JsonIgnore
override fun getCommittees(): Array<Any> {
return bill.committeesArr
}
override fun getOfficialTitle(): String {
return bill.official_title
}
override fun getPopularTitle(): String? {
return bill.popular_title
}
//TODO
override fun getRelatedBills(): Array<PublicRelatedBill>? {
return null//bill.related_bills
}
override fun getShortTitle(): String? {
return bill.short_title
}
//@JsonIgnore
override fun getCurrentStatus(): FixedStatus { //todo make this into an enum and parse out of actions
//val cleanStatus = bill.currentStatus.replace(':','_').toLowerCase()
return FixedStatus.valueOfDb(bill.currentStatus)
//return bill.currentStatus
}
//@JsonSerialize(using = DbDateSerializer::class)
override fun getCurrentStatusAt(): String {
return DbDateSerializer().serializeDate(bill.status_at)
}
//@JsonIgnore
override fun getSubjects(): Array<String> {
return bill.subjectsArr
}
override fun getSubjectsTopTerm(): String? {
return bill.subjects_top_term
}
//@JsonIgnore
override fun getSummary(): PublicSummary? {
return bill.billSummary
}
//@JsonIgnore
//TODO
override fun getTitles(): Array<PublicTitle>? {
return null//bill.titlesArr
}
//@JsonSerialize(using = DbDateSerializer::class)
override fun getUpdatedAt(): String {
return DbDateSerializer().serializeDate(bill.updated_at)
}
//@JsonIgnore
override fun getUrl(): String {
return bill.urlBill
}
}
/**
* Created by stew on 3/19/17.
*/
fun Bill.toPublicDelegated(): BillDelegated {
return BillDelegated(this)
}
fun toPublicBillCollection(
mongoQueryResult: Collection<Bill>): Collection<BillDelegated> {
return mongoQueryResult.map(Bill::toPublicDelegated)
}
fun toPublicBillCollection(mongoQueryResult: Collection<Bill>,
people: Map<String, LegislatorData>): Collection<BillDelegated> {
return mongoQueryResult.map({
BillDelegated(it, people)
})
}
| apache-2.0 | 74f16e01150bc758ac3ae53e93d49b51 | 29.030151 | 105 | 0.680221 | 4.30858 | false | false | false | false |
hpost/kommon | app/src/main/java/cc/femto/kommon/ui/widget/ContentLoadingRelativeLayout.kt | 1 | 3026 | package cc.femto.kommon.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
/**
* ContentLoadingRelativeLayout implements a RelativeLayout that waits a minimum time to be
* dismissed before showing. Once visible, the view will be visible for
* a minimum amount of time to avoid "flashes" in the UI when an event could take
* a largely variable time to complete (from none, to a user perceivable amount)
*
* @see android.support.v4.widget.ContentLoadingProgressBar
*/
class ContentLoadingRelativeLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : RelativeLayout(context, attrs, 0) {
internal var startTime: Long = -1
internal var postedHide = false
internal var postedShow = false
internal var dismissed = false
private val delayedHide = Runnable {
postedHide = false
startTime = -1
visibility = View.GONE
}
private val delayedShow = Runnable {
postedShow = false
if (!dismissed) {
startTime = System.currentTimeMillis()
visibility = View.VISIBLE
}
}
public override fun onAttachedToWindow() {
super.onAttachedToWindow()
removeCallbacks()
}
public override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
removeCallbacks()
}
private fun removeCallbacks() {
removeCallbacks(delayedHide)
removeCallbacks(delayedShow)
}
/**
* Hide the view if it is visible. The view will not be
* hidden until it has been shown for at least a minimum show time. If the
* view was not yet visible, cancels showing the view.
*/
fun hide() {
dismissed = true
removeCallbacks(delayedShow)
val diff = System.currentTimeMillis() - startTime
if (diff >= MIN_SHOW_TIME || startTime == -1L) {
// The progress spinner has been shown long enough
// OR was not shown yet. If it wasn't shown yet,
// it will just never be shown.
visibility = View.GONE
} else {
// The progress spinner is shown, but not long enough,
// so put a delayed message in to hide it when its been
// shown long enough.
if (!postedHide) {
postDelayed(delayedHide, MIN_SHOW_TIME - diff)
postedHide = true
}
}
}
/**
* Show the view after waiting for a minimum delay.
* If during that time, hide() is called, the view is never made visible.
*/
fun show() {
// Reset the start time.
startTime = -1
dismissed = false
removeCallbacks(delayedHide)
if (!postedShow) {
postDelayed(delayedShow, MIN_DELAY.toLong())
postedShow = true
}
}
companion object {
private val MIN_SHOW_TIME = 500 // ms
private val MIN_DELAY = 500 // ms
}
}
| apache-2.0 | 71e428b84087cbb6620eb67093aba5a4 | 30.195876 | 145 | 0.624917 | 4.772871 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.