repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
smmribeiro/intellij-community
platform/statistics/src/com/intellij/internal/statistic/local/FileTypeUsageLocalSummary.kt
9
2293
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.local import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.XMap @State(name = "FileTypeUsageLocalSummary", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)], reportStatistic = false) class FileTypeUsageLocalSummary : PersistentStateComponent<FileTypeUsageLocalSummaryState>, FileTypeUsageSummaryProvider, SimpleModificationTracker() { @Volatile private var state = FileTypeUsageLocalSummaryState() override fun getState() = state override fun loadState(state: FileTypeUsageLocalSummaryState) { this.state = state } override fun getFileTypeStats(): Map<String, FileTypeUsageSummary> { return if (state.data.isEmpty()) { emptyMap() } else { HashMap(state.data) } } @Synchronized override fun updateFileTypeSummary(fileTypeName: String) { val summary = state.data.computeIfAbsent(fileTypeName) { FileTypeUsageSummary() } summary.usageCount++ summary.lastUsed = System.currentTimeMillis() incModificationCount() } } data class FileTypeUsageLocalSummaryState( @get:XMap(entryTagName = "fileType", keyAttributeName = "name") @get:Property(surroundWithTag = false) internal val data: MutableMap<String, FileTypeUsageSummary> = HashMap() ) private class FileTypeSummaryListener : FileEditorManagerListener { override fun fileOpened(source: FileEditorManager, file: VirtualFile) { val service = source.project.getService(FileTypeUsageSummaryProvider::class.java) val fileTypeName = file.fileType.name service.updateFileTypeSummary(fileTypeName) } }
apache-2.0
e958d3f72ff4e484c32102f891df9a3f
38.534483
158
0.772787
4.787056
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/AccessorProcessor.kt
12
1951
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors import com.intellij.lang.java.beans.PropertyKind import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.ResolveState import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.ElementClassHint.DeclarationKind import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.util.checkKind import org.jetbrains.plugins.groovy.lang.psi.util.getAccessorName import org.jetbrains.plugins.groovy.lang.resolve.AccessorResolveResult import org.jetbrains.plugins.groovy.lang.resolve.GenericAccessorResolveResult import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments class AccessorProcessor( propertyName: String, private val propertyKind: PropertyKind, private val arguments: Arguments?, private val place: PsiElement ) : BaseMethodProcessor(propertyKind.getAccessorName(propertyName)), GrResolverProcessor<GroovyResolveResult> { init { hint(ElementClassHint.KEY, ElementClassHint { it == DeclarationKind.METHOD && acceptMore }) hint(GroovyResolveKind.HINT_KEY, GroovyResolveKind.Hint { it == GroovyResolveKind.METHOD && acceptMore }) } override val results: List<GroovyResolveResult> get() = myCandidates override fun candidate(element: PsiMethod, state: ResolveState): GroovyMethodResult? { if (!element.checkKind(propertyKind)) return null return if (element.hasTypeParameters()) { GenericAccessorResolveResult(element, place, state, arguments) } else { AccessorResolveResult(element, place, state, arguments) } } }
apache-2.0
58e6fe488e0b587e687eeefaafcc2f32
40.510638
140
0.796002
4.404063
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/ToggleZenModeAction.kt
6
2371
package com.intellij.ide.actions import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.WindowManagerEx class ToggleZenModeAction : DumbAwareAction() { companion object { private fun isFullScreenApplicable() = WindowManager.getInstance().isFullScreenSupportedInCurrentOS private fun Project.getFrame() = WindowManagerEx.getInstanceEx().findFrameHelper(this) fun isZenModeEnabled(project: Project): Boolean { if (!ToggleDistractionFreeModeAction.isDistractionFreeModeEnabled()) return false if (isFullScreenApplicable()) { val frame = project.getFrame() if (frame != null && !frame.isInFullScreen) return false } return true } } private val toggleDistractionFreeModeAction = ToggleDistractionFreeModeAction() override fun update(e: AnActionEvent) { if (!isFullScreenApplicable()) { // If the full screen mode is not applicable, the action is identical to the distraction free mode, // and should be hidden to reduce confusion. e.presentation.isVisible = false return } val project = e.project if (project == null) { e.presentation.isEnabled = false return } e.presentation.text = if (isZenModeEnabled(project)) ActionsBundle.message("action.ToggleZenMode.exit") else ActionsBundle.message("action.ToggleZenMode.enter") } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return applyZenMode(e, !isZenModeEnabled(project)) } private fun applyZenMode(e: AnActionEvent, state: Boolean) { val project = e.project ?: return if (ToggleDistractionFreeModeAction.isDistractionFreeModeEnabled() != state) toggleDistractionFreeModeAction.actionPerformed(e) if (isFullScreenApplicable()) { val frame = project.getFrame() if (frame != null && frame.isInFullScreen != state) frame.toggleFullScreen(state) } } }
apache-2.0
22a95512c443ed0a835d571872e6db64
35.492308
111
0.659216
4.97065
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/ext/logback/LogbackDelegateMemberContributor.kt
3
5354
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.ext.logback import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.NameHint import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTreeUtil import groovy.lang.Closure.DELEGATE_FIRST import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrMethodWrapper import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_KEY import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_STRATEGY_KEY import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getContainingCall import org.jetbrains.plugins.groovy.lang.resolve.wrapClassType class LogbackDelegateMemberContributor : NonCodeMembersContributor() { override fun getParentClassName() = componentDelegateFqn override fun processDynamicElements(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { val name = processor.getHint(NameHint.KEY)?.getName(state) val componentClass = getComponentClass(place) ?: return val componentProcessor = ComponentProcessor(processor, place, name) if (name == null) { componentClass.processDeclarations(componentProcessor, state, null, place) } else { for (prefix in arrayOf("add", "set")) { for (method in componentClass.findMethodsByName(prefix + name.capitalize(), true)) { if (!componentProcessor.execute(method, state)) return } } } } fun getComponentClass(place: PsiElement): PsiClass? { val reference = place as? GrReferenceExpression ?: return null if (reference.isQualified) return null val closure = PsiTreeUtil.getParentOfType(reference, GrClosableBlock::class.java) ?: return null val call = getContainingCall(closure) ?: return null val arguments = PsiUtil.getAllArguments(call) if (arguments.isEmpty()) return null val lastIsClosure = (arguments.last().type as? PsiClassType)?.resolve()?.qualifiedName == GROOVY_LANG_CLOSURE val componentArgumentIndex = (if (lastIsClosure) arguments.size - 1 else arguments.size) - 1 val componentArgument = arguments.getOrNull(componentArgumentIndex) val componentType = ResolveUtil.unwrapClassType(componentArgument?.type) as? PsiClassType return componentType?.resolve() } class ComponentProcessor(val delegate: PsiScopeProcessor, val place: PsiElement, val name: String?) : PsiScopeProcessor { override fun execute(method: PsiElement, state: ResolveState): Boolean { method as? PsiMethod ?: return true val prefix = if (GroovyPropertyUtils.isSetterLike(method, "set")) { if (!delegate.execute(method, state)) return false "set" } else if (GroovyPropertyUtils.isSetterLike(method, "add")) { val newName = method.name.replaceFirst("add", "set") val wrapper = GrMethodWrapper.wrap(method, newName) if (!delegate.execute(wrapper, state)) return false "add" } else { return true } val propertyName = method.name.removePrefix(prefix).decapitalize() if (name != null && name != propertyName) return true val parameter = method.parameterList.parameters.singleOrNull() ?: return true val classType = wrapClassType(parameter.type, place) ?: return true val wrappedBase = GrLightMethodBuilder(place.manager, propertyName).apply { returnType = PsiType.VOID navigationElement = method } // (name, clazz) // (name, clazz, configuration) wrappedBase.copy().apply { addParameter("name", JAVA_LANG_STRING) addParameter("clazz", classType) addParameter("configuration", GROOVY_LANG_CLOSURE, true) }.let { if (!delegate.execute(it, state)) return false } // (clazz) // (clazz, configuration) wrappedBase.copy().apply { addParameter("clazz", classType) addAndGetParameter("configuration", GROOVY_LANG_CLOSURE, true).apply { putUserData(DELEGATES_TO_KEY, componentDelegateFqn) putUserData(DELEGATES_TO_STRATEGY_KEY, DELEGATE_FIRST) } }.let { if (!delegate.execute(it, state)) return false } return true } override fun <T : Any?> getHint(hintKey: Key<T>) = if (hintKey == ElementClassHint.KEY) { @Suppress("UNCHECKED_CAST") ElementClassHint { it == ElementClassHint.DeclarationKind.METHOD } as T } else { null } } }
apache-2.0
713a1f70ec69272ed7b38663029a09af
42.185484
140
0.728241
4.465388
false
false
false
false
MaTriXy/gradle-play-publisher-1
play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/internal/DefaultPlayPublisher.kt
1
9571
package com.github.triplet.gradle.androidpublisher.internal import com.github.triplet.gradle.androidpublisher.EditResponse import com.github.triplet.gradle.androidpublisher.GppProduct import com.github.triplet.gradle.androidpublisher.PlayPublisher import com.github.triplet.gradle.androidpublisher.UpdateProductResponse import com.github.triplet.gradle.androidpublisher.UploadInternalSharingArtifactResponse import com.google.api.client.googleapis.json.GoogleJsonResponseException import com.google.api.client.googleapis.media.MediaHttpUploader import com.google.api.client.googleapis.services.AbstractGoogleClientRequest import com.google.api.client.http.FileContent import com.google.api.client.json.jackson2.JacksonFactory import com.google.api.services.androidpublisher.AndroidPublisher import com.google.api.services.androidpublisher.model.Apk import com.google.api.services.androidpublisher.model.AppDetails import com.google.api.services.androidpublisher.model.Bundle import com.google.api.services.androidpublisher.model.DeobfuscationFilesUploadResponse import com.google.api.services.androidpublisher.model.ExpansionFile import com.google.api.services.androidpublisher.model.Image import com.google.api.services.androidpublisher.model.InAppProduct import com.google.api.services.androidpublisher.model.Listing import com.google.api.services.androidpublisher.model.Track import java.io.File import java.io.InputStream import kotlin.math.roundToInt internal class DefaultPlayPublisher( private val publisher: AndroidPublisher, override val appId: String ) : InternalPlayPublisher { override fun insertEdit(): EditResponse { return try { EditResponse.Success(publisher.edits().insert(appId, null).execute().id) } catch (e: GoogleJsonResponseException) { EditResponse.Failure(e) } } override fun getEdit(id: String): EditResponse { return try { EditResponse.Success(publisher.edits().get(appId, id).execute().id) } catch (e: GoogleJsonResponseException) { EditResponse.Failure(e) } } override fun commitEdit(id: String) { publisher.edits().commit(appId, id).execute() } override fun getAppDetails(editId: String): AppDetails { return publisher.edits().details().get(appId, editId).execute() } override fun getListings(editId: String): List<Listing> { return publisher.edits().listings().list(appId, editId).execute()?.listings.orEmpty() } override fun getImages(editId: String, locale: String, type: String): List<Image> { val response = publisher.edits().images().list(appId, editId, locale, type).execute() return response?.images.orEmpty() } override fun updateDetails(editId: String, details: AppDetails) { publisher.edits().details().update(appId, editId, details).execute() } override fun updateListing(editId: String, locale: String, listing: Listing) { publisher.edits().listings().update(appId, editId, locale, listing).execute() } override fun deleteImages(editId: String, locale: String, type: String) { publisher.edits().images().deleteall(appId, editId, locale, type).execute() } override fun uploadImage(editId: String, locale: String, type: String, image: File) { val content = FileContent(MIME_TYPE_IMAGE, image) publisher.edits().images().upload(appId, editId, locale, type, content).execute() } override fun getTrack(editId: String, track: String): Track { return try { publisher.edits().tracks().get(appId, editId, track).execute() } catch (e: GoogleJsonResponseException) { if (e has "notFound") { Track().setTrack(track) } else { throw e } } } override fun listTracks(editId: String): List<Track> { return publisher.edits().tracks().list(appId, editId).execute()?.tracks.orEmpty() } override fun updateTrack(editId: String, track: Track) { println("Updating ${track.releases.map { it.status }.distinct()} release " + "($appId:${track.releases.flatMap { it.versionCodes.orEmpty() }}) " + "in track '${track.track}'") publisher.edits().tracks().update(appId, editId, track.track, track).execute() } override fun uploadBundle(editId: String, bundleFile: File): Bundle { val content = FileContent(MIME_TYPE_STREAM, bundleFile) return publisher.edits().bundles().upload(appId, editId, content) .trackUploadProgress("App Bundle", bundleFile) .execute() } override fun uploadApk(editId: String, apkFile: File): Apk { val content = FileContent(MIME_TYPE_APK, apkFile) return publisher.edits().apks().upload(appId, editId, content) .trackUploadProgress("APK", apkFile) .execute() } override fun attachObb(editId: String, type: String, appVersion: Int, obbVersion: Int) { val obb = ExpansionFile().also { it.referencesVersion = obbVersion } publisher.edits().expansionfiles() .update(appId, editId, appVersion, type, obb) .execute() } override fun uploadDeobfuscationFile( editId: String, mappingFile: File, versionCode: Int ): DeobfuscationFilesUploadResponse { val mapping = FileContent(MIME_TYPE_STREAM, mappingFile) return publisher.edits().deobfuscationfiles() .upload(appId, editId, versionCode, "proguard", mapping) .trackUploadProgress("mapping file", mappingFile) .execute() } override fun uploadInternalSharingBundle(bundleFile: File): UploadInternalSharingArtifactResponse { val bundle = publisher.internalappsharingartifacts() .uploadbundle(appId, FileContent(MIME_TYPE_STREAM, bundleFile)) .trackUploadProgress("App Bundle", bundleFile) .execute() return UploadInternalSharingArtifactResponse(bundle.toPrettyString(), bundle.downloadUrl) } override fun uploadInternalSharingApk(apkFile: File): UploadInternalSharingArtifactResponse { val apk = publisher.internalappsharingartifacts() .uploadapk(appId, FileContent(MIME_TYPE_APK, apkFile)) .trackUploadProgress("APK", apkFile) .execute() return UploadInternalSharingArtifactResponse(apk.toPrettyString(), apk.downloadUrl) } override fun getInAppProducts(): List<GppProduct> { fun AndroidPublisher.Inappproducts.List.withToken(token: String?) = apply { this.token = token } val products = mutableListOf<InAppProduct>() var token: String? = null do { val response = publisher.inappproducts().list(appId).withToken(token).execute() products += response.inappproduct.orEmpty() token = response.tokenPagination?.nextPageToken } while (token != null) return products.map { GppProduct(it.sku, JacksonFactory.getDefaultInstance().toPrettyString(it)) } } override fun insertInAppProduct(productFile: File) { publisher.inappproducts().insert(appId, readProductFile(productFile)) .apply { autoConvertMissingPrices = true } .execute() } override fun updateInAppProduct(productFile: File): UpdateProductResponse { val product = readProductFile(productFile) try { publisher.inappproducts().update(appId, product.sku, product) .apply { autoConvertMissingPrices = true } .execute() } catch (e: GoogleJsonResponseException) { if (e.statusCode == 404) { return UpdateProductResponse(true) } else { throw e } } return UpdateProductResponse(false) } private fun readProductFile(product: File) = product.inputStream().use { JacksonFactory.getDefaultInstance() .createJsonParser(it) .parse(InAppProduct::class.java) } private fun <T, R : AbstractGoogleClientRequest<T>> R.trackUploadProgress( thing: String, file: File ): R { mediaHttpUploader?.setProgressListener { @Suppress("NON_EXHAUSTIVE_WHEN") when (it.uploadState) { MediaHttpUploader.UploadState.INITIATION_STARTED -> println("Starting $thing upload: $file") MediaHttpUploader.UploadState.MEDIA_IN_PROGRESS -> println("Uploading $thing: ${(it.progress * 100).roundToInt()}% complete") MediaHttpUploader.UploadState.MEDIA_COMPLETE -> println("${thing.capitalize()} upload complete") } } return this } class Factory : PlayPublisher.Factory { override fun create( credentials: InputStream, appId: String ): PlayPublisher { val publisher = createPublisher(credentials) return DefaultPlayPublisher(publisher, appId) } } private companion object { const val MIME_TYPE_STREAM = "application/octet-stream" const val MIME_TYPE_APK = "application/vnd.android.package-archive" const val MIME_TYPE_IMAGE = "image/*" } }
mit
d882ccca8e708c46a2ed3ce55df1b150
39.555085
103
0.656149
4.86826
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/chatroom/messaging/reading/display/room_event/room/creation.kt
1
1356
package koma.gui.view.window.chatroom.messaging.reading.display.room_event.room import javafx.geometry.Pos import koma.gui.view.window.chatroom.messaging.reading.display.room_event.util.DatatimeView import koma.gui.view.window.chatroom.messaging.reading.display.room_event.util.StateEventUserView import koma.koma_app.AppStore import koma.matrix.event.room_message.MRoomCreate import kotlinx.coroutines.ExperimentalCoroutinesApi import link.continuum.desktop.gui.HBox import link.continuum.desktop.gui.add import link.continuum.desktop.gui.message.MessageCellContent import link.continuum.desktop.gui.text import link.continuum.desktop.util.http.MediaServer @ExperimentalCoroutinesApi class MRoomCreationViewNode constructor( store: AppStore ): MessageCellContent<MRoomCreate> { override val root = HBox(5.0) private val userView = StateEventUserView(store.userData) private val timeView = DatatimeView() init { root.apply { alignment = Pos.CENTER text("This room is create by") { opacity = 0.5 } add(userView.root) add(timeView.root) } } override fun update(message: MRoomCreate, mediaServer: MediaServer) { userView.updateUser(message.sender, mediaServer) timeView.updateTime(message.origin_server_ts) } }
gpl-3.0
10b6ef591c94a3f22415149065ddca81
34.684211
97
0.738938
3.988235
false
false
false
false
SkyA1ex/kotlin-crdt
src/main/kotlin/vertx/verticleMessage.kt
1
3895
package vertx import cmrdt.set.operation.ORSetOperation import cmrdt.set.operation.SetOperation import io.vertx.core.json.JsonObject import vertx.VerticleMessage.Companion.FIELD_OP_TAGS import vertx.VerticleMessage.Companion.FIELD_OP_TYPE import vertx.VerticleMessage.Companion.FIELD_OP_VALUE /** * Created by jackqack on 09/06/17. */ enum class MessageType { REQUEST_STATE, RESPONSE_STATE, SEND_OPERATION } data class VerticleMessage(val type: MessageType, val data: String? = null) { companion object { const val FIELD_TYPE = "type" const val FIELD_DATA = "data" const val FIELD_OP_TYPE = "type" const val FIELD_OP_VALUE = "value" const val FIELD_OP_TAGS = "tags" } fun toJson(): JsonObject { val json = JsonObject() json.put(FIELD_TYPE, type.name) json.put(FIELD_DATA, data) return json } } private fun fromJson(json: JsonObject): VerticleMessage? { if (!json.isEmpty && json.containsKey(VerticleMessage.FIELD_TYPE)) { when (json.getString(VerticleMessage.FIELD_TYPE)) { MessageType.REQUEST_STATE.name -> { return VerticleMessage(MessageType.REQUEST_STATE) } MessageType.REQUEST_STATE.name -> { return VerticleMessage(MessageType.RESPONSE_STATE, json.getString(VerticleMessage.FIELD_DATA)) } MessageType.SEND_OPERATION.name -> { if (json.containsKey(VerticleMessage.FIELD_DATA)) { return VerticleMessage(MessageType.SEND_OPERATION, json.getString(VerticleMessage.FIELD_DATA)) } } } return null } else return null } private fun operationFromJson(json: JsonObject): ORSetOperation<Int>? { if (!json.isEmpty && json.containsKey(FIELD_OP_TYPE) && json.containsKey(FIELD_OP_VALUE) && json.containsKey(FIELD_OP_TAGS)) { val type: SetOperation.Type try { type = SetOperation.Type.valueOf(json.getString(FIELD_OP_TYPE)) } catch (e: IllegalArgumentException) { return null } val value = json.getInteger(FIELD_OP_VALUE) ?: return null val tags = ArrayList<String>() val jsonTags = json.getJsonArray(FIELD_OP_TAGS) ?: return null for ((i, _) in jsonTags.withIndex()) { val s = jsonTags.getString(i) ?: return null tags.add(s) } return ORSetOperation(type, value, tags) } else return null } private fun stateFromJson(json: JsonObject): MutableMap<Int, MutableSet<String>>? { if (!json.isEmpty) { val map = HashMap<Int, MutableSet<String>>() for (str in json.fieldNames()) { try { val tags = HashSet<String>() map.put(str.toInt(), tags) val jsonTags = json.getJsonArray(str) ?: return null for ((i, _) in jsonTags.withIndex()) { val s = jsonTags.getString(i) ?: return null tags.add(s) } } catch (e: NumberFormatException) { return null } } return map } else return null } fun parseMessage(str: String): VerticleMessage? { try { val json = JsonObject(str) return fromJson(json) } catch (e: Exception) { return null } } fun parseState(str: String): MutableMap<Int, MutableSet<String>>? { try { val json = JsonObject(str) return stateFromJson(json) } catch (e: Exception) { return null } } fun parseOperation(str: String): ORSetOperation<Int>? { try { val json = JsonObject(str) return operationFromJson(json) } catch (e: Exception) { return null } } fun toJson(op: ORSetOperation<Int>): JsonObject { return JsonObject.mapFrom(op) }
mit
9ab6923910f187a1299ef0e3a0970743
28.732824
114
0.602054
4.13482
false
false
false
false
Kotlin/kotlinx.dom
src/main/kotlin/Mutations.kt
1
1824
package kotlinx.dom import org.w3c.dom.* /** Removes all the children from this node */ fun Node.clear() { while (hasChildNodes()) { removeChild(firstChild!!) } } /** * Removes this node from parent node. Does nothing if no parent node */ fun Node.removeFromParent() { parentNode?.removeChild(this) } operator fun Node.plus(child: Node): Node { appendChild(child) return this } operator fun Element.plus(text: String): Element = appendText(text) operator fun Element.plusAssign(text: String): Unit { appendText(text) } /** Returns the owner document of the element or uses the provided document */ fun Node.ownerDocument(doc: Document? = null): Document = when { nodeType == Node.DOCUMENT_NODE -> this as Document else -> doc ?: ownerDocument ?: throw IllegalArgumentException("Neither node contains nor parameter doc provides an owner document for $this") } /** * Adds a newly created text node to an element which either already has an owner Document or one must be provided as a parameter */ @Deprecated("Use appendText() instead", ReplaceWith("appendText(text, doc)")) fun Element.addText(text: String, doc: Document? = null): Element = appendText(text, doc) /** * Adds a newly created text node to an element which either already has an owner Document or one must be provided as a parameter */ @Deprecated("Use appendText() instead", ReplaceWith("appendText(text)")) fun Element.addText(text: String): Element = appendText(text) /** * Creates text node and append it to the element */ fun Element.appendText(text: String, doc : Document? = null): Element { appendChild(ownerDocument(doc).createTextNode(text)) return this } /** * Appends the node to the specified parent element */ fun Node.appendTo(parent: Element) { parent.appendChild(this) }
apache-2.0
a409bcf94a601bb4c86df8839acaa412
28.901639
146
0.71875
4.098876
false
false
false
false
virvar/magnetic-ball-2
MagneticBallCore/src/main/kotlin/ru/virvar/apps/magneticBallCore/Level.kt
1
1576
package ru.virvar.apps.magneticBallCore import ru.virvar.apps.magneticBallCore.gameActions.AddAction import ru.virvar.apps.magneticBallCore.gameActions.MoveAction import ru.virvar.apps.magneticBallCore.gameActions.RemoveAction open class Level( val fieldSize: Int, val moveBehavior: IMoveBehavior, val moveHelper: IMoveHelper) { private val field: Field private val stateManager: LevelStateManager var score: Int = 0 var gameState: GameState = GameState.LOOSE val freeCells: List<Int> get () = this.field.freeCells val blocks: Map<Int, Block> get() = this.field.blocks init { field = Field(fieldSize) stateManager = LevelStateManager() } fun getBlock(x: Int, y: Int, depth: Int = 0): Block? = field.getBlock(x, y, depth) fun isOutOfField(point: Point2D): Boolean = field.isOutOfField(point) fun addBlock(block: Block) { field.addBlock(block) stateManager.addAction(AddAction(block)) } fun removeBlock(block: Block) { field.removeBlock(block) stateManager.addAction(RemoveAction(block)) } fun moveBlock(block: Block, newPosition: Point2D) { field.moveBlock(block, newPosition) stateManager.addAction(MoveAction(block, newPosition)) } fun commitChanges() { // todo: Implement changes logic. } fun resetChanges() { // todo: Implement changes logic. } fun nextState(updateInterval: Long): List<Block> { return stateManager.nextState(updateInterval) } }
gpl-2.0
fa8796bc2214c2072d6b4d48aafa7783
27.654545
86
0.673858
4.125654
false
false
false
false
theostanton/LFGSS
app/src/main/java/com/theostanton/lfgss/listitem/ListItemListDeserialiser.kt
1
2157
package com.theostanton.lfgss.listitem import com.google.gson.* import com.theostanton.lfgss.api.get.Comment import com.theostanton.lfgss.api.get.Conversation import com.theostanton.lfgss.home.Microcosm import timber.log.Timber import java.lang.reflect.Type import java.util.* /** * Created by theostanton on 22/02/16. */ class ListItemListDeserialiser : JsonSerializer<ArrayList<out ListItem>>, JsonDeserializer<ArrayList<out ListItem>> { val gson by lazy { BuildGson.getGson() } override fun serialize(p0: ArrayList<out ListItem>?, p1: Type?, p2: JsonSerializationContext?): JsonElement? { throw UnsupportedOperationException() } override fun deserialize(element: JsonElement?, type: Type?, context: JsonDeserializationContext?): ArrayList<out ListItem>? { val jarr = element?.asJsonArray ?: return ArrayList() val list = ArrayList<ListItem>(jarr.size()) var listItem: ListItem? var cls: Type? var jsonObj: JsonObject? for (el in jarr) { try { jsonObj = el.asJsonObject cls = jsonToClass(jsonObj) listItem = gson.fromJson(jsonObj.get("item"), cls) Timber.d("listItem=$listItem") if (listItem != null) list.add(listItem) } catch(ex: Exception) { Timber.e("deseriale exception ${ex.message}", ex) // Toasts.d(ex.message) } catch(ex: IllegalStateException) { Timber.e("deseriale IllegalStateException ${ex.message}", ex) // Toasts.d(ex.message) } } return list } fun jsonToClass(jsonObject: JsonObject): Type? { if (jsonObject.has("itemType")) { if (jsonObject.has("markdown")) return Comment::class.java when (jsonObject.get("itemType").asString) { "conversation" -> return Conversation::class.java "microcosm" -> return Microcosm::class.java "huddle" -> return Comment::class.java } } return null } }
mit
da9327dedc5049a0d0c778e818344e9e
32.2
130
0.599444
4.522013
false
false
false
false
davinkevin/Podcast-Server
backend/src/test/kotlin/com/github/davinkevin/podcastserver/MockServer.kt
1
1504
package com.github.davinkevin.podcastserver import com.github.tomakehurst.wiremock.WireMockServer import org.junit.jupiter.api.extension.* import org.springframework.boot.web.reactive.function.client.WebClientCustomizer import org.springframework.web.reactive.function.client.ClientRequest import org.springframework.web.reactive.function.client.ExchangeFilterFunction import reactor.kotlin.core.publisher.toMono import java.net.URI class MockServer: BeforeEachCallback, AfterEachCallback, ParameterResolver { private lateinit var server: WireMockServer override fun beforeEach(p0: ExtensionContext?) { server = WireMockServer(5555) server.start() } override fun afterEach(context: ExtensionContext?) { server.stop() server.resetAll() } override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean { return parameterContext.parameter.type == WireMockServer::class.java } override fun resolveParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext): Any { return server } } fun remapToMockServer(host: String) = WebClientCustomizer { it.filter(ExchangeFilterFunction.ofRequestProcessor { c -> val mockServerUrl = c.url().toASCIIString() .replace("https", "http") .replace(host, "localhost:5555") ClientRequest.from(c) .url(URI(mockServerUrl)) .build() .toMono() }) }
apache-2.0
f5b06c1f7be3b79581bd33b56162324f
33.976744
118
0.736037
4.931148
false
false
false
false
MaridProject/marid
marid-moans/src/main/kotlin/org/marid/moan/Context.kt
1
11870
/* * MARID, the visual component programming environment. * Copyright (C) 2020 Dzmitry Auchynnikau * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.marid.moan import java.lang.ref.Cleaner import java.math.BigInteger import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedDeque import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicReference import java.util.logging.Level.INFO import kotlin.reflect.* import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.isSubtypeOf typealias Closer = (Runnable) -> Runnable class Context private constructor( val name: String, val parent: Context?, closer: Closer, val properties: Properties ): MoanFetcher, AutoCloseable { private val queue = ConcurrentLinkedDeque<MoanHolder<*>>() private val typedMap = ConcurrentHashMap<KClassifier, ConcurrentLinkedQueue<MoanHolder<*>>>() private val namedMap = ConcurrentHashMap<String, MoanHolder<*>>() private val closeListeners = ConcurrentLinkedDeque<() -> Unit>() private val uid = UIDS.getAndUpdate(BigInteger::inc) val path: String = generateSequence(this) { it.parent }.map { it.name }.reduce { a, b -> "$b/$a" } init { val name = this.path val queue = this.queue val typedMap = this.typedMap val namedMap = this.namedMap val closeListeners = this.closeListeners val closeTask = { uid: BigInteger -> closer(Runnable { name.asLogger.log(INFO, "Cleaning") close(uid, name, queue, typedMap, namedMap, closeListeners) }) } if (parent != null) { val uid = this.uid val listener = { closeTask(uid).run() } val parent = this.parent parent.addCloseListener(listener) addCloseListener { parent.removeCloseListener(listener) } } CLEANABLES.computeIfAbsent(uid) { uid -> CLEANER.register(this, closeTask(uid)) } } fun addCloseListener(listener: () -> Unit) { closeListeners.addFirst(listener) } fun removeCloseListener(listener: () -> Unit) { closeListeners.removeIf { it === listener } } override fun by(type: KType, name: String?, optional: Boolean): MoanResult<Any?> { return when (type.classifier) { Seq::class -> { val list = byType(type).toList() if (list.isEmpty()) { when { optional -> MoanResult(null, true) type.isMarkedNullable -> MoanResult(null) else -> MoanResult(Seq(emptySequence<Any?>())) } } else { MoanResult(Seq(list.asSequence().map { it.moan })) } } Ref::class -> by(type.arguments.first().type!!, name, optional) Context::class -> { if (name == null) { MoanResult(this, false) } else { MoanResult(generateSequence(this) { it.parent }.find { it.name == name } ?: this, false) } } else -> { if (name == null) { by0(type, name, optional) } else { try { MoanResult(byName(name, type).moan) } catch (e: NoSuchElementException) { by0(type, name, optional) } } } } } private fun by0(type: KType, name: String?, optional: Boolean): MoanResult<Any?> { val list = byType(type).toList() return when (list.size) { 0 -> when { optional -> MoanResult(null, true) type.isMarkedNullable -> MoanResult(null) else -> throw NoSuchElementException("No moan of type $type for $name") } 1 -> MoanResult(list[0].moan) else -> throw MultipleBindingException("Multiple moans of type $type for $name: ${list.map { it.name }}") } } private fun byType(type: KType): Sequence<MoanHolder<*>> { val c = when (val c = type.classifier) { is KClassifier -> typedMap[c]?.let(Collection<MoanHolder<*>>::asSequence) ?: emptySequence() else -> queue.asSequence().filter { it.type.isSubtypeOf(type) } } return when (parent) { null -> c else -> c + parent.byType(type) } } private fun byName(name: String, type: KType): MoanHolder<*> { return when (val m = namedMap[name]) { null -> when (parent) { null -> throw NoSuchElementException(name) else -> parent.byName(name, type) } else -> when { m.type.isSubtypeOf(type) -> m else -> when (parent) { null -> throw ClassCastException("Moan $name of ${m.type} cannot be cast to $type") else -> { try { parent.byName(name, type) } catch (e: NoSuchElementException) { val x = ClassCastException("Moan $name of ${m.type} cannot be cast to $type") x.initCause(e) throw x } catch (e: ClassCastException) { val x = ClassCastException("Moan $name of ${m.type} cannot be cast to $type") x.initCause(e) throw x } } } } } } fun <T, H: MoanHolder<T>> register(holder: H, scope: Scope? = null) { namedMap.compute(holder.name) { n, old -> if (old == null) { if (scope != null && holder is ScopedMoanHolder<*>) { scope.add(holder, this) } queue += holder val type = holder.type when (val c = type.classifier) { is KClassifier -> typedMap.computeIfAbsent(c) { ConcurrentLinkedQueue<MoanHolder<*>>() } += holder } path.asLogger.log(INFO, "Registered $holder") holder } else { throw DuplicatedMoanException(n) } } } private fun unregister0(old: MoanHolder<*>): MoanHolder<*>? { queue.removeIf { it === old } val classifier = old.type.classifier if (classifier != null) { typedMap.computeIfPresent(classifier) { _, oldList -> oldList.removeIf { it === old } if (oldList.isEmpty()) null else oldList } } return null } fun unregister(name: String) { namedMap.computeIfPresent(name) { _, old -> unregister0(old) } } fun unregister(holder: MoanHolder<*>) { namedMap.computeIfPresent(holder.name) { _, old -> if (old === holder) unregister0(old) else old } } fun init(moduleFactory: (Context) -> Module, dependencyMapper: DependencyMapper = { sequenceOf(it) }): Context { try { val module = moduleFactory(this) module.initialize(dependencyMapper) return this } catch (e: Throwable) { try { close() } catch (x: Throwable) { e.addSuppressed(x) } throw e } } override fun close() = close(uid, name, queue, typedMap, namedMap, closeListeners) override fun toString(): String = path companion object { private val CLEANER = Cleaner.create() private val UIDS = AtomicReference(BigInteger.ZERO) private val CLEANABLES = ConcurrentHashMap<BigInteger, Cleaner.Cleanable>(128, 0.5f) init { Scope.cleanOnShutdown("ContextCleaner", CLEANABLES) } operator fun invoke( name: String, parent: Context? = null, closer: Closer = { it }, properties: Properties = System.getProperties() ) = Context(name, parent, closer, properties) fun <T, H: MoanHolder<T>> H.withInitHook(hook: (T) -> Unit): H { postConstructHooks.add(hook) return this } private fun close( uid: BigInteger, name: String, queue: ConcurrentLinkedDeque<MoanHolder<*>>, typedMap: ConcurrentHashMap<KClassifier, ConcurrentLinkedQueue<MoanHolder<*>>>, namedMap: ConcurrentHashMap<String, MoanHolder<*>>, closeListeners: ConcurrentLinkedDeque<() -> Unit> ) { CLEANABLES.remove(uid) val exception = ContextCloseException(name) closeListeners.removeIf { try { it() } catch (e: Throwable) { exception.addSuppressed(e) } true } val it = queue.descendingIterator() val logger = name.asLogger while (it.hasNext()) { val e = it.next() try { logger.log(INFO, "Closing moan ${e.name}") e.close() logger.log(INFO, "Closed moan ${e.name}") } catch (x: Throwable) { exception.addSuppressed(x) } finally { namedMap.remove(e.name) val classifier = e.type.classifier if (classifier != null) { typedMap.computeIfPresent(classifier) { _, old -> old.removeIf { it === e } if (old.isEmpty()) null else old } } it.remove() } } try { check(queue.isEmpty()) { "queue is not empty" } check(typedMap.isEmpty()) { "typedMap is not empty" } check(namedMap.isEmpty()) { "namedMap is not empty" } } catch (e: Throwable) { exception.addSuppressed(e) } if (exception.suppressed.isNotEmpty()) { throw exception } } internal fun Context.args(callable: KCallable<*>): Map<KParameter, Any?> { val parameters = callable.parameters val args = mutableMapOf<KParameter, Any?>() for (p in parameters) { val propAnnotation = p.findAnnotation<Prop>() if (propAnnotation == null) { when (p.kind) { KParameter.Kind.INSTANCE -> args[p] = this KParameter.Kind.EXTENSION_RECEIVER -> throw IllegalStateException() KParameter.Kind.VALUE -> { val result = by(p.type, p.name, p.isOptional) if (!result.empty) { args[p] = result.value } } } } else { val propName = propAnnotation.value.ifEmpty { p.name } val propValue = properties.getProperty(propName) if (propValue == null) { if (!p.isOptional) { if (p.type.isMarkedNullable) { args[p] = null } else { throw IllegalArgumentException("Parameter ${p.name} of $callable has no default value") } } } else { val converted = convert(propValue, p.type) args[p] = converted } } } return args } } private fun convert(arg: String, to: KType): Any { val klass = to.classifier as KClass<*> return when (klass) { Int::class -> arg.toInt() Long::class -> arg.toLong() Boolean::class -> arg.toBoolean() String::class -> arg UInt::class -> arg.toUInt() ULong::class -> arg.toULong() List::class -> { val values = arg.split(',') val t = to.arguments[0].type!! values.map { convert(it.trim(), t) } } Set::class -> { val values = arg.split(',') val t = to.arguments[0].type!! values.map { convert(it.trim(), t) }.toSet() } SortedSet::class -> { val values = arg.split(',') val t = to.arguments[0].type!! TreeSet(values.map { convert(it.trim(), t) }) } else -> throw IllegalArgumentException("Unable to convert $arg to $to") } } }
agpl-3.0
b76c989f868976f80f2c9df92f028f7e
31.434426
114
0.585678
4.153254
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/games/GameAutoEventController.kt
1
4435
package ca.josephroque.bowlingcompanion.games import android.content.SharedPreferences import android.os.Handler import ca.josephroque.bowlingcompanion.common.Android import ca.josephroque.bowlingcompanion.settings.Settings import kotlinx.coroutines.experimental.launch /** * Copyright (C) 2018 Joseph Roque * * Control automatic game events. */ class GameAutoEventController( preferences: SharedPreferences, private val delegate: GameAutoEventDelegate ) { companion object { @Suppress("unused") private const val TAG = "GameAutoEventController" private var autoAdvanceTotalDelay: Int = 0 } init { init(preferences) } fun init(preferences: SharedPreferences) { // Enable auto lock val autoLockEnabled = Settings.BooleanSetting.EnableAutoLock.getValue(preferences) if (autoLockEnabled) { enable(AutoEvent.Lock) } else { AutoEvent.Lock.isEnabled = false } // Enable auto advance val autoAdvanceEnabled = Settings.BooleanSetting.EnableAutoAdvance.getValue(preferences) if (autoAdvanceEnabled) { enable(AutoEvent.AdvanceFrame) } else { AutoEvent.AdvanceFrame.isEnabled = false } // Set auto advance delay time val strDelay = Settings.StringSetting.AutoAdvanceTime.getValue(preferences) val strDelayComponents = strDelay.split(" ") autoAdvanceTotalDelay = Integer.valueOf(strDelayComponents[0]) } private val autoEventHandler: HashMap<AutoEvent, Handler> by lazy { val map = HashMap<AutoEvent, Handler>() AutoEvent.values().forEach { map[it] = Handler() } return@lazy map } private val autoEventRunnable: HashMap<AutoEvent, Runnable> by lazy { val map = HashMap<AutoEvent, Runnable>() map[AutoEvent.AdvanceFrame] = Runnable { launch(Android) { if (!AutoEvent.AdvanceFrame.isEnabled) { return@launch } if (autoAdvanceSecondsRemaining > 0) { autoAdvanceSecondsRemaining -= 1 start(AutoEvent.AdvanceFrame) delegate.autoAdvanceCountDown(autoAdvanceSecondsRemaining) } else { delegate.autoEventFired(AutoEvent.AdvanceFrame) } } } map[AutoEvent.Lock] = Runnable { launch(Android) { if (!AutoEvent.Lock.isEnabled) { return@launch } delegate.autoEventFired(AutoEvent.Lock) pause(AutoEvent.Lock) } } return@lazy map } private var autoAdvanceSecondsRemaining: Int = 0 // MARK: GameAutoEventController fun disable(event: AutoEvent) { autoEventHandler[event]?.removeCallbacks(autoEventRunnable[event]) event.isEnabled = false } fun pause(event: AutoEvent) { autoEventHandler[event]?.removeCallbacks(autoEventRunnable[event]) delegate.autoEventPaused(event) } fun start(event: AutoEvent) { if (!event.isEnabled) { return } autoEventHandler[event]?.postDelayed(autoEventRunnable[event], event.delay) } fun delay(event: AutoEvent) { pause(event) when (event) { AutoEvent.AdvanceFrame -> autoAdvanceSecondsRemaining = autoAdvanceTotalDelay AutoEvent.Lock -> {} // Do nothing } start(event) delegate.autoEventDelayed(event) } fun pauseAll() { AutoEvent.values().forEach { pause(it) } } // MARK: Private functions private fun enable(event: AutoEvent) { event.isEnabled = true } // MARK: AutoEvent enum class AutoEvent { AdvanceFrame, Lock; val delay: Long get() { return when (this) { AdvanceFrame -> ADVANCE_FRAME_DELAY Lock -> LOCK_DELAY } } var isEnabled: Boolean = false companion object { var ADVANCE_FRAME_DELAY = 1000L var LOCK_DELAY = 5000L } } // MARK: GameAutoEventDelegate interface GameAutoEventDelegate { fun autoEventFired(event: AutoEvent) fun autoEventDelayed(event: AutoEvent) fun autoEventPaused(event: AutoEvent) fun autoAdvanceCountDown(secondsRemaining: Int) } }
mit
7b81710a417cc637669324590830110c
28.765101
96
0.619166
4.72311
false
false
false
false
pchrysa/Memento-Calendar
android_mobile/src/main/java/com/alexstyl/specialdates/contact/AndroidContactFactory.kt
1
3745
package com.alexstyl.specialdates.contact import android.content.ContentResolver import android.content.ContentUris import android.database.Cursor import android.provider.ContactsContract import com.alexstyl.specialdates.ErrorTracker import com.alexstyl.specialdates.contact.AndroidContactsQuery.SORT_ORDER import com.alexstyl.specialdates.contact.ContactSource.SOURCE_DEVICE import java.net.URI import java.util.Collections internal class AndroidContactFactory(private val resolver: ContentResolver) { fun getAllContacts(): Contacts { val cursor: Cursor? try { cursor = resolver.query( AndroidContactsQuery.CONTENT_URI, AndroidContactsQuery.PROJECTION, WHERE, null, AndroidContactsQuery.SORT_ORDER ) } catch (e: Exception) { ErrorTracker.track(e) return Contacts(SOURCE_DEVICE, emptyList()) } return cursor.use { return@use Contacts(SOURCE_DEVICE, List(it.count, { index -> it.moveToPosition(index) createContactFrom(it) })) } } @Throws(ContactNotFoundException::class) fun createContactWithId(contactID: Long): Contact { val cursor = queryContactsWithContactId(contactID) if (isInvalid(cursor)) { throw RuntimeException("Cursor was invalid") } cursor.use { if (it.moveToFirst()) { return createContactFrom(it) } } throw ContactNotFoundException(contactID) } fun queryContacts(ids: List<Long>): Contacts { val cursor = queryContactsWithContactId(ids) return cursor.use { return@use Contacts(SOURCE_DEVICE, List(it.count) { index -> it.moveToPosition(index) createContactFrom(it) }) } } private fun queryContactsWithContactId(ids: List<Long>): Cursor { return resolver.query( AndroidContactsQuery.CONTENT_URI, AndroidContactsQuery.PROJECTION, "${AndroidContactsQuery._ID} IN (${Collections.nCopies(ids.size, "?").joinToString(",")})", ids.map { it.toString() }.toTypedArray(), SORT_ORDER ) } private fun createContactFrom(cursor: Cursor): Contact { val contactID = getContactIdFrom(cursor) val displayName = getDisplayNameFrom(cursor) val imagePath = URI.create(ContentUris.withAppendedId(AndroidContactsQuery.CONTENT_URI, contactID).toString()) return Contact(contactID, displayName, imagePath, SOURCE_DEVICE) } private fun queryContactsWithContactId(contactID: Long): Cursor { return resolver.query( AndroidContactsQuery.CONTENT_URI, AndroidContactsQuery.PROJECTION, SELECTION_CONTACT_WITH_ID, makeSelectionArgumentsFor(contactID), SORT_ORDER + " LIMIT 1" ) } private fun makeSelectionArgumentsFor(contactID: Long): Array<String> = arrayOf(contactID.toString()) companion object { private val WHERE = ContactsContract.Data.IN_VISIBLE_GROUP + "=1" private val SELECTION_CONTACT_WITH_ID = AndroidContactsQuery._ID + " = ?" private fun isInvalid(cursor: Cursor?): Boolean = cursor == null || cursor.isClosed private fun getContactIdFrom(cursor: Cursor): Long = cursor.getLong(AndroidContactsQuery.CONTACT_ID) private fun getDisplayNameFrom(cursor: Cursor): DisplayName = DisplayName.from(cursor.getString(AndroidContactsQuery.DISPLAY_NAME)) } }
mit
28c8f63c69b934768f156c250d3bdfe7
34.330189
118
0.631509
4.908257
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/database/table/RPKChatGroupInviteTable.kt
1
6221
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.database.table import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatgroup.RPKChatGroup import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupId import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupInvite import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupService import com.rpkit.chat.bukkit.database.create import com.rpkit.chat.bukkit.database.jooq.Tables.RPKIT_CHAT_GROUP_INVITE import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileId import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.logging.Level.SEVERE /** * Represents chat group invite table. */ class RPKChatGroupInviteTable(private val database: Database, private val plugin: RPKChatBukkit) : Table { fun insert(entity: RPKChatGroupInvite): CompletableFuture<Void> { val chatGroupId = entity.chatGroup.id ?: return CompletableFuture.completedFuture(null) val minecraftProfileId = entity.minecraftProfile.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .insertInto( RPKIT_CHAT_GROUP_INVITE, RPKIT_CHAT_GROUP_INVITE.CHAT_GROUP_ID, RPKIT_CHAT_GROUP_INVITE.MINECRAFT_PROFILE_ID ) .values( chatGroupId.value, minecraftProfileId.value ) .execute() } } /** * Gets a list of invites for a particular chat group. * * @param chatGroup The chat group * @return A list of chat group invites */ fun get(chatGroup: RPKChatGroup): CompletableFuture<List<RPKChatGroupInvite>> { val chatGroupId = chatGroup.id ?: return CompletableFuture.completedFuture(emptyList()) return CompletableFuture.supplyAsync { return@supplyAsync database.create .select(RPKIT_CHAT_GROUP_INVITE.MINECRAFT_PROFILE_ID) .from(RPKIT_CHAT_GROUP_INVITE) .where(RPKIT_CHAT_GROUP_INVITE.CHAT_GROUP_ID.eq(chatGroupId.value)) .fetch() .mapNotNull { result -> val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return@mapNotNull null val minecraftProfile = minecraftProfileService .getMinecraftProfile(RPKMinecraftProfileId(result[RPKIT_CHAT_GROUP_INVITE.MINECRAFT_PROFILE_ID])) .join() ?: return@mapNotNull null return@mapNotNull RPKChatGroupInvite( chatGroup, minecraftProfile ) } }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to get chat group invites", exception) throw exception } } /** * Gets a list of chat group invites for a particular Minecraft profile. * * @param minecraftProfile The Minecraft profile * @return A list of chat group invites for the Minecraft profile */ fun get(minecraftProfile: RPKMinecraftProfile): CompletableFuture<List<RPKChatGroupInvite>> { val minecraftProfileId = minecraftProfile.id ?: return CompletableFuture.completedFuture(emptyList()) return CompletableFuture.supplyAsync { return@supplyAsync database.create .select(RPKIT_CHAT_GROUP_INVITE.CHAT_GROUP_ID) .from(RPKIT_CHAT_GROUP_INVITE) .where(RPKIT_CHAT_GROUP_INVITE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value)) .fetch() .mapNotNull { result -> val chatGroupService = Services[RPKChatGroupService::class.java] ?: return@mapNotNull null val chatGroup = chatGroupService .getChatGroup(RPKChatGroupId(result[RPKIT_CHAT_GROUP_INVITE.CHAT_GROUP_ID])).join() ?: return@mapNotNull null return@mapNotNull RPKChatGroupInvite( chatGroup, minecraftProfile ) } } } fun delete(entity: RPKChatGroupInvite): CompletableFuture<Void> { val chatGroupId = entity.chatGroup.id ?: return CompletableFuture.completedFuture(null) val minecraftProfileId = entity.minecraftProfile.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .deleteFrom(RPKIT_CHAT_GROUP_INVITE) .where(RPKIT_CHAT_GROUP_INVITE.CHAT_GROUP_ID.eq(chatGroupId.value)) .and(RPKIT_CHAT_GROUP_INVITE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value)) .execute() } } fun delete(minecraftProfileId: RPKMinecraftProfileId): CompletableFuture<Void> = runAsync { database.create .deleteFrom(RPKIT_CHAT_GROUP_INVITE) .where(RPKIT_CHAT_GROUP_INVITE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value)) .execute() }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete chat group invites for Minecraft profile id", exception) throw exception } }
apache-2.0
7d4c26a144a7a992e6d332dd28de89e6
43.442857
121
0.652146
5.057724
false
false
false
false
rori-dev/lunchbox
backend-spring-kotlin/src/main/kotlin/lunchbox/util/pdf/PdfExtractor.kt
1
1104
package lunchbox.util.pdf import mu.KotlinLogging import org.apache.pdfbox.pdmodel.PDDocument import java.io.FileNotFoundException import java.net.URL /** * Extrahiert Daten aus PDF-Dateien. */ object PdfExtractor { private val logger = KotlinLogging.logger {} fun extractLines(pdfUrl: URL): List<TextLine> = extract(pdfUrl) { PdfTextGroupStripper().getTextLines(it) } fun extractStrings(pdfUrl: URL): List<String> = extractLines(pdfUrl).map { it.toString() } fun extractGroups(pdfUrl: URL): List<TextGroup> = extract(pdfUrl) { PdfTextGroupStripper().getTextGroups(it) } private fun <T> extract(pdfUrl: URL, transform: (pdfDoc: PDDocument) -> List<T>): List<T> { var pdfDoc: PDDocument? = null try { pdfDoc = PDDocument.load(pdfUrl.openStream()) if (pdfDoc != null) return transform(pdfDoc) } catch (fnf: FileNotFoundException) { logger.error { "file $pdfUrl not found" } } catch (t: Throwable) { logger.error(t) { "Fehler beim Einlesen von $pdfUrl" } } finally { pdfDoc?.close() } return emptyList() } }
mit
eec3562215ef1b537233211bc17602fa
27.307692
93
0.678442
3.460815
false
false
false
false
hotpodata/Twistris
app/src/main/java/com/hotpodata/twistris/adapter/TwistrisSideBarAdapter.kt
1
3948
package com.hotpodata.twistris.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.hotpodata.common.adapter.SideBarAdapter import com.hotpodata.common.data.App import com.hotpodata.common.enums.HotPoDataApps import com.hotpodata.common.enums.Libraries import com.hotpodata.common.interfaces.IAnalyticsProvider import com.hotpodata.twistris.R import com.hotpodata.twistris.adapter.viewholder.SignInViewHolder import com.hotpodata.twistris.interfaces.IGameController import com.hotpodata.twistris.interfaces.IGooglePlayGameServicesProvider import java.util.* /** * Created by jdrotos on 11/7/15. */ class TwistrisSideBarAdapter(ctx: Context, val gameController: IGameController, val playGameServicesProvider: IGooglePlayGameServicesProvider, val analytics: IAnalyticsProvider?) : SideBarAdapter(ctx, analytics, App.Factory.createApp(ctx, HotPoDataApps.TWISTRIS), false, false, Libraries.AutoFitTextView, Libraries.Picasso, Libraries.RxAndroid, Libraries.RxJava, Libraries.RxKotlin, Libraries.Timber) { private val ROW_TYPE_SIGN_IN = 100 init{ rebuildRowSet() } override fun genCustomRows(): List<Any> { var sideBarRows = ArrayList<Any>() var helpRow = RowSettings(ctx.resources.getString(R.string.how_to_play), "", View.OnClickListener { gameController.showHelp() }, R.drawable.ic_info_outline_24dp) sideBarRows.add(ctx.resources.getString(R.string.game)) if (playGameServicesProvider.isLoggedIn()) { sideBarRows.add(RowSettings(ctx.resources.getString(R.string.high_scores), "", View.OnClickListener { playGameServicesProvider.showLeaderBoard() }, R.drawable.ic_trophy_black_48dp)) sideBarRows.add(RowDiv(true)) sideBarRows.add(RowSettings(ctx.resources.getString(R.string.achievements), "", View.OnClickListener { playGameServicesProvider.showAchievements() }, R.drawable.ic_grade_24dp)) sideBarRows.add(RowDiv(true)) sideBarRows.add(helpRow) sideBarRows.add(RowDiv(true)) sideBarRows.add(RowSettings(ctx.resources.getString(R.string.sign_out), "", View.OnClickListener { playGameServicesProvider.logout() }, R.drawable.ic_highlight_remove_24dp)) } else { sideBarRows.add(RowSignIn(View.OnClickListener { playGameServicesProvider.login() })) sideBarRows.add(RowDiv(false)) sideBarRows.add(helpRow) } return sideBarRows } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? { return when (viewType) { ROW_TYPE_SIGN_IN -> { val inflater = LayoutInflater.from(parent.context) val v = inflater.inflate(R.layout.row_signin, parent, false) SignInViewHolder(v) } else -> super.onCreateViewHolder(parent, viewType) } } @Suppress("DEPRECATION") override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val type = getItemViewType(position) val objData = mRows[position] when (type) { ROW_TYPE_SIGN_IN -> { val vh = holder as SignInViewHolder val data = objData as RowSignIn vh.signInBtn.setOnClickListener(data.onClickListener) } else -> super.onBindViewHolder(holder, position) } } override fun getItemViewType(position: Int): Int { val data = mRows[position] return when (data) { is RowSignIn -> ROW_TYPE_SIGN_IN else -> super.getItemViewType(position) } } class RowSignIn(val onClickListener: View.OnClickListener) }
apache-2.0
74694c8cb336b79e03c2bfd9eb1ae9da
41.462366
402
0.676798
4.272727
false
false
false
false
Tomlezen/RxCommons
lib/src/main/java/com/tlz/rxcommons/permission/RxPermissions.kt
1
5195
package com.tlz.rxcommons.permission import android.annotation.TargetApi import android.app.Activity import android.content.pm.PackageManager import android.os.Build import android.support.v4.app.ActivityCompat import android.support.v4.app.FragmentActivity import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import java.lang.ref.WeakReference import java.util.* /** * Created by LeiShao. * Data 2017/5/24. * Time 10:57. * Email [email protected]. */ class RxPermissions private constructor(activity: FragmentActivity) { private val activityRef = WeakReference<FragmentActivity>(activity) private val subjectMap = HashMap<String, PublishSubject<Permission>>() private var permissionFragment: PermissionFragment? = null fun request(permissions: Array<String>): Observable<Boolean> { return Observable.just(Any()).compose { upstream -> request(upstream, *permissions) } } private fun request(observable: Observable<Any>, vararg permissions: String): Observable<Boolean> { return doRequest(observable, *permissions) .buffer(permissions.size) .flatMap { if (it.isEmpty()) { return@flatMap Observable.empty<Boolean>() } Observable.just(!it.any { !it.granted }) } } fun requestEach(vararg permissions: String): Observable<Permission> { return Observable.just(true).compose { upstream -> doRequest(upstream, *permissions) } } private fun doRequest(observable: Observable<*>, vararg permissions: String): Observable<Permission> { if (permissions.isEmpty()) { throw IllegalArgumentException("Requires at least one input permission") } return observable.flatMap { doRequest(*permissions) } } private fun doRequest(vararg permissions: String): Observable<Permission> { val list = ArrayList<Observable<Permission>>(permissions.size) val unrequestedPermissions = ArrayList<String>() Observable.fromArray(*permissions) .filter{ s -> if (isGranted(s)) { list.add(Observable.just(Permission(s, true))) return@filter false } if (isRevoked(s)) { list.add(Observable.just(Permission(s, false))) return@filter false } true } .subscribe({ s -> var subject: PublishSubject<Permission>? = subjectMap[s] if (subject == null) { unrequestedPermissions.add(s) subject = PublishSubject.create<Permission>() subjectMap[s] = subject } list.add(subject!!) }) if (!unrequestedPermissions.isEmpty()) { if (permissionFragment == null) { permissionFragment = PermissionFragment() } permissionFragment?.let { if (it.isAdded && it.activity != activityRef.get()) { it.removeSelf() addFragment(it) } else if (!it.isAdded) { addFragment(it) } it.requestPermissions(this, unrequestedPermissions.toTypedArray()) } } return Observable.concat(Observable.fromIterable(list)) } private fun addFragment(permissionFragment: PermissionFragment) { activityRef.get()?.supportFragmentManager?.beginTransaction()?.add(permissionFragment, PermissionFragment.TAG)?.commitNowAllowingStateLoss() } internal fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { permissions.forEachIndexed { index, s -> val subject = subjectMap[s] ?: throw IllegalStateException("didn't find the corresponding permission request.") subjectMap.remove(s) val granted = grantResults[index] == PackageManager.PERMISSION_GRANTED subject.onNext(Permission(s, granted)) subject.onComplete() } } fun shouldShowRequestPermissionRationale(activity: Activity, vararg permissions: String): Observable<Boolean> { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return Observable.just(false) } return Observable.just(shouldShowRequestPermissionRationaleM(activity, *permissions)) } @TargetApi(Build.VERSION_CODES.M) private fun shouldShowRequestPermissionRationaleM(activity: Activity, vararg permissions: String): Boolean { return permissions.none { !isGranted(it) && !activity.shouldShowRequestPermissionRationale(it) } } fun isGranted(permission: String): Boolean { return activityRef.get()?.let { return ActivityCompat.checkSelfPermission(it, permission) == PackageManager.PERMISSION_GRANTED } ?: false } fun isRevoked(permission: String): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return isM() && isRevokedM(permission) } return false } private fun isM(): Boolean { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M } @TargetApi(Build.VERSION_CODES.M) private fun isRevokedM(permission: String): Boolean { return activityRef.get()?.let { return it.packageManager.isPermissionRevokedByPolicy(permission, it.packageName) } ?: false } companion object { @JvmStatic fun with(activity: FragmentActivity) = RxPermissions(activity) } }
apache-2.0
deb0672184663d809dea4464fc1d8594
32.74026
144
0.690857
4.585172
false
false
false
false
cypressious/learning-spaces
app/src/main/java/de/maxvogler/learningspaces/fragments/LocationListFragment.kt
1
2426
package de.maxvogler.learningspaces.fragments import android.os.Bundle import android.support.v4.app.ListFragment import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import com.squareup.otto.Subscribe import de.maxvogler.learningspaces.R import de.maxvogler.learningspaces.activities.MainActivity import de.maxvogler.learningspaces.adapters.LocationListAdapter import de.maxvogler.learningspaces.events.LocationFocusChangeEvent import de.maxvogler.learningspaces.events.UpdateLocationsEvent import de.maxvogler.learningspaces.services.BusProvider import org.jetbrains.anko.find /** * A Fragment, displaying all [Location]s in a ListView. */ public class LocationListFragment : ListFragment() { private var adapter: LocationListAdapter get() = listAdapter as LocationListAdapter set(adapter: LocationListAdapter) { listAdapter = adapter } private val bus = BusProvider.instance private val mainActivity: MainActivity get() = activity as MainActivity override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val layout = inflater.inflate(R.layout.fragment_list, container, false) val menu = layout.find<Toolbar>(R.id.toolbar) menu.title = activity.title menu.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp) menu.setNavigationOnClickListener { mainActivity.animateListFragmentVisibility(false) } if(mainActivity.isTranslucentStatusBar()) { (menu.layoutParams as ViewGroup.MarginLayoutParams).topMargin = mainActivity.calculateStatusBarHeight() } return layout } override fun onResume() { super.onResume() bus.register(this) } override fun onPause() { bus.unregister(this) super.onPause() } override fun onListItemClick(l: ListView?, v: View?, position: Int, id: Long) { bus.post(LocationFocusChangeEvent(adapter.getItem(position), animateMap = true)) } @Subscribe public fun onUpdateLocations(event: UpdateLocationsEvent) { adapter = LocationListAdapter(activity, event.locations.map { it.getValue() }) } companion object { public fun newInstance(): LocationListFragment = LocationListFragment() } }
gpl-2.0
afa6595fe665a6252b80d7b6304bc0fc
32.246575
116
0.735367
4.794466
false
false
false
false
JackParisi/DroidBox
droidbox/src/main/java/com/github/giacomoparisi/droidbox/network/DroidRxDataProvider.kt
1
5552
package com.github.giacomoparisi.droidbox.network import androidx.annotation.MainThread import androidx.annotation.WorkerThread import com.github.giacomoparisi.droidbox.architecture.model.exception.EmptyRepositoryException import io.reactivex.* import io.reactivex.schedulers.Schedulers import timber.log.Timber /** * Created by Giacomo Parisi on 09/07/2017. * https://github.com/giacomoParisi */ /** * * Data provider based on RX * Load data from database and perform network requests with RX Flowable * The repository follow this FLOW*: * should load from db? * YES ==> load from db ==> should fetch from network? * YES ==> should load from db before fetch? * YES ==> emit database data ==> fetch form network ==> save data to db ==> emit fetched data * NO ==> fetch form network ==> save data to db ==> emit fetched data * NO ==> emit database data * NO ==> should fetch from network? * YES ==> fetch from network ==> save data to db ==> emit fetch data * NO ==> exit */ abstract class DroidRxDataProvider<ResultType> : DroidDataProvider<Flowable<DroidResource<ResultType>>>() { // Repository flowable (subscribe to it to start the repository) override final var repository: Flowable<DroidResource<ResultType>> = Flowable.create({ emitter: FlowableEmitter<DroidResource<ResultType>> -> startRepository(emitter) }, BackpressureStrategy.BUFFER) /** * * Start to load/fetch the data based on the repository FLOW* * * @param emitter The emitter of the flowable that execute this function */ private fun startRepository(emitter: FlowableEmitter<DroidResource<ResultType>>) { val dbSource = loadFromDb(databaseData) when { dbSource != null -> dbSource.subscribeOn(Schedulers.io()) .subscribe({ if (shouldFetch(it)) { fetchFromNetwork(it, emitter) } else { emitter.onNext(DroidResource.DatabaseResource(it)) } }, { Timber.e(it.message) emitter.onError(it) }) shouldFetch(null) -> fetchFromNetwork(null, emitter) else -> emitter.onError(EmptyRepositoryException()) } } /** * * Emit the database data if exist and if shouldLoadFromDbBeforeFetch, * then fetch from network and try save the data to db * * @param dbSource Database data (load previously) * @param emitter The emitter of the flowable that execute this function */ private fun fetchFromNetwork(dbSource: ResultType?, emitter: FlowableEmitter<DroidResource<ResultType>>) { val apiResponse = fetchFromNetwork(networkData) if (dbSource != null && shouldLoadFromDbBeforeFetch()) { emitter.onNext(DroidResource.DatabaseResource(dbSource)) } apiResponse?.subscribeOn(Schedulers.io()) ?.subscribe({ if (it != null) { saveResult(it, emitter) } }, { emitter.onError(it) }) } /** * * Try to save the data to database and after emit them * * @param apiResponse The new data to save (fetched from network) * @param emitter The emitter of the flowable that execute this function */ private fun saveResult(apiResponse: ResultType, emitter: FlowableEmitter<DroidResource<ResultType>>) { val save = Single.create(SingleOnSubscribe<ResultType> { saveCallResult(apiResponse) it.onSuccess(apiResponse) }) save.subscribeOn(Schedulers.io()) .subscribe( { emitter.onNext(DroidResource.NetworkResource(apiResponse)) }, { Timber.e(it.message) emitter.onError(it) } ) } /** * * Called to save the new fetched data to db * * @param data The new data to save (fetched from network) */ @WorkerThread protected abstract fun saveCallResult(data: ResultType?) /** * * Called to know if the repository should fetch the data from the network * * @param data The data loaded from the database (null if not exist) */ @MainThread protected abstract fun shouldFetch(data: ResultType?): Boolean /** * * Called to know if the repository should emit the data loaded from db * before fetch the new data */ @MainThread protected abstract fun shouldLoadFromDbBeforeFetch(): Boolean /** * * Called to create the call to get the cached data from the database * * @param data The map of data needed for the database load request */ @MainThread protected abstract fun loadFromDb(data: Map<String, String>?): Flowable<ResultType>? /** * * Called to create the API call to fetch the new data from network * * @param data The map of data needed for the API request */ @MainThread protected abstract fun fetchFromNetwork(data: Map<String, String>?): Single<ResultType>? // Called when the fetch fails. The child class may want to reset components // like rate limiter. @MainThread protected fun onFetchFailed() { } }
apache-2.0
c76a579928368b98c4dd3ec50e47df50
33.484472
110
0.605908
4.992806
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/quip/QuipAuthInterceptor.kt
1
2630
package com.baulsupp.okurl.services.quip import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.oksocial.output.readPasswordString import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.completion.ApiCompleter import com.baulsupp.okurl.completion.BaseUrlCompleter import com.baulsupp.okurl.completion.CompletionVariableCache import com.baulsupp.okurl.completion.UrlList import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.query import com.baulsupp.okurl.services.quip.model.User import okhttp3.OkHttpClient import okhttp3.Response class QuipAuthInterceptor : Oauth2AuthInterceptor() { override val serviceDefinition = Oauth2ServiceDefinition( "platform.quip.com", "Quip API", "quip", "https://quip.com/dev/automation/documentation", "https://quip.com/dev/token" ) override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { outputHandler.openLink("https://quip.com/dev/token") val token = System.console().readPasswordString("Enter Token: ") return Oauth2Token(token) } override suspend fun apiCompleter( prefix: String, client: OkHttpClient, credentialsStore: CredentialsStore, completionVariableCache: CompletionVariableCache, tokenSet: Token ): ApiCompleter { val urlList = UrlList.fromResource(name()) val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache) completer.withCachedVariable(name(), "folderId") { credentialsStore.get(serviceDefinition, tokenSet)?.let { currentUser(client, tokenSet).let { user -> listOfNotNull( user.starred_folder_id, user.private_folder_id, user.desktop_folder_id, user.archive_folder_id ) + user.shared_folder_ids.orEmpty() } } } return completer } override suspend fun validate( client: OkHttpClient, credentials: Oauth2Token ): ValidatedCredentials = ValidatedCredentials( currentUser( client, TokenValue(credentials) ).name ) private suspend fun currentUser(client: OkHttpClient, tokenSet: Token) = client.query<User>("https://platform.quip.com/1/users/current", tokenSet) }
apache-2.0
1116b7678318a950bcaf5712cff13fa0
32.291139
97
0.754373
4.427609
false
false
false
false
spark/photon-tinker-android
meshui/src/main/java/io/particle/mesh/ui/controlpanel/BaseControlPanelFragment.kt
1
2023
package io.particle.mesh.ui.controlpanel import androidx.annotation.MainThread import androidx.annotation.WorkerThread import io.particle.android.sdk.cloud.ParticleCloudSDK import io.particle.android.sdk.cloud.ParticleDevice import io.particle.mesh.setup.BarcodeData.CompleteBarcodeData import io.particle.mesh.setup.SerialNumber import io.particle.mesh.setup.fetchBarcodeData import io.particle.mesh.setup.utils.safeToast import io.particle.mesh.ui.BaseFlowFragment import io.particle.mesh.ui.TitleBarOptions import mu.KotlinLogging interface DeviceProvider { val device: ParticleDevice } open class BaseControlPanelFragment : BaseFlowFragment() { private val log = KotlinLogging.logger {} override val titleBarOptions = TitleBarOptions( showBackButton = true ) val device: ParticleDevice by lazy { (activity!! as DeviceProvider).device } @MainThread suspend fun startFlowWithBarcode( flowStarter: (device: ParticleDevice, barcode: CompleteBarcodeData) -> Unit ) { val cloud = ParticleCloudSDK.getCloud() flowSystemInterface.showGlobalProgressSpinner(true) val barcode = try { flowScopes.withWorker { cloud.fetchBarcodeData(device.id) } } catch (ex: Exception) { null } flowSystemInterface.showGlobalProgressSpinner(false) if (barcode == null) { activity?.safeToast("Unable to communicate with the Particle Cloud. Please try again.") return } flowStarter(device, barcode) } @WorkerThread private fun fetchBarcodeData(deviceId: String): CompleteBarcodeData { val cloud = ParticleCloudSDK.getCloud() val device = cloud.getDevice(deviceId) val barcode = CompleteBarcodeData( serialNumber = SerialNumber(device.serialNumber!!), mobileSecret = device.mobileSecret!! ) log.info { "Built barcode: $barcode" } return barcode } }
apache-2.0
b17f694f76a032c867fe4b2f0f125f81
28.318841
100
0.69649
4.76
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl-tooling-builders/src/test/kotlin/org/gradle/kotlin/dsl/tooling/builders/EditorReportsBuilderTest.kt
1
4276
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.tooling.builders import org.gradle.kotlin.dsl.tooling.models.EditorReportSeverity import org.gradle.kotlin.dsl.resolver.EditorMessages import org.gradle.internal.exceptions.LocationAwareException import org.gradle.kotlin.dsl.fixtures.TestWithTempFiles import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.nullValue import org.junit.Assert.assertThat import org.junit.Test class EditorReportsBuilderTest : TestWithTempFiles() { @Test fun `report file warning on runtime failure in currently edited script on out of range line number`() { val script = withTwoLinesScript() val reports = buildEditorReportsFor( script, listOf(LocationAwareException(Exception("BOOM"), script.canonicalPath, 3)), true ) assertThat(reports.size, equalTo(1)) reports.single().let { report -> assertThat(report.severity, equalTo(EditorReportSeverity.WARNING)) assertThat(report.position, nullValue()) assertThat(report.message, equalTo(EditorMessages.buildConfigurationFailedInCurrentScript)) } } @Test fun `report line warning on runtime failure in currently edited script last line without new line before eof`() { val script = file("some.gradle.kts").also { it.writeText("\n\nno-new-line") } val reports = buildEditorReportsFor( script, listOf(LocationAwareException(Exception("BOOM"), script.canonicalPath, 3)), true ) assertThat(reports.size, equalTo(1)) reports.single().let { report -> assertThat(report.severity, equalTo(EditorReportSeverity.WARNING)) assertThat(report.position, notNullValue()) assertThat(report.position!!.line, equalTo(3)) assertThat(report.message, equalTo("BOOM")) } } @Test fun `report line warning on runtime failure in currently edited script with cause without message`() { val script = withTwoLinesScript() val reports = buildEditorReportsFor( script, listOf( LocationAwareException(java.lang.Exception(null as String?), script.canonicalPath, 1), LocationAwareException(java.lang.Exception(""), script.canonicalPath, 2) ), true ) assertThat(reports.size, equalTo(2)) reports.forEachIndexed { idx, report -> assertThat(report.severity, equalTo(EditorReportSeverity.WARNING)) assertThat(report.position, notNullValue()) assertThat(report.position!!.line, equalTo(idx + 1)) assertThat(report.message, equalTo(EditorMessages.defaultLocationAwareHintMessageFor(java.lang.Exception()))) } } @Test fun `valid line number range for file`() { val file = file("script.gradle.kts") file.writeText("") assertThat(file.readLinesRange(), equalTo(0..0L)) file.writeText("some") assertThat(file.readLinesRange(), equalTo(1..1L)) file.writeText("some\n") assertThat(file.readLinesRange(), equalTo(1..1L)) file.writeText("some\nmore") assertThat(file.readLinesRange(), equalTo(1..2L)) file.writeText("some\nmore\n") assertThat(file.readLinesRange(), equalTo(1..2L)) file.writeText("some\nmore\nthings") assertThat(file.readLinesRange(), equalTo(1..3L)) } private fun withTwoLinesScript() = file("two.gradle.kts").also { it.writeText("\n\n") } }
apache-2.0
289a0d0e4ed653f3520b562e984b824b
33.208
121
0.669083
4.49632
false
true
false
false
anton-okolelov/intellij-rust
debugger/src/main/kotlin/org/rust/debugger/runconfig/RsDebugProcess.kt
1
1841
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.debugger.runconfig import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.filters.TextConsoleBuilder import com.intellij.openapi.project.Project import com.intellij.xdebugger.XDebugSession import com.jetbrains.cidr.cpp.execution.debugger.backend.GDBDriverConfiguration import com.jetbrains.cidr.cpp.toolchains.CPPToolchains import com.jetbrains.cidr.execution.Installer import com.jetbrains.cidr.execution.RunParameters import com.jetbrains.cidr.execution.TrivialInstaller import com.jetbrains.cidr.execution.debugger.CidrLocalDebugProcess import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.LLDBDriverConfiguration import com.jetbrains.cidr.execution.debugger.breakpoints.CidrBreakpointHandler import org.rust.debugger.RsLineBreakpointType class RsDebugProcess(parameters: RunParameters, session: XDebugSession, consoleBuilder: TextConsoleBuilder) : CidrLocalDebugProcess(parameters, session, consoleBuilder) { override fun createBreakpointHandler(): CidrBreakpointHandler = CidrBreakpointHandler(this, RsLineBreakpointType::class.java) } class RsDebugRunParameters( val project: Project, val cmd: GeneralCommandLine ) : RunParameters() { override fun getDebuggerDriverConfiguration(): DebuggerDriverConfiguration { val toolchain = CPPToolchains.getInstance().defaultToolchain if (toolchain == null || toolchain.isUseLLDB) return LLDBDriverConfiguration() return GDBDriverConfiguration(project, toolchain) } override fun getInstaller(): Installer = TrivialInstaller(cmd) override fun getArchitectureId(): String? = null }
mit
a9aa0528bc58c48dba4bb79995d05f4d
39.911111
107
0.816947
4.591022
false
true
false
false
ze-pequeno/okhttp
okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt
3
2597
/* * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.InetAddress import java.net.UnknownHostException import okio.Buffer import org.assertj.core.api.Assertions.assertThat class FakeDns : Dns { private val hostAddresses: MutableMap<String, List<InetAddress>> = mutableMapOf() private val requestedHosts: MutableList<String> = mutableListOf() private var nextAddress = 0xff000064L // 255.0.0.100 in IPv4; ::ff00:64 in IPv6. /** Sets the results for `hostname`. */ operator fun set( hostname: String, addresses: List<InetAddress> ): FakeDns { hostAddresses[hostname] = addresses return this } /** Clears the results for `hostname`. */ fun clear(hostname: String): FakeDns { hostAddresses.remove(hostname) return this } @Throws(UnknownHostException::class) fun lookup( hostname: String, index: Int ): InetAddress { return hostAddresses[hostname]!![index] } @Throws(UnknownHostException::class) override fun lookup(hostname: String): List<InetAddress> { requestedHosts.add(hostname) return hostAddresses[hostname] ?: throw UnknownHostException() } fun assertRequests(vararg expectedHosts: String?) { assertThat(requestedHosts).containsExactly(*expectedHosts) requestedHosts.clear() } /** Allocates and returns `count` fake IPv4 addresses like [255.0.0.100, 255.0.0.101]. */ fun allocate(count: Int): List<InetAddress> { val from = nextAddress nextAddress += count return (from until nextAddress) .map { return@map InetAddress.getByAddress( Buffer().writeInt(it.toInt()).readByteArray() ) } } /** Allocates and returns `count` fake IPv6 addresses like [::ff00:64, ::ff00:65]. */ fun allocateIpv6(count: Int): List<InetAddress> { val from = nextAddress nextAddress += count return (from until nextAddress) .map { return@map InetAddress.getByAddress( Buffer().writeLong(0L).writeLong(it).readByteArray() ) } } }
apache-2.0
7a834c888422d24528917d972d6763a2
29.916667
92
0.695418
4.102686
false
false
false
false
square/leakcanary
shark-graph/src/main/java/shark/HeapObject.kt
2
21884
package shark import shark.HprofRecord.HeapDumpRecord.ObjectRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord.FieldRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.InstanceDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ObjectArrayDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ByteArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.CharArrayDump import shark.ValueHolder.ReferenceHolder import shark.internal.IndexedObject.IndexedClass import shark.internal.IndexedObject.IndexedInstance import shark.internal.IndexedObject.IndexedObjectArray import shark.internal.IndexedObject.IndexedPrimitiveArray import java.nio.charset.Charset import java.util.Locale import kotlin.LazyThreadSafetyMode.NONE import kotlin.reflect.KClass import shark.PrimitiveType.INT /** * An object in the heap dump. */ sealed class HeapObject { /** * The graph of objects in the heap, which you can use to navigate the heap. */ abstract val graph: HeapGraph /** * The heap identifier of this object. */ abstract val objectId: Long /** * [objectId] masked to be a positive unique identifier, as reported in Android Studio. */ val positiveObjectId: Long get() = objectId and (-0x1L ushr (8 - graph.identifierByteSize) * 8) /** * An positive object index that's specific to how Shark stores objects in memory. * The index starts at 0 and ends at [HeapGraph.objectCount] - 1. There are no gaps, every index * value corresponds to an object. Classes are first, then instances, then object arrays then * primitive arrays. */ abstract val objectIndex: Int /** * Reads and returns the underlying [ObjectRecord]. * * This may trigger IO reads. */ abstract fun readRecord(): ObjectRecord /** * The total byte size for the record of this object in the heap dump. */ abstract val recordSize: Int /** * This [HeapObject] as a [HeapClass] if it is one, or null otherwise */ val asClass: HeapClass? get() = if (this is HeapClass) this else null /** * This [HeapObject] as a [HeapInstance] if it is one, or null otherwise */ val asInstance: HeapInstance? get() = if (this is HeapInstance) this else null /** * This [HeapObject] as a [HeapObjectArray] if it is one, or null otherwise */ val asObjectArray: HeapObjectArray? get() = if (this is HeapObjectArray) this else null /** * This [HeapObject] as a [HeapPrimitiveArray] if it is one, or null otherwise */ val asPrimitiveArray: HeapPrimitiveArray? get() = if (this is HeapPrimitiveArray) this else null /** * A class in the heap dump. */ class HeapClass internal constructor( private val hprofGraph: HprofHeapGraph, private val indexedObject: IndexedClass, override val objectId: Long, override val objectIndex: Int ) : HeapObject() { override val graph: HeapGraph get() = hprofGraph /** * Whether this is class is a primitive wrapper type */ val isPrimitiveWrapperClass: Boolean get() = (name in primitiveWrapperClassNames) /** * The name of this class, identical to [Class.getName]. * If this class is an array class, the name has a suffix of brackets for each dimension of * the array, e.g. `com.Foo[][]` is a class for 2 dimensional arrays of `com.Foo`. * * The behavior for primitive types changes depending on the VM that dumped the heap. JVM * heap dumps don't have any [HeapClass] object for primitive types, instead the * `java.land.Class` class has 9 instances (the 8 primitive types and `void`). Android heap * dumps have an [HeapClass] object for primitive type and the `java.land.Class` class has no * instance. * * If this is an array class, you can find the component type by removing the brackets at the * end, e.g. `name.substringBefore('[')`. Be careful when doing this for JVM heap dumps though, * as if the component type is a primitive type there will not be a [HeapClass] object for it. * This is especially tricky with N dimension primitive type arrays, which are instances of * [HeapObjectArray] (vs single dimension primitive type arrays which are instances of * [HeapPrimitiveArray]). */ val name: String get() = hprofGraph.className(objectId) /** * Returns [name] stripped of any string content before the last period (included). */ val simpleName: String get() = classSimpleName(name) /** * The total byte size of fields for instances of this class, as registered in the class dump. * This includes the size of fields from superclasses. * * @see readFieldsByteSize */ val instanceByteSize: Int get() = indexedObject.instanceSize override val recordSize: Int get() = indexedObject.recordSize.toInt() val hasReferenceInstanceFields: Boolean get() = hprofGraph.classDumpHasReferenceFields(indexedObject) /** * Returns true if this class is an array class, and false otherwise. */ val isArrayClass: Boolean get() = name.endsWith("[]") val isPrimitiveArrayClass: Boolean get() = name in primitiveTypesByPrimitiveArrayClassName val isObjectArrayClass: Boolean get() = isArrayClass && !isPrimitiveArrayClass /** * The total byte size of fields for instances of this class, computed as the sum of the * individual size of each field of this class. This does not include the size of fields from * superclasses. * * This may trigger IO reads. * * @see instanceByteSize */ fun readFieldsByteSize(): Int { return readRecordFields().sumBy { if (it.type == PrimitiveType.REFERENCE_HPROF_TYPE) { hprofGraph.identifierByteSize } else PrimitiveType.byteSizeByHprofType.getValue(it.type) } } /** * The [HeapClass] representing the superclass of this [HeapClass]. If this [HeapClass] * represents either the [Object] class or a primitive type, then * null is returned. If this [HeapClass] represents an array class then the * [HeapClass] object representing the [Object] class is returned. */ val superclass: HeapClass? get() { if (indexedObject.superclassId == ValueHolder.NULL_REFERENCE) return null return hprofGraph.findObjectById(indexedObject.superclassId) as HeapClass } /** * The class hierarchy starting at this class (included) and ending at the [Object] class * (included). */ val classHierarchy: Sequence<HeapClass> get() = generateSequence(this) { it.superclass } /** * All the subclasses (direct and indirect) of this class, * in the order they were recorded in the heap dump. */ val subclasses: Sequence<HeapClass> get() = hprofGraph.classes.filter { it subclassOf this } /** * Returns true if [subclass] is a sub class of this [HeapClass]. */ infix fun superclassOf(subclass: HeapClass): Boolean { return subclass.classHierarchy.any { it.objectId == objectId } } /** * Returns true if [superclass] is a superclass of this [HeapClass]. */ infix fun subclassOf(superclass: HeapClass): Boolean { return superclass.objectId != objectId && classHierarchy.any { it.objectId == superclass.objectId } } /** * All instances of this class, including instances of subclasses of this class. */ val instances: Sequence<HeapInstance> get() = if (!isArrayClass) { hprofGraph.instances.filter { it instanceOf this } } else { emptySequence() } val objectArrayInstances: Sequence<HeapObjectArray> get() = if (isObjectArrayClass) { hprofGraph.objectArrays.filter { it.indexedObject.arrayClassId == objectId } } else { emptySequence() } /** * Primitive arrays are one dimensional arrays of a primitive type. * N-dimension arrays of primitive types (e.g. int[][]) are object arrays pointing to primitive * arrays. */ val primitiveArrayInstances: Sequence<HeapPrimitiveArray> get() { val primitiveType = primitiveTypesByPrimitiveArrayClassName[name] return if (primitiveType != null) { hprofGraph.primitiveArrays.filter { it.primitiveType == primitiveType } } else { emptySequence() } } /** * All direct instances of this class, ie excluding any instance of subclasses of this class. */ val directInstances: Sequence<HeapInstance> get() = hprofGraph.instances.filter { it.indexedObject.classId == objectId } /** * Reads and returns the underlying [ClassDumpRecord]. * * This may trigger IO reads. */ override fun readRecord(): ClassDumpRecord { return hprofGraph.readClassDumpRecord(objectId, indexedObject) } fun readRecordStaticFields() = hprofGraph.classDumpStaticFields(indexedObject) fun readRecordFields() = hprofGraph.classDumpFields(indexedObject) /** * Returns the name of the field declared in this class for the specified [fieldRecord]. */ fun instanceFieldName(fieldRecord: FieldRecord): String { return hprofGraph.fieldName(objectId, fieldRecord) } /** * The static fields of this class, as a sequence of [HeapField]. * * This may trigger IO reads. */ fun readStaticFields(): Sequence<HeapField> { return readRecordStaticFields().asSequence() .map { fieldRecord -> HeapField( this, hprofGraph.staticFieldName(objectId, fieldRecord), HeapValue(hprofGraph, fieldRecord.value) ) } } /** * Returns a [HeapField] object that reflects the specified declared * field of the class represented by this [HeapClass] object, or null if this field does not * exist. The [name] parameter specifies the simple name of the desired field. * * Also available as a convenience operator: [get] * * This may trigger IO reads. */ fun readStaticField(fieldName: String): HeapField? { for (fieldRecord in readRecordStaticFields()) { val recordFieldName = hprofGraph.staticFieldName(objectId, fieldRecord) if (recordFieldName == fieldName) { return HeapField(this, fieldName, HeapValue(hprofGraph, fieldRecord.value)) } } return null } /** * @see readStaticField */ operator fun get(fieldName: String) = readStaticField(fieldName) override fun toString(): String { return "class $name" } } /** * An instance in the heap dump. */ class HeapInstance internal constructor( private val hprofGraph: HprofHeapGraph, internal val indexedObject: IndexedInstance, override val objectId: Long, override val objectIndex: Int ) : HeapObject() { /** * Whether this is an instance of a primitive wrapper type. */ val isPrimitiveWrapper: Boolean get() = instanceClassName in primitiveWrapperClassNames override val graph: HeapGraph get() = hprofGraph /** * @see HeapClass.instanceByteSize */ val byteSize get() = instanceClass.instanceByteSize /** * The name of the class of this instance, identical to [Class.getName]. */ val instanceClassName: String get() = hprofGraph.className(indexedObject.classId) /** * Returns [instanceClassName] stripped of any string content before the last period (included). */ val instanceClassSimpleName: String get() = classSimpleName(instanceClassName) /** * The class of this instance. */ val instanceClass: HeapClass get() = hprofGraph.findObjectById(indexedObject.classId) as HeapClass /** * The heap identifier of the class of this instance. */ val instanceClassId: Long get() = indexedObject.classId /** * Reads and returns the underlying [InstanceDumpRecord]. * * This may trigger IO reads. */ override fun readRecord(): InstanceDumpRecord { return hprofGraph.readInstanceDumpRecord(objectId, indexedObject) } override val recordSize: Int get() = indexedObject.recordSize.toInt() /** * Returns true if this is an instance of the class named [className] or an instance of a * subclass of that class. */ infix fun instanceOf(className: String): Boolean = instanceClass.classHierarchy.any { it.name == className } /** * Returns true if this is an instance of [expectedClass] or an instance of a subclass of that * class. */ infix fun instanceOf(expectedClass: KClass<*>) = this instanceOf expectedClass.java.name /** * Returns true if this is an instance of [expectedClass] or an instance of a subclass of that * class. */ infix fun instanceOf(expectedClass: HeapClass) = instanceClass.classHierarchy.any { it.objectId == expectedClass.objectId } /** * @see readField */ fun readField( declaringClass: KClass<out Any>, fieldName: String ): HeapField? { return readField(declaringClass.java.name, fieldName) } /** * Returns a [HeapField] object that reflects the specified declared * field of the instance represented by this [HeapInstance] object, or null if this field does * not exist. The [declaringClassName] specifies the class in which the desired field is * declared, and the [fieldName] parameter specifies the simple name of the desired field. * * Also available as a convenience operator: [get] * * This may trigger IO reads. */ fun readField( declaringClassName: String, fieldName: String ): HeapField? { return readFields().firstOrNull { field -> field.declaringClass.name == declaringClassName && field.name == fieldName } } /** * @see readField */ operator fun get( declaringClass: KClass<out Any>, fieldName: String ): HeapField? { return readField(declaringClass, fieldName) } /** * @see readField */ operator fun get( declaringClassName: String, fieldName: String ) = readField(declaringClassName, fieldName) /** * The fields of this instance, as a sequence of [HeapField]. * * This may trigger IO reads. */ fun readFields(): Sequence<HeapField> { val fieldReader by lazy(NONE) { hprofGraph.createFieldValuesReader(readRecord()) } return instanceClass.classHierarchy .map { heapClass -> heapClass.readRecordFields().asSequence() .map { fieldRecord -> val fieldName = hprofGraph.fieldName(heapClass.objectId, fieldRecord) val fieldValue = fieldReader.readValue(fieldRecord) HeapField(heapClass, fieldName, HeapValue(hprofGraph, fieldValue)) } } .flatten() } /** * If this [HeapInstance] is an instance of the [String] class, returns a [String] instance * with content that matches the string in the heap dump. Otherwise returns null. * * This may trigger IO reads. */ fun readAsJavaString(): String? { if (instanceClassName != "java.lang.String") { return null } // JVM strings don't have a count field. val count = this["java.lang.String", "count"]?.value?.asInt if (count == 0) { return "" } // Prior to API 26 String.value was a char array. // Since API 26 String.value is backed by native code. The vast majority of strings in a // heap dump are backed by a byte array, but we still find a few backed by a char array. when (val valueRecord = this["java.lang.String", "value"]!!.value.asObject!!.readRecord()) { is CharArrayDump -> { // < API 23 // As of Marshmallow, substrings no longer share their parent strings' char arrays // eliminating the need for String.offset // https://android-review.googlesource.com/#/c/83611/ val offset = this["java.lang.String", "offset"]?.value?.asInt val chars = if (count != null && offset != null) { // Handle heap dumps where all primitive arrays have been replaced with empty arrays, // e.g. with HprofPrimitiveArrayStripper val toIndex = if (offset + count > valueRecord.array.size) { valueRecord.array.size } else offset + count valueRecord.array.copyOfRange(offset, toIndex) } else { valueRecord.array } return String(chars) } is ByteArrayDump -> { return String(valueRecord.array, Charset.forName("UTF-8")) } else -> throw UnsupportedOperationException( "'value' field ${this["java.lang.String", "value"]!!.value} was expected to be either" + " a char or byte array in string instance with id $objectId" ) } } override fun toString(): String { return "instance @$objectId of $instanceClassName" } } /** * An object array in the heap dump. */ class HeapObjectArray internal constructor( private val hprofGraph: HprofHeapGraph, internal val indexedObject: IndexedObjectArray, override val objectId: Long, override val objectIndex: Int ) : HeapObject() { override val graph: HeapGraph get() = hprofGraph /** * The name of the class of this array, identical to [Class.getName]. */ val arrayClassName: String get() = hprofGraph.className(indexedObject.arrayClassId) /** * Returns [arrayClassName] stripped of any string content before the last period (included). */ val arrayClassSimpleName: String get() = classSimpleName(arrayClassName) /** * The class of this array. */ val arrayClass: HeapClass get() = hprofGraph.findObjectById(indexedObject.arrayClassId) as HeapClass /** * The heap identifier of the class of this array. */ val arrayClassId: Long get() = indexedObject.arrayClassId @Deprecated("Use byteSize property instead", ReplaceWith("byteSize")) fun readByteSize() = byteSize /** * The total byte shallow size of elements in this array. */ val byteSize: Int get() = recordSize - hprofGraph.objectArrayRecordNonElementSize /** * Reads and returns the underlying [ObjectArrayDumpRecord]. * * This may trigger IO reads. */ override fun readRecord(): ObjectArrayDumpRecord { return hprofGraph.readObjectArrayDumpRecord(objectId, indexedObject) } override val recordSize: Int get() = indexedObject.recordSize.toInt() /** * The elements in this array, as a sequence of [HeapValue]. * * This may trigger IO reads. */ fun readElements(): Sequence<HeapValue> { return readRecord().elementIds.asSequence() .map { HeapValue(hprofGraph, ReferenceHolder(it)) } } override fun toString(): String { return "object array @$objectId of $arrayClassName" } } /** * A primitive array in the heap dump. */ class HeapPrimitiveArray internal constructor( private val hprofGraph: HprofHeapGraph, private val indexedObject: IndexedPrimitiveArray, override val objectId: Long, override val objectIndex: Int ) : HeapObject() { override val graph: HeapGraph get() = hprofGraph @Deprecated("Use byteSize property instead", ReplaceWith("byteSize")) fun readByteSize() = byteSize /** * The total byte shallow size of elements in this array. */ val byteSize: Int get() = recordSize - hprofGraph.primitiveArrayRecordNonElementSize /** * The [PrimitiveType] of elements in this array. */ val primitiveType: PrimitiveType get() = indexedObject.primitiveType /** * The name of the class of this array, identical to [Class.getName]. */ val arrayClassName: String get() = "${primitiveType.name.toLowerCase(Locale.US)}[]" /** * The class of this array. */ val arrayClass: HeapClass get() = graph.findClassByName(arrayClassName)!! /** * Reads and returns the underlying [PrimitiveArrayDumpRecord]. * * This may trigger IO reads. */ override fun readRecord(): PrimitiveArrayDumpRecord { return hprofGraph.readPrimitiveArrayDumpRecord(objectId, indexedObject) } override val recordSize: Int get() = indexedObject.recordSize.toInt() override fun toString(): String { return "primitive array @$objectId of $arrayClassName" } } companion object { internal val primitiveTypesByPrimitiveArrayClassName = PrimitiveType.values().associateBy { "${it.name.toLowerCase(Locale.US)}[]" } private val primitiveWrapperClassNames = setOf<String>( Boolean::class.javaObjectType.name, Char::class.javaObjectType.name, Float::class.javaObjectType.name, Double::class.javaObjectType.name, Byte::class.javaObjectType.name, Short::class.javaObjectType.name, Int::class.javaObjectType.name, Long::class.javaObjectType.name ) private fun classSimpleName(className: String): String { val separator = className.lastIndexOf('.') return if (separator == -1) { className } else { className.substring(separator + 1) } } } }
apache-2.0
3284d14871f4a5df28a27728c79fe202
31.324963
125
0.66295
4.600378
false
false
false
false
shaeberling/euler
kotlin/src/com/s13g/aoc/aoc2020/Day21.kt
1
2556
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 21: Allergen Assessment --- * https://adventofcode.com/2020/day/21 */ class Day21 : Solver { override fun solve(lines: List<String>): Result { val foods = lines.map { parseLine(it) } // Allergen --> the ingredient they map to. val candidates = mutableMapOf<String, MutableSet<String>>() // At first, an allergens can be any kind of ingredient in their food. for (food in foods) { for (allergen in food.allergens) { if (allergen !in candidates) candidates[allergen] = food.ingredients.toMutableSet() // If the ingredient has candidates, intersect with new list to narrow down the options. else candidates[allergen] = candidates[allergen]!!.intersect(food.ingredients).toMutableSet() } } // We look at allergens that have only a single candidate, then set that and remove it from the other // candidate lists. We repeat the process until all allergens have been mapped to their incredient. val allergenIngredient = mutableMapOf<String, String>() while (candidates.isNotEmpty()) { for (can in candidates) { if (can.value.size == 1) { // We found a match! val ingredient = can.value.first() allergenIngredient[can.key] = ingredient candidates.filter { ingredient in it.value }.forEach { it.value.remove(ingredient) } } } // Remove the found allergen from all candidate lists. allergenIngredient.forEach { candidates.remove(it.key) } } // Safe foods (non-allergens) are the ones that are not in the allergen list. val safeFoods = foods.flatMap { it.ingredients }.subtract(allergenIngredient.values) // Count how often safe foods are appearing in the ingredient lists. var resultA = 0 for (food in foods) resultA += safeFoods.count { it in food.ingredients } // Create a sorted list of the allergen names, then use that order to produce a // comma-separated list of their matching ingredients. val allergensSorted = allergenIngredient.keys.toSortedSet() var resultB = allergensSorted.map { allergenIngredient[it] }.joinToString(",") return Result("$resultA", resultB) } private fun parseLine(line: String): Food { val split = line.split(" (contains ") return Food(split[0].split(' '), split[1].substring(0, split[1].lastIndex).split(',').map { it.trim() }) } private data class Food(val ingredients: List<String>, val allergens: List<String>) }
apache-2.0
44481de16b550fdf258f73f503a7bf88
41.616667
108
0.684664
3.914242
false
false
false
false
HerbLuo/shop-api
src/main/java/cn/cloudself/model/OrderAnItemEntity.kt
1
668
package cn.cloudself.model import org.hibernate.annotations.DynamicInsert import javax.persistence.* /** * @author HerbLuo * @version 1.0.0.d */ @Entity @DynamicInsert @Table(name = "order_an_item", schema = "shop") data class OrderAnItemEntity( @get:Id @get:Column(name = "id", nullable = false) @get:GeneratedValue(strategy = GenerationType.IDENTITY) var id: Int = 0, @get:Basic @get:Column(name = "quantity", nullable = false) var quantity: Int = 0, @get:ManyToOne @get:JoinColumn(name = "item_id", referencedColumnName = "id", nullable = false) var item: ItemEntity? = null )
mit
421c4346cdeb0c23aa1ec48239c0ed0f
23.740741
88
0.633234
3.591398
false
false
false
false
MyDogTom/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/RethrowCaughtException.kt
1
1019
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config 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 io.gitlab.arturbosch.detekt.rules.collectByType import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.KtThrowExpression class RethrowCaughtException(config: Config = Config.empty) : Rule(config) { override val issue = Issue("RethrowCaughtException", Severity.Defect, "Do not rethrow a caught exception of the same type") override fun visitCatchSection(catchClause: KtCatchClause) { val throwExpression = catchClause.catchBody?.collectByType<KtThrowExpression>()?.firstOrNull { it.thrownExpression?.text == catchClause.catchParameter?.name } if (throwExpression != null) { report(CodeSmell(issue, Entity.from(throwExpression))) } } }
apache-2.0
f7c4e5c002f6ea2243bc8fa6c2c9afe7
38.192308
96
0.804711
4.027668
false
true
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/source/online/english/Kissmanga.kt
1
9121
package eu.kanade.tachiyomi.source.online.english import com.squareup.duktape.Duktape import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import timber.log.Timber import java.text.SimpleDateFormat import java.util.regex.Pattern class Kissmanga : ParsedHttpSource() { override val id: Long = 4 override val name = "Kissmanga" override val baseUrl = "http://kissmanga.com" override val lang = "en" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient override fun popularMangaSelector() = "table.listing tr:gt(1)" override fun latestUpdatesSelector() = "table.listing tr:gt(1)" override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/MangaList/MostPopular?page=$page", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("http://kissmanga.com/MangaList/LatestUpdate?page=$page", headers) } override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() element.select("td a:eq(0)").first().let { manga.setUrlWithoutDomain(it.attr("href")) val title = it.text() //check if cloudfire email obfuscation is affecting title name if (title.contains("[email protected]", true)) { try { var str: String = it.html() //get the number str = str.substringAfter("data-cfemail=\"") str = str.substringBefore("\">[email") val sb = StringBuilder() //convert number to char val r = Integer.valueOf(str.substring(0, 2), 16)!! var i = 2 while (i < str.length) { val c = (Integer.valueOf(str.substring(i, i + 2), 16) xor r).toChar() sb.append(c) i += 2 } //replace the new word into the title manga.title = title.replace("[email protected]", sb.toString(), true) } catch (e: Exception) { //on error just default to obfuscated title Timber.e("error parsing [email protected]", e) manga.title = title } } else { manga.title = title } } return manga } override fun latestUpdatesFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun popularMangaNextPageSelector() = "li > a:contains(› Next)" override fun latestUpdatesNextPageSelector(): String = "ul.pager > li > a:contains(Next)" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val form = FormBody.Builder().apply { add("mangaName", query) for (filter in if (filters.isEmpty()) getFilterList() else filters) { when (filter) { is Author -> add("authorArtist", filter.state) is Status -> add("status", arrayOf("", "Completed", "Ongoing")[filter.state]) is GenreList -> filter.state.forEach { genre -> add("genres", genre.state.toString()) } } } } return POST("$baseUrl/AdvanceSearch", headers, form.build()) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun searchMangaNextPageSelector() = null override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.barContent").first() val manga = SManga.create() manga.author = infoElement.select("p:has(span:contains(Author:)) > a").first()?.text() manga.genre = infoElement.select("p:has(span:contains(Genres:)) > *:gt(0)").text() manga.description = infoElement.select("p:has(span:contains(Summary:)) ~ p").text() manga.status = infoElement.select("p:has(span:contains(Status:))").first()?.text().orEmpty().let { parseStatus(it) } manga.thumbnail_url = document.select(".rightBox:eq(0) img").first()?.attr("src") return manga } fun parseStatus(status: String) = when { status.contains("Ongoing") -> SManga.ONGOING status.contains("Completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "table.listing tr:gt(1)" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text() chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let { SimpleDateFormat("MM/dd/yyyy").parse(it).time } ?: 0 return chapter } override fun pageListRequest(chapter: SChapter) = POST(baseUrl + chapter.url, headers) override fun pageListParse(response: Response): List<Page> { val body = response.body()!!.string() val pages = mutableListOf<Page>() // Kissmanga now encrypts the urls, so we need to execute these two scripts in JS. val ca = client.newCall(GET("$baseUrl/Scripts/ca.js", headers)).execute().body()!!.string() val lo = client.newCall(GET("$baseUrl/Scripts/lo.js", headers)).execute().body()!!.string() Duktape.create().use { it.evaluate(ca) it.evaluate(lo) // There are two functions in an inline script needed to decrypt the urls. We find and // execute them. var p = Pattern.compile("(.*CryptoJS.*)") var m = p.matcher(body) while (m.find()) { it.evaluate(m.group(1)) } // Finally find all the urls and decrypt them in JS. p = Pattern.compile("""lstImages.push\((.*)\);""") m = p.matcher(body) var i = 0 while (m.find()) { val url = it.evaluate(m.group(1)) as String pages.add(Page(i++, "", url)) } } return pages } override fun pageListParse(document: Document): List<Page> { throw Exception("Not used") } override fun imageUrlRequest(page: Page) = GET(page.url) override fun imageUrlParse(document: Document) = "" private class Status : Filter.TriState("Completed") private class Author : Filter.Text("Author") private class Genre(name: String) : Filter.TriState(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Genres", genres) override fun getFilterList() = FilterList( Author(), Status(), GenreList(getGenreList()) ) // $("select[name=\"genres\"]").map((i,el) => `Genre("${$(el).next().text().trim()}", ${i})`).get().join(',\n') // on http://kissmanga.com/AdvanceSearch private fun getGenreList() = listOf( Genre("4-Koma"), Genre("Action"), Genre("Adult"), Genre("Adventure"), Genre("Comedy"), Genre("Comic"), Genre("Cooking"), Genre("Doujinshi"), Genre("Drama"), Genre("Ecchi"), Genre("Fantasy"), Genre("Gender Bender"), Genre("Harem"), Genre("Historical"), Genre("Horror"), Genre("Josei"), Genre("Lolicon"), Genre("Manga"), Genre("Manhua"), Genre("Manhwa"), Genre("Martial Arts"), Genre("Mature"), Genre("Mecha"), Genre("Medical"), Genre("Music"), Genre("Mystery"), Genre("One shot"), Genre("Psychological"), Genre("Romance"), Genre("School Life"), Genre("Sci-fi"), Genre("Seinen"), Genre("Shotacon"), Genre("Shoujo"), Genre("Shoujo Ai"), Genre("Shounen"), Genre("Shounen Ai"), Genre("Slice of Life"), Genre("Smut"), Genre("Sports"), Genre("Supernatural"), Genre("Tragedy"), Genre("Webtoon"), Genre("Yaoi"), Genre("Yuri") ) }
apache-2.0
407e8249729730a4f22551bbc1e1a841
34.91498
124
0.550022
4.775275
false
false
false
false
rahulsom/grooves
grooves-example-pushstyle/src/main/kotlin/grooves/example/push/EventService.kt
1
3030
package grooves.example.push import com.github.rahulsom.grooves.api.EventApplyOutcome.CONTINUE import com.github.rahulsom.grooves.queries.Grooves import com.google.common.eventbus.Subscribe import com.google.inject.Inject import io.reactivex.Flowable.empty import io.reactivex.Flowable.just import io.reactivex.Maybe import io.reactivex.schedulers.Schedulers import org.jooq.DSLContext import org.slf4j.LoggerFactory class EventService { @Inject lateinit var database: Database @Inject lateinit var dslContext: DSLContext private val log = LoggerFactory.getLogger(this.javaClass) // Suppress warnings since this is a documented fragment and having variable names is better @Suppress("UNUSED_ANONYMOUS_PARAMETER") // tag::documented[] private val query = Grooves.versioned<Account, String, Transaction, String, Balance>() // <1> .withSnapshot { version, account -> // <2> log.info("getBalance($account, $version)") Maybe.fromCallable { database.getBalance(account, version) } .map { dbBalance -> Balance(dbBalance) } .toFlowable() } .withEmptySnapshot { Balance() } // <3> .withEvents { account, balance, version -> // <4> val transaction = ContextManager.get()?.get("transaction") as Transaction? if (transaction != null) just(transaction) else empty() } .withApplyEvents { balance -> true } // <5> .withDeprecator { balance, deprecatingAccount -> /* No op */ } // <6> .withExceptionHandler { exception, balance, transaction -> // <7> log.warn("$exception occurred") just(CONTINUE) } .withEventHandler(this::updateBalance) // <8> .build() // <9> private fun updateBalance(transaction: Transaction, balance: Balance) = when (transaction) { is Transaction.Deposit -> { balance.balance += transaction.amount just(CONTINUE) } is Transaction.Withdraw -> { balance.balance -= transaction.amount just(CONTINUE) } } // end::documented[] @Suppress("unused") @Subscribe fun onTransaction(transaction: Transaction) { log.info("Received $transaction") just(mapOf("transaction" to transaction)) .observeOn(ContextAwareScheduler) .doOnNext { ContextManager.set(it) } .flatMap { query.computeSnapshot(transaction.aggregate!!, transaction.position) } .observeOn(Schedulers.io()) .blockingForEach { balance -> log.info("Saving $balance") dslContext.executeInsert(balance.toBalanceRecord()) } log.info("End $transaction") } }
apache-2.0
1d29129652a400759fc4f8692ec45678
35.518072
96
0.583168
4.863563
false
false
false
false
JimSeker/ui
Material Design/SupportDesignDemo_kt/app/src/main/java/edu/cs4730/supportdesigndemo_kt/TextInputLayoutFragment.kt
1
1936
package edu.cs4730.supportdesigndemo_kt import android.widget.EditText import com.google.android.material.textfield.TextInputLayout import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.text.TextWatcher import android.text.Editable import android.view.View import androidx.fragment.app.Fragment /** * A simple example to show how to use the text input layout for a editText. * in the xml the textinputlayout is wrapped around the edittext. it will display the hint * even after the user starts typing and allows you to set an error message as well. */ class TextInputLayoutFragment : Fragment() { lateinit var et1: EditText lateinit var et2: EditText lateinit var mTextInputLayout: TextInputLayout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment_textinputlayout, container, false) et1 = myView.findViewById(R.id.edittext01) mTextInputLayout = myView.findViewById(R.id.textinput02) et2 = myView.findViewById(R.id.edittext02) et2.addTextChangedListener(object : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (s.toString() != "abc") { //set the error message that will display below the edittext mTextInputLayout.error = "Incorrect input." } else { mTextInputLayout.error = "" //clear the error message. } } //I don't care about this methods... override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} }) return myView } }
apache-2.0
8ce1baa3b83b03de0431bf25d3347608
39.354167
98
0.676136
4.699029
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/datastore/services/EntitySetService.kt
1
27048
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.datastore.services import com.codahale.metrics.annotation.Timed import com.google.common.base.Preconditions.checkArgument import com.google.common.base.Preconditions.checkState import com.google.common.collect.Sets import com.google.common.eventbus.EventBus import com.hazelcast.core.HazelcastInstance import com.hazelcast.map.IMap import com.hazelcast.query.Predicates import com.hazelcast.query.QueryConstants import com.openlattice.assembler.events.MaterializedEntitySetEdmChangeEvent import com.openlattice.assembler.processors.EntitySetContainsFlagEntryProcessor import com.openlattice.auditing.AuditRecordEntitySetsManager import com.openlattice.auditing.AuditingConfiguration import com.openlattice.auditing.AuditingTypes import com.openlattice.authorization.* import com.openlattice.authorization.securable.SecurableObjectType import com.openlattice.authorization.securable.SecurableObjectType.PropertyTypeInEntitySet import com.openlattice.controllers.exceptions.ResourceNotFoundException import com.openlattice.data.storage.PostgresEntitySetSizesInitializationTask import com.openlattice.data.storage.partitions.PartitionManager import com.openlattice.datastore.util.Util import com.openlattice.edm.EntitySet import com.openlattice.edm.events.* import com.openlattice.edm.processors.EntitySetsFlagFilteringAggregator import com.openlattice.edm.processors.GetEntityTypeFromEntitySetEntryProcessor import com.openlattice.edm.processors.GetNormalEntitySetIdsEntryProcessor import com.openlattice.edm.processors.GetPropertiesFromEntityTypeEntryProcessor import com.openlattice.edm.requests.MetadataUpdate import com.openlattice.edm.set.EntitySetFlag import com.openlattice.edm.set.EntitySetPropertyKey import com.openlattice.edm.set.EntitySetPropertyMetadata import com.openlattice.edm.type.AssociationType import com.openlattice.edm.type.EntityType import com.openlattice.edm.type.PropertyType import com.openlattice.edm.types.processors.UpdateEntitySetMetadataProcessor import com.openlattice.edm.types.processors.UpdateEntitySetPropertyMetadataProcessor import com.openlattice.hazelcast.HazelcastMap import com.openlattice.hazelcast.processors.AddEntitySetsToLinkingEntitySetProcessor import com.openlattice.hazelcast.processors.RemoveDataExpirationPolicyProcessor import com.openlattice.hazelcast.processors.RemoveEntitySetsFromLinkingEntitySetProcessor import com.openlattice.organizations.OrganizationMetadataEntitySetsService import com.openlattice.postgres.PostgresColumn import com.openlattice.postgres.mapstores.EntitySetMapstore import com.openlattice.rhizome.hazelcast.DelegatedUUIDSet import com.zaxxer.hikari.HikariDataSource import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.util.* import kotlin.collections.LinkedHashSet @Service class EntitySetService( hazelcastInstance: HazelcastInstance, private val eventBus: EventBus, private val aclKeyReservations: HazelcastAclKeyReservationService, private val authorizations: AuthorizationManager, private val partitionManager: PartitionManager, private val edm: EdmManager, private val hds: HikariDataSource, private val organizationMetadataEntitySetsService: OrganizationMetadataEntitySetsService, auditingConfiguration: AuditingConfiguration ) : EntitySetManager { init { organizationMetadataEntitySetsService.entitySetsManager = this } private val aresManager = AuditRecordEntitySetsManager( AuditingTypes(edm, auditingConfiguration), this, partitionManager, authorizations, hazelcastInstance ) companion object { private val logger = LoggerFactory.getLogger(EntitySetManager::class.java) } private val entitySets = HazelcastMap.ENTITY_SETS.getMap(hazelcastInstance) private val entityTypes = HazelcastMap.ENTITY_TYPES.getMap(hazelcastInstance) private val associationTypes: IMap<UUID, AssociationType> = HazelcastMap.ASSOCIATION_TYPES.getMap(hazelcastInstance) private val propertyTypes = HazelcastMap.PROPERTY_TYPES.getMap(hazelcastInstance) private val entitySetPropertyMetadata: IMap<EntitySetPropertyKey, EntitySetPropertyMetadata> = HazelcastMap.ENTITY_SET_PROPERTY_METADATA.getMap(hazelcastInstance) private val aclKeys = HazelcastMap.ACL_KEYS.getMap(hazelcastInstance) override fun createEntitySet(principal: Principal, entitySet: EntitySet): UUID { ensureValidEntitySet(entitySet) when { entitySet.isMetadataEntitySet -> { Principals.ensureOrganization(principal) } entitySet.isAudit -> { Principals.ensureUserOrOrganization(principal) } else -> { Principals.ensureUser(principal) } } if (entitySet.partitions.isEmpty()) { partitionManager.allocateEntitySetPartitions(entitySet) } val entityType = entityTypes.getValue(entitySet.entityTypeId) if (entityType.category == SecurableObjectType.AssociationType) { entitySet.addFlag(EntitySetFlag.ASSOCIATION) } else if (entitySet.flags.contains(EntitySetFlag.ASSOCIATION)) { entitySet.removeFlag(EntitySetFlag.ASSOCIATION) } val entitySetId = reserveEntitySetIfNotExists(entitySet) try { setupDefaultEntitySetPropertyMetadata(entitySetId, entitySet.entityTypeId) val aclKey = AclKey(entitySetId) authorizations.setSecurableObjectType(aclKey, SecurableObjectType.EntitySet) authorizations.addPermission(aclKey, principal, EnumSet.allOf(Permission::class.java)) val aclKeys = entityType.properties.mapTo(mutableSetOf()) { propertyTypeId -> AclKey( entitySetId, propertyTypeId ) } authorizations.setSecurableObjectTypes(aclKeys, PropertyTypeInEntitySet) authorizations.addPermissions( aclKeys, principal, EnumSet.allOf(Permission::class.java), PropertyTypeInEntitySet ) if (!entitySet.isMetadataEntitySet) { setupOrganizationMetadataAndAuditEntitySets(entitySet) } val ownablePropertyTypes = propertyTypes.getAll(entityType.properties).values.toList() eventBus.post(EntitySetCreatedEvent(entitySet, ownablePropertyTypes)) } catch (e: Exception) { logger.error("Unable to create entity set ${entitySet.name} (${entitySet.id}) for principal $principal", e) deleteEntitySet(entitySet, entityType) throw IllegalStateException("Unable to create entity set ${entitySet.id}. $e") } return entitySetId } override fun setupOrganizationMetadataAndAuditEntitySets(entitySet: EntitySet) { organizationMetadataEntitySetsService.addDataset(entitySet) val propertyTypes = edm.getPropertyTypesOfEntityType(entitySet.entityTypeId) organizationMetadataEntitySetsService.addDatasetColumns(entitySet, propertyTypes.values) aresManager.createAuditEntitySetForEntitySet(entitySet) } private fun reserveEntitySetIfNotExists(entitySet: EntitySet): UUID { aclKeyReservations.reserveIdAndValidateType(entitySet) checkState(entitySets.putIfAbsent(entitySet.id, entitySet) == null, "Entity set already exists.") return entitySet.id } private fun setupDefaultEntitySetPropertyMetadata(entitySetId: UUID, entityTypeId: UUID) { val et = edm.getEntityType(entityTypeId) val propertyTags = et.propertyTags entitySetPropertyMetadata.putAll(edm.getPropertyTypes(et.properties).associate { property -> val key = EntitySetPropertyKey(entitySetId, property.id) val metadata = EntitySetPropertyMetadata( property.title, property.description, propertyTags.getOrDefault(property.id, LinkedHashSet()), true ) key to metadata }) } private fun ensureValidEntitySet(entitySet: EntitySet) { checkArgument( entityTypes.containsKey(entitySet.entityTypeId), "Entity Set Type does not exists." ) if (entitySet.isLinking) { entitySet.linkedEntitySets.forEach { linkedEntitySetId -> checkArgument( getEntityTypeByEntitySetId(linkedEntitySetId).id == entitySet.entityTypeId, "Entity type of linked entity sets must be the same as of the linking entity set." ) checkArgument( !getEntitySet(linkedEntitySetId)!!.isLinking, "Cannot add linking entity set as linked entity set." ) } } } override fun deleteEntitySet(entitySet: EntitySet) { // If this entity set is linked to a linking entity set, we need to collect all the linking ids of the entity // set first in order to be able to reindex those, before entity data is unavailable if (!entitySet.isLinking) { checkAndRemoveEntitySetLinks(entitySet.id) } val entityType = edm.getEntityType(entitySet.entityTypeId) deleteEntitySet(entitySet, entityType) eventBus.post(EntitySetDeletedEvent(entitySet.id, entityType.id)) logger.info("Entity set ${entitySet.name} (${entitySet.id}) deleted successfully.") } private fun deleteEntitySet(entitySet: EntitySet, entityType: EntityType) { /* * We cleanup permissions first as this will make entity set unavailable, even if delete fails. */ authorizations.deletePermissions(AclKey(entitySet.id)) entityType.properties .map { propertyTypeId -> AclKey(entitySet.id, propertyTypeId) } .forEach { aclKey -> authorizations.deletePermissions(aclKey) entitySetPropertyMetadata.delete(EntitySetPropertyKey(aclKey[0], aclKey[1])) } aclKeyReservations.release(entitySet.id) Util.deleteSafely(entitySets, entitySet.id) } /** * Checks and removes links if deleted entity set is linked to a linking entity set * * @param entitySetId the id of the deleted entity set */ private fun checkAndRemoveEntitySetLinks(entitySetId: UUID) { edm.getAllLinkingEntitySetIdsForEntitySet(entitySetId).forEach { linkingEntitySetId -> removeLinkedEntitySets(linkingEntitySetId, setOf(entitySetId)) logger.info( "Removed link between linking entity set ($linkingEntitySetId) and deleted entity set " + "($entitySetId)" ) } } private val GET_ENTITY_SET_COUNT = """ SELECT ${PostgresColumn.COUNT} FROM ${PostgresEntitySetSizesInitializationTask.ENTITY_SET_SIZES_VIEW} WHERE ${PostgresColumn.ENTITY_SET_ID.name} = ? """.trimIndent() override fun getEntitySetSize(entitySetId: UUID): Long { return hds.connection.use { connection -> connection.prepareStatement(GET_ENTITY_SET_COUNT).use { ps -> ps.setObject(1, entitySetId) ps.executeQuery().use { rs -> if (rs.next()) { rs.getLong(1) } else { 0 } } } } } override fun getEntitySet(entitySetId: UUID): EntitySet? { return Util.getSafely(entitySets, entitySetId) } override fun getEntitySet(entitySetName: String): EntitySet? { val id = Util.getSafely(aclKeys, entitySetName) return if (id == null) { null } else { getEntitySet(id) } } override fun getEntitySetsAsMap(entitySetIds: Set<UUID>): Map<UUID, EntitySet> { return entitySets.getAll(entitySetIds) } override fun getEntitySets(): Iterable<EntitySet> { return entitySets.values } override fun getEntitySetsOfType(entityTypeIds: Set<UUID>): Collection<EntitySet> { return entitySets.values(Predicates.`in`(EntitySetMapstore.ENTITY_TYPE_ID_INDEX, *entityTypeIds.toTypedArray())) } override fun getEntitySetsOfType(entityTypeId: UUID): Collection<EntitySet> { return entitySets.values(Predicates.equal(EntitySetMapstore.ENTITY_TYPE_ID_INDEX, entityTypeId)) } override fun getEntitySetIdsOfType(entityTypeId: UUID): Collection<UUID> { return entitySets.keySet(Predicates.equal(EntitySetMapstore.ENTITY_TYPE_ID_INDEX, entityTypeId)) } @Suppress("UNCHECKED_CAST") override fun getEntitySetIdsWithFlags(entitySetIds: Set<UUID>, filteringFlags: Set<EntitySetFlag>): Set<UUID> { return entitySets.aggregate( EntitySetsFlagFilteringAggregator(filteringFlags), Predicates.`in`( QueryConstants.KEY_ATTRIBUTE_NAME.value(), *entitySetIds.toTypedArray() ) ) } override fun getEntitySetsForOrganization(organizationId: UUID): Set<UUID> { return entitySets.keySet(Predicates.equal(EntitySetMapstore.ORGANIZATION_INDEX, organizationId)) } override fun filterEntitySetsForOrganization(organizationId: UUID, entitySetIds: Collection<UUID>): Set<UUID> { return entitySets.keySet( Predicates.and( Predicates.equal<UUID, EntitySet>(EntitySetMapstore.ORGANIZATION_INDEX, organizationId), Predicates.`in`<UUID, EntitySet>(EntitySetMapstore.ID_INDEX, *entitySetIds.toTypedArray()) ) ) } override fun getEntityTypeByEntitySetId(entitySetId: UUID): EntityType { val entityTypeId = getEntitySet(entitySetId)!!.entityTypeId return edm.getEntityType(entityTypeId) } @Suppress("UNCHECKED_CAST") override fun getEntityTypeIdsByEntitySetIds(entitySetIds: Set<UUID>): Map<UUID, UUID> { return entitySets.executeOnKeys(entitySetIds, GetEntityTypeFromEntitySetEntryProcessor()) as Map<UUID, UUID> } override fun getAssociationTypeByEntitySetId(entitySetId: UUID): AssociationType { val entityTypeId = getEntitySet(entitySetId)!!.entityTypeId return edm.getAssociationType(entityTypeId) } override fun getAssociationTypeDetailsByEntitySetIds(entitySetIds: Set<UUID>): Map<UUID, AssociationType> { val entityTypeIdsByEntitySetId = getEntityTypeIdsByEntitySetIds(entitySetIds) val associationTypesByEntityTypeId = associationTypes.getAll( Sets.newHashSet(entityTypeIdsByEntitySetId.values) ) return entitySetIds.associateWith { associationTypesByEntityTypeId.getValue(entityTypeIdsByEntitySetId.getValue(it)) } } override fun isAssociationEntitySet(entitySetId: UUID): Boolean { return containsFlag(entitySetId, EntitySetFlag.ASSOCIATION) } override fun containsFlag(entitySetId: UUID, flag: EntitySetFlag): Boolean { return entitySets.executeOnKey(entitySetId, EntitySetContainsFlagEntryProcessor(flag)) as Boolean } override fun entitySetsContainFlag(entitySetIds: Set<UUID>, flag: EntitySetFlag): Boolean { return entitySets.executeOnKeys( entitySetIds, EntitySetContainsFlagEntryProcessor(flag) ).values.any { it as Boolean } } @Timed @Suppress("UNCHECKED_CAST") override fun filterToAuthorizedNormalEntitySets( entitySetIds: Set<UUID>, permissions: EnumSet<Permission>, principals: Set<Principal> ): Set<UUID> { val accessChecks = mutableMapOf<AclKey, EnumSet<Permission>>() val entitySetIdToNormalEntitySetIds = entitySets.executeOnKeys( entitySetIds, GetNormalEntitySetIdsEntryProcessor() ).mapValues { val set = (it.value as DelegatedUUIDSet).unwrap() set.forEach { accessChecks.putIfAbsent(AclKey(it), permissions) } set } val entitySetsToAuthorizedStatus = authorizations.authorize(accessChecks, principals) .map { it.key.first() to it.value.values.all { bool -> bool } }.toMap() return entitySetIdToNormalEntitySetIds.filterValues { it.all { id -> entitySetsToAuthorizedStatus.getValue( id ) } }.keys } @Timed override fun getPropertyTypesOfEntitySets(entitySetIds: Set<UUID>): Map<UUID, Map<UUID, PropertyType>> { val entityTypesOfEntitySets = getEntityTypeIdsByEntitySetIds(entitySetIds) val missingEntitySetIds = entitySetIds - entityTypesOfEntitySets.keys check(missingEntitySetIds.isEmpty()) { "Missing the following entity set ids: $missingEntitySetIds" } val entityTypesAsMap = edm.getEntityTypesAsMap(entityTypesOfEntitySets.values.toSet()) val propertyTypesAsMap = edm.getPropertyTypesAsMap( entityTypesAsMap.values.map { it.properties }.flatten().toSet() ) return entitySetIds.associateWith { entityTypesAsMap.getValue(entityTypesOfEntitySets.getValue(it)) .properties .associateWith { ptId -> propertyTypesAsMap.getValue(ptId) } } } override fun exists(entitySetId: UUID): Boolean = entitySets.containsKey(entitySetId) @Timed @Suppress("UNCHECKED_CAST") override fun getPropertyTypesForEntitySet(entitySetId: UUID): Map<UUID, PropertyType> { val maybeEtId = entitySets.executeOnKey(entitySetId, GetEntityTypeFromEntitySetEntryProcessor()) as? UUID ?: throw ResourceNotFoundException("Entity set $entitySetId does not exist.") val maybeEtProps = entityTypes.executeOnKey(maybeEtId, GetPropertiesFromEntityTypeEntryProcessor()) as? DelegatedUUIDSet ?: throw ResourceNotFoundException("Entity type $maybeEtId does not exist.") return propertyTypes.getAll(maybeEtProps) } override fun getEntitySetPropertyMetadata(entitySetId: UUID, propertyTypeId: UUID): EntitySetPropertyMetadata { val key = EntitySetPropertyKey(entitySetId, propertyTypeId) if (!entitySetPropertyMetadata.containsKey(key)) { val entityTypeId = getEntitySet(entitySetId)!!.entityTypeId setupDefaultEntitySetPropertyMetadata(entitySetId, entityTypeId) } return entitySetPropertyMetadata.getValue(key) } override fun getAllEntitySetPropertyMetadata(entitySetId: UUID): Map<UUID, EntitySetPropertyMetadata> { return getEntityTypeByEntitySetId(entitySetId).properties.associateWith { getEntitySetPropertyMetadata(entitySetId, it) } } @Suppress("UNCHECKED_CAST") override fun getAllEntitySetPropertyMetadataForIds( entitySetIds: Set<UUID> ): Map<UUID, Map<UUID, EntitySetPropertyMetadata>> { val entityTypesByEntitySetId = entitySets.executeOnKeys( entitySetIds, GetEntityTypeFromEntitySetEntryProcessor() ) as Map<UUID, UUID> val entityTypesById = entityTypes.getAll(entityTypesByEntitySetId.values.toSet()) val keys = entitySetIds .flatMap { entitySetId -> entityTypesById.getValue(entityTypesByEntitySetId.getValue(entitySetId)).properties .map { propertyTypeId -> EntitySetPropertyKey(entitySetId, propertyTypeId) } } .toSet() val metadataMap = entitySetPropertyMetadata.getAll(keys) val missingKeys = Sets.difference(keys, metadataMap.keys).toSet() val missingPropertyTypesById = propertyTypes.getAll( missingKeys.map(EntitySetPropertyKey::getPropertyTypeId).toSet() ) missingKeys.forEach { newKey -> val propertyType = missingPropertyTypesById.getValue(newKey.propertyTypeId) val propertyTags = entityTypesById.getValue(entityTypesByEntitySetId.getValue(newKey.entitySetId)) .propertyTags.getOrDefault(newKey.propertyTypeId, LinkedHashSet()) val defaultMetadata = EntitySetPropertyMetadata( propertyType.title, propertyType.description, LinkedHashSet(propertyTags), true ) metadataMap[newKey] = defaultMetadata entitySetPropertyMetadata[newKey] = defaultMetadata } return metadataMap.entries .groupBy { it.key.entitySetId } .mapValues { it.value.associateBy({ it.key.propertyTypeId }, { it.value }) } } override fun updateEntitySetPropertyMetadata(entitySetId: UUID, propertyTypeId: UUID, update: MetadataUpdate) { val key = EntitySetPropertyKey(entitySetId, propertyTypeId) entitySetPropertyMetadata.executeOnKey(key, UpdateEntitySetPropertyMetadataProcessor(update)) } override fun updateEntitySetMetadata(entitySetId: UUID, update: MetadataUpdate) { if (update.name.isPresent || update.organizationId.isPresent) { val oldEntitySet = getEntitySet(entitySetId)!! if (update.name.isPresent) { aclKeyReservations.renameReservation(entitySetId, update.name.get()) // If entity set name is changed, change also name of materialized view eventBus.post(EntitySetNameUpdatedEvent(entitySetId, update.name.get(), oldEntitySet.name)) } if (update.organizationId.isPresent) { // If an entity set is being moved across organizations, its audit entity sets should also be moved to // the new organization val aclKey = AclKey(entitySetId) val auditEntitySetIds = Sets.union( aresManager.getAuditRecordEntitySets(aclKey), aresManager.getAuditEdgeEntitySets(aclKey) ) entitySets.executeOnKeys( auditEntitySetIds, UpdateEntitySetMetadataProcessor( MetadataUpdate( Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), update.organizationId, Optional.empty(), Optional.empty() ) ) ) // If an entity set is being moved across organizations, its materialized entity set should be deleted // from old organization assembly eventBus.post(EntitySetOrganizationUpdatedEvent(entitySetId, oldEntitySet.organizationId)) } } val newEntitySet = entitySets.executeOnKey(entitySetId, UpdateEntitySetMetadataProcessor(update)) as EntitySet eventBus.post(EntitySetMetadataUpdatedEvent(newEntitySet)) } override fun addLinkedEntitySets(entitySetId: UUID, linkedEntitySets: Set<UUID>): Int { val linkingEntitySet = Util.getSafely(entitySets, entitySetId) val startSize = linkingEntitySet.linkedEntitySets.size val updatedLinkingEntitySet = entitySets.executeOnKey( entitySetId, AddEntitySetsToLinkingEntitySetProcessor(linkedEntitySets) ) as EntitySet markMaterializedEntitySetDirtyWithEdmChanges(linkingEntitySet.id) eventBus.post(LinkedEntitySetAddedEvent(entitySetId)) return updatedLinkingEntitySet.linkedEntitySets.size - startSize } override fun removeLinkedEntitySets(entitySetId: UUID, linkedEntitySets: Set<UUID>): Int { val linkingEntitySet = Util.getSafely(entitySets, entitySetId) val startSize = linkingEntitySet.linkedEntitySets.size val updatedLinkingEntitySet = entitySets.executeOnKey( entitySetId, RemoveEntitySetsFromLinkingEntitySetProcessor(linkedEntitySets) ) as EntitySet markMaterializedEntitySetDirtyWithEdmChanges(linkingEntitySet.id) eventBus.post(LinkedEntitySetRemovedEvent(entitySetId)) return startSize - updatedLinkingEntitySet.linkedEntitySets.size } private fun markMaterializedEntitySetDirtyWithEdmChanges(entitySetId: UUID) { eventBus.post(MaterializedEntitySetEdmChangeEvent(entitySetId)) } override fun getLinkedEntitySets(entitySetId: UUID): Set<EntitySet> { val linkedEntitySetIds = getEntitySet(entitySetId)!!.linkedEntitySets return entitySets.getAll(linkedEntitySetIds).values.toSet() } override fun getLinkedEntitySetIds(entitySetId: UUID): Set<UUID> { return entitySets.executeOnKey(entitySetId) { DelegatedUUIDSet.wrap( it.value?.linkedEntitySets ?: mutableSetOf() ) } } override fun removeDataExpirationPolicy(entitySetId: UUID) { entitySets.executeOnKey(entitySetId, RemoveDataExpirationPolicyProcessor()) } override fun getAuditRecordEntitySetsManager(): AuditRecordEntitySetsManager { return aresManager } }
gpl-3.0
6679bde79c622bcfa2a88069038fd4fc
41.731438
120
0.673654
5.435691
false
false
false
false
gantsign/restrulz-jvm
com.gantsign.restrulz.jackson/src/main/kotlin/com/gantsign/restrulz/jackson/writer/JacksonObjectWriter.kt
1
11142
/*- * #%L * Restrulz * %% * Copyright (C) 2017 GantSign 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. * #L% */ package com.gantsign.restrulz.jackson.writer import com.fasterxml.jackson.core.JsonEncoding import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.util.DefaultPrettyPrinter import com.gantsign.restrulz.json.writer.JsonObjectWriter import java.io.OutputStream import java.io.StringWriter /** * Base class for implementing writing objects as JSON using Jackson. * * @param T the type of object being written out. */ @Suppress("unused") abstract class JacksonObjectWriter<in T> : JsonObjectWriter<T> { /** * Convenience method for outputting a field entry ("member") * that has the specified numeric value. Equivalent to: * * ``` * writeFieldName(fieldName); * if (value == null) { * writeNull(); * } else { * writeNumber(value); * } * ``` * * @param fieldName the name of the field being written out. * @param value the value to write out. */ protected fun JsonGenerator.writeNumberField(fieldName: String, value: Byte?) { if (value === null) { writeNullField(fieldName) } else { writeNumberField(fieldName, value.toInt()) } } /** * Convenience method for outputting a field entry ("member") * that has the specified numeric value. Equivalent to: * * ``` * writeFieldName(fieldName); * if (value == null) { * writeNull(); * } else { * writeNumber(value); * } * ``` * * @param fieldName the name of the field being written out. * @param value the value to write out. */ protected fun JsonGenerator.writeNumberField(fieldName: String, value: Short?) { if (value === null) { writeNullField(fieldName) } else { writeNumberField(fieldName, value.toInt()) } } /** * Convenience method for outputting a field entry ("member") * that has the specified numeric value. Equivalent to: * * ``` * writeFieldName(fieldName); * if (value == null) { * writeNull(); * } else { * writeNumber(value); * } * ``` * * @param fieldName the name of the field being written out. * @param value the value to write out. */ protected fun JsonGenerator.writeNumberField(fieldName: String, value: Int?) { if (value === null) { writeNullField(fieldName) } else { writeNumberField(fieldName, value) } } /** * Convenience method for outputting a field entry ("member") * that has the specified numeric value. Equivalent to: * * ``` * writeFieldName(fieldName); * if (value == null) { * writeNull(); * } else { * writeNumber(value); * } * ``` * * @param fieldName the name of the field being written out. * @param value the value to write out. */ protected fun JsonGenerator.writeNumberField(fieldName: String, value: Long?) { if (value === null) { writeNullField(fieldName) } else { writeNumberField(fieldName, value) } } /** * Convenience method for outputting a field entry ("member") * that has the specified array value. Equivalent to: * * ``` * writeFieldName(fieldName) * writeStartArray(values.size) * for (value in values) { * writeString(value) * } * writeEndArray() * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ protected fun JsonGenerator.writeStringArrayField(fieldName: String, values: List<String>) { writeFieldName(fieldName) writeStartArray(values.size) for (value in values) { writeString(value) } writeEndArray() } /** * Convenience method for outputting a field entry ("member") * that has the specified array value. Equivalent to: * * ``` * writeFieldName(fieldName) * writeStartArray(values.size) * for (value in values) { * writeBoolean(value) * } * writeEndArray() * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ protected fun JsonGenerator.writeBooleanArrayField(fieldName: String, values: List<Boolean>) { writeFieldName(fieldName) writeStartArray(values.size) for (value in values) { writeBoolean(value) } writeEndArray() } /** * Convenience method for outputting a field entry ("member") * that has the specified array value. Equivalent to: * * ``` * writeFieldName(fieldName) * writeStartArray(values.size) * for (value in values) { * writeNumber(value) * } * writeEndArray() * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ protected fun JsonGenerator.writeByteArrayField(fieldName: String, values: List<Byte>) { writeFieldName(fieldName) writeStartArray(values.size) for (value in values) { writeNumber(value.toInt()) } writeEndArray() } /** * Convenience method for outputting a field entry ("member") * that has the specified array value. Equivalent to: * * ``` * writeFieldName(fieldName) * writeStartArray(values.size) * for (value in values) { * writeNumber(value) * } * writeEndArray() * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ protected fun JsonGenerator.writeShortArrayField(fieldName: String, values: List<Short>) { writeFieldName(fieldName) writeStartArray(values.size) for (value in values) { writeNumber(value) } writeEndArray() } /** * Convenience method for outputting a field entry ("member") * that has the specified array value. Equivalent to: * * ``` * writeFieldName(fieldName) * writeStartArray(values.size) * for (value in values) { * writeNumber(value) * } * writeEndArray() * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ protected fun JsonGenerator.writeIntArrayField(fieldName: String, values: List<Int>) { writeFieldName(fieldName) writeStartArray(values.size) for (value in values) { writeNumber(value) } writeEndArray() } /** * Convenience method for outputting a field entry ("member") * that has the specified array value. Equivalent to: * * ``` * writeFieldName(fieldName) * writeStartArray(values.size) * for (value in values) { * writeNumber(value) * } * writeEndArray() * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ protected fun JsonGenerator.writeLongArrayField(fieldName: String, values: List<Long>) { writeFieldName(fieldName) writeStartArray(values.size) for (value in values) { writeNumber(value) } writeEndArray() } /** * Writes the specified object to the specified [JsonGenerator]. * * @param generator the low level API for writing JSON. * @param value the object to write out. */ abstract fun writeObject(generator: JsonGenerator, value: T?) /** * Convenience method for outputting a field entry ("member") * that has contents of specific Java object as its value. * Equivalent to: * * ``` * writeFieldName(fieldName); * writeObject(value); * ``` * * @param fieldName the name of the field being written out. * @param value the value to write out. */ fun writeObjectField(generator: JsonGenerator, fieldName: String, value: T?) { generator.writeFieldName(fieldName) writeObject(generator, value) } /** * Writes the specified list of objects to the specified [JsonGenerator]. * * @param generator the low level API for writing JSON. * @param values the list of objects to write out. */ fun writeArray(generator: JsonGenerator, values: List<T>) { generator.writeStartArray() for (value in values) { writeObject(generator, value) } generator.writeEndArray() } /** * Convenience method for outputting a field entry ("member") * that has contents of specific Java object as its value. * Equivalent to: * * ``` * writeFieldName(fieldName); * writeArray(values); * ``` * * @param fieldName the name of the field being written out. * @param values the values to write out. */ fun writeArrayField(generator: JsonGenerator, fieldName: String, values: List<T>) { generator.writeFieldName(fieldName) writeArray(generator, values) } override fun writeAsJson(output: OutputStream, value: T) { val factory = JsonFactory() factory.createGenerator(output, JsonEncoding.UTF8).use { generator -> writeObject(generator, value) } } override fun toJsonString(value: T): String { val writer = StringWriter() val factory = JsonFactory() factory.createGenerator(writer).use { generator -> generator.prettyPrinter = DefaultPrettyPrinter() writeObject(generator, value) } return writer.toString() } override fun writeAsJsonArray(output: OutputStream, values: List<T>) { val factory = JsonFactory() factory.createGenerator(output, JsonEncoding.UTF8).use { generator -> writeArray(generator, values) } } override fun toJsonArrayString(values: List<T>): String { val writer = StringWriter() val factory = JsonFactory() factory.createGenerator(writer).use { generator -> generator.prettyPrinter = DefaultPrettyPrinter() writeArray(generator, values) } return writer.toString() } }
apache-2.0
0f5b2a1f49887d2d0af7a37428dbb8f5
28.712
98
0.60779
4.514587
false
false
false
false
jguerinet/mobile-string-parser
src/main/java/config/ConstantsConfig.kt
1
3304
/* * Copyright 2013-2021 Julien Guerinet * * 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.guerinet.weave.config import com.guerinet.weave.config.ConstantsConfig.Casing import kotlinx.serialization.KSerializer import kotlinx.serialization.Required import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder /** * Config for a list of constants (ex: Analytics) * @author Julien Guerinet * @since 5.0.0 * * @param title Name of this set of Constants, used for debugging * @param sources List of [Source]s the Constants are coming from * @param path Path to the file to write to * @param packageName Optional package name used on Android * @param typeColumnName Name of the column that holds the type * @param valueColumnName Name of the column that holds the key * @param valuesAlignColumn Number of tabs to do in order to align the keys. Defaults to 0 (unaligned) * @param typeCasing [Casing] to name the types, defaults to Pascal * @param keyCasing [Casing] to name the keys, defaults to camel * @param isTopLevelClassCreated True if there should be a top level class created from the file name, false otherwise * Defaults to true */ @Serializable class ConstantsConfig( @Required val title: String, @Required val sources: List<Source> = listOf(), @Required val path: String = "", val packageName: String? = null, val typeColumnName: String = "", val valueColumnName: String = "value", val valuesAlignColumn: Int = 0, val typeCasing: Casing = Casing.PASCAL_CASE, val keyCasing: Casing = Casing.CAMEL_CASE, val isTopLevelClassCreated: Boolean = true ) { /** * Casing to use for naming the tags */ @Serializable(with = Casing.Companion::class) enum class Casing { NONE, CAMEL_CASE, PASCAL_CASE, SNAKE_CASE, CAPS; companion object : KSerializer<Casing> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Casing", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): Casing = when (decoder.decodeString().lowercase()) { "camel", "camelcase" -> CAMEL_CASE "pascal", "pascalcase" -> PASCAL_CASE "snake", "snakecase" -> SNAKE_CASE "caps" -> CAPS else -> NONE } override fun serialize(encoder: Encoder, value: Casing) = error("This object should not be serialized") } } }
apache-2.0
b4906cb37ea2f8fafb155ffbdf9c16bd
36.977011
118
0.696429
4.324607
false
true
false
false
square/duktape-android
zipline-loader/src/androidMain/kotlin/app/cash/zipline/loader/internal/cache/databaseAndroid.kt
1
1297
/* * Copyright (C) 2022 Block, 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 app.cash.zipline.loader.internal.cache import android.content.Context import android.database.SQLException import com.squareup.sqldelight.android.AndroidSqliteDriver import com.squareup.sqldelight.db.SqlDriver import okio.Path internal actual class SqlDriverFactory( private val context: Context, ) { actual fun create(path: Path, schema: SqlDriver.Schema): SqlDriver { validateDbPath(path) return AndroidSqliteDriver( schema = schema, context = context, name = path.toString(), useNoBackupDirectory = false, // The cache directory is already in a no-backup directory. ) } } internal actual fun isSqlException(e: Exception) = e is SQLException
apache-2.0
2258e931c507d658c1f46f04563e3829
33.131579
95
0.745567
4.183871
false
false
false
false
xiaopansky/Sketch
sample/src/main/java/me/panpf/sketch/sample/ImageOptions.kt
1
6394
/* * Copyright (C) 2019 Peng fei Pan <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.panpf.sketch.sample import android.content.Context import android.graphics.Bitmap import android.graphics.Color import androidx.annotation.IntDef import android.util.SparseArray import me.panpf.sketch.display.TransitionImageDisplayer import me.panpf.sketch.process.GaussianBlurImageProcessor import me.panpf.sketch.request.DisplayOptions import me.panpf.sketch.request.DownloadOptions import me.panpf.sketch.request.LoadOptions import me.panpf.sketch.request.ShapeSize import me.panpf.sketch.shaper.CircleImageShaper import me.panpf.sketch.shaper.RoundRectImageShaper import me.panpf.sketch.state.DrawableStateImage import me.panpf.sketch.state.OldStateImage import me.panpf.sketch.util.SketchUtils object ImageOptions { /** * 通用矩形 */ const val RECT = 101 /** * 带描边的圆形 */ const val CIRCULAR_STROKE = 102 /** * 窗口背景 */ const val WINDOW_BACKGROUND = 103 /** * 圆角矩形 */ const val ROUND_RECT = 104 /** * 充满列表 */ const val LIST_FULL = 105 @JvmStatic private val OPTIONS_ARRAY = SparseArray<OptionsHolder>() init { val transitionImageDisplayer = TransitionImageDisplayer() OPTIONS_ARRAY.append(ImageOptions.RECT, object : OptionsHolder() { override fun onCreateOptions(context: Context): DownloadOptions { return DisplayOptions() .setLoadingImage(R.drawable.image_loading) .setErrorImage(R.drawable.image_error) .setPauseDownloadImage(R.drawable.image_pause_download) .setDisplayer(transitionImageDisplayer) .setShapeSize(ShapeSize.byViewFixedSize()) } }) OPTIONS_ARRAY.append(ImageOptions.CIRCULAR_STROKE, object : OptionsHolder() { override fun onCreateOptions(context: Context): DownloadOptions { return DisplayOptions() .setLoadingImage(R.drawable.image_loading) .setErrorImage(R.drawable.image_error) .setPauseDownloadImage(R.drawable.image_pause_download) .setDisplayer(transitionImageDisplayer) .setShaper(CircleImageShaper().setStroke(Color.WHITE, SketchUtils.dp2px(context, 1))) .setShapeSize(ShapeSize.byViewFixedSize()) } }) OPTIONS_ARRAY.append(ImageOptions.WINDOW_BACKGROUND, object : OptionsHolder() { override fun onCreateOptions(context: Context): DownloadOptions { return DisplayOptions() .setProcessor(GaussianBlurImageProcessor.makeLayerColor(Color.parseColor("#66000000"))) .setCacheProcessedImageInDisk(true) .setBitmapConfig(Bitmap.Config.ARGB_8888) // 效果比较重要 .setShapeSize(ShapeSize.byViewFixedSize()) .setMaxSize(context.resources.displayMetrics.widthPixels / 4, context.resources.displayMetrics.heightPixels / 4) .setDisplayer(TransitionImageDisplayer(true)) } }) OPTIONS_ARRAY.append(ImageOptions.ROUND_RECT, object : OptionsHolder() { override fun onCreateOptions(context: Context): DownloadOptions { return DisplayOptions() .setLoadingImage(R.drawable.image_loading) .setErrorImage(R.drawable.image_error) .setPauseDownloadImage(R.drawable.image_pause_download) .setShaper(RoundRectImageShaper(SketchUtils.dp2px(context, 6).toFloat())) .setDisplayer(transitionImageDisplayer) .setShapeSize(ShapeSize.byViewFixedSize()) } }) OPTIONS_ARRAY.append(ImageOptions.LIST_FULL, object : OptionsHolder() { override fun onCreateOptions(context: Context): DownloadOptions { val displayMetrics = context.resources.displayMetrics return DisplayOptions() .setLoadingImage(R.drawable.image_loading) .setErrorImage(R.drawable.image_error) .setPauseDownloadImage(R.drawable.image_pause_download) .setMaxSize(displayMetrics.widthPixels, displayMetrics.heightPixels) .setDisplayer(transitionImageDisplayer) } }) } fun getDisplayOptions(context: Context, @Type optionsId: Int): DisplayOptions { return OPTIONS_ARRAY.get(optionsId).getOptions(context) as DisplayOptions } fun getLoadOptions(context: Context, @Type optionsId: Int): LoadOptions { return OPTIONS_ARRAY.get(optionsId).getOptions(context) as LoadOptions } fun getDownloadOptions(context: Context, @Type optionsId: Int): DownloadOptions { return OPTIONS_ARRAY.get(optionsId).getOptions(context) } private abstract class OptionsHolder { private var options: DownloadOptions? = null fun getOptions(context: Context): DownloadOptions { if (options == null) { synchronized(this) { if (options == null) { options = onCreateOptions(context) } } } return options!! } protected abstract fun onCreateOptions(context: Context): DownloadOptions } @IntDef(RECT, CIRCULAR_STROKE, WINDOW_BACKGROUND, ROUND_RECT, LIST_FULL) @Retention(AnnotationRetention.SOURCE) annotation class Type }
apache-2.0
e170c39ef534836a13e69cbdc712e698
38.36646
111
0.631745
4.776187
false
false
false
false
afollestad/material-dialogs
core/src/main/java/com/afollestad/materialdialogs/utils/Dialogs.kt
2
3844
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialdialogs.utils import android.content.Context.INPUT_METHOD_SERVICE import android.graphics.Typeface import android.graphics.drawable.Drawable import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.ImageView import android.widget.TextView import androidx.annotation.DrawableRes import androidx.annotation.RestrictTo import androidx.annotation.RestrictTo.Scope import androidx.annotation.StringRes import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.callbacks.invokeAll import com.afollestad.materialdialogs.checkbox.getCheckBoxPrompt import com.afollestad.materialdialogs.customview.CUSTOM_VIEW_NO_VERTICAL_PADDING import com.afollestad.materialdialogs.utils.MDUtil.maybeSetTextColor import com.afollestad.materialdialogs.utils.MDUtil.resolveDrawable import com.afollestad.materialdialogs.utils.MDUtil.resolveString @RestrictTo(Scope.LIBRARY_GROUP) fun MaterialDialog.invalidateDividers( showTop: Boolean, showBottom: Boolean ) = view.invalidateDividers(showTop, showBottom) internal fun MaterialDialog.preShow() { val customViewNoVerticalPadding = config[CUSTOM_VIEW_NO_VERTICAL_PADDING] as? Boolean == true this.preShowListeners.invokeAll(this) this.view.run { if (titleLayout.shouldNotBeVisible() && !customViewNoVerticalPadding) { // Reduce top and bottom padding if we have no title or buttons contentLayout.modifyFirstAndLastPadding( top = frameMarginVertical, bottom = frameMarginVertical ) } if (getCheckBoxPrompt().isVisible()) { // Zero out bottom content padding if we have a checkbox prompt contentLayout.modifyFirstAndLastPadding(bottom = 0) } else if (contentLayout.haveMoreThanOneChild()) { contentLayout.modifyScrollViewPadding(bottom = frameMarginVerticalLess) } } } internal fun MaterialDialog.populateIcon( imageView: ImageView, @DrawableRes iconRes: Int?, icon: Drawable? ) { val drawable = resolveDrawable(windowContext, res = iconRes, fallback = icon) if (drawable != null) { (imageView.parent as View).visibility = View.VISIBLE imageView.visibility = View.VISIBLE imageView.setImageDrawable(drawable) } else { imageView.visibility = View.GONE } } internal fun MaterialDialog.populateText( textView: TextView, @StringRes textRes: Int? = null, text: CharSequence? = null, @StringRes fallback: Int = 0, typeface: Typeface?, textColor: Int? = null ) { val value = text ?: resolveString(this, textRes, fallback) if (value != null) { (textView.parent as View).visibility = View.VISIBLE textView.visibility = View.VISIBLE textView.text = value if (typeface != null) { textView.typeface = typeface } textView.maybeSetTextColor(windowContext, textColor) } else { textView.visibility = View.GONE } } internal fun MaterialDialog.hideKeyboard() { val imm = windowContext.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager val currentFocus = currentFocus if (currentFocus != null) { currentFocus.windowToken } else { view.windowToken }.let { imm.hideSoftInputFromWindow(it, 0) } }
apache-2.0
e72e4866e651ca5de48414b93b302e36
33.321429
95
0.760406
4.418391
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/render/world/components/LightUniform.kt
1
1849
package com.fracturedskies.render.world.components import com.fracturedskies.api.World import com.fracturedskies.engine.collections.MultiTypeMap import com.fracturedskies.engine.jeact.* import com.fracturedskies.engine.loadByteBuffer import com.fracturedskies.engine.math.* import com.fracturedskies.render.common.components.gl.glUniform import com.fracturedskies.render.common.shaders.color.ColorShaderProgram import com.fracturedskies.render.world.LightLevels import javax.inject.Inject import kotlin.math.PI class LightUniform : Component<Unit>(Unit) { companion object { fun Node.Builder<*>.lightUniform(additionalProps: MultiTypeMap = MultiTypeMap()) { nodes.add(Node(LightUniform::class, additionalProps)) } private val skyLightDirection = Vector3(0f, -1f, -0.5f).normalize() } @Inject private lateinit var world: World private lateinit var skyLightLevels: LightLevels private lateinit var blockLightLevels: LightLevels override fun componentDidMount() { skyLightLevels = LightLevels.load(loadByteBuffer("SkyLightLevels.png", this::class.java), 240) blockLightLevels = LightLevels.load(loadByteBuffer("BlockLightLevels.png", this::class.java), 16) } override fun shouldComponentUpdate(nextProps: MultiTypeMap, nextState: Unit): Boolean = false override fun glRender(bounds: Bounds) { super.glRender(bounds) val timeOfDay = world.timeOfDay val lightDirection = skyLightDirection * Quaternion4(Vector3.AXIS_Z, timeOfDay * 2f * PI.toFloat()) val skyLight = skyLightLevels.getColorBuffer(timeOfDay) val blockLight = blockLightLevels.getColorBuffer(timeOfDay) glUniform(ColorShaderProgram.LIGHT_DIRECTION_LOCATION, lightDirection) glUniform(ColorShaderProgram.SKY_COLORS_LOCATION, skyLight) glUniform(ColorShaderProgram.BLOCK_COLORS_LOCATION, blockLight) } }
unlicense
55ae08b089f0c1f7073d35811aefd669
37.541667
103
0.789616
4.127232
false
false
false
false
cfig/Nexus_boot_image_editor
bbootimg/src/main/kotlin/packable/IPackable.kt
1
2879
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.packable import avb.AVBInfo import cfig.Avb import cfig.helper.Helper import cfig.helper.Helper.Companion.check_call import cfig.helper.Helper.Companion.check_output import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File interface IPackable { val loopNo: Int fun capabilities(): List<String> { return listOf("^dtbo\\.img$") } fun unpack(fileName: String = "dtbo.img") fun pack(fileName: String = "dtbo.img") fun flash(fileName: String = "dtbo.img", deviceName: String = "dtbo") { "adb root".check_call() val abUpdateProp = "adb shell getprop ro.build.ab_update".check_output() log.info("ro.build.ab_update=$abUpdateProp") val slotSuffix = if (abUpdateProp == "true") { "adb shell getprop ro.boot.slot_suffix".check_output() } else { "" } log.info("slot suffix = $slotSuffix") "adb push $fileName /mnt/file.to.burn".check_call() "adb shell dd if=/mnt/file.to.burn of=/dev/block/by-name/$deviceName$slotSuffix".check_call() "adb shell rm /mnt/file.to.burn".check_call() } fun pull(fileName: String = "dtbo.img", deviceName: String = "dtbo") { "adb root".check_call() val abUpdateProp = "adb shell getprop ro.build.ab_update".check_output() log.info("ro.build.ab_update=$abUpdateProp") val slotSuffix = if (abUpdateProp == "true") { "adb shell getprop ro.boot.slot_suffix".check_output() } else { "" } log.info("slot suffix = $slotSuffix") "adb shell dd if=/dev/block/by-name/$deviceName$slotSuffix of=/mnt/file.to.pull".check_call() "adb pull /mnt/file.to.pull $fileName".check_call() "adb shell rm /mnt/file.to.pull".check_call() } // invoked solely by reflection fun `@verify`(fileName: String) { val ai = AVBInfo.parseFrom(fileName).dumpDefault(fileName) Avb().verify(ai, fileName) } fun cleanUp() { val workDir = Helper.prop("workDir") if (File(workDir).exists()) File(workDir).deleteRecursively() File(workDir).mkdirs() } companion object { val log: Logger = LoggerFactory.getLogger(IPackable::class.java) } }
apache-2.0
6a6bba86df48be4f2c13b3142554c19a
35.443038
101
0.649878
3.691026
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/loadtest/frontend/GcsFrontendSimulatorRunner.kt
1
1369
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.loadtest.frontend import org.wfanet.measurement.common.commandLineMain import org.wfanet.measurement.gcloud.gcs.GcsFromFlags import org.wfanet.measurement.gcloud.gcs.GcsStorageClient import picocli.CommandLine @CommandLine.Command( name = "GcsFrontendSimulatorRunner", description = ["Daemon for GcsFrontendSimulatorRunner."], mixinStandardHelpOptions = true, showDefaultValues = true ) class GcsFrontendSimulatorRunner : FrontendSimulatorRunner() { @CommandLine.Mixin private lateinit var gcsFlags: GcsFromFlags.Flags override fun run() { val gcs = GcsFromFlags(gcsFlags) run(GcsStorageClient.fromFlags(gcs)) } } fun main(args: Array<String>) = commandLineMain(GcsFrontendSimulatorRunner(), args)
apache-2.0
64a917efe06344393b8de0df9b171622
36
83
0.778671
4.346032
false
false
false
false
googleapis/gapic-generator-kotlin
generator/src/main/kotlin/com/google/api/kotlin/ClientPlugin.kt
1
4744
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin import com.google.api.kotlin.config.ProtobufExtensionRegistry import com.google.api.kotlin.config.ProtobufTypeMapper import com.google.api.kotlin.config.asSwappableConfiguration import com.google.api.kotlin.generator.DSLBuilderGenerator import com.google.api.kotlin.generator.GRPCGenerator import com.google.api.kotlin.types.isNotWellKnown import com.google.devtools.common.options.OptionsParser import com.google.protobuf.compiler.PluginProtos import com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest import mu.KotlinLogging import java.io.FileInputStream import java.nio.file.Paths private val log = KotlinLogging.logger {} /** * Main entry point. */ fun main(args: Array<String>) { // parse arguments val optionParser = OptionsParser.newOptionsParser(ClientPluginOptions::class.java) optionParser.parse(*args) var options = optionParser.getOptions(ClientPluginOptions::class.java) ?: throw IllegalStateException("Unable to parse command line options") // usage if (options.help) { println("Usage:") println( optionParser.describeOptions( mapOf(), OptionsParser.HelpVerbosity.LONG ) ) return } // parse request val runAsPlugin = options.inputFile.isBlank() val request = if (runAsPlugin) { CodeGeneratorRequest.parseFrom(System.`in`, ProtobufExtensionRegistry.INSTANCE) } else { FileInputStream(options.inputFile).use { CodeGeneratorRequest.parseFrom(it, ProtobufExtensionRegistry.INSTANCE) } } // parse plugin opts and override if (runAsPlugin) { log.debug { "parsing plugin options: '${request.parameter}'" } // override val pluginsOpts = request.parameter.split(",").map { "--$it" } val parser = OptionsParser.newOptionsParser(ClientPluginOptions::class.java) parser.parse(pluginsOpts) options = parser.getOptions(ClientPluginOptions::class.java) ?: throw IllegalStateException("Unable to parse plugins options") } log.info { "Using source directory: ${options.sourceDirectory}" } // create type map val typeMap = ProtobufTypeMapper.fromProtos(request.protoFileList) log.debug { "Discovered type: $typeMap" } // create & run generator val generator = KotlinClientGenerator( when { options.fallback -> throw RuntimeException("gRPC fallback support is not implemented") else -> GRPCGenerator() }, options.asSwappableConfiguration(typeMap), DSLBuilderGenerator() ) val (sourceCode, testCode) = generator.generate(request, typeMap, options) { proto -> if (options.includeGoogleCommon) true else proto.isNotWellKnown() } // utility for creating files val writeFile = { directory: String, file: PluginProtos.CodeGeneratorResponse.File -> val f = Paths.get(directory, file.name).toFile() log.debug { "creating file: ${f.absolutePath}" } // ensure directory exists if (!f.parentFile.exists()) { f.parentFile.mkdirs() } // ensure file is empty and write data if (f.exists()) { f.delete() } f.createNewFile() f.printWriter().use { it.print(file.content) } } // write source code try { if (options.outputDirectory.isBlank()) { sourceCode.writeTo(System.out) } else { log.info { "Writing source code output to: '${options.outputDirectory}'" } sourceCode.fileList.forEach { writeFile(options.outputDirectory, it) } } // write test code if (options.testOutputDirectory.isNotBlank()) { log.info { "Writing test code output to: '${options.testOutputDirectory}'" } testCode.fileList.forEach { writeFile(options.testOutputDirectory, it) } } else { log.warn { "Test output directory not specified. Omitted generated tests." } } } catch (e: Exception) { log.error(e) { "Unable to write result" } } }
apache-2.0
d49bd2e58d34ee2883ffa4087cab85c2
34.939394
98
0.672639
4.45446
false
true
false
false
McGars/percents
common/src/main/java/com/gars/percents/data/Percent.kt
1
440
package com.gars.percents.data import java.io.Serializable /** * Created by gars on 29.12.2016. */ data class Percent ( var percent: Float = 10f, var deposit: Float = 0f, var monthAdd: Int = 0, var monthAddBreak: Int = 0, var years: Int = 1, var portion: Int = 1, var takeOff: Float = 0f, var takeOffEndMonth: Int = 0, var takeOffCount: Float = 0f ) : Serializable
apache-2.0
0f2870287f9b024f603dc275d791c927
23.5
37
0.586364
3.4375
false
false
false
false
Finnerale/FileBase
src/main/kotlin/de/leopoldluley/filebase/controller/SortCtrl.kt
1
2696
package de.leopoldluley.filebase.controller import de.leopoldluley.filebase.SortMode.* import de.leopoldluley.filebase.Utils import de.leopoldluley.filebase.models.Entry import javafx.collections.transformation.SortedList import tornadofx.* import java.time.Instant class SortCtrl : Controller() { private val settingsCtrl: SettingsCtrl by inject() private val dataCtrl: DataCtrl by inject() fun configSort(list: SortedList<Entry>) { list.setComparator(when (settingsCtrl.sortMode) { None -> null Name -> this::sortByName Type -> this::sortByType Extension-> this::sortByExtension FileSize -> this::sortByFileSize LastEdit -> this::sortByLastEdit }) } private infix fun String.comp(other: String) = if (settingsCtrl.invertSort) this < other else this > other private infix fun Long.comp(other: Long) = if (settingsCtrl.invertSort) this > other else this < other private infix fun Instant.comp(other: Instant) = if (settingsCtrl.invertSort) this > other else this < other private fun sortByName(first: Entry?, second: Entry?) = if (first == null) -1 else if (second == null) 1 else if (first.name == second.name) 0 else if (first.name comp second.name) 1 else -1 private fun sortByType(first: Entry?, second: Entry?) = if (first == null) -1 else if (second == null) 1 else if (first.type == second.type) 0 else if (first.type.localize() comp second.type.localize()) 1 else -1 private fun sortByFileSize(first: Entry?, second: Entry?): Int { if (first == null) return -1 if (second == null) return 1 val m1 = dataCtrl.getMetaData(first) val m2 = dataCtrl.getMetaData(second) return if (m1.fileSize == m2.fileSize) 0 else if (m1.fileSize comp m2.fileSize) 1 else -1 } private fun sortByExtension(first: Entry?, second: Entry?): Int { if (first == null) return -1 if (second == null) return 1 val e1 = Utils.getFileNameExtension(first.file) val e2 = Utils.getFileNameExtension(second.file) return if (e1 == e2) 0 else if (e1 comp e2) 1 else -1 } private fun sortByLastEdit(first: Entry?, second: Entry?): Int { if (first == null) return -1 if (second == null) return 1 val m1 = dataCtrl.getMetaData(first) val m2 = dataCtrl.getMetaData(second) return if (m1.lastEdit == m2.lastEdit) 0 else if (m1.lastEdit comp m2.lastEdit) 1 else -1 } }
mit
405a98d147f057cd3760a8a0f838df17
33.576923
112
0.617211
3.982275
false
false
false
false
pjq/rpi
android/app/src/main/java/me/pjq/rpicar/MyRealmMigration.kt
1
1965
package me.pjq.rpicar import io.realm.DynamicRealm import io.realm.DynamicRealmObject import io.realm.RealmMigration import io.realm.RealmObjectSchema import io.realm.RealmSchema /** * Created by i329817([email protected]) on 13/10/2017. */ class MyRealmMigration : RealmMigration { override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) { var oldVersion = oldVersion val realmSchema = realm.schema //version 0 -> version 1 if (oldVersion == DataManager.SCHEME_VERSION_0) { //add String name; val realmObjectSchema = realmSchema.get("Settings") realmObjectSchema!!.addField("name", String::class.java) oldVersion++ } if (oldVersion == DataManager.SCHEME_VERSION_1) { //Change String name -> int name; val realmObjectSchema = realmSchema.get("Settings") realmObjectSchema!!.addField("name_tmp", Int::class.javaPrimitiveType) .transform { obj -> var value = 0 try { value = Integer.valueOf(obj.getString("name"))!! } catch (e: Exception) { e.printStackTrace() } obj.setInt("name_tmp", value) } .removeField("name") .renameField("name_tmp", "name") oldVersion++ } if (oldVersion == DataManager.SCHEME_VERSION_2) { oldVersion++ } if (oldVersion == DataManager.SCHEME_VERSION_3) { oldVersion++ } } override fun hashCode(): Int { return MyRealmMigration::class.java.hashCode() } override fun equals(`object`: Any?): Boolean { return if (`object` == null) { false } else `object` is MyRealmMigration } }
apache-2.0
0ed767d4486ca78fd8eef3496243bd8f
27.897059
83
0.540967
4.781022
false
false
false
false
gotev/android-upload-service
examples/app/demoapp/src/main/java/net/gotev/uploadservicedemo/adapteritems/UploadItem.kt
2
1516
package net.gotev.uploadservicedemo.adapteritems import android.view.View import android.widget.ImageView import android.widget.TextView import net.gotev.recycleradapter.AdapterItem import net.gotev.recycleradapter.RecyclerAdapterViewHolder import net.gotev.uploadservicedemo.R class UploadItem( val type: Type, val title: String, val subtitle: String, private val delegate: Delegate ) : AdapterItem<UploadItem.Holder>(type.toString() + title + subtitle) { interface Delegate { fun onRemoveUploadItem(position: Int) } enum class Type { Header, Parameter, File } private val icons = intArrayOf( R.drawable.ic_dehaze, R.drawable.ic_code, R.drawable.ic_description ) override fun getLayoutId() = R.layout.item_upload override fun bind(firstTime: Boolean, holder: Holder) { holder.image.setImageResource(icons[type.ordinal]) holder.title.text = title holder.subtitle.text = subtitle } class Holder(itemView: View) : RecyclerAdapterViewHolder(itemView) { val title: TextView = itemView.findViewById(R.id.title) val subtitle: TextView = itemView.findViewById(R.id.subtitle) val image: ImageView = itemView.findViewById(R.id.image) init { itemView.findViewById<ImageView>(R.id.remove).setOnClickListener { (getAdapterItem() as? UploadItem)?.delegate?.onRemoveUploadItem(adapterPosition) } } } }
apache-2.0
7055141ebe5f0c66b1d876cb0c3773f7
28.72549
96
0.682058
4.458824
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/TrackerButtonStartPauseResume.kt
1
844
package ch.bailu.aat_gtk.view import ch.bailu.aat_gtk.lib.extensions.setLabel import ch.bailu.aat_lib.dispatcher.OnContentUpdatedInterface import ch.bailu.aat_lib.gpx.GpxInformation import ch.bailu.aat_lib.service.ServicesInterface import ch.bailu.gtk.gtk.Button class TrackerButtonStartPauseResume(private val services: ServicesInterface) : OnContentUpdatedInterface{ val button = Button() private var text = services.trackerService.pauseResumeText init { button.onClicked { services.trackerService.onStartPauseResume() } button.setLabel(text) } override fun onContentUpdated(iid: Int, info: GpxInformation) { val newText = services.trackerService.pauseResumeText if (text != newText) { text = newText button.setLabel(text) } } }
gpl-3.0
1439c20efbf7caf69ff86f1665f6861a
29.142857
105
0.709716
4.137255
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/extensions/links/DefaultIngestionLinksService.kt
1
814
package net.nemerosa.ontrack.extension.github.ingestion.extensions.links import net.nemerosa.ontrack.extension.github.ingestion.support.IngestionEventService import net.nemerosa.ontrack.json.asJson import org.springframework.stereotype.Service import java.util.* @Service class DefaultIngestionLinksService( private val ingestionEventService: IngestionEventService, ) : IngestionLinksService { override fun ingestLinks(input: AbstractGitHubIngestionLinksInput): UUID { val payload = input.toPayload() return ingestionEventService.sendIngestionEvent( event = IngestionLinksEventProcessor.EVENT, owner = input.owner, repository = input.repository, payload = payload.asJson(), payloadSource = payload.getSource(), ) } }
mit
b0b980acd8f82d49d43551f55fe7e3bf
36.045455
84
0.739558
4.816568
false
false
false
false
sakebook/BottomNavigationViewSample
app/src/main/java/com/sakebook/android/sample/bottomnavigationviewsample/MainAdapter.kt
1
1681
package com.sakebook.android.sample.bottomnavigationviewsample import android.content.Context import android.support.design.widget.Snackbar import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView /** * Created by sakemotoshinya on 2017/02/06. */ class MainAdapter(val context: Context, val items: List<String>): RecyclerView.Adapter<RecyclerView.ViewHolder>() { val inflater = LayoutInflater.from(context) val SMALL_VIEW_TYPE = 1 val LARGE_VIEW_TYPE = 2 override fun getItemViewType(position: Int): Int { return when(position % 2) { 1 -> SMALL_VIEW_TYPE else -> LARGE_VIEW_TYPE } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? { return when(viewType) { SMALL_VIEW_TYPE -> ViewHolder(inflater.inflate(R.layout.list_item, parent, false)) else -> ViewHolder(inflater.inflate(R.layout.list_item_large, parent, false)) }.apply { this.itemView.setOnClickListener { Snackbar.make(this.itemView, "item: $adapterPosition", Snackbar.LENGTH_SHORT).show() } } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { holder as ViewHolder holder.textView.text = items[position] } override fun getItemCount(): Int { return items.count() } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView: TextView = itemView.findViewById(R.id.text_view) as TextView } }
apache-2.0
433b23826b9f78dd95ba2daa53f367e9
31.960784
115
0.682927
4.343669
false
false
false
false
goodwinnk/intellij-community
python/src/com/jetbrains/python/packaging/pipenv/PyPipEnvPackageManager.kt
1
5015
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.packaging.pipenv import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.google.gson.annotations.SerializedName import com.intellij.execution.ExecutionException import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.jetbrains.python.packaging.PyPackage import com.jetbrains.python.packaging.PyPackageManager import com.jetbrains.python.packaging.PyRequirement import com.jetbrains.python.packaging.PyRequirementParser import com.jetbrains.python.sdk.PythonSdkType import com.jetbrains.python.sdk.associatedModule import com.jetbrains.python.sdk.baseDir import com.jetbrains.python.sdk.pipenv.pipFileLockRequirements import com.jetbrains.python.sdk.pipenv.runPipEnv import com.jetbrains.python.sdk.pythonSdk /** * @author vlan */ class PyPipEnvPackageManager(val sdk: Sdk) : PyPackageManager() { @Volatile private var packages: List<PyPackage>? = null override fun installManagement() {} override fun hasManagement() = true override fun install(requirementString: String) { install(parseRequirements(requirementString), emptyList()) } override fun install(requirements: List<PyRequirement>?, extraArgs: List<String>) { val args = listOfNotNull(listOf("install"), requirements?.flatMap { it.installOptions }, extraArgs) .flatten() try { runPipEnv(sdk, *args.toTypedArray()) } finally { sdk.associatedModule?.baseDir?.refresh(true, false) refreshAndGetPackages(true) } } override fun uninstall(packages: List<PyPackage>) { val args = listOf("uninstall") + packages.map { it.name } try { runPipEnv(sdk, *args.toTypedArray()) } finally { sdk.associatedModule?.baseDir?.refresh(true, false) refreshAndGetPackages(true) } } override fun refresh() { with(ApplicationManager.getApplication()) { invokeLater { runWriteAction { val files = sdk.rootProvider.getFiles(OrderRootType.CLASSES) VfsUtil.markDirtyAndRefresh(true, true, true, *files) } PythonSdkType.getInstance().setupSdkPaths(sdk) } } } override fun createVirtualEnv(destinationDir: String, useGlobalSite: Boolean): String { throw ExecutionException("Creating virtual environments based on Pipenv environments is not supported") } override fun getPackages() = packages override fun refreshAndGetPackages(alwaysRefresh: Boolean): List<PyPackage> { if (alwaysRefresh || packages == null) { val output = try { runPipEnv(sdk, "graph", "--json") } catch (e: ExecutionException) { packages = emptyList() throw e } packages = parsePipEnvGraph(output) } return packages ?: emptyList() } override fun getRequirements(module: Module): List<PyRequirement>? = module.pythonSdk?.pipFileLockRequirements override fun parseRequirements(text: String): List<PyRequirement> = PyRequirementParser.fromText(text) override fun parseRequirement(line: String): PyRequirement? = PyRequirementParser.fromLine(line) override fun parseRequirements(file: VirtualFile): List<PyRequirement> = PyRequirementParser.fromFile(file) override fun getDependents(pkg: PyPackage): Set<PyPackage> { // TODO: Parse the dependency information from `pipenv graph` return emptySet() } companion object { private data class GraphPackage(@SerializedName("key") var key: String, @SerializedName("package_name") var packageName: String, @SerializedName("installed_version") var installedVersion: String, @SerializedName("required_version") var requiredVersion: String?) private data class GraphEntry(@SerializedName("package") var pkg: GraphPackage, @SerializedName("dependencies") var dependencies: List<GraphPackage>) /** * Parses the output of `pipenv graph --json` into a list of packages. */ private fun parsePipEnvGraph(input: String): List<PyPackage> { val entries = try { Gson().fromJson(input, Array<GraphEntry>::class.java) } catch (e: JsonSyntaxException) { // TODO: Log errors return emptyList() } return entries .asSequence() .filterNotNull() .flatMap { sequenceOf(it.pkg) + it.dependencies.asSequence() } .map { PyPackage(it.packageName, it.installedVersion, null, emptyList()) } .distinct() .toList() } } }
apache-2.0
53080566e56660e153b63ae5766f94c0
33.833333
140
0.691725
4.5967
false
false
false
false
thatJavaNerd/JRAW
lib/src/main/kotlin/net/dean/jraw/ratelimit/FixedIntervalRefillStrategy.kt
2
1722
package net.dean.jraw.ratelimit import java.util.concurrent.TimeUnit /** * Refills a permit bucket at a fixed, configurable interval */ class FixedIntervalRefillStrategy internal constructor( /** How many permits to add to the bucket every time one `unit` goes by */ val permitsPerPeriod: Long, unit: TimeUnit, private val timeAdapter: TimeAdapter ) : RefillStrategy { /** * @param permitsPerPeriod The amount of permits issued per one unit of time * @param unit The unit of time used by [permitsPerPeriod] */ constructor(permitsPerPeriod: Long, unit: TimeUnit) : this(permitsPerPeriod, unit, SystemTimeAdapter()) private val durationNanos = unit.toNanos(permitsPerPeriod) private var lastRefillTime: Long private var nextRefillTime: Long private val lock = Any() init { val now = timeAdapter.nanoTime() lastRefillTime = now nextRefillTime = now + durationNanos } override fun refill(): Long = synchronized(lock) { val now = timeAdapter.nanoTime() if (now < nextRefillTime) return 0 // Calculate how many time periods have elapsed val numPeriods = Math.max(0, (now - lastRefillTime) / durationNanos) // Move up the last refill time by that many periods lastRefillTime += numPeriods * durationNanos // Update the next refill time to 1 time period in the future nextRefillTime = lastRefillTime + durationNanos return numPeriods * permitsPerPeriod } override fun timeUntilNextRefill(unit: TimeUnit): Long { val now = timeAdapter.nanoTime() return unit.convert(Math.max(0, nextRefillTime - now), TimeUnit.NANOSECONDS) } }
mit
0bbf3fdecfa916005c8d291a7b8ce7b0
32.115385
107
0.688153
4.46114
false
false
false
false
BlurEngine/Blur
src/main/java/com/blurengine/blur/components/cooldown/Cooldowns.kt
1
5549
/* * Copyright 2017 Ali Moghnieh * * 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.blurengine.blur.components.cooldown import com.blurengine.blur.events.players.PlayerLeaveSessionEvent import com.blurengine.blur.framework.AbstractComponent import com.blurengine.blur.framework.ModuleManager import com.blurengine.blur.framework.ticking.Tick import com.blurengine.blur.session.BlurPlayer import com.google.common.collect.HashMultimap import com.google.common.collect.Multimaps import com.google.common.collect.SetMultimap import org.bukkit.event.EventHandler import java.util.Collections class CooldownsManager(moduleManager: ModuleManager) : AbstractComponent(moduleManager) { private val _cooldowns = HashMultimap.create<BlurPlayer, CooldownEntry>() val cooldowns: SetMultimap<BlurPlayer, CooldownEntry> get() = Multimaps.unmodifiableSetMultimap(_cooldowns) operator fun get(blurPlayer: BlurPlayer): Set<CooldownEntry> = Collections.unmodifiableSet(_cooldowns[blurPlayer]) operator fun get(blurPlayer: BlurPlayer, cooldown: Cooldown<CooldownEntry>): CooldownEntry? = _cooldowns[blurPlayer].single { it.cooldown == cooldown } operator fun set(blurPlayer: BlurPlayer, cooldown: Cooldown<CooldownEntry>) = apply(blurPlayer, cooldown) fun remove(blurPlayer: BlurPlayer, cooldown: Cooldown<CooldownEntry>): Boolean { val foundEntry = _cooldowns[blurPlayer].filter { it.cooldown == cooldown }.firstOrNull() return foundEntry?.let { _cooldowns.remove(blurPlayer, it) } ?: false } fun removeAll(blurPlayer: BlurPlayer): MutableSet<CooldownEntry> = _cooldowns.removeAll(blurPlayer) fun <T : CooldownEntry> apply(blurPlayer: BlurPlayer, cooldown: Cooldown<T>): T { val ticks = cooldown.getCooldownFor(blurPlayer) val entry = cooldown.createEntry(this, blurPlayer, ticks) _cooldowns.put(blurPlayer, entry) return entry } fun <T : CooldownEntry> isOnCooldown(blurPlayer: BlurPlayer, cooldown: Cooldown<T>): Boolean { return _cooldowns.get(blurPlayer).any { it.cooldown == cooldown } } @Tick fun tick() { this._cooldowns.values().forEach { it.ticks-- } this._cooldowns.entries().filter { it.value.ticks <= 0 }.forEach { it.value.cooldown.onComplete(it.value) this._cooldowns.remove(it.key, it.value) } } @EventHandler fun onPlayerLeaveSession(event: PlayerLeaveSessionEvent) { if (isSession(event)) { this._cooldowns.removeAll(event.blurPlayer) } } } interface Cooldown<out T : CooldownEntry> { val cooldownTicks: Int fun createEntry(manager: CooldownsManager, blurPlayer: BlurPlayer, ticks: Int): T fun getCooldownFor(blurPlayer: BlurPlayer) = cooldownTicks fun tick(entry: @UnsafeVariance T) {} fun onComplete(entry: @UnsafeVariance T) {} } interface BasicCooldown : Cooldown<CooldownEntry> { override fun createEntry(manager: CooldownsManager, blurPlayer: BlurPlayer, ticks: Int) = CooldownEntry(manager, this, blurPlayer, ticks) } open class CooldownEntry(val manager: CooldownsManager, val cooldown: Cooldown<CooldownEntry>, val blurPlayer: BlurPlayer, ticks: Int) { internal var _ticks = ticks open var ticks: Int get() = _ticks set(value) { _ticks = value cooldown.tick(this) } } interface ExpCooldown : Cooldown<ExpCooldownEntry> { override fun createEntry(manager: CooldownsManager, blurPlayer: BlurPlayer, ticks: Int) = ExpCooldownEntry(manager, this, blurPlayer, ticks) override fun tick(entry: ExpCooldownEntry) { super.tick(entry) if (!entry.active) return val exp: Float if (!entry.increment) { exp = Math.min(entry.ticks * entry.incrementation, 1f) } else { exp = Math.max((entry.maxTicks - entry.ticks) * entry.incrementation, 0f) } entry.blurPlayer.player.exp = exp } } class ExpCooldownEntry(manager: CooldownsManager, cooldown: Cooldown<ExpCooldownEntry>, blurPlayer: BlurPlayer, ticks: Int) : CooldownEntry(manager, cooldown, blurPlayer, ticks) { var increment: Boolean = false var incrementation: Float = 1.0f / ticks private set var maxTicks: Int = ticks set(value) { field = value incrementation = 1.0f / ticks } override var ticks: Int get() = super.ticks set(value) { super.ticks = value if (maxTicks < ticks) { maxTicks = ticks } } private var _active: Boolean = false var active: Boolean get() = _active set(value) { // Deactivate all other ExpCooldownEntry for (entry in manager.cooldowns.values().filterIsInstance<ExpCooldownEntry>().filter { it != this && it.blurPlayer == blurPlayer}) { entry._active = false } _active = value } }
apache-2.0
371502fc8cf4cc03904fa34bac7dd837
34.8
155
0.682285
4.092183
false
false
false
false
cashapp/sqldelight
dialects/sqlite-3-18/src/main/kotlin/app/cash/sqldelight/dialects/sqlite_3_18/SqliteDialect.kt
1
2492
package app.cash.sqldelight.dialects.sqlite_3_18 import app.cash.sqldelight.dialect.api.SqlDelightDialect import app.cash.sqldelight.dialect.api.TypeResolver import app.cash.sqldelight.dialects.sqlite_3_18.grammar.SqliteParserUtil import app.cash.sqldelight.dialects.sqlite_3_18.grammar.mixins.ColumnDefMixin import app.cash.sqldelight.dialects.sqlite_3_18.grammar.mixins.StatementValidatorMixin import app.cash.sqldelight.dialects.sqlite_3_18.grammar.psi.SqliteTypes import com.alecstrong.sql.psi.core.SqlParserUtil import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.icons.AllIcons import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.PluginId import com.intellij.psi.stubs.StubElementTypeHolderEP import timber.log.Timber /** * A dialect for SQLite. */ open class SqliteDialect : SqlDelightDialect { override val isSqlite = true override val icon = AllIcons.Providers.Sqlite override val migrationStrategy = SqliteMigrationStrategy() override val connectionManager = SqliteConnectionManager() override fun setup() { Timber.i("Setting up SQLite Dialect") SqlParserUtil.reset() registerTypeHolder() SqliteParserUtil.reset() SqliteParserUtil.overrideSqlParser() val currentElementCreation = SqliteParserUtil.createElement SqliteParserUtil.createElement = { when (it.elementType) { SqlTypes.COLUMN_DEF -> ColumnDefMixin(it) SqlTypes.STMT -> StatementValidatorMixin(it) else -> currentElementCreation(it) } } } private fun registerTypeHolder() { ApplicationManager.getApplication()?.apply { if (extensionArea.hasExtensionPoint(StubElementTypeHolderEP.EP_NAME)) { val exPoint = extensionArea.getExtensionPoint(StubElementTypeHolderEP.EP_NAME) if (!exPoint.extensions().anyMatch { it.holderClass == SqliteTypes::class.java.name }) { Timber.i("Registering Stub extension point") exPoint.registerExtension( StubElementTypeHolderEP().apply { holderClass = SqliteTypes::class.java.name }, PluginManagerCore.getPlugin(PluginId.getId("com.squareup.sqldelight"))!!, this, ) Timber.i("Registered Stub extension point") } } } } override fun typeResolver(parentResolver: TypeResolver): TypeResolver { return SqliteTypeResolver(parentResolver) } }
apache-2.0
630f78e26bac0cb8a78ea1443004174f
35.647059
96
0.744382
4.498195
false
false
false
false
pyamsoft/pasterino
app/src/main/java/com/pyamsoft/pasterino/main/PasterinoNavigator.kt
1
2014
/* * Copyright 2021 Peter Kenji Yamanaka * * 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.pyamsoft.pasterino.main import android.os.Bundle import androidx.annotation.IdRes import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import com.pyamsoft.pasterino.settings.AppSettings import com.pyamsoft.pydroid.ui.navigator.FragmentNavigator import com.pyamsoft.pydroid.ui.navigator.Navigator import javax.inject.Inject class PasterinoNavigator @Inject internal constructor( activity: FragmentActivity, @IdRes fragmentContainerId: Int, ) : FragmentNavigator<Unit>(activity, fragmentContainerId) { override val defaultScreen: Navigator.Screen<Unit> = DEFAULT_SCREEN override fun performFragmentTransaction( container: Int, data: FragmentTag, newScreen: Navigator.Screen<Unit>, previousScreen: Unit?, ) { commitNow { replace(container, data.fragment(newScreen.arguments), data.tag) } } override fun provideFragmentTagMap(): Map<Unit, FragmentTag> { return mapOf(Unit to FRAGMENT_TAG) } companion object { private val FRAGMENT_TAG = object : FragmentTag { override val fragment: (arguments: Bundle?) -> Fragment = { AppSettings.newInstance() } override val tag: String = AppSettings.TAG } val DEFAULT_SCREEN = object : Navigator.Screen<Unit> { override val arguments: Bundle? = null override val screen: Unit = Unit } } }
apache-2.0
15f217548c09ece05ae9c20f621e118f
30.46875
97
0.727905
4.3878
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/statuses/PublicTimelineFragment.kt
1
2514
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment.statuses import android.content.Context import android.os.Bundle import android.support.v4.content.Loader import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.fragment.ParcelableStatusesFragment import de.vanita5.twittnuker.loader.statuses.PublicTimelineLoader import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.util.Utils import java.util.* class PublicTimelineFragment : ParcelableStatusesFragment() { override val savedStatusesFileArgs: Array<String>? get() { val accountKey = Utils.getAccountKey(context, arguments) val result = ArrayList<String>() result.add(AUTHORITY_PUBLIC_TIMELINE) result.add("account=$accountKey") return result.toTypedArray() } override val readPositionTagWithArguments: String? get() { val tabPosition = arguments.getInt(EXTRA_TAB_POSITION, -1) if (tabPosition < 0) return null return "public_timeline" } override fun onCreateStatusesLoader(context: Context, args: Bundle, fromUser: Boolean): Loader<List<ParcelableStatus>?> { refreshing = true val data = adapterData val accountKey = Utils.getAccountKey(context, args) val tabPosition = args.getInt(EXTRA_TAB_POSITION, -1) val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false) return PublicTimelineLoader(context, accountKey, data, savedStatusesFileArgs, tabPosition, fromUser, loadingMore) } }
gpl-3.0
e17ecbb70b12603e2c2cdf11155f5f17
38.920635
98
0.709626
4.465364
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/dataclient/mwapi/EditorTaskCounts.kt
1
3990
package org.wikipedia.dataclient.mwapi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.decodeFromJsonElement import org.wikipedia.json.JsonUtil import org.wikipedia.settings.Prefs @Serializable class EditorTaskCounts { @SerialName("revert_counts") private val revertCounts: JsonElement? = null @SerialName("edit_streak") private val editStreak: JsonElement? = null private val counts: JsonElement? = null private val descriptionEditsPerLanguage: Map<String, Int> get() { var editsPerLanguage: Map<String, Int>? = null if (counts != null && counts !is JsonArray) { editsPerLanguage = JsonUtil.json.decodeFromJsonElement<Counts>(counts).appDescriptionEdits } return editsPerLanguage ?: emptyMap() } private val captionEditsPerLanguage: Map<String, Int> get() { var editsPerLanguage: Map<String, Int>? = null if (counts != null && counts !is JsonArray) { editsPerLanguage = JsonUtil.json.decodeFromJsonElement<Counts>(counts).appCaptionEdits } return editsPerLanguage ?: emptyMap() } private val descriptionRevertsPerLanguage: Map<String, Int> get() { var revertsPerLanguage: Map<String, Int>? = null if (revertCounts != null && revertCounts !is JsonArray) { revertsPerLanguage = JsonUtil.json.decodeFromJsonElement<Counts>(revertCounts).appDescriptionEdits } return revertsPerLanguage ?: emptyMap() } private val captionRevertsPerLanguage: Map<String, Int> get() { var revertsPerLanguage: Map<String, Int>? = null if (revertCounts != null && revertCounts !is JsonArray) { revertsPerLanguage = JsonUtil.json.decodeFromJsonElement<Counts>(revertCounts).appCaptionEdits } return revertsPerLanguage ?: emptyMap() } private val totalDepictsReverts: Int get() { var revertsPerLanguage: Map<String, Int>? = null if (revertCounts != null && revertCounts !is JsonArray) { revertsPerLanguage = JsonUtil.json.decodeFromJsonElement<Counts>(revertCounts).appDepictsEdits } return revertsPerLanguage?.get("*") ?: 0 } val totalDepictsEdits: Int get() { var editsPerLanguage: Map<String, Int>? = null if (counts != null && counts !is JsonArray) { editsPerLanguage = JsonUtil.json.decodeFromJsonElement<Counts>(counts).appDepictsEdits } return editsPerLanguage?.get("*") ?: 0 } val totalEdits: Int get() { return if (Prefs.shouldOverrideSuggestedEditCounts()) { Prefs.overrideSuggestedEditCount } else { descriptionEditsPerLanguage.values.sum() + captionEditsPerLanguage.values.sum() + totalDepictsEdits } } val totalDescriptionEdits: Int get() = descriptionEditsPerLanguage.values.sum() val totalImageCaptionEdits: Int get() = captionEditsPerLanguage.values.sum() val totalReverts: Int get() { return if (Prefs.shouldOverrideSuggestedEditCounts()) { Prefs.overrideSuggestedRevertCount } else { descriptionRevertsPerLanguage.values.sum() + captionRevertsPerLanguage.values.sum() + totalDepictsReverts } } @Serializable class Counts { @SerialName("app_description_edits") val appDescriptionEdits: Map<String, Int>? = null @SerialName("app_caption_edits") val appCaptionEdits: Map<String, Int>? = null @SerialName("app_depicts_edits") val appDepictsEdits: Map<String, Int>? = null } }
apache-2.0
9bb7196214d5f062d4e8a44d5399f07d
37.365385
121
0.639599
4.784173
false
false
false
false
stripe/stripe-android
link/src/main/java/com/stripe/android/link/ui/wallet/ConfirmRemoveDialog.kt
1
1720
package com.stripe.android.link.ui.wallet import androidx.compose.material.AlertDialog import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import com.stripe.android.link.R import com.stripe.android.link.model.removeConfirmation import com.stripe.android.link.theme.linkColors import com.stripe.android.model.ConsumerPaymentDetails @Composable internal fun ConfirmRemoveDialog( paymentDetails: ConsumerPaymentDetails.PaymentDetails, showDialog: Boolean, onDialogDismissed: (Boolean) -> Unit ) { if (showDialog) { AlertDialog( onDismissRequest = { onDialogDismissed(false) }, confirmButton = { TextButton( onClick = { onDialogDismissed(true) } ) { Text( text = stringResource(R.string.remove), color = MaterialTheme.linkColors.actionLabel ) } }, dismissButton = { TextButton( onClick = { onDialogDismissed(false) } ) { Text( text = stringResource(R.string.cancel), color = MaterialTheme.linkColors.actionLabel ) } }, text = { Text(stringResource(paymentDetails.removeConfirmation)) } ) } }
mit
db5d8a9885e40ba417a9c7d3a8e58ca8
30.851852
71
0.543023
5.639344
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/PlaceholderTest.kt
3
17531
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.Dp import org.junit.Rule import org.junit.Test import com.google.common.truth.Truth.assertThat import kotlin.math.max class PlaceholderTest { @get:Rule val rule = createComposeRule() @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalWearMaterialApi::class) @Test fun placeholder_initially_show_content() { var contentReady = true lateinit var placeholderState: PlaceholderState rule.setContentWithTheme { placeholderState = rememberPlaceholderState { contentReady } Chip( modifier = Modifier .testTag("test-item") .fillMaxWidth(), content = {}, onClick = {}, colors = ChipDefaults.secondaryChipColors(), border = ChipDefaults.chipBorder() ) } // For testing we need to manually manage the frame clock for the placeholder animation placeholderState.initializeTestFrameMillis(PlaceholderStage.ShowContent) // Advance placeholder clock without changing the content ready and confirm still in // ShowPlaceholder placeholderState.advanceToNextPlaceholderAnimationLoopAndCheckStage( PlaceholderStage.ShowContent ) contentReady = false // Check that the state does not go to ShowPlaceholder placeholderState.advanceToNextPlaceholderAnimationLoopAndCheckStage( PlaceholderStage.ShowContent ) } @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalWearMaterialApi::class) @Test fun placeholder_initially_show_placeholder_transitions_correctly() { var contentReady = false lateinit var placeholderState: PlaceholderState rule.setContentWithTheme { placeholderState = rememberPlaceholderState { contentReady } Chip( modifier = Modifier .testTag("test-item") .fillMaxWidth(), content = {}, onClick = {}, colors = ChipDefaults.secondaryChipColors(), border = ChipDefaults.chipBorder() ) } // For testing we need to manually manage the frame clock for the placeholder animation placeholderState.initializeTestFrameMillis() // Advance placeholder clock without changing the content ready and confirm still in // ShowPlaceholder placeholderState.advanceFrameMillisAndCheckState( PLACEHOLDER_GAP_BETWEEN_ANIMATION_LOOPS_MS, PlaceholderStage.ShowPlaceholder) // Change contentReady and confirm that state is still ShowPlaceholder contentReady = true placeholderState.advanceFrameMillisAndCheckState( 0L, PlaceholderStage.ShowPlaceholder ) // Advance the clock by one cycle and check we have moved to WipeOff placeholderState.advanceFrameMillisAndCheckState( PLACEHOLDER_GAP_BETWEEN_ANIMATION_LOOPS_MS, PlaceholderStage.WipeOff ) // Advance the clock by one cycle and check we have moved to ShowContent placeholderState.advanceFrameMillisAndCheckState( PLACEHOLDER_GAP_BETWEEN_ANIMATION_LOOPS_MS, PlaceholderStage.ShowContent ) } @RequiresApi(Build.VERSION_CODES.O) @Test fun default_placeholder_is_correct_color() { placeholder_is_correct_color(null) } @RequiresApi(Build.VERSION_CODES.O) @Test fun custom_placeholder_is_correct_color() { placeholder_is_correct_color(Color.Blue) } @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalWearMaterialApi::class) fun placeholder_is_correct_color(placeholderColor: Color?) { var expectedPlaceholderColor = Color.Transparent var expectedBackgroundColor = Color.Transparent var contentReady = false lateinit var placeholderState: PlaceholderState rule.setContentWithTheme { placeholderState = rememberPlaceholderState { contentReady } expectedPlaceholderColor = placeholderColor ?: MaterialTheme.colors.onSurface.copy(alpha = 0.1f) .compositeOver(MaterialTheme.colors.surface) expectedBackgroundColor = MaterialTheme.colors.primary Chip( modifier = Modifier .testTag("test-item") .then( if (placeholderColor != null) Modifier.placeholder( placeholderState = placeholderState, color = placeholderColor ) else Modifier.placeholder(placeholderState = placeholderState) ), content = {}, onClick = {}, colors = ChipDefaults.primaryChipColors(), border = ChipDefaults.chipBorder() ) } // For testing we need to manually manage the frame clock for the placeholder animation placeholderState.initializeTestFrameMillis() rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor( expectedPlaceholderColor ) contentReady = true // Advance the clock to the next placeholder animation loop and check for wipe-off mode placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.WipeOff) // Advance the clock to the next placeholder animation loop and check for show content mode placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.ShowContent) rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor( expectedBackgroundColor ) } @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalWearMaterialApi::class) @Test fun placeholder_shimmer_visible_during_showplaceholder_only() { var expectedBackgroundColor = Color.Transparent var contentReady = false lateinit var placeholderState: PlaceholderState var expectedShimmerColor = Color.Transparent rule.setContentWithTheme { placeholderState = rememberPlaceholderState { contentReady } expectedBackgroundColor = MaterialTheme.colors.surface expectedShimmerColor = MaterialTheme.colors.onSurface.copy(0.13f) .compositeOver(expectedBackgroundColor) Chip( modifier = Modifier .testTag("test-item") .fillMaxWidth() .placeholderShimmer(placeholderState = placeholderState), content = {}, onClick = {}, colors = ChipDefaults.secondaryChipColors(), border = ChipDefaults.chipBorder() ) } placeholderState.initializeTestFrameMillis() // Check the background color is correct rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor( expectedBackgroundColor, 80f ) // Check that there is no shimmer color rule.onNodeWithTag("test-item") .captureToImage() .assertDoesNotContainColor( expectedShimmerColor ) // Move the start of the next placeholder animation loop and them advance the clock 267 // milliseconds (PLACEHOLDER_PROGRESSION_DURATION_MS / 3) to show the shimmer. placeholderState.moveToStartOfNextAnimationLoop() placeholderState.advanceFrameMillisAndCheckState( PLACEHOLDER_PROGRESSION_DURATION_MS / 3, PlaceholderStage.ShowPlaceholder ) // The placeholder shimmer effect is faint and largely transparent gradiant, so we are // looking for a very small amount to be visible. rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor( expectedShimmerColor, 1f ) // Prepare to start to wipe off and show contents. contentReady = true placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.WipeOff) // Check that the shimmer is no longer visible rule.onNodeWithTag("test-item") .captureToImage() .assertDoesNotContainColor( expectedShimmerColor ) placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.ShowContent) // Check that the shimmer is no longer visible rule.onNodeWithTag("test-item") .captureToImage() .assertDoesNotContainColor( expectedShimmerColor ) } @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalWearMaterialApi::class) @Test fun wipeoff_takes_background_offset_into_account() { var contentReady = false lateinit var placeholderState: PlaceholderState var expectedBackgroundColor = Color.Transparent var expectedBackgroundPlaceholderColor: Color = Color.Transparent rule.setContentWithTheme { placeholderState = rememberPlaceholderState { contentReady } val maxScreenDimensionPx = with(LocalDensity.current) { Dp(max(screenHeightDp(), screenWidthDp()).toFloat()).toPx() } // Set the offset to be 50% of the screen placeholderState.backgroundOffset = Offset(maxScreenDimensionPx / 2f, maxScreenDimensionPx / 2f) expectedBackgroundColor = MaterialTheme.colors.primary expectedBackgroundPlaceholderColor = MaterialTheme.colors.surface Chip( modifier = Modifier .testTag("test-item") .fillMaxWidth(), content = {}, onClick = {}, colors = PlaceholderDefaults.placeholderChipColors( originalChipColors = ChipDefaults.primaryChipColors(), placeholderState = placeholderState, ), border = ChipDefaults.chipBorder() ) } placeholderState.initializeTestFrameMillis() // Check the background color is correct rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor(expectedBackgroundPlaceholderColor, 80f) // Check that there is primary color showing rule.onNodeWithTag("test-item") .captureToImage() .assertDoesNotContainColor( expectedBackgroundColor ) // Prepare to start to wipe off and show contents. contentReady = true placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.WipeOff) // Check that placeholder background is still visible rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor(expectedBackgroundPlaceholderColor, 80f) // Move forward by 25% of the wipe-off and confirm that no wipe-off has happened yet due // to our offset placeholderState.advanceFrameMillisAndCheckState( PLACEHOLDER_WIPE_OFF_PROGRESSION_DURATION_MS / 4, PlaceholderStage.WipeOff ) // Check that placeholder background is still visible rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor(expectedBackgroundPlaceholderColor, 80f) // Now move the end of the wipe-off and confirm that the proper chip background is visible placeholderState.advanceFrameMillisAndCheckState( PLACEHOLDER_PROGRESSION_DURATION_MS - (PLACEHOLDER_PROGRESSION_DURATION_MS / 4), PlaceholderStage.WipeOff ) // Check that normal chip background is now visible rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor(expectedBackgroundColor, 80f) } @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalWearMaterialApi::class) @Test fun placeholder_background_is_correct_color() { var expectedPlaceholderBackgroundColor = Color.Transparent var expectedBackgroundColor = Color.Transparent var contentReady = false lateinit var placeholderState: PlaceholderState rule.setContentWithTheme { placeholderState = rememberPlaceholderState { contentReady } expectedPlaceholderBackgroundColor = MaterialTheme.colors.surface expectedBackgroundColor = MaterialTheme.colors.primary Chip( modifier = Modifier .testTag("test-item"), content = {}, onClick = {}, colors = PlaceholderDefaults.placeholderChipColors( originalChipColors = ChipDefaults.primaryChipColors(), placeholderState = placeholderState, ), border = ChipDefaults.chipBorder() ) LaunchedEffect(placeholderState) { placeholderState.startPlaceholderAnimation() } } placeholderState.initializeTestFrameMillis() rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor( expectedPlaceholderBackgroundColor ) contentReady = true // Advance the clock to the next placeholder animation loop to move into wipe-off mode placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.WipeOff) // Advance the clock to the next placeholder animation loop to move into show content mode placeholderState .advanceToNextPlaceholderAnimationLoopAndCheckStage(PlaceholderStage.ShowContent) rule.onNodeWithTag("test-item") .captureToImage() .assertContainsColor( expectedBackgroundColor ) } @OptIn(ExperimentalWearMaterialApi::class) private fun PlaceholderState.advanceFrameMillisAndCheckState( timeToAdd: Long, expectedStage: PlaceholderStage ) { frameMillis.value += timeToAdd rule.waitForIdle() assertThat(placeholderStage).isEqualTo(expectedStage) } @OptIn(ExperimentalWearMaterialApi::class) private fun PlaceholderState.advanceToNextPlaceholderAnimationLoopAndCheckStage( expectedStage: PlaceholderStage ) { frameMillis.value += PLACEHOLDER_GAP_BETWEEN_ANIMATION_LOOPS_MS rule.waitForIdle() assertThat(placeholderStage).isEqualTo(expectedStage) } @OptIn(ExperimentalWearMaterialApi::class) private fun PlaceholderState.initializeTestFrameMillis( initialPlaceholderStage: PlaceholderStage = PlaceholderStage.ShowPlaceholder ): Long { val currentTime = rule.mainClock.currentTime frameMillis.value = currentTime rule.waitForIdle() assertThat(placeholderStage).isEqualTo(initialPlaceholderStage) return currentTime } @OptIn(ExperimentalWearMaterialApi::class) private fun PlaceholderState.moveToStartOfNextAnimationLoop( expectedPlaceholderStage: PlaceholderStage = PlaceholderStage.ShowPlaceholder ) { val animationLoopStart = (frameMillis.value.div(PLACEHOLDER_GAP_BETWEEN_ANIMATION_LOOPS_MS) + 1) * PLACEHOLDER_GAP_BETWEEN_ANIMATION_LOOPS_MS frameMillis.value = animationLoopStart rule.waitForIdle() assertThat(placeholderStage).isEqualTo(expectedPlaceholderStage) } }
apache-2.0
f415a5730e6e73cad8fb6262818a7275
36.784483
99
0.640523
5.627929
false
true
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/rest/patch/src/main/kotlin/org/tsdes/advanced/rest/patch/CounterRest.kt
1
9871
package org.tsdes.advanced.rest.patch import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiParam import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.net.URI import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong /** * Created by arcuri82 on 20-Jul-17. */ @Api("Handle named, numeric counters") @RequestMapping(path = ["/patch/api/counters"]) @RestController class CounterRest { /** * Used to create unique ids. * Note the fact that this is atomic to avoid * concurrency issues if serving 2 HTTP requests * at same time in different threads */ private val idGenerator = AtomicLong(0) /** * Map for the dtos, where the key is the dto.id */ private val map: MutableMap<Long, CounterDto> = ConcurrentHashMap() /* WARNING: the above is "internal" state of the API. Usually, this is a "a bad thing", and should be avoided. But here we have it just to make the example simpler, so do not have to deal with databases. We ll go back to this point when we will speak of "scaling horizontally" in microservices. */ @ApiOperation("Create a new counter") @PostMapping(consumes = [(MediaType.APPLICATION_JSON_VALUE)]) fun create(@RequestBody dto: CounterDto): ResponseEntity<Void> { if (dto.id == null) { dto.id = idGenerator.getAndIncrement() } else if (map.containsKey(dto.id!!)) { //Should not create a new counter with id that already exists return ResponseEntity.status(400).build() } if (dto.value == null) { dto.value = 0 } map.put(dto.id!!, dto) /* here created will set the "Location" header, by specifying the URI of where we can GET it from. A relative (ie not absolute) URI will resolve against the URI of the request, eg "http://localhost:8080". Note that the response here has no body. The return status of "created()" is 201 */ return ResponseEntity.created(URI.create("/patch/api/counters/" + dto.id)).build() } @ApiOperation("Get all the existing counters") @GetMapping(produces = [(MediaType.APPLICATION_JSON_VALUE)]) fun getAll(): Collection<CounterDto> { return map.values } @ApiOperation("Return the counter with the given id") @GetMapping(path = ["/{id}"], produces = [(MediaType.APPLICATION_JSON_VALUE)]) fun getById( @ApiParam("The unique id of the counter") @PathVariable("id") id: Long): ResponseEntity<CounterDto> { val dto = map[id] ?: return ResponseEntity.status(404).build() // No counter with id exists return ResponseEntity.ok(dto) } /* A PUT does completely replace the resource with a new one */ @ApiOperation("Replace a counter") @PutMapping(path = ["/{id}"], consumes = [(MediaType.APPLICATION_JSON_VALUE)]) fun update(@ApiParam("The unique id of the counter") @PathVariable("id") id: Long, // @ApiParam("The new state of the resource") @RequestBody dto: CounterDto): ResponseEntity<Void> { if (dto.id != id) { //Should not have inconsistent id return ResponseEntity.status(409).build() } if (dto.value == null) { dto.value = 0 } /* Note: here we are allowing PUT to create a new resource Here, I am allowing creating resources with PUT. Using 201 (created) to mark this event instead of a generic 204 (OK, but no content to return). Also note that this code leads to a BUG, as IDs could clash with the ones used afterwards when we create a new resource with POST, ie we must guarantee that POST will pick unused ids. */ val code = if (map.containsKey(id)) 204 else 201 map.put(id, dto) return ResponseEntity.status(code).build() } /* A PATCH does a partial update of a resource. However, there is no strict rule on how the resource should be updated. The client has to send "instructions" in a format that the server can recognize and execute. Can also be a custom format, like in this case. */ @ApiOperation("Modify the counter based on the instructions in the request body") @PatchMapping(path = ["/{id}"], // could have had a custom type here, but then would need an unmarshaller for it consumes = [(MediaType.TEXT_PLAIN_VALUE)]) fun patch(@ApiParam("The unique id of the counter") @PathVariable("id") id: Long, // @ApiParam("The instructions on how to modify the counter. " + "In this specific case, it should be a single numeric value " + "representing a delta that " + "will be applied on the counter value") @RequestBody text: String) : ResponseEntity<Void> { val dto = map[id] ?: return ResponseEntity.status(404).build() val delta = try { text.toInt() } catch (e: NumberFormatException) { //Invalid instructions. Should contain just a number return ResponseEntity.status(400).build() } dto.value = dto.value!! + delta return ResponseEntity.status(204).build() } /* When dealing with resources that can be expressed/modelled with JSON, there are two main formats for instructions: - (1) JSON Patch - (2) JSON Merge Patch (1) provide a list of operations (eg, add, remove, move, test). It is more expressive than (2), but at the same time more complicated to handle. (2) is just sending a subset of the JSON, and each of specified changes will be applied, ie overwritten. The only tricky thing to keep in mind is the handling of "null" values. Missing/unspecified elements will be ignored, whereas elements with null will get null. For example, if you have: {"A":... , "B":...} as JSON resource, and you get a patch with: {"B":null}, then A will not be modified, whereas B will be removed, ie results of the resource would be: {"A":...} without the B. Note: in JSON there is a difference between a missing element and and an element with null, ie {"A":...} and {"A":... , "B":null} are technically not the same. However, as we will deal with Kotlin objects, we can safely "ignore" this distinction in our model: ie make no difference between a missing element and an element with null value. The only catch is in the parsing of the PATCH JSON Merge objects. We CANNOT unmarshal it to a DTO, as we would have no way to distinguish between missing elements and actual null values. */ @ApiOperation("Modify the counter using JSON Merge Patch") @PatchMapping(path = ["/{id}"], consumes = ["application/merge-patch+json"]) fun mergePatch(@ApiParam("The unique id of the counter") @PathVariable("id") id: Long?, @ApiParam("The partial patch") @RequestBody jsonPatch: String) : ResponseEntity<Void> { val dto = map[id] ?: return ResponseEntity.status(404).build() val jackson = ObjectMapper() val jsonNode: JsonNode try { jsonNode = jackson.readValue(jsonPatch, JsonNode::class.java) } catch (e: Exception) { //Invalid JSON data as input return ResponseEntity.status(400).build() } if (jsonNode.has("id")) { //shouldn't be allowed to modify the counter id return ResponseEntity.status(409).build() } //do not alter dto till all data is validated. A PATCH has to be atomic, //either all modifications are done, or none. var newName = dto.name var newValue = dto.value if (jsonNode.has("name")) { val nameNode = jsonNode.get("name") if (nameNode.isNull) { newName = null } else if (nameNode.isTextual) { newName = nameNode.asText() } else { //Invalid JSON. Non-string name return ResponseEntity.status(400).build() } //Doing this here would be wrong!!! //eg, what happened if "value" parsing fail? we ll have side-effects // //dto.name = newName; } if (jsonNode.has("value")) { val valueNode = jsonNode.get("value") if (valueNode.isNull) { newValue = 0 } else if (valueNode.isNumber) { //note: if this is not numeric, it silently returns 0... newValue = valueNode.intValue() } else { //Invalid JSON. Non-numeric value return ResponseEntity.status(400).build() } } //now that the input is validated, do the update dto.name = newName dto.value = newValue return ResponseEntity.status(204).build() } }
lgpl-3.0
bd6bf2a674caa4ace7dd5e561d6bc8a0
33.638596
117
0.588795
4.704957
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/guide/__IntroductionFragment.kt
1
9608
package com.exyui.android.debugbottle.components.guide import android.Manifest import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.support.annotation.IdRes import android.support.v4.app.ActivityCompat import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v7.widget.AppCompatCheckBox import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.exyui.android.debugbottle.components.R import com.exyui.android.debugbottle.components.DTSettings /** * Created by yuriel on 9/10/16. */ class __IntroductionFragment: Fragment() { companion object { private val BACKGROUND_COLOR = "backgroundColor" private val PAGE = "page" fun newInstance(backgroundColor: Int, page: Int): __IntroductionFragment { val result = __IntroductionFragment() val b = Bundle() b.putInt(BACKGROUND_COLOR, backgroundColor) b.putInt(PAGE, page) result.arguments = b return result } private val binder1 = object: ViewBinder() { override val layoutRes: Int = R.layout.__fragment_intro_1 override val titleRes: Int = R.string.__dt_intro_title_welcome override val iconAppAlpha: Float = 0f override val iconArrowAlpha: Float = 0f override val iconBottleAlpha: Float = 1f override val textAlpha: Float = 1f override val done = false override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) { } } private val binder2 = object: ViewBinder() { override val layoutRes: Int = R.layout.__fragment_intro_2 override val titleRes: Int = R.string.__dt_intro_title_check_permission override val iconAppAlpha: Float = 1f override val iconArrowAlpha: Float = 1f override val iconBottleAlpha: Float = 1f override val textAlpha: Float = -1f override val done = false internal val permissions = listOf( /*Manifest.permission.SYSTEM_ALERT_WINDOW,*/ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE ) override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) { checkPermission() } override fun updatePermission() { checkPermission() } fun checkPermission(): Boolean { val storage = v(R.id.__dt_write_external_storage) as ImageView val phoneState = v(R.id.__dt_read_phone_state) as ImageView val submit = v(R.id.__dt_request_permission) as TextView var result: Boolean = true if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { storage.setImageResource(R.drawable.__ic_check_circle_white_24dp) } else { storage.setImageResource(R.drawable.__ic_security_white_24dp) result = false } if (hasPermission(Manifest.permission.READ_PHONE_STATE)) { phoneState.setImageResource(R.drawable.__ic_check_circle_white_24dp) } else { phoneState.setImageResource(R.drawable.__ic_security_white_24dp) result = false } if (!result) { submit.setText(R.string.__dt_intro_request_permissions) submit.setOnClickListener { requestPermission() } } else { submit.setText(R.string.__dt_intro_permission_done) submit.setOnClickListener { } } return result } private fun hasPermission(permission: String) = PackageManager.PERMISSION_DENIED != ContextCompat.checkSelfPermission(context!!, permission) private fun requestPermission() { context?: return for (p in permissions) { // Here, thisActivity is the current activity if (ContextCompat.checkSelfPermission(context!!, p) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(context as Activity, arrayOf(p), 1) } } } } private val binder3 = object: ViewBinder() { override val layoutRes: Int = R.layout.__fragment_intro_3 override val titleRes: Int = R.string.__dt_intro_title_enable_features override val iconAppAlpha: Float = 1f override val iconArrowAlpha: Float = 1f override val iconBottleAlpha: Float = 1f override val textAlpha: Float = -1f override val done = false override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) { val bottle = v(R.id.__dt_enable_bottle) as AppCompatCheckBox val strict = v(R.id.__dt_enable_strict_mode) as AppCompatCheckBox val leak = v(R.id.__dt_enable_leak_canary) as AppCompatCheckBox val block = v(R.id.__dt_enable_block_canary) as AppCompatCheckBox val sniffer = v(R.id.__dt_enable_http_sniffer) as AppCompatCheckBox bottle.setOnCheckedChangeListener { compoundButton, b -> DTSettings.bottleEnable = b } strict.setOnCheckedChangeListener { compoundButton, b -> DTSettings.strictMode = b } leak.setOnCheckedChangeListener { compoundButton, b -> DTSettings.leakCanaryEnable = b } block.setOnCheckedChangeListener { compoundButton, b -> DTSettings.blockCanaryEnable = b } sniffer.setOnCheckedChangeListener { compoundButton, b -> DTSettings.networkSniff = b } } } private val binder4 = object: ViewBinder() { override val layoutRes: Int = R.layout.__fragment_intro_4 override val titleRes: Int = R.string.__dt_intro_title_done override val iconAppAlpha: Float = 1f override val iconArrowAlpha: Float = 0.3f override val iconBottleAlpha: Float = 0.3f override val textAlpha: Float = -1f override val done = true override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) { } } } private var backgroundColor: Int? = null private var page: Int? = null private val binder by lazy { when (page) { 0 -> binder1 1 -> binder2 2 -> binder3 3 -> binder4 else -> throw NotImplementedError("Fragment must contain a \"$PAGE\" argument!") } } @Throws(RuntimeException::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!arguments.containsKey(BACKGROUND_COLOR)) throw RuntimeException("Fragment must contain a \"$BACKGROUND_COLOR\" argument!") backgroundColor = arguments.getInt(BACKGROUND_COLOR) if (!arguments.containsKey(PAGE)) throw RuntimeException("Fragment must contain a \"$PAGE\" argument!") page = arguments.getInt(PAGE) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = binder.getView(inflater, container, savedInstanceState) view?.tag = FragmentPageTag(page!!, getColor(), binder.iconAppAlpha, binder.iconArrowAlpha, binder.iconBottleAlpha, binder.textAlpha, binder.done) return view } override fun onResume() { super.onResume() updatePermission() } override fun onDestroyView() { super.onDestroyView() binder.release() } fun getColor() = backgroundColor!! fun updatePermission() { binder.updatePermission() } private abstract class ViewBinder { var rootView: View? = null val context: Context? get() = rootView?.context abstract val layoutRes: Int abstract val titleRes: Int abstract val iconAppAlpha: Float abstract val iconArrowAlpha: Float abstract val iconBottleAlpha: Float abstract val textAlpha: Float abstract val done: Boolean abstract fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) open fun release() { rootView = null } fun v(@IdRes id: Int): View? = rootView?.findViewById(id) fun getView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(layoutRes, container, false) (v(R.id.__dt_title) as TextView).setText(titleRes) createView(inflater, container, savedInstanceState) return rootView } open fun updatePermission() {} } }
apache-2.0
01a728123062bd144248a1a09d5ec88a
37.282869
152
0.601998
5.102496
false
false
false
false
androidx/androidx
room/room-runtime/src/main/java/androidx/room/util/TableInfo.kt
3
23423
/* * 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 androidx.room.util import android.annotation.SuppressLint import android.database.Cursor import android.os.Build import androidx.annotation.IntDef import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import androidx.room.ColumnInfo import androidx.room.ColumnInfo.SQLiteTypeAffinity import androidx.sqlite.db.SupportSQLiteDatabase import java.util.Locale import java.util.TreeMap /** * A data class that holds the information about a table. * * It directly maps to the result of `PRAGMA table_info(<table_name>)`. Check the * [PRAGMA table_info](http://www.sqlite.org/pragma.html#pragma_table_info) * documentation for more details. * * Even though SQLite column names are case insensitive, this class uses case sensitive matching. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) // if you change this class, you must change TableInfoValidationWriter.kt class TableInfo( /** * The table name. */ @JvmField val name: String, @JvmField val columns: Map<String, Column>, @JvmField val foreignKeys: Set<ForeignKey>, @JvmField val indices: Set<Index>? = null ) { /** * Identifies from where the info object was created. */ @Retention(AnnotationRetention.SOURCE) @IntDef(value = [CREATED_FROM_UNKNOWN, CREATED_FROM_ENTITY, CREATED_FROM_DATABASE]) internal annotation class CreatedFrom() /** * For backward compatibility with dbs created with older versions. */ @SuppressWarnings("unused") constructor( name: String, columns: Map<String, Column>, foreignKeys: Set<ForeignKey> ) : this(name, columns, foreignKeys, emptySet<Index>()) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is TableInfo) return false if (name != other.name) return false if (columns != other.columns) { return false } if (foreignKeys != other.foreignKeys) { return false } return if (indices == null || other.indices == null) { // if one us is missing index information, seems like we couldn't acquire the // information so we better skip. true } else indices == other.indices } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + columns.hashCode() result = 31 * result + foreignKeys.hashCode() // skip index, it is not reliable for comparison. return result } override fun toString(): String { return ("TableInfo{name='$name', columns=$columns, foreignKeys=$foreignKeys, " + "indices=$indices}") } companion object { /** * Identifier for when the info is created from an unknown source. */ const val CREATED_FROM_UNKNOWN = 0 /** * Identifier for when the info is created from an entity definition, such as generated code * by the compiler or at runtime from a schema bundle, parsed from a schema JSON file. */ const val CREATED_FROM_ENTITY = 1 /** * Identifier for when the info is created from the database itself, reading information * from a PRAGMA, such as table_info. */ const val CREATED_FROM_DATABASE = 2 /** * Reads the table information from the given database. * * @param database The database to read the information from. * @param tableName The table name. * @return A TableInfo containing the schema information for the provided table name. */ @JvmStatic fun read(database: SupportSQLiteDatabase, tableName: String): TableInfo { return readTableInfo( database = database, tableName = tableName ) } } /** * Holds the information about a database column. */ class Column( /** * The column name. */ @JvmField val name: String, /** * The column type affinity. */ @JvmField val type: String, /** * Whether or not the column can be NULL. */ @JvmField val notNull: Boolean, @JvmField val primaryKeyPosition: Int, @JvmField val defaultValue: String?, @CreatedFrom @JvmField val createdFrom: Int ) { /** * The column type after it is normalized to one of the basic types according to * https://www.sqlite.org/datatype3.html Section 3.1. * * * This is the value Room uses for equality check. */ @SQLiteTypeAffinity @JvmField val affinity: Int = findAffinity(type) @Deprecated("Use {@link Column#Column(String, String, boolean, int, String, int)} instead.") constructor(name: String, type: String, notNull: Boolean, primaryKeyPosition: Int) : this( name, type, notNull, primaryKeyPosition, null, CREATED_FROM_UNKNOWN ) /** * Implements https://www.sqlite.org/datatype3.html section 3.1 * * @param type The type that was given to the sqlite * @return The normalized type which is one of the 5 known affinities */ @SQLiteTypeAffinity private fun findAffinity(type: String?): Int { if (type == null) { return ColumnInfo.BLOB } val uppercaseType = type.uppercase(Locale.US) if (uppercaseType.contains("INT")) { return ColumnInfo.INTEGER } if (uppercaseType.contains("CHAR") || uppercaseType.contains("CLOB") || uppercaseType.contains("TEXT") ) { return ColumnInfo.TEXT } if (uppercaseType.contains("BLOB")) { return ColumnInfo.BLOB } if (uppercaseType.contains("REAL") || uppercaseType.contains("FLOA") || uppercaseType.contains("DOUB") ) { return ColumnInfo.REAL } // sqlite returns NUMERIC here but it is like a catch all. We already // have UNDEFINED so it is better to use UNDEFINED for consistency. return ColumnInfo.UNDEFINED } companion object { /** * Checks if the default values provided match. Handles the special case in which the * default value is surrounded by parenthesis (e.g. encountered in b/182284899). * * Surrounding parenthesis are removed by SQLite when reading from the database, hence * this function will check if they are present in the actual value, if so, it will * compare the two values by ignoring the surrounding parenthesis. * */ @SuppressLint("SyntheticAccessor") @VisibleForTesting @JvmStatic fun defaultValueEquals(current: String, other: String?): Boolean { if (current == other) { return true } else if (containsSurroundingParenthesis(current)) { return current.substring(1, current.length - 1).trim() == other } return false } /** * Checks for potential surrounding parenthesis, if found, removes them and checks if * remaining paranthesis are balanced. If so, the surrounding parenthesis are redundant, * and returns true. */ private fun containsSurroundingParenthesis(current: String): Boolean { if (current.isEmpty()) { return false } var surroundingParenthesis = 0 current.forEachIndexed { i, c -> if (i == 0 && c != '(') { return false } if (c == '(') { surroundingParenthesis++ } else if (c == ')') { surroundingParenthesis-- if (surroundingParenthesis == 0 && i != current.length - 1) { return false } } } return surroundingParenthesis == 0 } } // TODO: problem probably here override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Column) return false if (Build.VERSION.SDK_INT >= 20) { if (primaryKeyPosition != other.primaryKeyPosition) return false } else { if (isPrimaryKey != other.isPrimaryKey) return false } if (name != other.name) return false if (notNull != other.notNull) return false // Only validate default value if it was defined in an entity, i.e. if the info // from the compiler itself has it. b/136019383 if ( createdFrom == CREATED_FROM_ENTITY && other.createdFrom == CREATED_FROM_DATABASE && defaultValue != null && !defaultValueEquals(defaultValue, other.defaultValue) ) { return false } else if ( createdFrom == CREATED_FROM_DATABASE && other.createdFrom == CREATED_FROM_ENTITY && other.defaultValue != null && !defaultValueEquals(other.defaultValue, defaultValue) ) { return false } else if ( createdFrom != CREATED_FROM_UNKNOWN && createdFrom == other.createdFrom && (if (defaultValue != null) !defaultValueEquals(defaultValue, other.defaultValue) else other.defaultValue != null) ) { return false } return affinity == other.affinity } /** * Returns whether this column is part of the primary key or not. * * @return True if this column is part of the primary key, false otherwise. */ val isPrimaryKey: Boolean get() = primaryKeyPosition > 0 override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + affinity result = 31 * result + if (notNull) 1231 else 1237 result = 31 * result + primaryKeyPosition // Default value is not part of the hashcode since we conditionally check it for // equality which would break the equals + hashcode contract. // result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0); return result } override fun toString(): String { return ("Column{name='$name', type='$type', affinity='$affinity', " + "notNull=$notNull, primaryKeyPosition=$primaryKeyPosition, " + "defaultValue='${defaultValue ?: "undefined"}'}") } } /** * Holds the information about an SQLite foreign key * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) class ForeignKey( @JvmField val referenceTable: String, @JvmField val onDelete: String, @JvmField val onUpdate: String, @JvmField val columnNames: List<String>, @JvmField val referenceColumnNames: List<String> ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ForeignKey) return false if (referenceTable != other.referenceTable) return false if (onDelete != other.onDelete) return false if (onUpdate != other.onUpdate) return false return if (columnNames != other.columnNames) false else referenceColumnNames == other.referenceColumnNames } override fun hashCode(): Int { var result = referenceTable.hashCode() result = 31 * result + onDelete.hashCode() result = 31 * result + onUpdate.hashCode() result = 31 * result + columnNames.hashCode() result = 31 * result + referenceColumnNames.hashCode() return result } override fun toString(): String { return ("ForeignKey{referenceTable='$referenceTable', onDelete='$onDelete +', " + "onUpdate='$onUpdate', columnNames=$columnNames, " + "referenceColumnNames=$referenceColumnNames}") } } /** * Temporary data holder for a foreign key row in the pragma result. We need this to ensure * sorting in the generated foreign key object. */ internal class ForeignKeyWithSequence( val id: Int, val sequence: Int, val from: String, val to: String ) : Comparable<ForeignKeyWithSequence> { override fun compareTo(other: ForeignKeyWithSequence): Int { val idCmp = id - other.id return if (idCmp == 0) { sequence - other.sequence } else { idCmp } } } /** * Holds the information about an SQLite index * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) class Index( @JvmField val name: String, @JvmField val unique: Boolean, @JvmField val columns: List<String>, @JvmField var orders: List<String> ) { init { orders = orders.ifEmpty { List(columns.size) { androidx.room.Index.Order.ASC.name } } } companion object { // should match the value in Index.kt const val DEFAULT_PREFIX = "index_" } @Deprecated("Use {@link #Index(String, boolean, List, List)}") constructor(name: String, unique: Boolean, columns: List<String>) : this( name, unique, columns, List<String>(columns.size) { androidx.room.Index.Order.ASC.name } ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Index) return false if (unique != other.unique) { return false } if (columns != other.columns) { return false } if (orders != other.orders) { return false } return if (name.startsWith(DEFAULT_PREFIX)) { other.name.startsWith(DEFAULT_PREFIX) } else { name == other.name } } override fun hashCode(): Int { var result = if (name.startsWith(DEFAULT_PREFIX)) { DEFAULT_PREFIX.hashCode() } else { name.hashCode() } result = 31 * result + if (unique) 1 else 0 result = 31 * result + columns.hashCode() result = 31 * result + orders.hashCode() return result } override fun toString(): String { return ("Index{name='$name', unique=$unique, columns=$columns, orders=$orders'}") } } } internal fun readTableInfo(database: SupportSQLiteDatabase, tableName: String): TableInfo { val columns = readColumns(database, tableName) val foreignKeys = readForeignKeys(database, tableName) val indices = readIndices(database, tableName) return TableInfo(tableName, columns, foreignKeys, indices) } private fun readForeignKeys( database: SupportSQLiteDatabase, tableName: String ): Set<TableInfo.ForeignKey> { // this seems to return everything in order but it is not documented so better be safe database.query("PRAGMA foreign_key_list(`$tableName`)").useCursor { cursor -> val idColumnIndex = cursor.getColumnIndex("id") val seqColumnIndex = cursor.getColumnIndex("seq") val tableColumnIndex = cursor.getColumnIndex("table") val onDeleteColumnIndex = cursor.getColumnIndex("on_delete") val onUpdateColumnIndex = cursor.getColumnIndex("on_update") val ordered = readForeignKeyFieldMappings(cursor) // Reset cursor as readForeignKeyFieldMappings has moved it cursor.moveToPosition(-1) return buildSet { while (cursor.moveToNext()) { val seq = cursor.getInt(seqColumnIndex) if (seq != 0) { continue } val id = cursor.getInt(idColumnIndex) val myColumns = mutableListOf<String>() val refColumns = mutableListOf<String>() ordered.filter { it.id == id }.forEach { key -> myColumns.add(key.from) refColumns.add(key.to) } add( TableInfo.ForeignKey( referenceTable = cursor.getString(tableColumnIndex), onDelete = cursor.getString(onDeleteColumnIndex), onUpdate = cursor.getString(onUpdateColumnIndex), columnNames = myColumns, referenceColumnNames = refColumns ) ) } } } } private fun readForeignKeyFieldMappings(cursor: Cursor): List<TableInfo.ForeignKeyWithSequence> { val idColumnIndex = cursor.getColumnIndex("id") val seqColumnIndex = cursor.getColumnIndex("seq") val fromColumnIndex = cursor.getColumnIndex("from") val toColumnIndex = cursor.getColumnIndex("to") return buildList { while (cursor.moveToNext()) { add( TableInfo.ForeignKeyWithSequence( id = cursor.getInt(idColumnIndex), sequence = cursor.getInt(seqColumnIndex), from = cursor.getString(fromColumnIndex), to = cursor.getString(toColumnIndex) ) ) } }.sorted() } private fun readColumns( database: SupportSQLiteDatabase, tableName: String ): Map<String, TableInfo.Column> { database.query("PRAGMA table_info(`$tableName`)").useCursor { cursor -> if (cursor.columnCount <= 0) { return emptyMap() } val nameIndex = cursor.getColumnIndex("name") val typeIndex = cursor.getColumnIndex("type") val notNullIndex = cursor.getColumnIndex("notnull") val pkIndex = cursor.getColumnIndex("pk") val defaultValueIndex = cursor.getColumnIndex("dflt_value") return buildMap { while (cursor.moveToNext()) { val name = cursor.getString(nameIndex) val type = cursor.getString(typeIndex) val notNull = 0 != cursor.getInt(notNullIndex) val primaryKeyPosition = cursor.getInt(pkIndex) val defaultValue = cursor.getString(defaultValueIndex) put( key = name, value = TableInfo.Column( name = name, type = type, notNull = notNull, primaryKeyPosition = primaryKeyPosition, defaultValue = defaultValue, createdFrom = TableInfo.CREATED_FROM_DATABASE ) ) } } } } /** * @return null if we cannot read the indices due to older sqlite implementations. */ private fun readIndices(database: SupportSQLiteDatabase, tableName: String): Set<TableInfo.Index>? { database.query("PRAGMA index_list(`$tableName`)").useCursor { cursor -> val nameColumnIndex = cursor.getColumnIndex("name") val originColumnIndex = cursor.getColumnIndex("origin") val uniqueIndex = cursor.getColumnIndex("unique") if (nameColumnIndex == -1 || originColumnIndex == -1 || uniqueIndex == -1) { // we cannot read them so better not validate any index. return null } return buildSet { while (cursor.moveToNext()) { val origin = cursor.getString(originColumnIndex) if ("c" != origin) { // Ignore auto-created indices continue } val name = cursor.getString(nameColumnIndex) val unique = cursor.getInt(uniqueIndex) == 1 // Read index but if we cannot read it properly so better not read it val index = readIndex(database, name, unique) ?: return null add(index) } } } } /** * @return null if we cannot read the index due to older sqlite implementations. */ private fun readIndex( database: SupportSQLiteDatabase, name: String, unique: Boolean ): TableInfo.Index? { return database.query("PRAGMA index_xinfo(`$name`)").useCursor { cursor -> val seqnoColumnIndex = cursor.getColumnIndex("seqno") val cidColumnIndex = cursor.getColumnIndex("cid") val nameColumnIndex = cursor.getColumnIndex("name") val descColumnIndex = cursor.getColumnIndex("desc") if ( seqnoColumnIndex == -1 || cidColumnIndex == -1 || nameColumnIndex == -1 || descColumnIndex == -1 ) { // we cannot read them so better not validate any index. return null } val columnsMap = TreeMap<Int, String>() val ordersMap = TreeMap<Int, String>() while (cursor.moveToNext()) { val cid = cursor.getInt(cidColumnIndex) if (cid < 0) { // Ignore SQLite row ID continue } val seq = cursor.getInt(seqnoColumnIndex) val columnName = cursor.getString(nameColumnIndex) val order = if (cursor.getInt(descColumnIndex) > 0) "DESC" else "ASC" columnsMap[seq] = columnName ordersMap[seq] = order } val columns = columnsMap.values.toList() val orders = ordersMap.values.toList() TableInfo.Index(name, unique, columns, orders) } }
apache-2.0
5395e79b5f7fe3ea15d171a44f69fe45
35.036923
100
0.55945
5.100828
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/module/mail/service/impl/ContentGenerator.kt
3
3475
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.mail.service.impl import com.mycollab.configuration.ApplicationConfiguration import com.mycollab.configuration.IDeploymentMode import com.mycollab.module.file.service.AbstractStorageService import com.mycollab.module.mail.service.IContentGenerator import com.mycollab.schedule.email.MailStyles import freemarker.template.Configuration import org.slf4j.LoggerFactory import org.springframework.beans.factory.InitializingBean import org.springframework.beans.factory.config.BeanDefinition import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component import java.io.StringWriter import java.time.LocalDate import java.util.* /** * @author MyCollab Ltd * @since 6.0.0 */ @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) class ContentGenerator(private val applicationConfiguration: ApplicationConfiguration, private val deploymentMode: IDeploymentMode, private val templateEngine: Configuration, private val storageFactory: AbstractStorageService) : IContentGenerator, InitializingBean { companion object { @JvmStatic private val LOG = LoggerFactory.getLogger(javaClass.enclosingClass) } private val templateContext = mutableMapOf<String, Any>() @Throws(Exception::class) override fun afterPropertiesSet() { val defaultUrls = mutableMapOf( "cdn_url" to deploymentMode.getCdnUrl(), "facebook_url" to (applicationConfiguration.facebookUrl ?: ""), "google_url" to (applicationConfiguration.googleUrl ?: ""), "linkedin_url" to (applicationConfiguration.linkedinUrl ?: ""), "twitter_url" to (applicationConfiguration.twitterUrl ?: "")) putVariable("defaultUrls", defaultUrls) putVariable("current_year", LocalDate.now().year) putVariable("siteName", applicationConfiguration.siteName) putVariable("styles", MailStyles.instance()) putVariable("storageFactory", storageFactory) } override fun putVariable(key: String, value: Any?) { if (value != null) templateContext[key] = value else LOG.warn("Can not put null value with key $key to template") } override fun parseFile(templateFilePath: String): String = parseFile(templateFilePath, null) override fun parseFile(templateFilePath: String, currentLocale: Locale?): String { val writer = StringWriter() val template = templateEngine.getTemplate(templateFilePath, currentLocale) template.dateFormat = "yyyy-MM-dd" template.dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss" template.process(templateContext, writer) return writer.toString() } }
agpl-3.0
62781648647171f1881bf3f7eec148ab
40.86747
114
0.724237
4.745902
false
true
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/scope/GlobalScope.kt
1
3089
package org.jetbrains.haskell.scope import org.jetbrains.haskell.fileType.HaskellFile import org.jetbrains.haskell.psi.ModuleName import org.jetbrains.haskell.util.ProcessRunner import java.util.HashMap import org.jetbrains.haskell.external.ghcfs.RamFile import com.intellij.psi.PsiManager import com.intellij.openapi.project.Project import org.jetbrains.haskell.util.joinPath import org.jetbrains.cabal.CabalInterface import java.io.File import org.jetbrains.haskell.vfs.TarGzArchive import org.jetbrains.haskell.vfs.TarGzFile import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.LocalFileSystem /** * Created by atsky on 12/9/14. */ public object GlobalScope { val cache = HashMap<String, HaskellFile>() val tarCache = HashMap<String, TarGzArchive>() fun getModule(project: Project, name: String): HaskellFile? { if (cache.containsKey(name)) { return cache[name]; } //val source = findSource(project, name) //if (source != null) { // val result = PsiManager.getInstance(project).findFile(source) as HaskellFile? // cache[name] = result // return result; //} /* val text = ProcessRunner(null).executeNoFail("ghc", "-e", ":browse! ${name}") if (text == "") { return null; } val content = "module ${name} where\n" + text val ramFile = RamFile(name + ".hs", content) val result = PsiManager.getInstance(project).findFile(ramFile) as HaskellFile? cache[name] = result return result */ return null } fun findSource(project: Project, name: String): VirtualFile? { val cabalInterface = CabalInterface(project) return findSource(File(cabalInterface.getRepo()), project, name) } fun findSource(directory: File, project: Project, name: String) : VirtualFile? { for (file in directory.listFiles()) { if (file.isDirectory()) { val result = findSource(file, project, name) if (result != null) { return result } } else { val fileName = file.getName() if (fileName.endsWith(".tar.gz")) { val filePath = file.getAbsolutePath() if (!tarCache.contains(filePath)) { tarCache[filePath] = TarGzArchive(file) } val result = findInArchive(tarCache[filePath], name) if (result != null) { return TarGzFile(LocalFileSystem.getInstance().findFileByIoFile(file), result); } } } } return null; } fun findInArchive(tarGzArchive: TarGzArchive, name: String) : String? { val fileEnd = name.replace("\\.".toRegex(), "/") + ".hs" for (file in tarGzArchive.filesList) { if (file.endsWith(fileEnd)) { return file } } return null } }
apache-2.0
da68489f7f48aa8ba5156586921477de
32.586957
103
0.589187
4.438218
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem84.kt
1
754
package leetcode import java.util.* import kotlin.math.max /** * https://leetcode.com/problems/largest-rectangle-in-histogram/ */ class Problem84 { fun largestRectangleArea(heights: IntArray): Int { var answer = 0 val stack = Stack<Int>() for (i in 0..heights.size) { var currentHeight = if (i == heights.size) -1 else heights[i] while (!stack.isEmpty() && currentHeight <= heights[stack.peek()]) { val prevIndex = stack.pop() val height = heights[prevIndex] val width = if (stack.isEmpty()) i else i - stack.peek() - 1 answer = max(answer, height * width) } stack += i } return answer } }
mit
62fa0947895dcf8ab42db25d2591c85f
29.16
80
0.549072
4.032086
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/multiDecl/ValCapturedInObjectLiteral.kt
5
282
class A { operator fun component1() = 1 operator fun component2() = 2 } fun box() : String { val (a, b) = A() val local = object { public fun run() : Int { return a } } return if (local.run() == 1 && b == 2) "OK" else "fail" }
apache-2.0
4e28f138a843faaf1bc3235ea4656aeb
16.625
59
0.471631
3.317647
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/settings/preference/composables/TimePickerPreference.kt
1
6339
package wangdaye.com.geometricweather.settings.preference.composables import android.content.Context import android.widget.TimePicker import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.material3.AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.ui.widgets.Material3CardListItem import wangdaye.com.geometricweather.common.ui.widgets.defaultCardListItemElevation import wangdaye.com.geometricweather.theme.compose.DayNightTheme import wangdaye.com.geometricweather.theme.compose.rememberThemeRipple @Composable fun TimePickerPreferenceView( @StringRes titleId: Int, currentTime: String, enabled: Boolean = true, onValueChanged: (String) -> Unit, ) = TimePickerPreferenceView( title = stringResource(titleId), summary = { _, it -> it }, currentTime = currentTime, enabled = enabled, onValueChanged = onValueChanged, ) @Composable fun TimePickerPreferenceView( title: String, summary: (Context, String) -> String?, // currentTime (xx:xx) -> summary. currentTime: String, enabled: Boolean = true, onValueChanged: (String) -> Unit, ) { val currentTimeState = remember { mutableStateOf(currentTime) } val dialogOpenState = remember { mutableStateOf(false) } Material3CardListItem( elevation = if (enabled) defaultCardListItemElevation else 0.dp ) { Column( modifier = Modifier .fillMaxWidth() .alpha(if (enabled) 1f else 0.5f) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberThemeRipple(), onClick = { dialogOpenState.value = true }, enabled = enabled, ) .padding(dimensionResource(R.dimen.normal_margin)), verticalArrangement = Arrangement.Center, ) { Column { Text( text = title, color = DayNightTheme.colors.titleColor, style = MaterialTheme.typography.titleMedium, ) val currentSummary = summary(LocalContext.current, currentTimeState.value) if (currentSummary?.isNotEmpty() == true) { Spacer(modifier = Modifier.height(dimensionResource(R.dimen.little_margin))) Text( text = currentSummary, color = DayNightTheme.colors.bodyColor, style = MaterialTheme.typography.bodyMedium, ) } } } } if (dialogOpenState.value) { val timePickerState = remember { mutableStateOf(currentTimeState.value) } AlertDialog( onDismissRequest = { dialogOpenState.value = false }, title = { Text( text = title, color = MaterialTheme.colorScheme.onSurface, style = MaterialTheme.typography.headlineSmall, ) }, text = { AndroidView( factory = { context -> val timePicker = TimePicker( context, null, R.style.Widget_Material3_MaterialTimePicker ) timePicker.setIs24HourView(true) timePicker.setOnTimeChangedListener { _, hour, minute -> timePickerState.value = timeToString(hour = hour, minute = minute) } val time = stringToTime(currentTimeState.value) timePicker.currentHour = time.elementAtOrNull(0) ?: 0 timePicker.currentMinute = time.elementAtOrNull(1) ?: 0 timePickerState.value = timeToString( hour = timePicker.currentHour, minute = timePicker.currentMinute ) timePicker } ) }, confirmButton = { TextButton( onClick = { currentTimeState.value = timePickerState.value dialogOpenState.value = false onValueChanged(currentTimeState.value) } ) { Text( text = stringResource(R.string.done), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.labelLarge, ) } }, dismissButton = { TextButton( onClick = { dialogOpenState.value = false } ) { Text( text = stringResource(R.string.cancel), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.labelLarge, ) } } ) } } private fun timeToString( hour: Int, minute: Int ) = when { hour == 0 -> "00" hour < 10 -> "0$hour" else -> hour.toString() } + ":" + when { minute == 0 -> "00" minute < 10 -> "0$minute" else -> minute.toString() } private fun stringToTime( time: String ) = time.split(":").map { it.toIntOrNull() ?: 0 }
lgpl-3.0
dd7b60658e17f8a8ff0426af437038ea
35.860465
96
0.56318
5.555653
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/migration/Migration261.kt
2
999
package com.commit451.gitlab.migration import com.commit451.gitlab.App import com.commit451.gitlab.data.Prefs import io.reactivex.rxjava3.core.Completable import java.util.* /** * We started saving username and email to the user account in a certain update * so that we could more easily fetch projects, but we did not account for the * fact that users that were already signed in would not have these values stored. * This makes sure that we add these values if they do not exist. */ object Migration261 { fun run(): Completable { return Completable.defer { val user = App.get().gitLab.getThisUser() .blockingGet() .body()!! val currentAccount = App.get().currentAccount currentAccount.lastUsed = Date() currentAccount.email = user.email currentAccount.username = user.username Prefs.updateAccount(currentAccount) Completable.complete() } } }
apache-2.0
3a8e8ce9ba80a3ac0cad56a0dcb400a4
33.482759
82
0.662663
4.646512
false
false
false
false
PlateStack/PlateAPI
src/main/kotlin/org/platestack/api/message/Text.kt
1
17769
/* * Copyright (C) 2017 José Roberto de Araújo Júnior * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused", "UNUSED_PARAMETER") package org.platestack.api.message import org.platestack.api.server.PlateStack import java.io.Serializable import java.util.* /** * A text message that is rendered by the client game and displayed to the player. * * This model is based on [this definition](https://minecraft.gamepedia.com/Commands#Raw_JSON_text) * @property style The style that will be applied to this text and all children. All null style properties will inherit the parent's style. * @property hoverEvent What happens when the player passes the mouse pointer hover this text. The parent's event is inherited when this property is null. * @property insertion When the text is shift-clicked by a player, this string will be inserted in their chat input. It will not overwrite any existing text the player was writing. * @property clickEvent What happens when the player clicks this text. The parent's event is inherited when this property is null. */ sealed class Text( val style: Style, val hoverEvent: HoverEvent?, val clickEvent: ClickEvent?, val insertion: String?, vararg extra: Text ): Serializable { /** * Array which holds the extra texts, this will not return a new copy like [extra]. * * **The returned array must not be changed!** */ protected val internalExtra = extra.clone() /** * Additional messages that are rendered after this text but inherits the same style and events as this. A new copy is returned on every read. */ val extra get() = internalExtra.clone() /** * Create a new compound concatenating both texts */ operator fun plus(text: Text) = Compound(Style.EMPTY, this, text) /** * Translates and converts this text to a JSON string using the current server implementation */ @Deprecated("The name causes confusion with json-extensions.kt") fun toJson(language: Language) = PlateStack.translator.toJson(this, language) /** * Converts this text to a JSON object with the same structure as the tellraw command */ @Deprecated("The name is shadowing json-extensions.kt") fun toJson() = PlateStack.internal.toJson(this) /** * Compares if this text matches all style, event, extra messages and information with the given object */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Text if (style != other.style) return false if (hoverEvent != other.hoverEvent) return false if (clickEvent != other.clickEvent) return false if (!Arrays.equals(internalExtra, other.internalExtra)) return false return true } /** * Generates a hashcode based on all properties */ override fun hashCode(): Int { var result = style.hashCode() result = 31 * result + (hoverEvent?.hashCode() ?: 0) result = 31 * result + (clickEvent?.hashCode() ?: 0) result = 31 * result + Arrays.hashCode(internalExtra) return result } /** * Converts this text to a verbose string */ override fun toString(): String { return "${javaClass.simpleName}(style=$style, hoverEvent=$hoverEvent, clickEvent=$clickEvent, extra=${Arrays.toString(internalExtra)})" } /** * A list of texts that shares the same parent style and events. * @constructor Creates a compound defining all properties * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ class Compound( style: Style, hoverEvent: HoverEvent?, clickEvent: ClickEvent?, insertion: String? = null, vararg extra: Text ) : Text(style, hoverEvent, clickEvent, insertion, *extra) { /** * Creates a compound without events * @param style See [Text.style] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ constructor(style: Style, insertion: String?, vararg extra: Text) : this(style, null, null, insertion, *extra) /** * Creates a compound without events * @param style See [Text.style] * @param extra See [Text.extra] */ constructor(style: Style, vararg extra: Text) : this(style, null, null, "", *extra) } /** * A raw text string. * @property text The text string which will be rendered. May contain formatting codes using section chars but * doing such may cause unexpected rendering issues. Lines can be broken with a simple `\n` * * @constructor Creates a raw text component * @param text See [text] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ class RawText @JvmOverloads constructor( val text: String, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ) : Text(style, hoverEvent, clickEvent, insertion, *extra) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as RawText if (text != other.text) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + text.hashCode() return result } override fun toString(): String { return "RawText(text='$text', style=$style, hoverEvent=$hoverEvent, clickEvent=$clickEvent, extra=${Arrays.toString(internalExtra)})" } } /** * A translation key which will be translated by the client's renderer. * * @property key The translation key * * @constructor Creates a translation component * @param key See [key] * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param insertion See [Text.insertion] * @param with A list of chat component arguments and/or string arguments to be used by translate * @param extra See [Text.extra] */ class Translation @JvmOverloads constructor( val key: String, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, val with: List<Text> = emptyList(), vararg extra: Text ) : Text(style, hoverEvent, clickEvent, insertion, *extra) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as Translation if (key != other.key) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + key.hashCode() return result } override fun toString(): String { return "Translation(key='$key', style=$style, hoverEvent=$hoverEvent, clickEvent=$clickEvent, extra=${Arrays.toString(internalExtra)})" } } /** * A string that can be used to display the key needed to preform a certain action. * * An example is `key.inventory` which will always display "E" unless the player has set a different key for opening their inventory. * * @since Minecraft 1.12 * * @property key The key identifier * * @constructor Creates a key binding component * @param key See [key] * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ class KeyBinding @JvmOverloads constructor( val key: String, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ) : Text(style, hoverEvent, clickEvent, insertion, *extra) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as KeyBinding if (key != other.key) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + key.hashCode() return result } override fun toString(): String { return "KeyBinding(key='$key', style=$style, hoverEvent=$hoverEvent, clickEvent=$clickEvent, extra=${Arrays.toString(internalExtra)})" } } /** * A player's score in an objective. * * Displays nothing if the player is not tracked in the given objective. * * @property name The name of the player whose score should be displayed. * * Selectors (such as `@p`) can be used, in addition to "fake" player names created by the scoreboard system. * * In addition, if the name is `"*"`, it will show the reader's own score * (for example, `/tellraw @a {score:{name:"*",objective:"obj"}}` will show every online player their own score in the "obj" objective). * * Note that non-player entity scores (such as `@e[type=Cow]`) do not show, even if the entity has been given a score in the objective. * * @property objective The internal name of the objective to display the player's score in. * @property value Optional. If present, this value is used regardless of what the score would have been. * * @constructor Creates a score component using translatable messages as parameters * @param name See [name] * @param objective See [objective] * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param value See [value] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ class Score @JvmOverloads constructor( val name: Message, val objective: Message, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, val value: Message? = null, insertion: String? = null, vararg extra: Text ) : Text(style, hoverEvent, clickEvent, insertion, *extra) { /** * Creates a score component using untranslatable strings as parameters. * @param name See [name] * @param objective See [objective] * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param value See [value] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ @JvmOverloads constructor( name: String, objective: String, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, value: String? = null, insertion: String? = null, vararg extra: Text ) : this(Message(name), Message(objective), style, hoverEvent, clickEvent, value?.let { Message(it) }, insertion, *extra) override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as Score if (name != other.name) return false if (objective != other.objective) return false if (value != other.value) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + name.hashCode() result = 31 * result + objective.hashCode() result = 31 * result + (value?.hashCode() ?: 0) return result } override fun toString(): String { return "Score(name='$name', objective='$objective', value=$value, style=$style, hoverEvent=$hoverEvent, clickEvent=$clickEvent, extra=${Arrays.toString(internalExtra)})" } } /** * A string containing a selector (`@p`,`@a`,`@r`, or `@e ) and, optionally, selector arguments. * * Unlike text, the selector will be translated into the correct player/entity names. * * If more than one player/entity is detected by the selector, it will be displayed * in a form such as 'Name1 and Name2' or 'Name1, Name2, Name3, and Name4'. * * Clicking a player's name inserted into a /tellraw command this way will suggest a command to whisper to that player. * Shift-clicking a player's name will insert that name into chat. * Shift-clicking a non-player entity's name will insert its UUID into chat. * @property selector The selector string * * @constructor Constructs a selector component using a translatable message * @param selector See [Selector] * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param insertion See [Text.insertion] * @param extra See [Text.extra] */ class Selector @JvmOverloads constructor( val selector: Message, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ) : Text(style, hoverEvent, clickEvent, insertion, *extra) { /** * Creates a selector component using an untranslatable message * @param selector See [Selector] * @param style See [Text.style] * @param hoverEvent See [Text.hoverEvent] * @param clickEvent See [Text.clickEvent] * @param extra See [Text.extra] */ @JvmOverloads constructor(selector: String, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ) : this(Message(selector), style, hoverEvent, clickEvent, insertion, *extra) override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as Selector if (selector != other.selector) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + selector.hashCode() return result } override fun toString(): String { return "Selector(selector='$selector', style=$style, hoverEvent=$hoverEvent, clickEvent=$clickEvent, extra=${Arrays.toString(internalExtra)})" } } class FormattedMessage @JvmOverloads constructor( val message: Message, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ): Text(style, hoverEvent, clickEvent, insertion, *extra) { @JvmOverloads constructor( sentence: Sentence, style: Style = Style.EMPTY, parameters: Map<String, Serializable> = emptyMap(), hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ): this(Message(sentence, parameters), style, hoverEvent, clickEvent, insertion, *extra) @JvmOverloads constructor( rawText: String, style: Style = Style.EMPTY, hoverEvent: HoverEvent? = null, clickEvent: ClickEvent? = null, insertion: String? = null, vararg extra: Text ): this(Message(rawText), style, hoverEvent, clickEvent, insertion, *extra) } }
apache-2.0
ea2a2a10731fd7826827f0a69c5e59f4
37.454545
181
0.606383
4.607365
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/mvp/presenter/NotificationsPresenter.kt
1
3162
package com.gkzxhn.mygithub.mvp.presenter import android.util.Log import com.gkzxhn.balabala.mvp.contract.BaseView import com.gkzxhn.mygithub.api.OAuthApi import com.gkzxhn.mygithub.bean.info.Notifications import com.gkzxhn.mygithub.extension.toast import com.gkzxhn.mygithub.ui.fragment.NotificationsFragment import com.gkzxhn.mygithub.utils.Utils import com.gkzxhn.mygithub.utils.rxbus.RxBus import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject /** * Created by Xuezhi on 2017/11/16. */ class NotificationsPresenter @Inject constructor(private val oAuthApi: OAuthApi, private val view: BaseView, private val rxBus: RxBus) { fun getNotifications( //owner:String,repo:String ) { view.showLoading() Log.e(javaClass.simpleName, "showLoading") oAuthApi//.getNotificationsInRepository(owner, repo, .getNotifications(true, false, since = Utils.getFormatTime(Utils.getDateBeforeOneMonth(-1)!!)!!, before = Utils.getFormatTime(Utils.getTiem())!! //since = "abc",before = "bcd" ) .bindToLifecycle(view as NotificationsFragment) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { view.hideLoading() } .subscribe({ notifications -> if (notifications.size > 0) { Log.i(javaClass.simpleName, "notifications = " + notifications.toString()) Log.i(javaClass.simpleName, "since = " + Utils.getFormatTime(Utils.getDateBeforeOneMonth(-1)!!)!!) Log.i(javaClass.simpleName, "before = " + Utils.getFormatTime(Utils.getTiem())!!) view.loadData(notifications) //view.loadData() } else { Log.i(javaClass.simpleName, "since = " + Utils.getFormatTime(Utils.getDateBeforeOneMonth(-1)!!)!!) Log.i(javaClass.simpleName, "before = " + Utils.getFormatTime(Utils.getTiem())!!) Log.i(javaClass.simpleName, "notificationgs = " + notifications.toString()) Log.i(javaClass.simpleName, "没有notifications数据") view.context.toast("没有消息数据") } }, { e -> Log.e(javaClass.simpleName, e.message) view.context.toast("网络错误") }) } fun subscribe() { rxBus.toFlowable(Notifications::class.java) .bindToLifecycle(view as NotificationsFragment) .subscribe( { notifications: Notifications? -> view.getNewData() } ) } }
gpl-3.0
8a76fc273da8ae927313f146c8c150f5
41.945205
122
0.564454
5.0144
false
false
false
false
MKA-Nigeria/MKAN-Report-Android
videos_module/src/main/java/com/abdulmujibaliu/koutube/data/models/Models.kt
1
1728
package com.abdulmujibaliu.koutube.data.models import android.text.format.DateUtils import org.joda.time.DateTime import org.joda.time.LocalTime import org.joda.time.format.DateTimeFormat import java.util.* /** * Created by abdulmujibaliu on 10/16/17. */ open class BaseModel { var itemID: String? = null var datePublished: DateTime? = null var channelID: String? = null var itemTitle: String? = null var itemDesc: String? = null var itemImageURL: String? = null var channelName: String? = null public fun getPublishText(): String { return if (datePublished == null) { "N/A" } else { DateUtils.getRelativeTimeSpanString(datePublished!!.millis, Calendar.getInstance().getTime().getTime(), 0L, DateUtils.FORMAT_24HOUR).toString(); } } } open class BaseModelWrapper(idList: MutableList<String>) { val ids: MutableList<String>? = idList var items = mutableListOf<BaseModel>() } class PlayList : BaseModel() { var itemCount: Int? = null } class PlayListsResult(idList: MutableList<String>) : BaseModelWrapper(idList) class PlayListItem : BaseModel() { var videoId: String? = null } class PlayListItemsResult(idList: MutableList<String>) : BaseModelWrapper(idList) class VideoResult : BaseModelWrapper(mutableListOf()) class YoutubeVideo : BaseModel() { //@SerializedName("id") var videoID: String? = null var duration: LocalTime? = null var numberOfViews: Int? = null fun getDurationText(): String { return if (duration == null) { "N/A" } else { val dtf = DateTimeFormat.forPattern("HH:mm:ss") dtf.print(duration) } } }
mit
e36c75ab66c90b2dc87cc078b545220a
20.6125
156
0.663194
4.046838
false
false
false
false
Heiner1/AndroidAPS
database/src/main/java/info/nightscout/androidaps/database/transactions/InsertAndCancelCurrentOfflineEventTransaction.kt
1
1190
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.entities.OfflineEvent import info.nightscout.androidaps.database.interfaces.end class InsertAndCancelCurrentOfflineEventTransaction( val offlineEvent: OfflineEvent ) : Transaction<InsertAndCancelCurrentOfflineEventTransaction.TransactionResult>() { constructor(timestamp: Long, duration: Long, reason: OfflineEvent.Reason) : this(OfflineEvent(timestamp = timestamp, reason = reason, duration = duration)) override fun run(): TransactionResult { val result = TransactionResult() val current = database.offlineEventDao.getOfflineEventActiveAt(offlineEvent.timestamp).blockingGet() if (current != null) { current.end = offlineEvent.timestamp database.offlineEventDao.updateExistingEntry(current) result.updated.add(current) } database.offlineEventDao.insertNewEntry(offlineEvent) result.inserted.add(offlineEvent) return result } class TransactionResult { val inserted = mutableListOf<OfflineEvent>() val updated = mutableListOf<OfflineEvent>() } }
agpl-3.0
52f2dc2546169d00fab6dfb6c04e2fde
38.7
108
0.736134
5.509259
false
false
false
false
square/wire
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/GroupElement.kt
1
1458
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema.internal.parser import com.squareup.wire.schema.Field import com.squareup.wire.schema.Location import com.squareup.wire.schema.internal.appendDocumentation import com.squareup.wire.schema.internal.appendIndented import com.squareup.wire.schema.internal.toEnglishLowerCase data class GroupElement( val label: Field.Label? = null, val location: Location, val name: String, val tag: Int, val documentation: String = "", val fields: List<FieldElement> = emptyList() ) { fun toSchema() = buildString { appendDocumentation(documentation) if (label != null) { append("${label.name.toEnglishLowerCase()} ") } append("group $name = $tag {") if (fields.isNotEmpty()) { append('\n') for (field in fields) { appendIndented(field.toSchema()) } } append("}\n") } }
apache-2.0
392ee0a8bbb0676e067c7aa6cb0743e9
30.695652
75
0.709877
3.940541
false
false
false
false
Adventech/sabbath-school-android-2
features/media/src/main/kotlin/app/ss/media/playback/ui/PlaybackMiniControls.kt
1
12030
package app.ss.media.playback.ui import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSizeIn import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.ContentAlpha import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.LocalContentAlpha import androidx.compose.material.ProgressIndicatorDefaults import androidx.compose.material.icons.rounded.ErrorOutline import androidx.compose.material.icons.rounded.HourglassBottom import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import app.ss.design.compose.extensions.isLargeScreen import app.ss.design.compose.extensions.isS import app.ss.design.compose.extensions.modifier.thenIf import app.ss.design.compose.theme.Dimens import app.ss.design.compose.theme.Spacing12 import app.ss.design.compose.theme.Spacing8 import app.ss.design.compose.theme.SsColor import app.ss.design.compose.theme.lighter import app.ss.design.compose.theme.onSurfaceSecondary import app.ss.design.compose.widget.icon.IconBox import app.ss.design.compose.widget.icon.IconButton import app.ss.design.compose.widget.icon.IconSlot import app.ss.design.compose.widget.icon.Icons import app.ss.media.R import app.ss.media.playback.PLAYBACK_PROGRESS_INTERVAL import app.ss.media.playback.PlaybackConnection import app.ss.media.playback.extensions.isActive import app.ss.media.playback.extensions.playPause import app.ss.media.playback.ui.common.Dismissible import app.ss.media.playback.ui.common.LocalPlaybackConnection import app.ss.media.playback.ui.spec.NowPlayingSpec import app.ss.media.playback.ui.spec.PlaybackStateSpec import app.ss.media.playback.ui.spec.toSpec import androidx.compose.material.icons.Icons as MaterialIcons import app.ss.translations.R.string as RString private object PlaybackMiniControlsDefaults { val height = 60.dp val maxWidth = 600.dp val playPauseSize = 30.dp val replaySize = 30.dp val cancelSize = 20.dp } @OptIn(ExperimentalLifecycleComposeApi::class) @Composable fun PlaybackMiniControls( modifier: Modifier = Modifier, playbackConnection: PlaybackConnection, onExpand: () -> Unit ) { val playbackState by playbackConnection.playbackState.collectAsStateWithLifecycle() val nowPlaying by playbackConnection.nowPlaying.collectAsStateWithLifecycle() val visible = (playbackState to nowPlaying).isActive AnimatedVisibility( visible = visible, modifier = modifier, enter = slideInVertically(initialOffsetY = { it / 2 }), exit = slideOutVertically(targetOffsetY = { it / 2 }) ) { PlaybackMiniControls( spec = playbackState.toSpec(), nowPlayingSpec = nowPlaying.toSpec(), playbackConnection = playbackConnection, onExpand = onExpand ) } } @Composable fun PlaybackMiniControls( spec: PlaybackStateSpec, nowPlayingSpec: NowPlayingSpec, modifier: Modifier = Modifier, height: Dp = PlaybackMiniControlsDefaults.height, playbackConnection: PlaybackConnection = LocalPlaybackConnection.current, onExpand: () -> Unit ) { val cancel: () -> Unit = { playbackConnection.transportControls?.stop() } val backgroundColor = playbackMiniBackgroundColor() val contentColor = playbackContentColor() Dismissible(onDismiss = cancel) { Box( modifier = Modifier.fillMaxWidth() ) { Surface( color = Color.Transparent, shape = MaterialTheme.shapes.medium, modifier = modifier .padding(horizontal = Dimens.grid_5) .padding(bottom = Dimens.grid_4) .thenIf(isLargeScreen()) { requiredSizeIn( maxWidth = PlaybackMiniControlsDefaults.maxWidth ) } .align(Alignment.Center) .clickable { onExpand() } ) { Column( modifier = Modifier.fillMaxWidth() ) { Row( horizontalArrangement = Arrangement.spacedBy(playbackButtonSpacing()), verticalAlignment = Alignment.CenterVertically, modifier = Modifier .height(height) .fillMaxWidth() .background(backgroundColor) ) { NowPlayingColumn( spec = nowPlayingSpec, onCancel = cancel ) PlaybackReplay( contentColor = contentColor, onRewind = { playbackConnection.transportControls?.rewind() } ) PlaybackPlayPause( spec = spec, contentColor = contentColor, onPlayPause = { playbackConnection.mediaController?.playPause() } ) Spacer(modifier = Modifier.width(Dimens.grid_2)) } PlaybackProgress( spec = spec, color = MaterialTheme.colorScheme.onSurfaceVariant, playbackConnection = playbackConnection ) } } } } } @Composable private fun playbackMiniBackgroundColor( isDark: Boolean = isSystemInDarkTheme() ): Color = if (isDark) { Color.Black.lighter() } else { SsColor.BaseGrey1 } @Composable internal fun playbackContentColor( isDark: Boolean = isSystemInDarkTheme() ): Color = when { isS() -> MaterialTheme.colorScheme.onSurface isDark -> Color.White else -> Color.Black } @Composable private fun playbackButtonSpacing( isLargeScreen: Boolean = isLargeScreen() ): Dp { return if (isLargeScreen) { Spacing12 } else { Spacing8 } } @OptIn(ExperimentalLifecycleComposeApi::class) @Composable private fun PlaybackProgress( spec: PlaybackStateSpec, color: Color, playbackConnection: PlaybackConnection = LocalPlaybackConnection.current ) { val progressState by playbackConnection.playbackProgress.collectAsStateWithLifecycle() val sizeModifier = Modifier .height(2.dp) .fillMaxWidth() when { spec.isBuffering -> { LinearProgressIndicator( color = color, modifier = sizeModifier ) } else -> { LinearProgressIndicator( progress = animateFloatAsState(progressState.progress, tween(PLAYBACK_PROGRESS_INTERVAL.toInt(), easing = LinearEasing)).value, color = color, backgroundColor = color.copy(ProgressIndicatorDefaults.IndicatorBackgroundOpacity), modifier = sizeModifier ) } } } @Composable private fun RowScope.NowPlayingColumn( spec: NowPlayingSpec, onCancel: () -> Unit ) { Row( horizontalArrangement = Arrangement.spacedBy(Dimens.grid_1), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f) ) { IconButton(onClick = onCancel) { IconBox( icon = Icons.Cancel, modifier = Modifier.size(PlaybackMiniControlsDefaults.cancelSize), contentColor = SsColor.BaseGrey2 ) } NowPlayingColumn( spec = spec, modifier = Modifier .weight(1f) ) } } @Composable private fun NowPlayingColumn( spec: NowPlayingSpec, modifier: Modifier = Modifier ) { Column( modifier = Modifier .fillMaxSize() .then(modifier), verticalArrangement = Arrangement.Center ) { Text( spec.title, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.labelMedium.copy( fontSize = 15.sp ), color = MaterialTheme.colorScheme.onSurface ) Spacer(modifier = Modifier.height(2.dp)) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( spec.artist, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall, color = onSurfaceSecondary() ) } Spacer(modifier = Modifier.height(4.dp)) } } @Composable private fun PlaybackReplay( size: Dp = PlaybackMiniControlsDefaults.replaySize, contentColor: Color, onRewind: () -> Unit ) { IconButton(onClick = onRewind) { IconBox( icon = IconSlot.fromResource( R.drawable.ic_audio_icon_backward, contentDescription = stringResource(id = RString.ss_action_rewind) ), modifier = Modifier.size(size), contentColor = contentColor ) } } @Composable private fun PlaybackPlayPause( spec: PlaybackStateSpec, size: Dp = PlaybackMiniControlsDefaults.playPauseSize, contentColor: Color, onPlayPause: () -> Unit ) { IconButton(onClick = onPlayPause) { val painter = when { spec.isPlaying -> painterResource(id = R.drawable.ic_audio_icon_pause) spec.isPlayEnabled -> painterResource(id = R.drawable.ic_audio_icon_play) spec.isError -> rememberVectorPainter(MaterialIcons.Rounded.ErrorOutline) else -> rememberVectorPainter(MaterialIcons.Rounded.HourglassBottom) } IconBox( icon = IconSlot.fromPainter( painter = painter, contentDescription = stringResource(id = RString.ss_action_play_pause) ), modifier = Modifier.size(size), contentColor = contentColor ) } }
mit
3ef59ac18ac0994f421bdec632c2d54c
33.668588
143
0.649127
5.052499
false
false
false
false
Maccimo/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowMessageHistoryAction.kt
1
6575
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.actions import com.intellij.icons.AllIcons import com.intellij.ide.TextCopyProvider import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys.COPY_PROVIDER import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.actions.ContentChooser.RETURN_SYMBOL import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.text.StringUtil.convertLineSeparators import com.intellij.openapi.util.text.StringUtil.first import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.awt.RelativePoint import com.intellij.ui.speedSearch.SpeedSearchUtil.applySpeedSearchHighlighting import com.intellij.util.ObjectUtils.sentinel import com.intellij.util.containers.nullize import com.intellij.util.ui.JBUI.scale import com.intellij.vcs.commit.NonModalCommitPanel import com.intellij.vcs.commit.message.CommitMessageInspectionProfile.getSubjectRightMargin import org.jetbrains.annotations.Nls import java.awt.Point import javax.swing.JList import javax.swing.ListSelectionModel.SINGLE_SELECTION /** * Action showing the history of recently used commit messages. Source code of this class is provided * as a sample of using the [CheckinProjectPanel] API. Actions to be shown in the commit dialog * should be added to the `Vcs.MessageActionGroup` action group. */ class ShowMessageHistoryAction : DumbAwareAction() { init { isEnabledInModalContext = true } override fun update(e: AnActionEvent) { val project = e.project val commitMessage = getCommitMessage(e) if (e.place == NonModalCommitPanel.COMMIT_TOOLBAR_PLACE) { e.presentation.icon = AllIcons.Vcs.HistoryInline e.presentation.hoveredIcon = AllIcons.Vcs.HistoryInlineHovered } e.presentation.isVisible = project != null && commitMessage != null e.presentation.isEnabled = e.presentation.isVisible && !VcsConfiguration.getInstance(project!!).recentMessages.isEmpty() } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val commitMessage = getCommitMessage(e)!! createPopup(project, commitMessage, VcsConfiguration.getInstance(project).recentMessages.reversed()) .showInBestPositionFor(e.dataContext) } private fun createPopup(project: Project, commitMessage: CommitMessage, messages: List<String>): JBPopup { var chosenMessage: String? = null var selectedMessage: String? = null val rightMargin = getSubjectRightMargin(project) val previewCommandGroup = sentinel("Preview Commit Message") return JBPopupFactory.getInstance().createPopupChooserBuilder(messages) .setFont(commitMessage.editorField.editor?.colorsScheme?.getFont(EditorFontType.PLAIN)) .setVisibleRowCount(7) .setSelectionMode(SINGLE_SELECTION) .setItemSelectedCallback { selectedMessage = it it?.let { preview(project, commitMessage, it, previewCommandGroup) } } .setItemChosenCallback { chosenMessage = it } .setRenderer(object : ColoredListCellRenderer<String>() { override fun customizeCellRenderer(list: JList<out String>, value: @Nls String, index: Int, selected: Boolean, hasFocus: Boolean) { append(first(convertLineSeparators(value, RETURN_SYMBOL), rightMargin, false)) applySpeedSearchHighlighting(list, this, true, selected) } }) .addListener(object : JBPopupListener { override fun beforeShown(event: LightweightWindowEvent) { val popup = event.asPopup() val relativePoint = RelativePoint(commitMessage.editorField, Point(0, -scale(3))) val screenPoint = Point(relativePoint.screenPoint).apply { translate(0, -popup.size.height) } popup.setLocation(screenPoint) } override fun onClosed(event: LightweightWindowEvent) { // IDEA-195094 Regression: New CTRL-E in "commit changes" breaks keyboard shortcuts commitMessage.editorField.requestFocusInWindow() // Use invokeLater() as onClosed() is called before callback from setItemChosenCallback getApplication().invokeLater { chosenMessage ?: cancelPreview(project, commitMessage) } } }) .setNamerForFiltering { it } .setAutoPackHeightOnFiltering(false) .createPopup() .apply { setDataProvider { dataId -> when (dataId) { // default list action does not work as "CopyAction" is invoked first, but with other copy provider COPY_PROVIDER.name -> object : TextCopyProvider() { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun getTextLinesToCopy() = listOfNotNull(selectedMessage).nullize() } else -> null } } } } private fun preview(project: Project, commitMessage: CommitMessage, message: String, groupId: Any) = CommandProcessor.getInstance().executeCommand(project, { commitMessage.setCommitMessage(message) commitMessage.editorField.selectAll() }, "", groupId, commitMessage.editorField.document) private fun cancelPreview(project: Project, commitMessage: CommitMessage) { val manager = UndoManager.getInstance(project) val fileEditor = commitMessage.editorField.editor?.let { TextEditorProvider.getInstance().getTextEditor(it) } if (manager.isUndoAvailable(fileEditor)) manager.undo(fileEditor) } private fun getCommitMessage(e: AnActionEvent) = e.getData(VcsDataKeys.COMMIT_MESSAGE_CONTROL) as? CommitMessage }
apache-2.0
1c8a069bc9b9c9281fdbfe2a278122d0
44.979021
140
0.751331
4.82746
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/notification/notificationUtils.kt
2
2111
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.notification import com.intellij.notification.Notification import com.intellij.notification.Notifications import com.intellij.openapi.application.impl.NonBlockingReadActionImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout fun catchNotificationText(project: Project, action: () -> Unit): String? { val notifications = catchNotifications(project, action).ifEmpty { return null } return notifications.single().content } fun catchNotifications(project: Project, action: () -> Unit): List<Notification> { val myDisposable = Disposer.newDisposable() try { val notifications = mutableListOf<Notification>() val connection = project.messageBus.connect(myDisposable) connection.subscribe(Notifications.TOPIC, object : Notifications { override fun notify(notification: Notification) { notifications += notification } }) action() connection.deliverImmediately() NonBlockingReadActionImpl.waitForAsyncTaskCompletion() return notifications } finally { Disposer.dispose(myDisposable) } } val Notification.asText: String get() = "Title: '$title'\nContent: '$content'" fun List<Notification>.asText(filterNotificationAboutNewKotlinVersion: Boolean = true): String = sortedBy { it.content } .filter { !filterNotificationAboutNewKotlinVersion || !it.content.contains( KotlinBundle.message( "kotlin.external.compiler.updates.notification.content.0", KotlinPluginLayout.standaloneCompilerVersion.kotlinVersion ) ) } .joinToString(separator = "\n-----\n", transform = Notification::asText)
apache-2.0
f4510f75227c73b00590a79112076d48
42.081633
120
0.687352
5.161369
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/reader/PsiKotlinReader.kt
2
10069
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.codegen.patcher import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.workspaceModel.deft.api.annotations.Ignore import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.annotations.Open import com.intellij.workspaceModel.codegen.deft.model.* import com.intellij.workspaceModel.codegen.deft.model.KtAnnotation import com.intellij.workspaceModel.codegen.deft.model.KtConstructor import com.intellij.workspaceModel.codegen.deft.model.KtFile import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi.psiUtil.startsWithComment class PsiKotlinReader(val file: KtFile) { val ktFile = PsiManager.getInstance(file.module.project!!).findFile(file.virtualFile!!)!! as org.jetbrains.kotlin.psi.KtFile val text: CharSequence = file.content() var pos = 0 val c get() = text[pos] var leafScope: KtScope = file.scope var leafBlock: KtBlock = file.block var leafConstructor: KtConstructor? = null private val src = file.asSrc() fun read() { head() blockContents(ktFile) } fun head() { var pkg: String? = null var importsStart = 0 var importsEnd = 0 val packageDirective = ktFile.packageDirective if (packageDirective != null) { importsEnd = packageDirective.textRange.endOffset pkg = packageDirective.qualifiedName } file.setPackage(pkg) val imports = mutableSetOf<String>() val importList = ktFile.importList if (importList != null) { importList.imports.forEach { ktImportDirective -> val importPath = ktImportDirective.importPath?.pathStr if (importPath != null) imports.add(importPath) } importsStart = importList.textRange.startOffset importsEnd = importList.textRange.endOffset } file.setImports(KtImports(importsStart..importsEnd, imports)) } fun blockContents(psiBlock: PsiElement) { var psiElement = psiBlock.firstChild while (psiElement != null) { when (psiElement) { is KtClass -> { when { psiElement.isEnum() -> `interface`(psiElement, WsEnum) psiElement.isData() -> `interface`(psiElement, WsData) psiElement.isSealed() -> `interface`(psiElement, WsSealed) psiElement.isInterface() -> `interface`(psiElement) else -> { } } } is KtObjectDeclaration -> { if (!psiElement.isCompanion()) `interface`(psiElement, WsObject) } is KtProperty -> { if (!isInsideGenerateBlock()) `val`(psiElement) } is PsiComment -> generatedCodeRegion(psiElement) else -> { if (psiElement.startsWithComment()) generatedCodeRegion(psiElement.firstChild as PsiComment) } } psiElement = psiElement.nextSibling } } fun `interface`(ktClass: KtClassOrObject, predefinedInterfaceKind: KtInterfaceKind? = null) { val nameRange = ktClass.nameIdentifier?.textRange ?: return val src = Src(ktClass.name!!) { ktClass.containingFile.text } val name = SrcRange(src, nameRange.startOffset until nameRange.endOffset) if (ktClass.startsWithComment()) generatedCodeRegion(ktClass.firstChild as PsiComment) val constructor = maybePrimaryConstructor(ktClass) val ktTypes = ktClass.superTypeListEntries.mapNotNull { type(it.typeReference) } val outer = leafScope val innerIface = KtInterface(file.module, outer, name, ktTypes, constructor, predefinedInterfaceKind, `annotation`(ktClass.annotationEntries, ktClass)) val inner = innerIface.scope outer.def(name.text, inner) leafScope = inner innerIface.body = maybeBlock(ktClass, inner) leafScope = outer } fun type(ktTypeReference: KtTypeReference?): KtType? { if (ktTypeReference == null) return null val ktAnnotations = `annotation`(ktTypeReference.annotationEntries, ktTypeReference) val typeElement = ktTypeReference.typeElement when (typeElement) { is KtUserType -> { val ktTypes = typeElement.typeArguments.mapNotNull { ktTypeProjection -> type(ktTypeProjection.typeReference) } val range = typeElement.referenceExpression?.srcRange ?: typeElement.srcRange return KtType(range, optional = false, args = ktTypes, annotations = ktAnnotations.list) } is KtNullableType -> { val innerType = typeElement.innerType if (innerType == null) return null val ktTypes: List<KtType> val classifierRange: SrcRange if (innerType is KtUserType) { ktTypes = innerType.typeArguments.mapNotNull { ktTypeProjection -> type(ktTypeProjection.typeReference) } classifierRange = innerType.referenceExpression?.srcRange ?: innerType.srcRange } else { ktTypes = listOf() classifierRange = innerType.srcRange } return KtType(classifierRange, args = ktTypes, optional = true, annotations = ktAnnotations.list) } } return null } fun maybeBlock(ktClass: KtClassOrObject, iface: KtScope? = null): KtBlock { val outer = leafBlock val classBody = ktClass.body if (classBody == null) { // Class has an empty body and the source skips curly braces val inner = KtBlock(src, outer, isStub = true, scope = iface) outer.children.add(inner) return inner } val inner = KtBlock(src, outer, scope = iface) outer.children.add(inner) leafBlock = inner blockContents(classBody) //ktClass.getProperties().forEach { ktProperty -> `val`(ktProperty) } inner.range = range(classBody) //PsiTreeUtil.findChildrenOfType(ktClass, PsiComment::class.java).forEach { psiComment -> generatedCodeRegion(psiComment) } leafBlock = outer return inner } private fun `val`(ktProperty: KtProperty) { val nameRange = ktProperty.nameIdentifier!!.srcRange val getterBody = ktProperty.getter?.bodyExpression?.text leafBlock.defs.add(DefField( nameRange, nameRange.text, type(ktProperty.typeReference), getterBody != null, getterBody, constructorParam = false, suspend = false, annotation(ktProperty.annotationEntries, ktProperty), type(ktProperty.receiverTypeReference), ktProperty.delegateExpression?.srcRange // TODO:: check that working )) } private fun maybePrimaryConstructor(ktClass: KtClassOrObject, iface: KtScope? = null): KtConstructor? { val ktPrimaryConstructor = ktClass.primaryConstructor ?: return null val outer = leafConstructor val constructor = KtConstructor(iface) leafConstructor = constructor val textRange = ktPrimaryConstructor.textRange val src = Src(ktPrimaryConstructor.text) { ktClass.containingFile.text } constructor.range = SrcRange(src, textRange.startOffset until textRange.endOffset) ktPrimaryConstructor.valueParameters.forEach { valueParameter -> constructorVariable(valueParameter) } leafConstructor = outer return constructor } private fun constructorVariable(ktParameter: KtParameter) { val nameRange = ktParameter.nameIdentifier!!.srcRange leafConstructor?.defs?.add(DefField( nameRange, nameRange.text, type(ktParameter.typeReference), expr = false, getterBody = null, true, suspend = false, annotation(ktParameter.annotationEntries, ktParameter) )) } private fun `annotation`(annotationEntries: List<KtAnnotationEntry>, parentElement: PsiElement): KtAnnotations { val annotations = KtAnnotations() listOf(Open::class.simpleName, Child::class.simpleName, Abstract::class.simpleName, Ignore::class.simpleName).forEach { annotationName -> val annotation = annotationEntries.find { it.shortName?.identifier == annotationName } if (annotation != null) { val intRange = (annotation.textRange.startOffset + 1) until annotation.textRange.endOffset val annotationSrc = Src(annotation.shortName?.identifier!!) { parentElement.containingFile.text } annotations.list.add(KtAnnotation(SrcRange(annotationSrc, intRange), emptyList())) } } return annotations } private fun generatedCodeRegion(comment: PsiComment) { if (comment.text.contains("region generated code")) { val extensionBlock = leafBlock.parent == null val block = if (extensionBlock) leafBlock.children.last() else leafBlock if (extensionBlock) { block._extensionCode = comment.startOffset..Int.MAX_VALUE } else { block._generatedCode = comment.startOffset..Int.MAX_VALUE } } if (comment.text.contains("endregion")) { val extensionBlock = leafBlock.parent == null val block = if (extensionBlock) leafBlock.children.last() else leafBlock if (extensionBlock && block._extensionCode != null) { block._extensionCode = block._extensionCode!!.first..comment.endOffset } if (!extensionBlock && block._generatedCode != null) { block._generatedCode = block._generatedCode!!.first..comment.endOffset } } } private fun isInsideGenerateBlock(): Boolean { return leafBlock.children.isNotEmpty() && leafBlock.children.last()._extensionCode != null && leafBlock.children.last()._extensionCode!!.last == Int.MAX_VALUE } private fun range(body: KtClassBody): SrcRange { val textRange = body.textRange return src.range((textRange.startOffset + 1) until (textRange.endOffset - 1)) } override fun toString(): String = SrcPos(src, pos).toString() private val PsiElement.srcRange: SrcRange get() { val src = Src(text) { containingFile.text } return SrcRange(src, textRange.startOffset until textRange.endOffset) } }
apache-2.0
ed592d6aebd41d00f05df54eb8f8e40f
37
162
0.70146
4.657262
false
false
false
false
Maccimo/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/PackageKotlinPlatformsPanel.kt
4
7537
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.HtmlChunk import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.util.HtmlEditorPane import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import org.jetbrains.packagesearch.api.v2.ApiStandardPackage import org.jetbrains.packagesearch.api.v2.ApiStandardPackage.ApiPlatform.PlatformTarget import org.jetbrains.packagesearch.api.v2.ApiStandardPackage.ApiPlatform.PlatformType import javax.swing.BoxLayout internal class PackageKotlinPlatformsPanel : HtmlEditorPane() { init { layout = BoxLayout(this, BoxLayout.Y_AXIS) border = emptyBorder(top = 8) background = PackageSearchUI.UsualBackgroundColor } fun display(platforms: List<ApiStandardPackage.ApiPlatform>) { clear() val chunks = mutableListOf<HtmlChunk>() chunks += HtmlChunk.p().addText(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.kotlinPlatforms")) chunks += HtmlChunk.ul().children( platforms.mapNotNull { platform -> val type: PlatformType = PlatformType.from(platform.type) @NlsSafe val displayName = type.displayName() ?: return@mapNotNull null HtmlChunk.li().addText(displayName).let { element -> val canHaveTargets = type == PlatformType.JS || type == PlatformType.NATIVE val targets = platform.targets if (canHaveTargets && !targets.isNullOrEmpty()) { element.children( HtmlChunk.br(), HtmlChunk.span("font-style: italic;").addText( targets.mapNotNull { PlatformTarget.from(it).displayName() }.joinToString(", ") ) ) } else { element } } } ) setBody(chunks) } fun clear() { clearBody() } private fun PlatformType.displayName() = when (this) { PlatformType.JS -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.js") PlatformType.JVM -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.jvm") PlatformType.COMMON -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.common") PlatformType.NATIVE -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.native") PlatformType.ANDROID_JVM -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.android_jvm") PlatformType.UNSUPPORTED -> null } @Suppress("ComplexMethod") // Not really complex, just a bit ol' lookup table private fun PlatformTarget.displayName() = when (this) { PlatformTarget.NODE -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.node") PlatformTarget.BROWSER -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.browser") PlatformTarget.ANDROID_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.android_x64") PlatformTarget.ANDROID_X86 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.android_x86") PlatformTarget.ANDROID_ARM32 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.android_arm32") PlatformTarget.ANDROID_ARM64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.android_arm64") PlatformTarget.IOS_ARM32 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.ios_arm32") PlatformTarget.IOS_ARM64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.ios_arm64") PlatformTarget.IOS_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.ios_x64") PlatformTarget.WATCHOS_ARM32 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.watchos_arm32") PlatformTarget.WATCHOS_ARM64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.watchos_arm64") PlatformTarget.WATCHOS_X86 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.watchos_x86") PlatformTarget.WATCHOS_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.watchos_x64") PlatformTarget.TVOS_ARM64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.tvos_arm64") PlatformTarget.TVOS_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.tvos_x64") PlatformTarget.LINUX_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.linux_x64") PlatformTarget.MINGW_X86 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.mingw_x86") PlatformTarget.MINGW_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.mingw_x64") PlatformTarget.MACOS_X64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.macos_x64") PlatformTarget.MACOS_ARM64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.macos_arm64") PlatformTarget.LINUX_ARM64 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.linux_arm64") PlatformTarget.LINUX_ARM32_HFP -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.linux_arm32_hfp") PlatformTarget.LINUX_MIPS32 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.linux_mips32") PlatformTarget.LINUX_MIPSEL32 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.linux_mipsel32") PlatformTarget.WASM_32 -> PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.platform.target.wasm32") PlatformTarget.UNSUPPORTED -> null } }
apache-2.0
a4692c2645fbf9ecdc930d2758ee8201
68.787037
150
0.733183
5.307746
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/mediapicker/LoaderViewHolder.kt
1
1074
package org.wordpress.android.ui.mediapicker import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.recyclerview.widget.StaggeredGridLayoutManager.LayoutParams import org.wordpress.android.R class LoaderViewHolder(parent: ViewGroup) : ThumbnailViewHolder(parent, R.layout.media_picker_loader_item) { private val progress: View = itemView.findViewById(R.id.progress) private val retry: Button = itemView.findViewById(R.id.button) fun bind(item: MediaPickerUiItem.NextPageLoader) { setFullWidth() if (item.isLoading) { item.loadAction() progress.visibility = View.VISIBLE retry.visibility = View.GONE } else { progress.visibility = View.GONE retry.visibility = View.VISIBLE retry.setOnClickListener { item.loadAction() } } } private fun setFullWidth() { val layoutParams = itemView.layoutParams as? LayoutParams layoutParams?.isFullSpan = true } }
gpl-2.0
b93de255956cf2de4752785cd65d96b6
32.5625
75
0.674115
4.649351
false
false
false
false
mvysny/vaadin-on-kotlin
vok-example-crud/src/main/kotlin/example/crudflow/person/CreateEditPerson.kt
1
2936
package example.crudflow.person import com.github.mvysny.karibudsl.v10.* import com.github.mvysny.kaributools.setPrimary import com.vaadin.flow.component.HasComponents import com.vaadin.flow.component.button.Button import com.vaadin.flow.component.dialog.Dialog import com.vaadin.flow.component.formlayout.FormLayout import com.vaadin.flow.component.orderedlayout.FlexComponent /** * Edits or creates a person. Use [Window.addCloseListener] to handle window close. * @property person the person to edit or create. */ class CreateEditPerson(val person: Person) : Dialog() { var onSaveOrCreateListener: () -> Unit = {} /** * True if we are creating a new person, false if we are editing an existing one. */ private val creating: Boolean get() = person.id == null private lateinit var persistButton: Button private lateinit var form: PersonForm init { // caption = if (creating) "New Person" else "Edit #${person.id}" verticalLayout { isMargin = true form = personForm() horizontalLayout { isSpacing = true; alignSelf = FlexComponent.Alignment.CENTER persistButton = button(if (creating) "Create" else "Save") { onLeftClick { okPressed() } setPrimary() } button("Cancel") { onLeftClick { close() } } } } form.binder.readBean(person) } private fun okPressed() { if (!form.binder.validate().isOk || !form.binder.writeBeanIfValid(person)) { return } person.save() onSaveOrCreateListener() close() } } /** * The form, which edits a single [Person]. * * To populate the fields, just call `form.binder.readBean(person)` * * To validate and save the data, just call `binder.validate().isOk && binder.writeBeanIfValid(person)` */ class PersonForm : FormLayout() { /** * Populates the fields with data from a bean. Also infers validations from JSR303 annotations attached to the Person class, when * the fieldGroup.bind() is called. */ val binder = beanValidationBinder<Person>() init { textField("Name:") { focus() bind(binder).trimmingConverter().bind(Person::name) } textField("Age:") { bind(binder).toInt().bind(Person::age) } datePicker("Date of birth:") { bind(binder).bind(Person::dateOfBirth) } comboBox<MaritalStatus>("Marital status:") { setItems(*MaritalStatus.values()) bind(binder).bind(Person::maritalStatus) } checkBox("Alive") { bind(binder).bind(Person::alive) } } } @VaadinDsl fun (@VaadinDsl HasComponents).personForm(block: (@VaadinDsl PersonForm).()->Unit = {}) = init(PersonForm(), block)
mit
64c0ec73112f06f50df19f44ac375cf4
31.263736
133
0.610014
4.273654
false
false
false
false
mdaniel/intellij-community
plugins/editorconfig/src/org/editorconfig/language/schema/descriptors/EditorConfigDescriptorVisitor.kt
16
1308
// 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.editorconfig.language.schema.descriptors import org.editorconfig.language.schema.descriptors.impl.* interface EditorConfigDescriptorVisitor { fun visitDescriptor(descriptor: EditorConfigDescriptor) {} fun visitConstant(constant: EditorConfigConstantDescriptor) = visitDescriptor(constant) fun visitOption(option: EditorConfigOptionDescriptor) = visitDescriptor(option) fun visitNumber(number: EditorConfigNumberDescriptor) = visitDescriptor(number) fun visitUnion(union: EditorConfigUnionDescriptor) = visitDescriptor(union) fun visitList(list: EditorConfigListDescriptor) = visitDescriptor(list) fun visitPair(pair: EditorConfigPairDescriptor) = visitDescriptor(pair) fun visitQualifiedKey(qualifiedKey: EditorConfigQualifiedKeyDescriptor) = visitDescriptor(qualifiedKey) fun visitString(string: EditorConfigStringDescriptor) = visitDescriptor(string) fun visitReference(reference: EditorConfigReferenceDescriptor) = visitDescriptor(reference) fun visitDeclaration(declaration: EditorConfigDeclarationDescriptor) = visitDescriptor(declaration) fun visitUnset(unset: EditorConfigUnsetValueDescriptor) = visitDescriptor(unset) }
apache-2.0
139a69a8a65f68095f8630fbf96f4fe4
64.4
140
0.838685
4.973384
false
true
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/chats/sms/SmsSettingsViewModel.kt
3
1373
package org.thoughtcrime.securesms.components.settings.app.chats.sms import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.Util import org.thoughtcrime.securesms.util.livedata.Store class SmsSettingsViewModel : ViewModel() { private val store = Store( SmsSettingsState( useAsDefaultSmsApp = Util.isDefaultSmsProvider(ApplicationDependencies.getApplication()), smsDeliveryReportsEnabled = SignalStore.settings().isSmsDeliveryReportsEnabled, wifiCallingCompatibilityEnabled = SignalStore.settings().isWifiCallingCompatibilityModeEnabled ) ) val state: LiveData<SmsSettingsState> = store.stateLiveData fun setSmsDeliveryReportsEnabled(enabled: Boolean) { store.update { it.copy(smsDeliveryReportsEnabled = enabled) } SignalStore.settings().isSmsDeliveryReportsEnabled = enabled } fun setWifiCallingCompatibilityEnabled(enabled: Boolean) { store.update { it.copy(wifiCallingCompatibilityEnabled = enabled) } SignalStore.settings().isWifiCallingCompatibilityModeEnabled = enabled } fun checkSmsEnabled() { store.update { it.copy(useAsDefaultSmsApp = Util.isDefaultSmsProvider(ApplicationDependencies.getApplication())) } } }
gpl-3.0
1459e9247f22e8c6df46c5e361d1349c
38.228571
118
0.80772
4.886121
false
false
false
false
micolous/metrodroid
src/main/java/au/id/micolous/metrodroid/activity/CardInfoActivity.kt
1
12142
/* * CardInfoActivity.kt * * Copyright (C) 2011 Eric Butler * Copyright 2015-2018 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.activity import android.annotation.SuppressLint import android.app.AlertDialog import android.content.Intent import android.net.Uri import android.os.AsyncTask import android.os.Build import android.os.Bundle import android.speech.tts.TextToSpeech import android.speech.tts.TextToSpeech.OnInitListener import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import androidx.viewpager.widget.ViewPager import au.id.micolous.farebot.R import au.id.micolous.metrodroid.card.Card import au.id.micolous.metrodroid.card.UnsupportedCardException import au.id.micolous.metrodroid.fragment.CardBalanceFragment import au.id.micolous.metrodroid.fragment.CardInfoFragment import au.id.micolous.metrodroid.fragment.CardTripsFragment import au.id.micolous.metrodroid.provider.CardsTableColumns import au.id.micolous.metrodroid.serializers.CardSerializer import au.id.micolous.metrodroid.serializers.XmlOrJsonCardFormat import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.transit.unknown.UnauthorizedClassicTransitData import au.id.micolous.metrodroid.ui.TabPagerAdapter import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.util.Utils /** * @author Eric Butler */ class CardInfoActivity : MetrodroidActivity() { private var mCard: Card? = null private var mTransitData: TransitData? = null private var mTabsAdapter: TabPagerAdapter? = null private var mTTS: TextToSpeech? = null private var mCardSerial: String? = null private var mShowCopyCardNumber = true private var mShowOnlineServices = false private var mShowMoreInfo = false private var mMenu: Menu? = null private fun speakTts(utt: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mTTS?.speak(utt, TextToSpeech.QUEUE_FLUSH, null, null) } else { @Suppress("DEPRECATION") mTTS?.speak(utt, TextToSpeech.QUEUE_FLUSH, null) } } private val mTTSInitListener = OnInitListener { status -> if (status == TextToSpeech.SUCCESS && mTransitData!!.balances != null) { for (balanceVal in mTransitData!!.balances!!) { val balance = balanceVal.balance.formatCurrencyString(true).spanned speakTts(getString(R.string.balance_speech, balance)) } } } @SuppressLint("StaticFieldLeak") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_card_info) val viewPager = findViewById<ViewPager>(R.id.pager) mTabsAdapter = TabPagerAdapter(this, viewPager) setDisplayHomeAsUpEnabled(true) supportActionBar?.setTitle(R.string.loading) object : AsyncTask<Void?, Void?, Void?>() { private var mSpeakBalanceEnabled: Boolean = false private var mException: Exception? = null override fun doInBackground(vararg voids: Void?): Void? { try { val uri = intent.data val cursor = contentResolver.query(uri!!, null, null, null, null) startManagingCursor(cursor) cursor!!.moveToFirst() val data = cursor.getString(cursor.getColumnIndex(CardsTableColumns.DATA)) mCard = XmlOrJsonCardFormat.parseString(data) mTransitData = mCard!!.parseTransitData() mSpeakBalanceEnabled = Preferences.speakBalance } catch (ex: Exception) { mException = ex } return null } override fun onPostExecute(aVoid: Void?) { findViewById<View>(R.id.loading).visibility = View.GONE findViewById<View>(R.id.pager).visibility = View.VISIBLE if (mException != null) { if (mCard == null) { Utils.showErrorAndFinish(this@CardInfoActivity, mException) } else { Log.e(TAG, "Error parsing transit data", mException) showAdvancedInfo(mException) finish() } return } if (mTransitData == null) { showAdvancedInfo(UnsupportedCardException()) finish() return } try { mShowCopyCardNumber = !Preferences.hideCardNumbers mCardSerial = if (mShowCopyCardNumber) { Utils.weakLTR(mTransitData?.serialNumber ?: mCard?.tagId?.toHexString() ?: "") } else { "" } supportActionBar!!.title = mTransitData!!.cardName supportActionBar!!.subtitle = mCardSerial val args = Bundle() args.putString(AdvancedCardInfoActivity.EXTRA_CARD, CardSerializer.toPersist(mCard!!)) args.putParcelable(EXTRA_TRANSIT_DATA, mTransitData) if (mTransitData is UnauthorizedClassicTransitData) { val ucView = findViewById<View>(R.id.unauthorized_card) val loadKeysView = findViewById<View>(R.id.load_keys) ucView.visibility = View.VISIBLE loadKeysView.setOnClickListener { AlertDialog.Builder(this@CardInfoActivity) .setMessage(R.string.add_key_directions) .setPositiveButton(android.R.string.ok, null) .show() } } if (mTransitData!!.balances != null || mTransitData!!.subscriptions != null) { mTabsAdapter!!.addTab(R.string.balances_and_subscriptions, CardBalanceFragment::class.java, args) } if (mTransitData!!.trips != null) { mTabsAdapter!!.addTab(R.string.history, CardTripsFragment::class.java, args) } if (TransitData.hasInfo(mTransitData!!)) { mTabsAdapter!!.addTab(R.string.info, CardInfoFragment::class.java, args) } val w = mTransitData!!.warning val hasUnknownStation = mTransitData!!.hasUnknownStations if (w != null || hasUnknownStation) { findViewById<View>(R.id.need_stations).visibility = View.VISIBLE var txt = "" if (hasUnknownStation) txt = getString(R.string.need_stations) if (w != null && txt.isNotEmpty()) txt += "\n" if (w != null) txt += w (findViewById<View>(R.id.need_stations_text) as TextView).text = txt findViewById<View>(R.id.need_stations_button).visibility = if (hasUnknownStation) View.VISIBLE else View.GONE } if (hasUnknownStation) findViewById<View>(R.id.need_stations_button).setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://micolous.github.io/metrodroid/unknown_stops"))) } mShowMoreInfo = mTransitData!!.moreInfoPage != null mShowOnlineServices = mTransitData!!.onlineServicesPage != null if (mMenu != null) { mMenu!!.findItem(R.id.online_services).isVisible = mShowOnlineServices mMenu!!.findItem(R.id.more_info).isVisible = mShowMoreInfo } val speakBalanceRequested = intent.getBooleanExtra(SPEAK_BALANCE_EXTRA, false) if (mSpeakBalanceEnabled && speakBalanceRequested) { mTTS = TextToSpeech(this@CardInfoActivity, mTTSInitListener) } if (savedInstanceState != null) { viewPager.currentItem = savedInstanceState.getInt(KEY_SELECTED_TAB, 0) } } catch (e: Exception) { Log.e(TAG, "Error parsing transit data", e) showAdvancedInfo(e) finish() } } }.execute() } override fun onSaveInstanceState(bundle: Bundle) { super.onSaveInstanceState(bundle) bundle.putInt(KEY_SELECTED_TAB, (findViewById<View>(R.id.pager) as ViewPager).currentItem) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.card_info_menu, menu) menu.findItem(R.id.copy_card_number).isVisible = mShowCopyCardNumber menu.findItem(R.id.online_services).isVisible = mShowOnlineServices menu.findItem(R.id.more_info).isVisible = mShowMoreInfo mMenu = menu return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { val intent = Intent(this, CardsActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) return true } R.id.copy_card_number -> { if (mShowCopyCardNumber && mCardSerial != null) { Utils.copyTextToClipboard(this, "Card number", mCardSerial!!) } return true } R.id.advanced_info -> { showAdvancedInfo(null) return true } R.id.more_info -> if (mTransitData!!.moreInfoPage != null) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(mTransitData!!.moreInfoPage))) return true } R.id.online_services -> if (mTransitData!!.onlineServicesPage != null) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(mTransitData!!.onlineServicesPage))) return true } } return false } private fun showAdvancedInfo(ex: Exception?) { val intent = Intent(this, AdvancedCardInfoActivity::class.java) intent.putExtra(AdvancedCardInfoActivity.EXTRA_CARD, CardSerializer.toPersist(mCard!!)) if (ex != null) { intent.putExtra(AdvancedCardInfoActivity.EXTRA_ERROR, ex) } startActivity(intent) } companion object { const val EXTRA_TRANSIT_DATA = "transit_data" const val SPEAK_BALANCE_EXTRA = "au.id.micolous.farebot.speak_balance" private const val KEY_SELECTED_TAB = "selected_tab" private const val TAG = "CardInfoActivity" } }
gpl-3.0
8d249a0ae85a1385ff88f23e6ef6fc8b
39.608696
200
0.5789
5.027743
false
false
false
false
darkoverlordofdata/entitas-kotlin
core/src/com/darkoverlordofdata/entitas/demo/systems/EntitySpawningTimerSystem.kt
1
1732
package com.darkoverlordofdata.entitas.demo.systems /** * EntitySpawningTimerSystem * * Periodically spawn enemy ships * */ import com.badlogic.gdx.Gdx import com.darkoverlordofdata.entitas.demo.* import com.darkoverlordofdata.entitas.IExecuteSystem import com.darkoverlordofdata.entitas.Pool class EntitySpawningTimerSystem(game: GameScene, pool: Pool) : IExecuteSystem { private val game = game private val pool = pool private val Timer1 = 2f private val Timer2 = 6f private val Timer3 = 12f private var t1 = Timer1 private var t2 = Timer2 private var t3 = Timer3 val toWorldX:Float get() = 320f/game.width val toWorldY:Float get() = 480f/game.height val width:Float get() = game.width*toWorldX val height:Float get() = game.height*toWorldY enum class Enemies { Enemy1, Enemy2, Enemy3 } override fun execute() { val delta = Gdx.graphics.deltaTime t1 = spawnEnemy(delta, t1, Enemies.Enemy1) t2 = spawnEnemy(delta, t2, Enemies.Enemy2) t3 = spawnEnemy(delta, t3, Enemies.Enemy3) } fun spawnEnemy(delta: Float, t:Float, enemy: Enemies): Float { val remaining = t - delta return if (remaining < 0) { when (enemy) { Enemies.Enemy1 -> { pool.createEnemy1(width, height) Timer1 } Enemies.Enemy2 -> { pool.createEnemy2(width, height) Timer2 } Enemies.Enemy3 -> { pool.createEnemy3(width, height) Timer3 } } } else remaining } }
mit
8414b97789495de9ebd8d23fa07b7495
25.661538
66
0.580831
3.848889
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/hierarchy/calls/callers/kotlinClass/main0.kt
13
412
class <caret>KA { val name = "A" fun foo(s: String): String = "A: $s" } fun packageFun(s: String): String = s + KA().name val packageVal = KA().name class KClient { init { KA() } companion object { val a = KA() } val bar: String get() = KA().name fun bar() { fun localFun() = KA() KA() } } object KClientObj { val a = KA() }
apache-2.0
5b14b3562c6b685dd9855ae44cf3e419
12.322581
49
0.475728
3.007299
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitThisInspection.kt
4
4960
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.util.getFactoryForImplicitReceiverWithSubtypeOf import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ImplicitThisInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) { if (expression.receiverExpression != null) return handle(expression, expression.callableReference, ::CallableReferenceFix) } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { if (expression !is KtNameReferenceExpression) return if (expression.parent is KtThisExpression) return if (expression.parent is KtCallableReferenceExpression) return if (expression.isSelectorOfDotQualifiedExpression()) return val parent = expression.parent if (parent is KtCallExpression && parent.isSelectorOfDotQualifiedExpression()) return handle(expression, expression, ::CallFix) } private fun handle(expression: KtExpression, reference: KtReferenceExpression, fixFactory: (String) -> LocalQuickFix) { val context = reference.safeAnalyzeNonSourceRootCode() val scope = reference.getResolutionScope(context) ?: return val resolvedCall = reference.getResolvedCall(context) ?: return val variableDescriptor = (resolvedCall as? VariableAsFunctionResolvedCall)?.variableCall?.resultingDescriptor val callableDescriptor = resolvedCall.resultingDescriptor val receiverDescriptor = variableDescriptor?.receiverDescriptor() ?: callableDescriptor.receiverDescriptor() ?: return val receiverType = receiverDescriptor.type val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType) ?: return val receiverText = if (expressionFactory.isImmediate) "this" else expressionFactory.expressionText val fix = fixFactory(receiverText) holder.registerProblem( expression, KotlinBundle.message("callable.reference.fix.family.name", receiverText), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fix ) } private fun CallableDescriptor.receiverDescriptor(): ReceiverParameterDescriptor? { return extensionReceiverParameter ?: dispatchReceiverParameter } private fun KtExpression.isSelectorOfDotQualifiedExpression(): Boolean { val parent = parent return parent is KtDotQualifiedExpression && parent.selectorExpression == this } } private class CallFix(private val receiverText: String) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("callable.reference.fix.family.name", receiverText) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtExpression ?: return val factory = KtPsiFactory(project) val call = expression.parent as? KtCallExpression ?: expression call.replace(factory.createExpressionByPattern("$0.$1", receiverText, call)) } } private class CallableReferenceFix(private val receiverText: String) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("callable.reference.fix.family.name", receiverText) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtCallableReferenceExpression ?: return val factory = KtPsiFactory(project) val reference = expression.callableReference expression.replace(factory.createExpressionByPattern("$0::$1", receiverText, reference)) } } }
apache-2.0
6249f7b34b7e9f61d9d95729cb3b254f
50.14433
158
0.737097
5.961538
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/capture/MediaCaptureRepository.kt
2
6723
package org.thoughtcrime.securesms.mediasend.v2.capture import android.annotation.SuppressLint import android.content.ContentUris import android.content.Context import android.net.Uri import android.os.Build import android.provider.MediaStore import androidx.annotation.WorkerThread import org.signal.core.util.CursorUtil import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.mediasend.Media import org.thoughtcrime.securesms.mediasend.MediaRepository import org.thoughtcrime.securesms.providers.BlobProvider import org.thoughtcrime.securesms.util.MediaUtil import org.thoughtcrime.securesms.util.StorageUtil import org.thoughtcrime.securesms.video.VideoUtil import java.io.FileDescriptor import java.io.FileInputStream import java.io.IOException import java.util.LinkedList import java.util.Optional private val TAG = Log.tag(MediaCaptureRepository::class.java) class MediaCaptureRepository(context: Context) { private val context: Context = context.applicationContext fun getMostRecentItem(callback: (Media?) -> Unit) { if (!StorageUtil.canReadFromMediaStore()) { Log.w(TAG, "Cannot read from storage.") callback(null) return } SignalExecutors.BOUNDED.execute { val media: List<Media> = getMediaInBucket(context, Media.ALL_MEDIA_BUCKET_ID, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true) callback(media.firstOrNull()) } } fun renderImageToMedia(data: ByteArray, width: Int, height: Int, onMediaRendered: (Media) -> Unit, onFailedToRender: () -> Unit) { SignalExecutors.BOUNDED.execute { val media: Media? = renderCaptureToMedia( dataSupplier = { data }, getLength = { data.size.toLong() }, createBlobBuilder = { blobProvider, bytes, _ -> blobProvider.forData(bytes) }, mimeType = MediaUtil.IMAGE_JPEG, width = width, height = height ) if (media != null) { onMediaRendered(media) } else { onFailedToRender() } } } fun renderVideoToMedia(fileDescriptor: FileDescriptor, onMediaRendered: (Media) -> Unit, onFailedToRender: () -> Unit) { SignalExecutors.BOUNDED.execute { val media: Media? = renderCaptureToMedia( dataSupplier = { FileInputStream(fileDescriptor) }, getLength = { it.channel.size() }, createBlobBuilder = BlobProvider::forData, mimeType = VideoUtil.RECORDED_VIDEO_CONTENT_TYPE, width = 0, height = 0 ) if (media != null) { onMediaRendered(media) } else { onFailedToRender() } } } private fun <T> renderCaptureToMedia( dataSupplier: () -> T, getLength: (T) -> Long, createBlobBuilder: (BlobProvider, T, Long) -> BlobProvider.BlobBuilder, mimeType: String, width: Int, height: Int ): Media? { return try { val data: T = dataSupplier() val length: Long = getLength(data) val uri: Uri = createBlobBuilder(BlobProvider.getInstance(), data, length) .withMimeType(mimeType) .createForSingleSessionOnDisk(context) Media( uri, mimeType, System.currentTimeMillis(), width, height, length, 0, false, false, Optional.of(Media.ALL_MEDIA_BUCKET_ID), Optional.empty(), Optional.empty() ) } catch (e: IOException) { return null } } companion object { @SuppressLint("VisibleForTests") @WorkerThread private fun getMediaInBucket(context: Context, bucketId: String, contentUri: Uri, isImage: Boolean): List<Media> { val media: MutableList<Media> = LinkedList() var selection: String? = MediaStore.Images.Media.BUCKET_ID + " = ? AND " + isNotPending() var selectionArgs: Array<String>? = arrayOf(bucketId) val sortBy = MediaStore.Images.Media.DATE_MODIFIED + " DESC" val projection: Array<String> = if (isImage) { arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.MIME_TYPE, MediaStore.Images.Media.DATE_MODIFIED, MediaStore.Images.Media.ORIENTATION, MediaStore.Images.Media.WIDTH, MediaStore.Images.Media.HEIGHT, MediaStore.Images.Media.SIZE) } else { arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.MIME_TYPE, MediaStore.Images.Media.DATE_MODIFIED, MediaStore.Images.Media.WIDTH, MediaStore.Images.Media.HEIGHT, MediaStore.Images.Media.SIZE, MediaStore.Video.Media.DURATION) } if (Media.ALL_MEDIA_BUCKET_ID == bucketId) { selection = isNotPending() selectionArgs = null } context.contentResolver.query(contentUri, projection, selection, selectionArgs, sortBy).use { cursor -> while (cursor != null && cursor.moveToNext()) { val rowId = CursorUtil.requireLong(cursor, projection[0]) val uri = ContentUris.withAppendedId(contentUri, rowId) val mimetype = CursorUtil.requireString(cursor, MediaStore.Images.Media.MIME_TYPE) val date = CursorUtil.requireLong(cursor, MediaStore.Images.Media.DATE_MODIFIED) val orientation = if (isImage) CursorUtil.requireInt(cursor, MediaStore.Images.Media.ORIENTATION) else 0 val width = CursorUtil.requireInt(cursor, getWidthColumn(orientation)) val height = CursorUtil.requireInt(cursor, getHeightColumn(orientation)) val size = CursorUtil.requireLong(cursor, MediaStore.Images.Media.SIZE) val duration = if (!isImage) CursorUtil.requireInt(cursor, MediaStore.Video.Media.DURATION).toLong() else 0.toLong() media.add( MediaRepository.fixMimeType( context, Media( uri, mimetype, date, width, height, size, duration, false, false, Optional.of(bucketId), Optional.empty(), Optional.empty() ) ) ) } } return media } private fun getWidthColumn(orientation: Int): String { return if (orientation == 0 || orientation == 180) MediaStore.Images.Media.WIDTH else MediaStore.Images.Media.HEIGHT } private fun getHeightColumn(orientation: Int): String { return if (orientation == 0 || orientation == 180) MediaStore.Images.Media.HEIGHT else MediaStore.Images.Media.WIDTH } @Suppress("DEPRECATION") private fun isNotPending(): String { return if (Build.VERSION.SDK_INT <= 28) MediaStore.Images.Media.DATA + " NOT NULL" else MediaStore.MediaColumns.IS_PENDING + " != 1" } } }
gpl-3.0
a3db44e83cfe7d40891829d10281d69a
35.145161
248
0.663097
4.396991
false
false
false
false
mdanielwork/intellij-community
platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsState.kt
1
7733
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.ui import com.intellij.openapi.components.BaseState import com.intellij.openapi.util.SystemInfo import com.intellij.util.PlatformUtils import com.intellij.util.ui.UIUtil import com.intellij.util.xmlb.Accessor import com.intellij.util.xmlb.SerializationFilter import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.Transient import javax.swing.SwingConstants class UISettingsState : BaseState() { companion object { /** * Returns the default font size scaled by #defFontScale * * @return the default scaled font size */ @JvmStatic val defFontSize: Int get() = Math.round(UIUtil.DEF_SYSTEM_FONT_SIZE * UISettings.defFontScale) } // These font properties should not be set in the default ctor, // so that to make the serialization logic judge if a property // should be stored or shouldn't by the provided filter only. @get:Property(filter = FontFilter::class) @get:OptionTag("FONT_FACE") var fontFace by string() @get:Property(filter = FontFilter::class) @get:OptionTag("FONT_SIZE") var fontSize by property(defFontSize) @get:Property(filter = FontFilter::class) @get:OptionTag("FONT_SCALE") var fontScale by property(0f) @get:OptionTag("RECENT_FILES_LIMIT") var recentFilesLimit by property(50) @get:OptionTag("CONSOLE_COMMAND_HISTORY_LIMIT") var consoleCommandHistoryLimit by property(300) @get:OptionTag("OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE") var overrideConsoleCycleBufferSize by property(false) @get:OptionTag("CONSOLE_CYCLE_BUFFER_SIZE_KB") var consoleCycleBufferSizeKb by property(1024) @get:OptionTag("EDITOR_TAB_LIMIT") var editorTabLimit by property(10) @get:OptionTag("REUSE_NOT_MODIFIED_TABS") var reuseNotModifiedTabs by property(false) @get:OptionTag("ANIMATE_WINDOWS") var animateWindows by property(true) @get:OptionTag("SHOW_TOOL_WINDOW_NUMBERS") var showToolWindowsNumbers by property(true) @get:OptionTag("HIDE_TOOL_STRIPES") var hideToolStripes by property(false) @get:OptionTag("WIDESCREEN_SUPPORT") var wideScreenSupport by property(false) @get:OptionTag("LEFT_HORIZONTAL_SPLIT") var leftHorizontalSplit by property(false) @get:OptionTag("RIGHT_HORIZONTAL_SPLIT") var rightHorizontalSplit by property(false) @get:OptionTag("SHOW_EDITOR_TOOLTIP") var showEditorToolTip by property(true) @get:OptionTag("SHOW_MEMORY_INDICATOR") var showMemoryIndicator by property(false) @get:OptionTag("ALLOW_MERGE_BUTTONS") var allowMergeButtons by property(true) @get:OptionTag("SHOW_MAIN_TOOLBAR") var showMainToolbar by property(false) @get:OptionTag("SHOW_STATUS_BAR") var showStatusBar by property(true) @get:OptionTag("SHOW_NAVIGATION_BAR") var showNavigationBar by property(true) @get:OptionTag("ALWAYS_SHOW_WINDOW_BUTTONS") var alwaysShowWindowsButton by property(false) @get:OptionTag("CYCLE_SCROLLING") var cycleScrolling by property(true) @get:OptionTag("SCROLL_TAB_LAYOUT_IN_EDITOR") var scrollTabLayoutInEditor by property(true) @get:OptionTag("HIDE_TABS_IF_NEED") var hideTabsIfNeed by property(true) @get:OptionTag("SHOW_CLOSE_BUTTON") var showCloseButton by property(true) @get:OptionTag("CLOSE_TAB_BUTTON_ON_THE_RIGHT") var closeTabButtonOnTheRight by property(true) @get:OptionTag("EDITOR_TAB_PLACEMENT") var editorTabPlacement: Int by property(SwingConstants.TOP) @get:OptionTag("HIDE_KNOWN_EXTENSION_IN_TABS") var hideKnownExtensionInTabs by property(false) @get:OptionTag("SHOW_ICONS_IN_QUICK_NAVIGATION") var showIconInQuickNavigation by property(true) @get:OptionTag("CLOSE_NON_MODIFIED_FILES_FIRST") var closeNonModifiedFilesFirst by property(false) @get:OptionTag("ACTIVATE_MRU_EDITOR_ON_CLOSE") var activeMruEditorOnClose by property(false) // TODO[anton] consider making all IDEs use the same settings @get:OptionTag("ACTIVATE_RIGHT_EDITOR_ON_CLOSE") var activeRightEditorOnClose by property(PlatformUtils.isAppCode()) @get:OptionTag("IDE_AA_TYPE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.ideAAType")) internal var ideAAType by property(AntialiasingType.SUBPIXEL) @get:OptionTag("EDITOR_AA_TYPE") @Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.editorAAType")) internal var editorAAType by property(AntialiasingType.SUBPIXEL) @get:OptionTag("COLOR_BLINDNESS") var colorBlindness by enum<ColorBlindness>() @get:OptionTag("MOVE_MOUSE_ON_DEFAULT_BUTTON") var moveMouseOnDefaultButton by property(false) @get:OptionTag("ENABLE_ALPHA_MODE") var enableAlphaMode by property(false) @get:OptionTag("ALPHA_MODE_DELAY") var alphaModeDelay by property(1500) @get:OptionTag("ALPHA_MODE_RATIO") var alphaModeRatio by property(0.5f) @get:OptionTag("MAX_CLIPBOARD_CONTENTS") var maxClipboardContents by property(5) @get:OptionTag("OVERRIDE_NONIDEA_LAF_FONTS") var overrideLafFonts by property(false) @get:OptionTag("SHOW_ICONS_IN_MENUS") var showIconsInMenus by property(!PlatformUtils.isAppCode()) // IDEADEV-33409, should be disabled by default on MacOS @get:OptionTag("DISABLE_MNEMONICS") var disableMnemonics by property(SystemInfo.isMac) @get:OptionTag("DISABLE_MNEMONICS_IN_CONTROLS") var disableMnemonicsInControls by property(false) @get:OptionTag("USE_SMALL_LABELS_ON_TABS") var useSmallLabelsOnTabs by property(SystemInfo.isMac) @get:OptionTag("MAX_LOOKUP_WIDTH2") var maxLookupWidth by property(500) @get:OptionTag("MAX_LOOKUP_LIST_HEIGHT") var maxLookupListHeight by property(11) @get:OptionTag("HIDE_NAVIGATION_ON_FOCUS_LOSS") var hideNavigationOnFocusLoss by property(true) @get:OptionTag("DND_WITH_PRESSED_ALT_ONLY") var dndWithPressedAltOnly by property(false) @get:OptionTag("DEFAULT_AUTOSCROLL_TO_SOURCE") var defaultAutoScrollToSource by property(false) @Transient var presentationMode: Boolean = false @get:OptionTag("PRESENTATION_MODE_FONT_SIZE") var presentationModeFontSize by property(24) @get:OptionTag("MARK_MODIFIED_TABS_WITH_ASTERISK") var markModifiedTabsWithAsterisk by property(false) @get:OptionTag("SHOW_TABS_TOOLTIPS") var showTabsTooltips by property(true) @get:OptionTag("SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES") var showDirectoryForNonUniqueFilenames by property(true) var smoothScrolling by property(SystemInfo.isMac && (SystemInfo.isJetBrainsJvm || SystemInfo.IS_AT_LEAST_JAVA9)) @get:OptionTag("NAVIGATE_TO_PREVIEW") var navigateToPreview by property(false) @get:OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY") var sortLookupElementsLexicographically by property(false) @get:OptionTag("MERGE_EQUAL_STACKTRACES") var mergeEqualStackTraces by property(true) @get:OptionTag("SORT_BOOKMARKS") var sortBookmarks by property(false) @get:OptionTag("PIN_FIND_IN_PATH_POPUP") var pinFindInPath by property(false) private class FontFilter : SerializationFilter { override fun accepts(accessor: Accessor, bean: Any): Boolean { val settings = bean as UISettingsState val fontData = systemFontFaceAndSize if ("fontFace" == accessor.name) { return fontData.first != settings.fontFace } // fontSize/fontScale should either be stored in pair or not stored at all // otherwise the fontSize restore logic gets broken (see loadState) return !(fontData.second == settings.fontSize && 1f == settings.fontScale) } } @Suppress("FunctionName") fun _incrementModificationCount() = incrementModificationCount() }
apache-2.0
79f97a8ca506c4be62837954f79504df
39.920635
140
0.766455
4.025508
false
false
false
false
kdwink/intellij-community
plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/ShowDecompiledClassAction.kt
4
2201
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.java.decompiler import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilBase class ShowDecompiledClassAction : AnAction(IdeaDecompilerBundle.message("action.show.decompiled.name")) { override fun update(e: AnActionEvent) { val visible = getPsiElement(e)?.containingFile is PsiClassOwner e.presentation.isVisible = visible e.presentation.isEnabled = visible && getOriginalFile(getPsiElement(e)) != null } override fun actionPerformed(e: AnActionEvent) { val file = getOriginalFile(getPsiElement(e)) if (file != null) { val vFile = file.virtualFile if (vFile != null) { OpenFileDescriptor(file.project, vFile, -1).navigate(true) } } } private fun getPsiElement(e: AnActionEvent): PsiElement? { val project = e.project ?: return null val editor = e.getData(CommonDataKeys.EDITOR) ?: return e.getData(CommonDataKeys.PSI_ELEMENT) return PsiUtilBase.getPsiFileInEditor(editor, project)?.findElementAt(editor.caretModel.offset) } private fun getOriginalFile(psiElement: PsiElement?): PsiFile? { val psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass::class.java, false) val original = psiClass?.originalElement return if (original != psiClass && original is PsiCompiledElement) original.containingFile else null } }
apache-2.0
c9f8bdb416c284c279eb4d2fa3ccd20f
39.777778
105
0.75602
4.393214
false
false
false
false
dahlstrom-g/intellij-community
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/statistician/SearchEverywhereActionStatistician.kt
4
1991
package com.intellij.ide.actions.searcheverywhere.ml.features.statistician import com.intellij.ide.ui.RegistryBooleanOptionDescriptor import com.intellij.ide.ui.RegistryTextOptionDescriptor import com.intellij.ide.ui.search.OptionDescription import com.intellij.ide.util.gotoByName.GotoActionModel.ActionWrapper import com.intellij.ide.util.gotoByName.GotoActionModel.MatchedValue import com.intellij.openapi.actionSystem.ActionManager import com.intellij.psi.statistics.StatisticsInfo internal class SearchEverywhereActionStatistician : SearchEverywhereStatistician<MatchedValue>(MatchedValue::class.java) { override fun serializeElement(element: MatchedValue, location: String): StatisticsInfo? { val value = getValue(element) ?: return null val context = getContext(element) ?: return null return StatisticsInfo(context, value) } private fun getValue(element: MatchedValue) = when (val value = element.value) { is ActionWrapper -> getValueForAction(value) is OptionDescription -> value.hit ?: value.option else -> null } private fun getValueForAction(action: ActionWrapper) = ActionManager.getInstance().getId(action.action) ?: action.action.javaClass.name override fun getContext(element: MatchedValue) = when (val value = element.value) { is ActionWrapper -> getContextForAction(value) is OptionDescription -> getContextForOption(value) else -> null }?.let { context -> "$contextPrefix#$context" } private fun getContextForAction(action: ActionWrapper): String { return action.groupMapping ?.firstGroup ?.mapNotNull { ActionManager.getInstance().getId(it) } ?.joinToString("|") ?: "action" } private fun getContextForOption(option: OptionDescription): String { return if (option is RegistryBooleanOptionDescriptor || option is RegistryTextOptionDescriptor) { "registry" } else { option.configurableId ?: option.groupName ?: "option" } } }
apache-2.0
faf3fef3475401bb04f5854f020492c1
39.653061
137
0.750879
4.630233
false
false
false
false
dahlstrom-g/intellij-community
platform/service-container/src/com/intellij/serviceContainer/constructorInjection.kt
8
8263
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.serviceContainer import com.intellij.diagnostic.PluginException import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.extensions.PluginId import com.intellij.util.messages.MessageBus import java.io.File import java.lang.Deprecated import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException import java.nio.file.Path import kotlin.Any import kotlin.Array import kotlin.Boolean import kotlin.Comparator import kotlin.Pair import kotlin.RuntimeException import kotlin.Suppress import kotlin.let internal fun <T> instantiateUsingPicoContainer(aClass: Class<*>, requestorKey: Any, pluginId: PluginId, componentManager: ComponentManagerImpl, parameterResolver: ConstructorParameterResolver): T { val sortedMatchingConstructors = getSortedMatchingConstructors(aClass) val parameterTypes: Array<Class<*>> val constructor: Constructor<*> if (sortedMatchingConstructors.size == 1) { constructor = sortedMatchingConstructors.first() parameterTypes = constructor.parameterTypes } else { // first round - try to find without extensions (because class can have several constructors - we cannot resolve using extension area at first place, // because some another constructor can be satisfiable val result = getGreediestSatisfiableConstructor(aClass, sortedMatchingConstructors, requestorKey, pluginId, componentManager, parameterResolver, false) constructor = result.first parameterTypes = result.second } try { constructor.isAccessible = true if (parameterTypes.isEmpty()) { @Suppress("UNCHECKED_CAST") return constructor.newInstance() as T } else { var isErrorLogged = false @Suppress("UNCHECKED_CAST") return constructor.newInstance(*Array(parameterTypes.size) { val parameterType = parameterTypes.get(it) if (!isErrorLogged && !ComponentManager::class.java.isAssignableFrom(parameterType) && parameterType != MessageBus::class.java) { isErrorLogged = true if (pluginId.idString != "org.jetbrains.kotlin") { LOG.warn("Do not use constructor injection (requestorClass=${aClass.name})") } } parameterResolver.resolveInstance(componentManager, requestorKey, aClass, constructor, parameterType, pluginId) }) as T } } catch (e: InvocationTargetException) { throw e.cause ?: e } catch (e: InstantiationException) { throw RuntimeException("Cannot create class $aClass", e) } } internal fun isNotApplicableClass(type: Class<*>): Boolean { return type.isPrimitive || type.isEnum || type.isArray || java.util.Collection::class.java.isAssignableFrom(type) || java.util.Map::class.java.isAssignableFrom(type) || type === java.lang.String::class.java || type === File::class.java || type === Path::class.java } private fun getGreediestSatisfiableConstructor(aClass: Class<*>, sortedMatchingConstructors: Array<Constructor<*>>, requestorKey: Any, pluginId: PluginId, componentManager: ComponentManagerImpl, parameterResolver: ConstructorParameterResolver, isExtensionSupported: Boolean): Pair<Constructor<*>, Array<Class<*>>> { var conflicts: MutableSet<Constructor<*>>? = null var unsatisfiableDependencyTypes: MutableSet<Array<Class<*>>>? = null var greediestConstructor: Constructor<*>? = null var greediestConstructorParameterTypes: Array<Class<*>>? = null var lastSatisfiableConstructorSize = -1 var unsatisfiedDependencyType: Class<*>? = null val lastIndex = sortedMatchingConstructors.size - 1 var someConstructorWasChecked = false for (index in 0..lastIndex) { val constructor = sortedMatchingConstructors[index] if (constructor.isSynthetic) { continue } var failedDependency = false val parameterTypes = constructor.parameterTypes // first, perform fast check to ensure that assert about getComponentAdapterOfType is thrown only if constructor is applicable if (parameterTypes.any(::isNotApplicableClass)) { continue } if (!someConstructorWasChecked && index == lastIndex) { // Don't call isResolvable at all - resolveInstance will do it. No need to check the only constructor in advance. return Pair(constructor, parameterTypes) } if (lastIndex > 0 && (constructor.isAnnotationPresent(NonInjectable::class.java) || constructor.isAnnotationPresent(Deprecated::class.java))) { continue } someConstructorWasChecked = true for (expectedType in parameterTypes) { // check whether this constructor is satisfiable if (parameterResolver.isResolvable(componentManager, requestorKey, aClass, constructor, expectedType, pluginId, isExtensionSupported)) { continue } if (unsatisfiableDependencyTypes == null) { unsatisfiableDependencyTypes = HashSet() } unsatisfiableDependencyTypes.add(parameterTypes) unsatisfiedDependencyType = expectedType failedDependency = true break } if (greediestConstructor != null && parameterTypes.size != lastSatisfiableConstructorSize) { if (conflicts.isNullOrEmpty()) { // we found our match (greedy and satisfied) return Pair(greediestConstructor, greediestConstructorParameterTypes!!) } else { // fits although not greedy conflicts.add(constructor) } } else if (!failedDependency && lastSatisfiableConstructorSize == parameterTypes.size) { // satisfied and same size as previous one? if (conflicts == null) { conflicts = HashSet() } conflicts.add(constructor) greediestConstructor?.let { conflicts.add(it) } } else if (!failedDependency) { greediestConstructor = constructor greediestConstructorParameterTypes = parameterTypes lastSatisfiableConstructorSize = parameterTypes.size } } when { !conflicts.isNullOrEmpty() -> { throw PluginException("Too many satisfiable constructors: ${sortedMatchingConstructors.joinToString { it.toString() }}", pluginId) } greediestConstructor != null -> { return Pair(greediestConstructor, greediestConstructorParameterTypes!!) } !unsatisfiableDependencyTypes.isNullOrEmpty() -> { // second (and final) round if (isExtensionSupported) { throw PluginException("${aClass.name} has unsatisfied dependency: $unsatisfiedDependencyType among unsatisfiable dependencies: " + "$unsatisfiableDependencyTypes where $componentManager was the leaf container being asked for dependencies.", pluginId) } else { return getGreediestSatisfiableConstructor(aClass, sortedMatchingConstructors, requestorKey, pluginId, componentManager, parameterResolver, true) } } else -> { throw PluginException("The specified parameters not match any of the following constructors: " + "${aClass.declaredConstructors.joinToString(separator = "\n") { it.toString() }}\n" + "for $aClass", pluginId) } } } private val constructorComparator = Comparator<Constructor<*>> { c0, c1 -> c1.parameterCount - c0.parameterCount } // filter out all constructors that will definitely not match // optimize list of constructors moving the longest at the beginning private fun getSortedMatchingConstructors(componentImplementation: Class<*>): Array<Constructor<*>> { val declaredConstructors = componentImplementation.declaredConstructors declaredConstructors.sortWith(constructorComparator) return declaredConstructors }
apache-2.0
ba5eaad6daff64498370254917898cc5
40.949239
155
0.684013
5.290013
false
false
false
false
evoasm/evoasm
src/evoasm/x64/Populations.kt
1
3078
package evoasm.x64 import kasm.x64.VroundssXmmXmmXmmm32Imm8 class LongPopulation(sampleSet: LongSampleSet, options: PopulationOptions) : NumberPopulation<Long>(sampleSet, options) { override val programSetInput = LongProgramSetInput(sampleSet.size, sampleSet.inputArity) override val programSetOutput = LongProgramSetOutput(programSet.programCount, programSetInput) override val interpreter = Interpreter(programSet, programSetInput, programSetOutput, options = options.interpreterOptions) init { loadInput(sampleSet) seed() } } class FloatPopulation(sampleSet: FloatSampleSet, options: PopulationOptions) : NumberPopulation<Float>(sampleSet, options) { override val programSetInput = FloatProgramSetInput(sampleSet.size, sampleSet.inputArity) override val programSetOutput = FloatProgramSetOutput(programSet.programCount, programSetInput) override val interpreter = Interpreter(programSet, programSetInput, programSetOutput, options = options.interpreterOptions) init { loadInput(sampleSet) seed() } fun compile(program: Program) { LOGGER.fine(interpreter.buffer.toByteString()) val programSetInput = FloatProgramSetInput(1, interpreter.input.arity) val programSetOutput = FloatProgramSetOutput(1, programSetInput) val compiledProgram = CompiledNumberProgram(program, interpreter, programSetInput, programSetOutput) for (i in 1..5) { LOGGER.fine("f($i) = ${compiledProgram.run(i.toFloat())}") } } fun compileBest() { compile(bestProgram) } } fun main() { val options = PopulationOptions( 128_000, 4, 123456, 12, InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_SS_AVX_XMM_INSTRUCTIONS.instructions.filterNot { it == VroundssXmmXmmXmmm32Imm8 }, moveInstructions = listOf(), compressOpcodes = false, forceMultithreading = false, threadCount = 5, unsafe = false), 0.01f, demeSize = 10, majorGenerationFrequency = 1, maxOffspringRatio = 0.05 ) val sampleSet = FloatSampleSet(1, 0.0f, 0.0f, 0.5f, 1.0606601717798212f, 1.0f, 1.7320508075688772f, 1.5f, 2.5248762345905194f, 2.0f, 3.4641016151377544f, 2.5f, 4.541475531146237f, 3.0f, 5.744562646538029f, 3.5f, 7.0622234459127675f, 4.0f, 8.48528137423857f, 4.5f, 10.00624804809475f, 5.0f, 11.61895003862225f ) // val sampleSet = FloatSampleSet.generate(0f, 5.0f, 0.5f) { // Math.sqrt(Math.pow(it.toDouble(), 3.0) + 4 * it).toFloat() // } val population = FloatPopulation(sampleSet, options) if(population.run()) { AbstractPopulation.LOGGER.fine("recompiling best solution...") population.compileBest() } }
agpl-3.0
548b80cc944d10f11bc3ce731abe9d9b
33.58427
156
0.636127
4.071429
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/util/AttachmentPicker.kt
1
8374
package jp.juggler.subwaytooter.util import android.Manifest import android.content.ContentValues import android.content.Intent import android.net.Uri import android.provider.MediaStore import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.dialog.ActionsDialog import jp.juggler.subwaytooter.kJson import jp.juggler.util.* import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString class AttachmentPicker( val activity: AppCompatActivity, val callback: Callback, ) { companion object { private val log = LogCategory("AttachmentPicker") private const val PERMISSION_REQUEST_CODE = 1 } // callback after media selected interface Callback { fun onPickAttachment(uri: Uri, mimeType: String? = null) fun onPickCustomThumbnail(pa: PostAttachment, src: GetContentResultEntry) fun resumeCustomThumbnailTarget(id: String?): PostAttachment? } // actions after permission granted enum class AfterPermission { Attachment, CustomThumbnail, } @Serializable data class States( @Serializable(with = UriSerializer::class) var uriCameraImage: Uri? = null, var customThumbnailTargetId: String? = null, ) private var states = States() //////////////////////////////////////////////////////////////////////// // activity result handlers private val arAttachmentChooser = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.handleGetContentResult(activity.contentResolver)?.pickAll() } private val arCamera = ActivityResultHandler(log) { r -> if (r.isNotOk) { // 失敗したら DBからデータを削除 states.uriCameraImage?.let { uri -> activity.contentResolver.delete(uri, null, null) states.uriCameraImage = null } } else { // 画像のURL when (val uri = r.data?.data ?: states.uriCameraImage) { null -> activity.showToast(false, "missing image uri") else -> callback.onPickAttachment(uri) } } } private val arCapture = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.data?.let { callback.onPickAttachment(it) } } private val arCustomThumbnail = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data ?.handleGetContentResult(activity.contentResolver) ?.firstOrNull() ?.let { callback.resumeCustomThumbnailTarget(states.customThumbnailTargetId)?.let { pa -> callback.onPickCustomThumbnail(pa, it) } } } private val prPickAttachment = PermissionRequester( permissions = listOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), deniedId = R.string.missing_permission_to_access_media, ) { openPicker() } private val prPickCustomThumbnail = PermissionRequester( permissions = listOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), deniedId = R.string.missing_permission_to_access_media, ) { callback.resumeCustomThumbnailTarget(states.customThumbnailTargetId) ?.let { openCustomThumbnail(it) } } init { // must register all ARHs before onStart prPickAttachment.register(activity) prPickCustomThumbnail.register(activity) arAttachmentChooser.register(activity) arCamera.register(activity) arCapture.register(activity) arCustomThumbnail.register(activity) } //////////////////////////////////////////////////////////////////////// // states fun reset() { states.uriCameraImage = null } fun encodeState(): String { val encoded = kJson.encodeToString(states) val decoded = kJson.decodeFromString<States>(encoded) log.d("encodeState: ${decoded.uriCameraImage},$encoded") return encoded } fun restoreState(encoded: String) { states = kJson.decodeFromString(encoded) log.d("restoreState: ${states.uriCameraImage},$encoded") } //////////////////////////////////////////////////////////////////////// fun openPicker() { if (!prPickAttachment.checkOrLaunch()) return // permissionCheck = ContextCompat.checkSelfPermission( this, Manifest.permission.CAMERA ); // if( permissionCheck != PackageManager.PERMISSION_GRANTED ){ // preparePermission(); // return; // } with(activity) { val a = ActionsDialog() a.addAction(getString(R.string.pick_images)) { openAttachmentChooser(R.string.pick_images, "image/*", "video/*") } a.addAction(getString(R.string.pick_videos)) { openAttachmentChooser(R.string.pick_videos, "video/*") } a.addAction(getString(R.string.pick_audios)) { openAttachmentChooser(R.string.pick_audios, "audio/*") } a.addAction(getString(R.string.image_capture)) { performCamera() } a.addAction(getString(R.string.video_capture)) { performCapture( MediaStore.ACTION_VIDEO_CAPTURE, "can't open video capture app." ) } a.addAction(getString(R.string.voice_capture)) { performCapture( MediaStore.Audio.Media.RECORD_SOUND_ACTION, "can't open voice capture app." ) } a.show(this, null) } } private fun openAttachmentChooser(titleId: Int, vararg mimeTypes: String) { // SAFのIntentで開く try { val intent = intentGetContent(true, activity.getString(titleId), mimeTypes) arAttachmentChooser.launch(intent) } catch (ex: Throwable) { log.trace(ex) activity.showToast(ex, "ACTION_GET_CONTENT failed.") } } private fun performCamera() { try { val values = ContentValues().apply { put(MediaStore.Images.Media.TITLE, "${System.currentTimeMillis()}.jpg") put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") } val newUri = activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) .also { states.uriCameraImage = it } val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply { putExtra(MediaStore.EXTRA_OUTPUT, newUri) } arCamera.launch(intent) } catch (ex: Throwable) { log.trace(ex) activity.showToast(ex, "opening camera app failed.") } } private fun performCapture(action: String, errorCaption: String) { try { arCapture.launch(Intent(action)) } catch (ex: Throwable) { log.trace(ex) activity.showToast(ex, errorCaption) } } private fun ArrayList<GetContentResultEntry>.pickAll() = forEach { callback.onPickAttachment(it.uri, it.mimeType) } /////////////////////////////////////////////////////////////////////////////// // Mastodon's custom thumbnail fun openCustomThumbnail(pa: PostAttachment) { states.customThumbnailTargetId = pa.attachment?.id?.toString() if (!prPickCustomThumbnail.checkOrLaunch()) return // SAFのIntentで開く try { arCustomThumbnail.launch( intentGetContent(false, activity.getString(R.string.pick_images), arrayOf("image/*")) ) } catch (ex: Throwable) { log.trace(ex) activity.showToast(ex, "ACTION_GET_CONTENT failed.") } } }
apache-2.0
703f2a2b60ffdd5fbc15067a1fad4ce3
33.130802
100
0.569661
4.889019
false
false
false
false
paplorinc/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameGrFieldProcessor.kt
6
8262
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.refactoring.rename import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PropertyUtilBase import com.intellij.psi.util.PsiFormatUtil import com.intellij.psi.util.PsiFormatUtilBase import com.intellij.psi.util.parentOfType import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenameJavaVariableProcessor import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodResolverProcessor import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle.message import java.util.* import kotlin.collections.HashMap /** * @author ilyas */ open class RenameGrFieldProcessor : RenameJavaVariableProcessor() { override fun canProcessElement(element: PsiElement): Boolean = element is GrField override fun findReferences(element: PsiElement): Collection<PsiReference> { assert(element is GrField) val refs = ArrayList<PsiReference>() val field = element as GrField val projectScope = GlobalSearchScope.projectScope(element.getProject()) val setter = field.setter if (setter != null) { refs.addAll(RenameAliasedUsagesUtil.filterAliasedRefs(MethodReferencesSearch.search(setter, projectScope, true).findAll(), setter)) } val getters = field.getters for (getter in getters) { refs.addAll(RenameAliasedUsagesUtil.filterAliasedRefs(MethodReferencesSearch.search(getter, projectScope, true).findAll(), getter)) } refs.addAll(RenameAliasedUsagesUtil.filterAliasedRefs(ReferencesSearch.search(field, projectScope, false).findAll(), field)) return refs } override fun renameElement(element: PsiElement, newName: String, usages: Array<out UsageInfo>, listener: RefactoringElementListener?) { val oldResolvedRefs = HashMap<GrReferenceExpression, PsiElement>() for (usage in usages) { val ref = usage.reference as? GrReferenceExpression ?: continue val resovled = ref.resolve() oldResolvedRefs[ref] = resovled ?: continue } val field = element as GrField for (usage in usages) { val ref = usage.reference if (ref is GrReferenceExpression) { val resolved = oldResolvedRefs[ref] ref.handleElementRename(resolved.getNewNameFromTransformations(newName)) } else if (ref != null) { handleElementRename(newName, ref, field.name) } } field.name = newName val manager = element.getManager() for (expression in oldResolvedRefs.keys) { val oldResolved = oldResolvedRefs[expression] ?: continue val resolved = expression.resolve() ?: continue if (manager.areElementsEquivalent(oldResolved, resolved)) continue if (oldResolved == field || isQualificationNeeded(manager, oldResolved, resolved)) { qualify(field, expression) } } listener?.elementRenamed(element) } private fun handleElementRename(newName: String, ref: PsiReference, fieldName: String) { val refText = if (ref is PsiQualifiedReference) { ref.referenceName } else { ref.canonicalText } val toRename: String = when { fieldName == refText -> newName GroovyPropertyUtils.getGetterNameNonBoolean(fieldName) == refText -> GroovyPropertyUtils.getGetterNameNonBoolean(newName) GroovyPropertyUtils.getGetterNameBoolean(fieldName) == refText -> GroovyPropertyUtils.getGetterNameBoolean(newName) GroovyPropertyUtils.getSetterName(fieldName) == refText -> GroovyPropertyUtils.getSetterName(newName) else -> newName } ref.handleElementRename(toRename) } private fun qualify(member: PsiMember, refExpr: GrReferenceExpression) { val referenceName = refExpr.referenceName ?: return val clazz = member.containingClass ?: return if (refExpr.qualifierExpression != null) return val manager = member.manager val project = manager.project val newText = when { member.hasModifierProperty(PsiModifier.STATIC) -> "${clazz.qualifiedName}.$referenceName" manager.areElementsEquivalent(refExpr.parentOfType<PsiClass>(), clazz) -> "this.$referenceName" else -> "${clazz.qualifiedName}.this.$referenceName" } val newRefExpr = GroovyPsiElementFactory.getInstance(project).createReferenceExpressionFromText(newText) val replaced = refExpr.replace(newRefExpr) JavaCodeStyleManager.getInstance(project).shortenClassReferences(replaced) } override fun findCollisions(element: PsiElement, newName: String, allRenames: Map<out PsiElement, String>, result: MutableList<UsageInfo>) { val collisions = ArrayList<UsageInfo>() for (info in result) { if (info !is MoveRenameUsageInfo) continue val refExpr = info.getElement() as? GrReferenceExpression ?: continue if (refExpr.parent !is GrCall) continue val referencedElement = info.referencedElement if (!(referencedElement is GrField || refExpr.advancedResolve().isInvokedOnProperty)) continue val argTypes = PsiUtil.getArgumentTypes(refExpr, false) val typeArguments = refExpr.typeArguments val processor = MethodResolverProcessor(newName, refExpr, false, null, argTypes, typeArguments) val resolved = ResolveUtil.resolveExistingElement(refExpr, processor, PsiMethod::class.java) ?: continue collisions.add(object : UnresolvableCollisionUsageInfo(resolved, refExpr) { override fun getDescription(): String = message( "usage.will.be.overriden.by.method", refExpr.parent.text, PsiFormatUtil.formatMethod(resolved, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME, PsiFormatUtilBase.SHOW_TYPE) ) }) } result.addAll(collisions) super.findCollisions(element, newName, allRenames, result) } override fun findExistingNameConflicts(element: PsiElement, newName: String, conflicts: MultiMap<PsiElement, String>) { super.findExistingNameConflicts(element, newName, conflicts) val field = element as GrField val containingClass = field.containingClass ?: return val getter = GroovyPropertyUtils.findGetterForField(field) if (getter is GrAccessorMethod) { val newGetter = PropertyUtilBase.findPropertyGetter(containingClass, newName, field.hasModifierProperty(PsiModifier.STATIC), true) if (newGetter != null && newGetter !is GrAccessorMethod) { conflicts.putValue(newGetter, message("implicit.getter.will.by.overriden.by.method", field.name, newGetter.name)) } } val setter = GroovyPropertyUtils.findSetterForField(field) if (setter is GrAccessorMethod) { val newSetter = PropertyUtilBase.findPropertySetter(containingClass, newName, field.hasModifierProperty(PsiModifier.STATIC), true) if (newSetter != null && newSetter !is GrAccessorMethod) { conflicts.putValue(newSetter, message("implicit.setter.will.by.overriden.by.method", field.name, newSetter.name)) } } } }
apache-2.0
1ed9820f7e686d3601608e4e7218f845
43.659459
140
0.742435
4.806283
false
false
false
false
lisuperhong/ModularityApp
KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/adapter/FollowCardAdapter.kt
1
2914
package com.lisuperhong.openeye.ui.adapter import android.app.Activity import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.lisuperhong.openeye.R import com.lisuperhong.openeye.mvp.model.bean.FollowCard import com.lisuperhong.openeye.utils.ImageLoad import com.lisuperhong.openeye.utils.JumpActivityUtil import com.lisuperhong.openeye.utils.TimeUtil import com.lisuperhong.openeye.utils.TypefaceUtil import kotlinx.android.synthetic.main.item_followcard.view.* /** * Author: lizhaohong * Time: Create on 2018/8/6 17:22 * Desc: */ class FollowCardAdapter(context: Context, datas: ArrayList<FollowCard>) : RecyclerView.Adapter<FollowCardAdapter.ViewHolder>() { private var context: Context? = null private var dataList: ArrayList<FollowCard> = ArrayList<FollowCard>() init { this.context = context this.dataList = datas } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_today_recommend, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return dataList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val followCard = dataList[position] val header = followCard.header holder.followCardTitle.typeface = TypefaceUtil.getTypefaceFromAsset(TypefaceUtil.FZLanTingCuHei) holder.followCardTitle.text = header.title holder.followCardSubTitle.text = header.description when (header.iconType) { "round" -> ImageLoad.loadCircleImage(holder.followCardIconIv, header.icon) "square" -> ImageLoad.loadImage(holder.followCardIconIv, header.icon, 5) else -> ImageLoad.loadImage(holder.followCardIconIv, header.icon) } val content = followCard.content val data = content.data val cover = data.cover ImageLoad.loadImage(holder.followCardCoverIv, cover.feed, 5) holder.followCardTimeTv.text = TimeUtil.secToTime(data.duration) holder.followCardCoverIv.setOnClickListener { val videoSmallCard = followCard.content.data JumpActivityUtil.startVideoDetail(context as Activity, holder.followCardCoverIv, videoSmallCard) } } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var followCardCoverIv: ImageView = view.followCardCoverIv var followCardTimeTv: TextView = view.followCardTimeTv var followCardIconIv: ImageView = view.followCardIconIv var followCardTitle: TextView = view.followCardTitle var followCardSubTitle: TextView = view.followCardSubTitle } }
apache-2.0
e071316e9a9dadd346e78b0a521995ce
37.355263
108
0.731297
4.291605
false
false
false
false
google/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/tests/testData/entityWithCollections/after/gen/CollectionFieldEntityImpl.kt
1
8277
package com.intellij.workspaceModel.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CollectionFieldEntityImpl(val dataSource: CollectionFieldEntityData) : CollectionFieldEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val versions: Set<Int> get() = dataSource.versions override val names: List<String> get() = dataSource.names override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: CollectionFieldEntityData?) : ModifiableWorkspaceEntityBase<CollectionFieldEntity>(), CollectionFieldEntity.Builder { constructor() : this(CollectionFieldEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CollectionFieldEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isVersionsInitialized()) { error("Field CollectionFieldEntity#versions should be initialized") } if (!getEntityData().isNamesInitialized()) { error("Field CollectionFieldEntity#names should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as CollectionFieldEntity this.entitySource = dataSource.entitySource this.versions = dataSource.versions.toMutableSet() this.names = dataSource.names.toMutableList() if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } private val versionsUpdater: (value: Set<Int>) -> Unit = { value -> changedProperty.add("versions") } override var versions: MutableSet<Int> get() { val collection_versions = getEntityData().versions if (collection_versions !is MutableWorkspaceSet) return collection_versions collection_versions.setModificationUpdateAction(versionsUpdater) return collection_versions } set(value) { checkModificationAllowed() getEntityData().versions = value versionsUpdater.invoke(value) } private val namesUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("names") } override var names: MutableList<String> get() { val collection_names = getEntityData().names if (collection_names !is MutableWorkspaceList) return collection_names collection_names.setModificationUpdateAction(namesUpdater) return collection_names } set(value) { checkModificationAllowed() getEntityData().names = value namesUpdater.invoke(value) } override fun getEntityData(): CollectionFieldEntityData = result ?: super.getEntityData() as CollectionFieldEntityData override fun getEntityClass(): Class<CollectionFieldEntity> = CollectionFieldEntity::class.java } } class CollectionFieldEntityData : WorkspaceEntityData<CollectionFieldEntity>() { lateinit var versions: MutableSet<Int> lateinit var names: MutableList<String> fun isVersionsInitialized(): Boolean = ::versions.isInitialized fun isNamesInitialized(): Boolean = ::names.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CollectionFieldEntity> { val modifiable = CollectionFieldEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): CollectionFieldEntity { return getCached(snapshot) { val entity = CollectionFieldEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): CollectionFieldEntityData { val clonedEntity = super.clone() clonedEntity as CollectionFieldEntityData clonedEntity.versions = clonedEntity.versions.toMutableWorkspaceSet() clonedEntity.names = clonedEntity.names.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CollectionFieldEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return CollectionFieldEntity(versions, names, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CollectionFieldEntityData if (this.entitySource != other.entitySource) return false if (this.versions != other.versions) return false if (this.names != other.names) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CollectionFieldEntityData if (this.versions != other.versions) return false if (this.names != other.names) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + versions.hashCode() result = 31 * result + names.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + versions.hashCode() result = 31 * result + names.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.versions?.let { collector.add(it::class.java) } this.names?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
aca2fa7dcc12d00a607ab1734105e4a2
33.202479
145
0.730337
5.431102
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/MacToolbarFrameHeader.kt
1
3801
// 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.openapi.wm.impl.customFrameDecorations.header import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.impl.IdeMenuBar import com.intellij.openapi.wm.impl.ToolbarHolder import com.intellij.openapi.wm.impl.customFrameDecorations.CustomFrameTitleButtons import com.intellij.openapi.wm.impl.headertoolbar.MainToolbar import com.intellij.ui.awt.RelativeRectangle import com.intellij.ui.mac.MacMainFrameDecorator import com.intellij.util.ui.JBUI import com.jetbrains.CustomWindowDecoration import com.jetbrains.JBR import java.awt.BorderLayout import java.awt.Component import java.awt.Rectangle import java.beans.PropertyChangeListener import javax.swing.JComponent import javax.swing.JFrame import javax.swing.JRootPane private const val GAP_FOR_BUTTONS = 80 private const val DEFAULT_HEADER_HEIGHT = 40 internal class MacToolbarFrameHeader(private val frame: JFrame, private val root: JRootPane, private val ideMenu: IdeMenuBar) : CustomHeader(frame), MainFrameCustomHeader, ToolbarHolder { private var toolbar: MainToolbar? private val LEFT_GAP = JBUI.scale(16) private val RIGHT_GAP = JBUI.scale(24) init { layout = BorderLayout() root.addPropertyChangeListener(MacMainFrameDecorator.FULL_SCREEN, PropertyChangeListener { updateBorders() }) add(ideMenu, BorderLayout.NORTH) toolbar = createToolBar() } private fun createToolBar(): MainToolbar { val toolbar = MainToolbar() toolbar.isOpaque = false toolbar.border = JBUI.Borders.empty(0, LEFT_GAP, 0, RIGHT_GAP) add(toolbar, BorderLayout.CENTER) return toolbar } override fun initToolbar() { var tb = toolbar if (tb == null) { tb = createToolBar() toolbar = tb } tb.init((frame as? IdeFrame)?.project) } override fun updateToolbar() { removeToolbar() val toolbar = createToolBar() this.toolbar = toolbar toolbar.init((frame as? IdeFrame)?.project) revalidate() updateCustomDecorationHitTestSpots() } override fun removeToolbar() { val toolbar = toolbar ?: return this.toolbar = null remove(toolbar) revalidate() } override fun windowStateChanged() { super.windowStateChanged() updateBorders() } override fun addNotify() { super.addNotify() updateBorders() val decor = JBR.getCustomWindowDecoration() decor.setCustomDecorationTitleBarHeight(frame, DEFAULT_HEADER_HEIGHT) } override fun createButtonsPane(): CustomFrameTitleButtons = CustomFrameTitleButtons.create(myCloseAction) override fun getHitTestSpots(): Sequence<Pair<RelativeRectangle, Int>> { return (toolbar ?: return emptySequence()) .components .asSequence() .filter { it.isVisible } .map { Pair(getElementRect(it), CustomWindowDecoration.MENU_BAR) } } override fun updateMenuActions(forceRebuild: Boolean) = ideMenu.updateMenuActions(forceRebuild) override fun getComponent(): JComponent = this override fun dispose() {} private fun getElementRect(comp: Component): RelativeRectangle { val rect = Rectangle(comp.size) return RelativeRectangle(comp, rect) } override fun getHeaderBackground(active: Boolean) = JBUI.CurrentTheme.CustomFrameDecorations.mainToolbarBackground(active) private fun updateBorders() { val isFullscreen = root.getClientProperty(MacMainFrameDecorator.FULL_SCREEN) != null border = if (isFullscreen) JBUI.Borders.empty() else JBUI.Borders.emptyLeft(GAP_FOR_BUTTONS) } override fun updateActive() { super.updateActive() toolbar?.background = getHeaderBackground(myActive) } }
apache-2.0
8ee8f4bf1f2d5b397999741217cf7676
30.421488
131
0.737174
4.46651
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/markerblocks/impl/HtmlBlockMarkerBlock.kt
1
2890
package org.intellij.markdown.parser.markerblocks.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl import org.intellij.markdown.parser.sequentialparsers.SequentialParser import kotlin.text.Regex public class HtmlBlockMarkerBlock(myConstraints: MarkdownConstraints, private val productionHolder: ProductionHolder, private val endCheckingRegex: Regex?, startPosition: LookaheadText.Position) : MarkerBlockImpl(myConstraints, productionHolder.mark()) { init { productionHolder.addProduction(listOf(SequentialParser.Node( startPosition.offset..startPosition.nextLineOrEofOffset, MarkdownTokenTypes.HTML_BLOCK_CONTENT))) } override fun allowsSubBlocks(): Boolean = false override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true override fun getDefaultAction(): MarkerBlock.ClosingAction { return MarkerBlock.ClosingAction.DONE } override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult { if (pos.offsetInCurrentLine != -1) { return MarkerBlock.ProcessingResult.CANCEL } val prevLine = pos.prevLine ?: return MarkerBlock.ProcessingResult.DEFAULT if (!MarkdownConstraints.fillFromPrevious(pos.currentLine, 0, constraints).extendsPrev(constraints)) { return MarkerBlock.ProcessingResult.DEFAULT } if (endCheckingRegex == null && MarkdownParserUtil.calcNumberOfConsequentEols(pos, constraints) >= 2) { return MarkerBlock.ProcessingResult.DEFAULT } else if (endCheckingRegex != null && endCheckingRegex.match(prevLine) != null) { return MarkerBlock.ProcessingResult.DEFAULT } if (pos.currentLine.isNotEmpty()) { productionHolder.addProduction(listOf(SequentialParser.Node( pos.offset + 1 + constraints.getCharsEaten(pos.currentLine)..pos.nextLineOrEofOffset, MarkdownTokenTypes.HTML_BLOCK_CONTENT))) } return MarkerBlock.ProcessingResult.CANCEL } override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int { return pos.nextLineOrEofOffset } override fun getDefaultNodeType(): IElementType { return MarkdownElementTypes.HTML_BLOCK } }
apache-2.0
bbed37be0157ee1809d78b1ee6284ef2
42.149254
133
0.729412
5.622568
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/reportUtils.kt
1
6577
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images.sync import java.nio.file.Path 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 ""}" return 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() } } internal fun findCommitsToSync(context: Context) { if (context.doSyncDevRepo && context.devSyncRequired()) { context.iconsCommitsToSync = findCommitsByRepo(context, context.iconRepoDir, context.byDesigners) } if (context.doSyncIconsRepo && context.iconsSyncRequired()) { context.devCommitsToSync = findCommitsByRepo(context, context.devRepoDir, context.byDev) } } internal fun Map<Path, Collection<CommitInfo>>.commitMessage(): String = values.flatten().joinToString(separator = "\n\n") { it.subject + "\n" + "Origin commit: ${it.hash}" } internal fun commit(context: Context) { if (context.iconsCommitsToSync.isEmpty()) { return } stageFiles(gitStatus(context.devRepoRoot).all(), context.devRepoRoot) if (gitStage(context.devRepoRoot).isEmpty()) { log("Nothing to commit") context.byDesigners.clear() } else { val user = triggeredBy() val branch = head(context.devRepoRoot) commit(branch, user.name, user.email, context.iconsCommitsToSync.commitMessage(), context.devRepoRoot) } } internal fun pushToIconsRepo(branch: String, context: Context): List<CommitInfo> = context.devCommitsToSync.values.flatten() .groupBy(CommitInfo::committer) .mapNotNull { (committer, commits) -> checkout(context.iconRepo, 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.iconRepo).isEmpty()) { log("Nothing to commit") context.byDev.clear() null } else { commitAndPush(branch, committer.name, committer.email, commits.groupBy(CommitInfo::repo).commitMessage(), context.iconRepo) } } private fun findCommitsByRepo(context: Context, root: Path, changes: Changes): Map<Path, Collection<CommitInfo>> { val commits = findCommits(context, root, changes) if (commits.isEmpty()) { return emptyMap() } log("${commits.size} commits found") return commits.map { it.key }.groupBy(CommitInfo::repo) } internal fun findRepo(file: Path) = findGitRepoRoot(file, silent = true) private fun findCommits(context: Context, root: Path, changes: Changes) = changes.all() .mapNotNull { change -> val absoluteFile = root.resolve(change) val repo = findRepo(absoluteFile) val commit = latestChangeCommit(repo.relativize(absoluteFile).toString(), 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.getValue(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, repo: Path): CommitInfo = run { execute(repo, GIT, "checkout", "-B", branch) commitAndPush(repo, branch, message, user, email) } private fun commit(branch: String, user: String, email: String, message: String, repo: Path) { execute(repo, GIT, "checkout", "-B", branch) commit(repo, message, user, email) } private val CHANNEL_WEB_HOOK = System.getProperty("intellij.icons.slack.channel") internal fun notifySlackChannel(investigator: Investigator, context: Context) { val investigation = if (investigator.isAssigned) { "Investigation is assigned to ${investigator.email}" } else "Unable to assign investigation to ${investigator.email}" notifySlackChannel(investigation, context, success = false) } internal fun notifySlackChannel(message: String, context: Context, success: Boolean) { val reaction = if (success) ":white_check_mark:" else ":sadfrog:" val build = "See ${slackLink("build log", thisBuildReportableLink())}" val text = "*${context.devRepoName}* $reaction\n${message.replace("\"", "\\\"")}\n$build" val body = """{ "text": "$text" }""" val response = try { post(CHANNEL_WEB_HOOK, body, mediaType = null) } catch (e: Exception) { log("Post of '$body' has failed") throw e } if (response != "ok") error("$CHANNEL_WEB_HOOK responded with $response, body is '$body'") } internal fun slackLink(linkText: String, linkUrl: String) = "<$linkUrl|$linkText>"
apache-2.0
17f98bac88c64ca31e6cfea8f76ffd59
40.898089
158
0.686483
3.938323
false
false
false
false
youdonghai/intellij-community
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileModifiableModel.kt
1
4397
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.ex import com.intellij.codeInspection.ModifiableModel import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.InvalidDataException import com.intellij.openapi.util.WriteExternalException import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.util.Consumer open class InspectionProfileModifiableModel(val source: InspectionProfileImpl) : InspectionProfileImpl(source.name, source.myRegistrar, source.profileManager, source.myBaseProfile, null), ModifiableModel { private var modified = false init { myUninitializedSettings.putAll(source.myUninitializedSettings) isProjectLevel = source.isProjectLevel myLockedProfile = source.myLockedProfile copyFrom(source) } fun isChanged() = modified || source.myLockedProfile != myLockedProfile fun setModified(value: Boolean) { modified = value } override fun copyToolsConfigurations(project: Project?) { copyToolsConfigurations(source, project) } override fun createTools(project: Project?) = source.getDefaultStates(project).map { it.tool } private fun copyToolsConfigurations(profile: InspectionProfileImpl, project: Project?) { try { for (toolList in profile.myTools.values) { val tools = myTools[toolList.shortName]!! val defaultState = toolList.defaultState tools.setDefaultState(copyToolSettings(defaultState.tool), defaultState.isEnabled, defaultState.level) tools.removeAllScopes() val nonDefaultToolStates = toolList.nonDefaultTools if (nonDefaultToolStates != null) { for (state in nonDefaultToolStates) { val toolWrapper = copyToolSettings(state.tool) val scope = state.getScope(project) if (scope == null) { tools.addTool(state.scopeName, toolWrapper, state.isEnabled, state.level) } else { tools.addTool(scope, toolWrapper, state.isEnabled, state.level) } } } tools.isEnabled = toolList.isEnabled } } catch (e: WriteExternalException) { LOG.error(e) } catch (e: InvalidDataException) { LOG.error(e) } } fun isProperSetting(toolId: String): Boolean { if (myBaseProfile != null) { val tools = myBaseProfile.getTools(toolId, null) val currentTools = myTools[toolId] return !Comparing.equal<Tools>(tools, currentTools) } return false } fun resetToBase(project: Project?) { initInspectionTools(project) copyToolsConfigurations(myBaseProfile, project) myChangedToolNames = null } //invoke when isChanged() == true fun commit() { source.commit(this) modified = false } fun resetToEmpty(project: Project) { initInspectionTools(project) for (toolWrapper in getInspectionTools(null)) { disableTool(toolWrapper.shortName, project) } } private fun InspectionProfileImpl.commit(model: InspectionProfileImpl) { name = model.name description = model.description isProjectLevel = model.isProjectLevel myLockedProfile = model.myLockedProfile myChangedToolNames = model.myChangedToolNames myTools = model.myTools profileManager = model.profileManager } override fun toString() = "$name (copy)" } fun modifyAndCommitProjectProfile(project: Project, action: Consumer<ModifiableModel>) { ProjectInspectionProfileManager.getInstance(project).currentProfile.edit { action.consume(this) } } inline fun InspectionProfileImpl.edit(task: InspectionProfileModifiableModel.() -> Unit) { val model = InspectionProfileModifiableModel(this) model.task() model.commit() profileManager.fireProfileChanged(this) }
apache-2.0
223ee0bcfdbb5c03d6dedca545e08da6
32.823077
205
0.726404
4.599372
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/ui/util/SingleValueModel.kt
2
1630
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.util import com.intellij.openapi.Disposable import com.intellij.util.EventDispatcher import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.plugins.github.pullrequest.ui.SimpleEventListener import org.jetbrains.plugins.github.util.GithubUtil class SingleValueModel<T>(initialValue: T) : com.intellij.util.ui.codereview.SingleValueModel<T> { private val changeEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java) override var value by GithubUtil.Delegates.observableField(initialValue, changeEventDispatcher) @RequiresEdt fun addAndInvokeValueChangedListener(listener: () -> Unit) = SimpleEventListener.addAndInvokeListener(changeEventDispatcher, listener) @RequiresEdt fun addValueChangedListener(disposable: Disposable, listener: () -> Unit) = SimpleEventListener.addDisposableListener(changeEventDispatcher, disposable, listener) @RequiresEdt fun addValueChangedListener(listener: () -> Unit) = SimpleEventListener.addListener(changeEventDispatcher, listener) @RequiresEdt override fun addValueUpdatedListener(listener: (newValue: T) -> Unit) { SimpleEventListener.addListener(changeEventDispatcher) { listener(value) } } fun <R> map(mapper: (T) -> R): SingleValueModel<R> { val mappedModel = SingleValueModel(value.let(mapper)) addValueChangedListener { mappedModel.value = value.let(mapper) } return mappedModel } }
apache-2.0
bbff94b7f2ff36ed59c6172ec9aaa7fe
38.780488
140
0.785276
4.697406
false
false
false
false