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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
anthonycr/Base47
|
sample/src/main/kotlin/com/anthonycr/base47/sample/MainActivity.kt
|
1
|
2927
|
package com.anthonycr.base47.sample
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.support.annotation.WorkerThread
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.TextView
import com.anthonycr.base47.Base47
import com.anthonycr.base47.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val handlerThread = HandlerThread("encoding-thread")
private val backgroundHandler by lazy { Handler(handlerThread.looper) }
@Volatile private var postRunnable: Runnable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
handlerThread.start()
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
postOrQueueRunnable(Runnable { encode(editable.toString(), textEncoded, textDecoded) })
}
})
editText.setText("Hello World \uD83D\uDE0E")
}
private fun postOrQueueRunnable(encodeRunnable: Runnable) {
val wrapperRunnable = object : Runnable {
override fun run() {
encodeRunnable.run()
val runnable = postRunnable
if (this != runnable && runnable != null) {
runnable.run()
} else {
postRunnable = null
}
}
}
if (postRunnable != null) {
postRunnable = wrapperRunnable
} else {
backgroundHandler.post(wrapperRunnable)
}
}
override fun onDestroy() {
super.onDestroy()
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2) {
handlerThread.quitSafely()
} else {
handlerThread.quit()
}
}
}
private val TAG = "MainActivity"
private val MAIN = Handler(Looper.getMainLooper())
@WorkerThread
private fun encode(textToEncode: String,
encodeView: TextView,
decodeView: TextView) {
val encoded = Base47.encode(textToEncode.toByteArray())
Log.d(TAG, "ENCODED: " + encoded)
val decoded = String(Base47.decode(encoded))
Log.d(TAG, "DECODED: " + decoded)
MAIN.post {
val context = encodeView.context
encodeView.text = context.getString(R.string.encoded, encoded)
decodeView.text = context.getString(R.string.decoded, decoded)
}
}
|
mit
|
91d775910c34c36a644de5b2fdfaeaaa
| 29.821053 | 103 | 0.649812 | 4.53096 | false | false | false | false |
ntemplon/legends-of-omterra
|
core/src/com/jupiter/europa/util/Quadtree.kt
|
1
|
6397
|
/*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.util
import java.awt.Rectangle
import java.util.HashSet
/**
* This class is still mostly untested; that will have to wait until there are enough entities running around to do
* something about it.
* @author Nathan Templon
* *
* @param
*/
public class Quadtree<T : RectangularBoundedObject>(public val bounds: Rectangle) {
// Fields
private val maxObjectsPerLeaf: Int
private val objects: MutableCollection<T>
private val children: Array<Quadtree<T>?>
init {
this.maxObjectsPerLeaf = DEFAULT_MAX_OBJECTS_PER_LEAF
this.objects = HashSet<T>()
this.children = arrayOfNulls<Quadtree<T>>(4)
}
// Public Methods
/**
* Temporary implementation, should change to include more cases to prevent reordering children so often.
* @param obj
*/
public fun insert(obj: T) {
val insertionBounds = obj.getBounds()
// Check if we are already split
if (this.children[0] != null) {
val index = this.getIndexOfContainer(insertionBounds)
if (index != -1) {
this.children[index]?.insert(obj)
return
}
}
// At this point, we know that either the object doesn't fit neatly into one of our containers, or we haven't split yet.
this.objects.add(obj)
// Let's see if we have too many objects available
if (this.objects.size() > this.maxObjectsPerLeaf) {
if (this.children[0] == null) {
this.split()
}
val toRemove = HashSet<T>()
this.objects.forEach { currentObject ->
val index = this.getIndexOfContainer(currentObject.getBounds())
if (index != PARENT_INDEX) {
this.children[index]?.insert(currentObject)
toRemove.add(currentObject)
}
}
toRemove.forEach { currentObject ->
this.objects.remove(currentObject)
}
}
}
public fun retrieve(bounds: Rectangle): Collection<T> {
val returnObjects = HashSet<T>()
// For each object in my collection, if it intersects the given bounds, add it to the return collection
this.objects
.filter { currentObject -> bounds.intersects(currentObject.getBounds()) }
.forEach { currentObject -> returnObjects.add(currentObject) }
for (child in this.children) {
if (child != null && bounds.intersects(child.bounds)) {
returnObjects.addAll(child.retrieve(bounds))
}
}
return returnObjects
}
public fun remove(obj: T) {
if (this.objects.contains(obj)) {
this.objects.remove(obj)
}
for (child in this.children) {
child?.remove(obj)
}
// If this takes our total count to below the maximum, we can collapse the child quadtrees
if (this.size() <= this.maxObjectsPerLeaf) {
this.recombine()
}
}
public fun clear() {
this.objects.clear()
for (i in children.indices) {
val node = this.children[i]
if (node != null) {
node.clear()
this.children[i] = null
}
}
}
public fun size(): Int {
var count = this.objects.size()
if (this.children[0] != null) {
for (child in this.children) {
count += child?.size() ?: 0
}
}
return count
}
// Private Methods
private fun split() {
val subWidth = this.bounds.width / 2
val subHeight = this.bounds.height / 2
val x = this.bounds.x
val y = this.bounds.y
this.children[TOP_LEFT_INDEX] = Quadtree<T>(Rectangle(x, y, subWidth, subHeight)) // Top Left
this.children[TOP_RIGHT_INDEX] = Quadtree<T>(Rectangle(x + subWidth, y, subWidth, subHeight)) // Top Right
this.children[BOTTOM_LEFT_INDEX] = Quadtree<T>(Rectangle(x, y + subHeight, subWidth, subHeight)) // Bottom Left
this.children[BOTTOM_RIGHT_INDEX] = Quadtree<T>(Rectangle(x + subWidth, y + subHeight, subWidth, subHeight)) // Bottom Right
}
private fun recombine() {
if (this.children[0] == null) {
return
}
for (i in this.children.indices) {
val child = this.children[i]
this.objects.addAll(child?.retrieve(child?.bounds ?: Rectangle()) ?: setOf())
this.children[i] = null
}
}
private fun getIndexOfContainer(rect: Rectangle): Int {
for (i in this.children.indices) {
if (this.children[i] != null) {
if (this.children[i]?.bounds?.contains(rect) ?: false) {
return i
}
}
}
return PARENT_INDEX
}
companion object {
// Constants
public val DEFAULT_MAX_OBJECTS_PER_LEAF: Int = 10
private val PARENT_INDEX = -1
private val TOP_LEFT_INDEX = 0
private val TOP_RIGHT_INDEX = 1
private val BOTTOM_LEFT_INDEX = 2
private val BOTTOM_RIGHT_INDEX = 3
}
}
|
mit
|
bcaf29e848a7fd162fd21f162b6cef46
| 30.512315 | 132 | 0.597155 | 4.339891 | false | false | false | false |
JimSeker/ui
|
RecyclerViews/ModelViewRecyclerViewDemo_kt/app/src/main/java/edu/cs4730/modelviewrecyclerviewdemo_kt/MainFragment.kt
|
1
|
2060
|
package edu.cs4730.modelviewrecyclerviewdemo_kt
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.lifecycle.ViewModelProvider
import java.util.*
/**
* A simple fragment that displays a recyclerview
*
*
* It does setup the ViewModel observer to see when the data changes, and logs it as part of
* the test to how it could work.
*/
class MainFragment : Fragment() {
lateinit var mViewModel: DataViewModel
lateinit var mRecyclerView: RecyclerView
lateinit var mAdapter: myAdapter
var TAG = "MainFragment"
private val mList: List<String>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val myView = inflater.inflate(R.layout.fragment_main, container, false)
mRecyclerView = myView.findViewById(R.id.listtrans)
mRecyclerView.setLayoutManager(LinearLayoutManager(activity))
mRecyclerView.setItemAnimator(DefaultItemAnimator())
mAdapter = myAdapter(mList, R.layout.row_layout, this)
//add the adapter to the recyclerview
mRecyclerView.setAdapter(mAdapter)
//needed the activity, Doc's Creates a ViewModelProvider, which retains ViewModels while a scope of given Activity is alive.
//otherwise, activity is not the same instance and so not triggered either.
mViewModel = ViewModelProvider(requireActivity()).get(DataViewModel::class.java)
mViewModel.itemLD.observe(viewLifecycleOwner) { s -> Log.d(TAG, "triggered $s") }
return myView
}
init {
mList = Arrays.asList(
"Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2"
)
}
}
|
apache-2.0
|
c31e639697c3276e7e8ff0f969966070
| 37.166667 | 132 | 0.718932 | 4.692483 | false | false | false | false |
JimSeker/ui
|
Advanced/EmojiCompatDemo_kt/app/src/main/java/edu/cs4730/emojicompatdemo_kt/CustomTextView.kt
|
1
|
2066
|
package edu.cs4730.emojicompatdemo_kt
import android.content.Context
import android.text.InputFilter
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.emoji.widget.EmojiTextViewHelper
/*
* 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.
*/
/**
* A sample implementation of custom TextView.
*
* You can use [EmojiTextViewHelper] to make your custom TextView compatible with
* EmojiCompat.
*/
class CustomTextView @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
AppCompatTextView(context!!, attrs, defStyleAttr) {
private var mEmojiTextViewHelper: EmojiTextViewHelper? = null
override fun setFilters(filters: Array<InputFilter>) {
super.setFilters(emojiTextViewHelper.getFilters(filters))
}
override fun setAllCaps(allCaps: Boolean) {
super.setAllCaps(allCaps)
emojiTextViewHelper.setAllCaps(allCaps)
}
/**
* Returns the [EmojiTextViewHelper] for this TextView.
*
*
* This method can be called from super constructors through [ ][.setFilters] or [.setAllCaps].
*/
private val emojiTextViewHelper: EmojiTextViewHelper
private get() {
if (mEmojiTextViewHelper == null) {
mEmojiTextViewHelper = EmojiTextViewHelper(this)
}
return mEmojiTextViewHelper!!
}
init {
emojiTextViewHelper.updateTransformationMethod()
}
}
|
apache-2.0
|
96a4165da834312f75f5b81fe9825f06
| 30.784615 | 99 | 0.71152 | 4.491304 | false | false | false | false |
http4k/http4k
|
http4k-serverless/lambda-runtime/src/main/kotlin/org/http4k/serverless/LambdaRuntimeAPI.kt
|
1
|
2273
|
package org.http4k.serverless
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.then
import org.http4k.lens.Header
import org.http4k.lens.long
import org.http4k.lens.string
import org.http4k.lens.uuid
import java.io.InputStream
import java.io.PrintWriter
import java.io.StringWriter
import java.time.Instant
import java.time.Instant.ofEpochMilli
/**
* Client API to retrieve requests and post responses back to the AWS Lambda controller.
*/
class LambdaRuntimeAPI(http: HttpHandler) {
private val safeHttp = Filter { next ->
{
next(it).apply {
if (!status.successful) error("""Lambda Runtime API error calling ${it.uri}: $body""")
}
}
}.then(http)
fun nextInvocation() =
with(safeHttp(Request(GET, "/2018-06-01/runtime/invocation/next"))) {
Request(POST, "").body(body).headers(headers)
}
fun success(invocation: Request, stream: InputStream) {
safeHttp(Request(POST, "/2018-06-01/runtime/invocation/${requestId(invocation)}/response").body(stream))
}
fun error(invocation: Request, exception: Exception) {
safeHttp(
Request(POST, "/2018-06-01/runtime/invocation/${requestId(invocation)}/error")
.body(exception.toBody())
)
}
fun initError(error: Exception) {
safeHttp(
Request(POST, "/2018-06-01/runtime/init/error")
.header("Lambda-Runtime-Function-Error-Type", "Unhandled")
.body(error.toBody())
)
}
companion object {
val requestId = Header.uuid().required("Lambda-Runtime-Aws-Request-Id")
val deadline = Header.long().map(::ofEpochMilli, Instant::toEpochMilli).required("Lambda-Runtime-Deadline-Ms")
val lambdaArn = Header.string().required("Lambda-Runtime-Invoked-Function-Arn")
val traceId = Header.string().required("Lambda-Runtime-Trace-Id")
}
}
internal fun Exception.toBody() =
StringWriter().use { output ->
PrintWriter(output).use { printer ->
printStackTrace(printer)
output.toString()
}
}
|
apache-2.0
|
9d1886da6f8ff775920c82f247c0183c
| 31.471429 | 118 | 0.653322 | 3.918966 | false | false | false | false |
msebire/intellij-community
|
platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsState.kt
|
1
|
7036
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.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.annotations.OptionTag
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)
}
@get:OptionTag("FONT_FACE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontFace"))
var fontFace by string()
@get:OptionTag("FONT_SIZE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontSize"))
var fontSize by property(defFontSize)
@get:OptionTag("FONT_SCALE")
@Deprecated("", replaceWith = ReplaceWith("NotRoamableUiOptions.fontScale"))
var fontScale by property(0f)
@get:OptionTag("RECENT_FILES_LIMIT")
var recentFilesLimit by property(50)
@get:OptionTag("RECENT_LOCATIONS_LIMIT")
var recentLocationsLimit by property(10)
@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)
@Suppress("FunctionName")
fun _incrementModificationCount() = incrementModificationCount()
}
|
apache-2.0
|
b0af1f43523d42ab7354c58608387967
| 39.442529 | 140 | 0.772456 | 4.013691 | false | false | false | false |
suncycheng/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/classpath/PathUtils.kt
|
9
|
2584
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.launcher.classpath
import com.intellij.testGuiFramework.launcher.system.SystemInfo
import java.io.File
class PathUtils(idePath: String) {
val myIdeDir = File(idePath)
companion object {
fun getJreBinPath(): String {
val homePath = System.getProperty("java.home")
val jreDir = File(homePath)
val homeDir = File(jreDir.parent)
val binDir = File(homeDir, "bin")
val javaName: String = if (System.getProperty("os.name").toLowerCase().contains("win")) "java.exe" else "java"
return File(binDir, javaName).path
}
}
fun getIdeRootContentDir(): File {
when (SystemInfo.getSystemType()) {
SystemInfo.SystemType.WINDOWS -> return myIdeDir
SystemInfo.SystemType.MAC -> return File(myIdeDir, "Contents")
SystemInfo.SystemType.UNIX -> return myIdeDir
}
}
fun getJdkDir(): File = File(getJreBinPath())
.parentFile //bin dir
.parentFile //home dir
fun getIdeLibDir(): File = File(getIdeRootContentDir(), "lib")
fun getIdePluginsDir(): File = File(getIdeRootContentDir(), "plugins")
fun getJUnitJarFile(): File = getIdeLibDir().listFiles().find { it.name.contains("junit-4.12.jar") }!!
fun getTestGuiFrameworkDir(): File {
val pluginDir = getIdePluginsDir().listFiles().find { it.name.toLowerCase().contains("testguiframework") }!!
return File(pluginDir, "lib")
}
fun getTestGuiFrameworkJar(): File {
return getTestGuiFrameworkDir().listFiles().find { it.name.toLowerCase().contains("testguiframework") && it.name.endsWith(".jar") }!!
}
fun makeClassPathBuilder(): ClassPathBuilder {
return ClassPathBuilder(ideaLibPath = getIdeLibDir().path,
jdkPath = getJdkDir().path,
jUnitPath = getJUnitJarFile().path,
festLibsPath = getTestGuiFrameworkDir().path,
testGuiFrameworkPath = getTestGuiFrameworkJar().path)
}
}
|
apache-2.0
|
8a2f9e3bdb3a9b40bd58f30c27cbb862
| 34.888889 | 137 | 0.684598 | 4.257002 | false | true | false | false |
androidthings/endtoend-base
|
shared/src/main/java/com/example/androidthings/endtoend/shared/data/FirestoreConstants.kt
|
1
|
937
|
/*
* 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.example.androidthings.endtoend.shared.data
import java.util.concurrent.Executors
val asyncExecutor = Executors.newFixedThreadPool(4)
// Firestore path elements
const val PATH_EMAILS = "emails"
const val PATH_USERS = "users"
const val PATH_GIZMOS = "gizmos"
// Firestore field names
const val FIELD_FIREBASE_ID = "firebaseId"
|
apache-2.0
|
50098bca97145a0ac2ea56ff186b6754
| 31.310345 | 75 | 0.754536 | 3.936975 | false | false | false | false |
carlphilipp/stock-tracker-android
|
src/fr/cph/stock/android/activity/ChartActivity.kt
|
1
|
8593
|
/**
* Copyright 2017 Carl-Philipp Harmant
*
*
* 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 fr.cph.stock.android.activity
import android.annotation.SuppressLint
import android.app.ActionBar.LayoutParams
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.webkit.WebView
import android.widget.RelativeLayout
import android.widget.TextView
import fr.cph.stock.android.Constants
import fr.cph.stock.android.R
import fr.cph.stock.android.StockTrackerApp
import fr.cph.stock.android.domain.ChartType
import fr.cph.stock.android.domain.Portfolio
import fr.cph.stock.android.domain.UrlType
import fr.cph.stock.android.task.MainTask
import fr.cph.stock.android.web.DebugWebChromeClient
import org.apache.commons.io.IOUtils
import org.json.JSONObject
import java.io.IOException
import java.io.InputStream
import java.io.StringWriter
/**
* This class reprents the chart activity
*
* @author Carl-Philipp Harmant
*/
class ChartActivity : Activity(), StockTrackerActivity {
/**
* Graphics components
*/
private lateinit var menuItem: MenuItem
private lateinit var errorView: TextView
private lateinit var chartType: ChartType
private lateinit var portfolio: Portfolio
private lateinit var webView: WebView
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.chart_activity)
portfolio = intent.getParcelableExtra(Constants.PORTFOLIO)
chartType = ChartType.getEnum(intent.getStringExtra("chartType"))
errorView = findViewById(R.id.errorMessage)
webView = findViewById(R.id.webView)
val data = data
webView.webChromeClient = DebugWebChromeClient()
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
// myWebView.setBackgroundColor(0x00000000);
// myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.loadDataWithBaseURL("file:///android_asset/www/", data, "text/html", "UTF-8", null)
webView.reload()
}
private val data: String?
get() {
val metrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics)
var data: String? = null
var source: InputStream? = null
try {
val writer = StringWriter()
when (chartType) {
ChartType.CAPITALIZATION -> {
source = applicationContext.assets.open("www/pie.html")
IOUtils.copy(source, writer, "UTF8")
data = writer.toString()
.replace("#DATA#", portfolio.chartCapData)
.replace("#TITLE#", portfolio.chartCapTitle)
.replace("#DRAW#", portfolio.chartCapDraw)
.replace("#COMPANIES#", portfolio.chartCapCompanies)
.replace("#WIDTH#".toRegex(), ((metrics.widthPixels / metrics.density).toInt() - 30).toString() + "")
.replace("#HEIGHT#".toRegex(), ((metrics.widthPixels / metrics.density).toInt() - 30).toString() + "")
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
actionBar.title = "Capitalization Chart"
webView.isHorizontalScrollBarEnabled = false
}
ChartType.SECTOR -> {
source = applicationContext.assets.open("www/pie.html")
IOUtils.copy(source, writer, "UTF8")
data = writer.toString()
data = data.replace("#DATA#", portfolio.chartSectorData)
data = data.replace("#TITLE#", portfolio.chartSectorTitle)
data = data.replace("#DRAW#", portfolio.chartSectorDraw)
data = data.replace("#COMPANIES#", portfolio.chartSectorCompanies)
data = data.replace("#WIDTH#".toRegex(), ((metrics.widthPixels / metrics.density).toInt() - 30).toString() + "")
data = data.replace("#HEIGHT#".toRegex(), ((metrics.widthPixels / metrics.density).toInt() - 30).toString() + "")
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
actionBar.title = "Sector Chart"
webView.isHorizontalScrollBarEnabled = false
}
ChartType.SHARE_VALUE -> {
source = applicationContext.assets.open("www/share_value.html")
IOUtils.copy(source, writer, "UTF8")
data = writer.toString()
data = data.replace("#DATA#", portfolio.chartData)
data = data.replace("#DRAW#", portfolio.chartDraw)
data = data.replace("#COLOR#", portfolio.chartColors)
data = data.replace("#DATE#", portfolio.chartDate)
data = data.replace("#WIDTH#".toRegex(), ((metrics.widthPixels / metrics.density).toInt() - 30).toString() + "")
data = data.replace("#HEIGHT#".toRegex(), (metrics.heightPixels.toDouble() / metrics.density.toDouble() / 1.35).toInt().toString() + "")
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
actionBar.title = "Share Value Chart"
}
}
} catch (e: IOException) {
Log.e(TAG, e.message, e)
} finally {
IOUtils.closeQuietly(source)
}
return data
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_logout -> consume { MainTask(this, UrlType.LOGOUT, emptyMap()).execute() }
R.id.refresh -> consume {
menuItem = item
menuItem.setActionView(R.layout.progressbar)
menuItem.expandActionView()
MainTask(this, UrlType.RELOAD, emptyMap()).execute()
}
android.R.id.home -> consume { finish() }
else -> super.onOptionsItemSelected(item)
}
override fun update(portfolio: Portfolio) {
menuItem.collapseActionView()
menuItem.actionView = null
val resultIntent = Intent()
resultIntent.putExtra(Constants.PORTFOLIO, portfolio)
this.portfolio = portfolio
val data = data
webView.loadDataWithBaseURL("file:///android_asset/www/", data, "text/html", "UTF-8", null)
setResult(Activity.RESULT_OK, resultIntent)
val app = application as StockTrackerApp
app.toast()
}
override fun displayError(json: JSONObject) {
val sessionError = (application as StockTrackerApp).isSessionError(json)
if (sessionError) {
(application as StockTrackerApp).loadErrorActivity(this, json)
} else {
errorView.text = json.optString("error")
val params = RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
params.addRule(RelativeLayout.BELOW, errorView.id)
val webView = findViewById<WebView>(R.id.webView)
webView.layoutParams = params
menuItem.collapseActionView()
menuItem.actionView = null
}
}
override fun logOut() {
(application as StockTrackerApp).logOut(this)
}
companion object {
private val TAG = "ChartActivity"
}
}
|
apache-2.0
|
72be9219e7cd98950295b6f22c3417a8
| 42.619289 | 160 | 0.61457 | 4.907481 | false | false | false | false |
EvidentSolutions/apina
|
apina-core/src/main/kotlin/fi/evident/apina/model/EndpointGroup.kt
|
1
|
533
|
package fi.evident.apina.model
import java.util.*
/**
* A group of related [Endpoint]s. As an example, web controllers are a group
* of individual endpoints (methods).
*/
class EndpointGroup(val name: String) {
private val _endpoints = TreeSet<Endpoint>(compareBy { it.name })
fun addEndpoint(endpoint: Endpoint) {
_endpoints += endpoint
}
val endpoints: Collection<Endpoint>
get() = _endpoints
override fun toString() = name
val endpointCount: Int
get() = _endpoints.size
}
|
mit
|
5b11fb9d292e4da6245a4c4c05c797c1
| 21.208333 | 77 | 0.662289 | 4.1 | false | false | false | false |
akvo/akvo-flow-mobile
|
app/src/main/java/org/akvo/flow/presentation/settings/SendDeviceInfoDialog.kt
|
1
|
4500
|
/*
* Copyright (C) 2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.akvo.flow.presentation.settings
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.method.DigitsKeyListener
import android.view.LayoutInflater
import android.widget.EditText
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.DialogFragment
import org.akvo.flow.BuildConfig
import org.akvo.flow.R
class SendDeviceInfoDialog : DialogFragment() {
private var listener: SendDeviceInfoListener? = null
private lateinit var userName: String
private lateinit var deviceId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
userName = arguments?.getString(PARAM_USER_NAME, "") as String
deviceId = arguments?.getString(PARAM_DEVICE_ID, "") as String
}
override fun onAttach(context: Context) {
super.onAttach(context)
val activity = activity
listener = if (activity is SendDeviceInfoListener) {
activity
} else {
throw IllegalArgumentException("Activity must implement DownloadFormListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = activity
val inputDialog = AlertDialog.Builder(activity)
inputDialog.setTitle(R.string.preference_send_info)
var instance = BuildConfig.INSTANCE_URL
instance = instance.removePrefix("https://")
instance = instance.removeSuffix(".akvoflow.org")
instance = instance.removeSuffix(".appspot.com")
val version = Build.VERSION.RELEASE
val model = Build.MANUFACTURER + Build.MODEL
val body =
"Android Device Info:" + "\r\n" +
"Android Version: $version" + "\r\n" +
"Device model: $model" + "\r\n" +
"App version: ${BuildConfig.VERSION_NAME}" + "\r\n" +
"User name: $userName" + "\r\n" +
"Device Identifier: $deviceId" + "\r\n" +
"Instance: $instance"
val message = getString(R.string.send_support_detail, body)
inputDialog.setMessage(message)
val main = LayoutInflater.from(activity).inflate(R.layout.send_device_info_dialog, null)
val input = main.findViewById<EditText>(R.id.reference_id_et)
input.keyListener = DigitsKeyListener(false, false)
inputDialog.setView(main)
inputDialog.setPositiveButton(R.string.okbutton) { _, _ ->
val referenceText = input.text.toString()
listener?.let { listener ->
if (referenceText.isNotEmpty() && referenceText.isDigitsOnly()) {
listener.sendDeviceInfo(referenceText.toInt(), body)
}
}
}
inputDialog.setNegativeButton(R.string.cancelbutton) { dialog, _ -> dialog.dismiss() }
return inputDialog.create()
}
interface SendDeviceInfoListener {
fun sendDeviceInfo(toInt: Int, body: String)
}
companion object {
const val TAG = "ReloadFormsConfirmationDialog"
const val PARAM_USER_NAME = "user_name"
const val PARAM_DEVICE_ID = "device_id"
fun newInstance(userName: String, deviceId: String): SendDeviceInfoDialog {
val sendDeviceInfoDialog = SendDeviceInfoDialog()
val args = Bundle(2)
args.putString(PARAM_USER_NAME, userName)
args.putString(PARAM_DEVICE_ID, deviceId)
sendDeviceInfoDialog.arguments = args
return sendDeviceInfoDialog
}
}
}
|
gpl-3.0
|
7de51d80ac87650fbc2b6799634f31ec
| 36.5 | 96 | 0.657111 | 4.513541 | false | false | false | false |
JetBrains/anko
|
anko/library/static/sqlite/src/main/java/ClassParser.kt
|
2
|
6050
|
/*
* Copyright 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.
*/
@file:Suppress("unused")
package org.jetbrains.anko.db
import org.jetbrains.anko.AnkoException
import org.jetbrains.anko.db.JavaSqliteUtils.PRIMITIVES_TO_WRAPPERS
import java.lang.reflect.Modifier
@Target(AnnotationTarget.CONSTRUCTOR)
annotation class ClassParserConstructor
@Suppress("NOTHING_TO_INLINE")
inline fun <reified T: Any> classParser(): RowParser<T> = classParser(T::class.java)
@PublishedApi
internal fun <T> classParser(clazz: Class<T>): RowParser<T> {
val applicableConstructors = clazz.declaredConstructors.filter { ctr ->
if (ctr.isVarArgs || !Modifier.isPublic(ctr.modifiers)) return@filter false
val types = ctr.parameterTypes
return@filter types != null && types.isNotEmpty() && types.all(::hasApplicableType)
}
if (applicableConstructors.isEmpty()) {
throw AnkoException("Can't initialize object parser for ${clazz.canonicalName}, no acceptable constructors found")
}
val preferredConstructor = if (applicableConstructors.size > 1) {
applicableConstructors
.filter { it.isAnnotationPresent(ClassParserConstructor::class.java) }
.singleOrNull()
?: throw AnkoException("Several constructors are annotated with ClassParserConstructor")
} else {
applicableConstructors[0]
}
return object : RowParser<T> {
private val parameterTypes = preferredConstructor.parameterTypes
override fun parseRow(columns: Array<Any?>): T {
if (parameterTypes.size != columns.size) {
val columnsRendered = columns.joinToString(prefix = "[", postfix = "]")
val parameterTypesRendered = parameterTypes.joinToString(prefix = "[", postfix = "]") { it.canonicalName }
throw AnkoException("Class parser for ${preferredConstructor.name} " +
"failed to parse the row: $columnsRendered (constructor parameter types: $parameterTypesRendered)")
}
for (index in 0..(parameterTypes.size - 1)) {
val type = parameterTypes[index]
val columnValue = columns[index]
if (!type.isInstance(columnValue)) {
// 'columns' array is created in Anko so it's safe to modify it directly
columns[index] = castValue(columnValue, type)
}
}
@Suppress("UNCHECKED_CAST")
return (JavaSqliteUtils.newInstance(preferredConstructor, columns)) as T
}
}
}
private fun hasApplicableType(type: Class<*>): Boolean {
if (type.isPrimitive) {
return true
}
return when (type) {
java.lang.String::class.java, java.lang.CharSequence::class.java,
java.lang.Long::class.java, java.lang.Integer::class.java,
java.lang.Byte::class.java, java.lang.Character::class.java,
java.lang.Boolean::class.java, java.lang.Float::class.java,
java.lang.Double::class.java, java.lang.Short::class.java -> true
else -> false
}
}
private fun castValue(value: Any?, type: Class<*>): Any? {
if (value == null && type.isPrimitive) {
throw AnkoException("null can't be converted to the value of primitive type ${type.canonicalName}")
}
if (value == null || type == Any::class.java) {
return value
}
if (type.isPrimitive && PRIMITIVES_TO_WRAPPERS[type] == value::class.java) {
return value
}
if (value is Double && (type == java.lang.Float.TYPE || type == java.lang.Float::class.java)) {
return value.toFloat()
}
if (value is Float && (type == java.lang.Double.TYPE || type == java.lang.Double::class.java)) {
return value.toDouble()
}
if (value is Char && CharSequence::class.java.isAssignableFrom(type)) {
return value.toString()
}
if (value is Long) {
if (type == java.lang.Integer.TYPE || type == java.lang.Integer::class.java) {
return value.toInt()
} else if (type == java.lang.Short.TYPE || type == java.lang.Short::class.java) {
return value.toShort()
} else if (type == java.lang.Byte.TYPE || type == java.lang.Byte::class.java) {
return value.toByte()
} else if (type == java.lang.Boolean.TYPE || type == java.lang.Boolean::class.java) {
return value != 0L
} else if (type == java.lang.Character.TYPE || type == java.lang.Character::class.java) {
return value.toChar()
}
}
if (value is Int) {
if (type == java.lang.Long.TYPE || type == java.lang.Long::class.java) {
return value.toLong()
} else if (type == java.lang.Short.TYPE || type == java.lang.Short::class.java) {
return value.toShort()
} else if (type == java.lang.Byte.TYPE || type == java.lang.Byte::class.java) {
return value.toByte()
} else if (type == java.lang.Boolean.TYPE || type == java.lang.Boolean::class.java) {
return value != 0
} else if (type == java.lang.Character.TYPE || type == java.lang.Character::class.java) {
return value.toChar()
}
}
if (value is String && value.length == 1
&& (type == java.lang.Character.TYPE || type == java.lang.Character::class.java)) {
return value[0]
}
throw AnkoException("Value $value of type ${value::class.java} can't be cast to ${type.canonicalName}")
}
|
apache-2.0
|
29d1f2aad99869adc0271f6d6ccb6e21
| 39.066225 | 123 | 0.62876 | 4.143836 | false | false | false | false |
lure0xaos/CoffeeTime
|
util/src/main/kotlin/gargoyle/ct/util/args/CTArgs.kt
|
1
|
3519
|
package gargoyle.ct.util.args
import gargoyle.ct.util.convert.Converters
interface CTArgs : CTAnyArgs {
fun getBoolean(index: Int): Boolean = getBoolean(index, false)
fun getBoolean(key: String): Boolean = getBoolean(key, false)
fun getBoolean(index: Int, def: Boolean): Boolean = get(index, Boolean::class, Converters[Boolean::class], def)
fun getBoolean(key: String, def: Boolean): Boolean = get(key, Boolean::class, Converters[Boolean::class], def)
fun getByte(index: Int): Byte = getByte(index, 0.toByte())
fun getByte(key: String): Byte = getByte(key, 0.toByte())
fun getByte(index: Int, def: Byte): Byte = get(index, Byte::class, Converters[Byte::class], def)
fun getByte(key: String, def: Byte): Byte = get(key, Byte::class, Converters[Byte::class], def)
fun getBytes(index: Int): ByteArray = getBytes(index, ByteArray(0))
fun getBytes(key: String): ByteArray = getBytes(key, ByteArray(0))
fun getBytes(index: Int, def: ByteArray): ByteArray =
get(index, ByteArray::class, Converters[ByteArray::class], def)
fun getBytes(key: String, def: ByteArray): ByteArray =
get(key, ByteArray::class, Converters[ByteArray::class], def)
fun getChar(index: Int): Char = getChar(index, '\u0000')
fun getChar(key: String): Char = getChar(key, '\u0000')
fun getChar(index: Int, def: Char): Char = get(index, Char::class, Converters[Char::class], def)
fun getChar(key: String, def: Char): Char = get(key, Char::class, Converters[Char::class], def)
fun getDouble(index: Int): Double = getDouble(index, 0.0)
fun getDouble(key: String): Double = getDouble(key, 0.0)
fun getDouble(index: Int, def: Double): Double = get(index, Double::class, Converters[Double::class], def)
fun getDouble(key: String, def: Double): Double = get(key, Double::class, Converters[Double::class], def)
fun getFloat(index: Int): Float = getFloat(index, 0.0f)
fun getFloat(key: String): Float = getFloat(key, 0.0f)
fun getFloat(index: Int, def: Float): Float = get(index, Float::class, Converters[Float::class], def)
fun getFloat(key: String, def: Float): Float = get(key, Float::class, Converters[Float::class], def)
fun getInteger(index: Int): Int = getInteger(index, 0)
fun getInteger(key: String): Int = getInteger(key, 0)
fun getInteger(index: Int, def: Int): Int = get(index, Int::class, Converters[Int::class], def)
fun getInteger(key: String, def: Int): Int = get(key, Int::class, Converters[Int::class], def)
fun getLong(index: Int): Long = getLong(index, 0L)
fun getLong(key: String): Long = getLong(key, 0L)
fun getLong(index: Int, def: Long): Long = get(index, Long::class, Converters[Long::class], def)
fun getLong(key: String, def: Long): Long = get(key, Long::class, Converters[Long::class], def)
fun getShort(index: Int): Short = getShort(index, 0.toShort())
fun getShort(key: String): Short = getShort(key, 0.toShort())
fun getShort(index: Int, def: Short): Short = get(index, Short::class, Converters[Short::class], def)
fun getShort(key: String, def: Short): Short = get(key, Short::class, Converters[Short::class], def)
fun getString(index: Int): String = getString(index, "")
fun getString(key: String): String = getString(key, "")
fun getString(index: Int, def: String): String = get(index, String::class, Converters[String::class], def)
fun getString(key: String, def: String): String = get(key, String::class, Converters[String::class], def)
}
|
unlicense
|
4cef471d3dd6a3c5625fa924f2748db7
| 58.644068 | 115 | 0.682012 | 3.587156 | false | false | false | false |
fossasia/open-event-android
|
app/src/main/java/org/fossasia/openevent/general/about/AboutEventFragment.kt
|
1
|
3995
|
package org.fossasia.openevent.general.about
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import com.google.android.material.appbar.AppBarLayout
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_about_event.view.aboutEventContent
import kotlinx.android.synthetic.main.fragment_about_event.view.aboutEventDetails
import kotlinx.android.synthetic.main.fragment_about_event.view.aboutEventImage
import kotlinx.android.synthetic.main.fragment_about_event.view.appBar
import kotlinx.android.synthetic.main.fragment_about_event.view.detailsHeader
import kotlinx.android.synthetic.main.fragment_about_event.view.eventName
import kotlinx.android.synthetic.main.fragment_about_event.view.progressBarAbout
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventUtils
import org.fossasia.openevent.general.utils.Utils.setToolbar
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.fossasia.openevent.general.utils.stripHtml
import org.jetbrains.anko.design.snackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
class AboutEventFragment : Fragment() {
private lateinit var rootView: View
private val aboutEventViewModel by viewModel<AboutEventViewModel>()
private lateinit var eventExtra: Event
private val safeArgs: AboutEventFragmentArgs by navArgs()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = layoutInflater.inflate(R.layout.fragment_about_event, container, false)
setToolbar(activity)
setHasOptionsMenu(true)
aboutEventViewModel.event
.nonNull()
.observe(viewLifecycleOwner, Observer {
loadEvent(it)
})
aboutEventViewModel.error
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.snackbar(it)
})
aboutEventViewModel.progressAboutEvent
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.progressBarAbout.isVisible = it
})
aboutEventViewModel.loadEvent(safeArgs.eventId)
return rootView
}
private fun loadEvent(event: Event) {
eventExtra = event
rootView.aboutEventContent.movementMethod = LinkMovementMethod.getInstance()
rootView.aboutEventContent.text = event.description?.stripHtml()
val startsAt = EventUtils.getEventDateTime(event.startsAt, event.timezone)
val endsAt = EventUtils.getEventDateTime(event.endsAt, event.timezone)
rootView.aboutEventDetails.text = EventUtils.getFormattedDateTimeRangeBulleted(startsAt, endsAt)
rootView.eventName.text = event.name
Picasso.get()
.load(event.originalImageUrl)
.placeholder(R.drawable.header)
.into(rootView.aboutEventImage)
rootView.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, offset ->
if (Math.abs(offset) == appBarLayout.totalScrollRange) {
rootView.detailsHeader.isVisible = false
setToolbar(activity, event.name)
} else {
rootView.detailsHeader.isVisible = true
setToolbar(activity)
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
activity?.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
|
apache-2.0
|
d8c1307f581f0f25abbef7d2a39d0589
| 38.95 | 116 | 0.7199 | 4.842424 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/repository/GameRepository.kt
|
1
|
6532
|
package com.boardgamegeek.repository
import androidx.core.content.contentValuesOf
import com.boardgamegeek.BggApplication
import com.boardgamegeek.db.GameDao
import com.boardgamegeek.db.PlayDao
import com.boardgamegeek.entities.GameCommentsEntity
import com.boardgamegeek.entities.GameEntity
import com.boardgamegeek.extensions.AccountPreferences
import com.boardgamegeek.extensions.get
import com.boardgamegeek.extensions.getImageId
import com.boardgamegeek.extensions.preferences
import com.boardgamegeek.io.Adapter
import com.boardgamegeek.mappers.mapToEntity
import com.boardgamegeek.mappers.mapToRatingEntities
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID
import com.boardgamegeek.provider.BggContract.Games
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class GameRepository(val application: BggApplication) {
private val dao = GameDao(application)
private val playDao = PlayDao(application)
private val bggService = Adapter.createForXml()
private val playRepository = PlayRepository(application)
private val username: String? by lazy { application.preferences()[AccountPreferences.KEY_USERNAME, ""] }
suspend fun loadGame(gameId: Int) = dao.load(gameId)
suspend fun refreshGame(gameId: Int) = withContext(Dispatchers.IO) {
val timestamp = System.currentTimeMillis()
val response = bggService.thing2(gameId, 1)
response.games.firstOrNull()?.let { game ->
dao.save(game.mapToEntity(), timestamp)
Timber.i("Synced game '$gameId'")
}
}
suspend fun refreshHeroImage(game: GameEntity): GameEntity = withContext(Dispatchers.IO) {
val response = Adapter.createGeekdoApi().image(game.thumbnailUrl.getImageId())
val url = response.images.medium.url
dao.upsert(game.id, contentValuesOf(Games.Columns.HERO_IMAGE_URL to url))
game.copy(heroImageUrl = url)
}
suspend fun loadComments(gameId: Int, page: Int): GameCommentsEntity? = withContext(Dispatchers.IO) {
val response = Adapter.createForXml().thingWithComments(gameId, page)
response.games.firstOrNull()?.mapToRatingEntities()
}
suspend fun loadRatings(gameId: Int, page: Int): GameCommentsEntity? = withContext(Dispatchers.IO) {
val response = Adapter.createForXml().thingWithRatings(gameId, page)
response.games.firstOrNull()?.mapToRatingEntities()
}
suspend fun getRanks(gameId: Int) = dao.loadRanks(gameId)
suspend fun getLanguagePoll(gameId: Int) = dao.loadPoll(gameId, BggContract.POLL_TYPE_LANGUAGE_DEPENDENCE)
suspend fun getAgePoll(gameId: Int) = dao.loadPoll(gameId, BggContract.POLL_TYPE_SUGGESTED_PLAYER_AGE)
suspend fun getPlayerPoll(gameId: Int) = dao.loadPlayerPoll(gameId)
suspend fun getDesigners(gameId: Int) = dao.loadDesigners(gameId)
suspend fun getArtists(gameId: Int) = dao.loadArtists(gameId)
suspend fun getPublishers(gameId: Int) = dao.loadPublishers(gameId)
suspend fun getCategories(gameId: Int) = dao.loadCategories(gameId)
suspend fun getMechanics(gameId: Int) = dao.loadMechanics(gameId)
suspend fun getExpansions(gameId: Int) = dao.loadExpansions(gameId)
suspend fun getBaseGames(gameId: Int) = dao.loadExpansions(gameId, true)
suspend fun refreshPlays(gameId: Int) = withContext(Dispatchers.IO) {
if (gameId != INVALID_ID || username.isNullOrBlank()) {
val timestamp = System.currentTimeMillis()
var page = 1
do {
val response = bggService.playsByGame(username, gameId, page++)
val playsPage = response.plays.mapToEntity(timestamp)
playRepository.saveFromSync(playsPage, timestamp)
} while (response.hasMorePages())
playDao.deleteUnupdatedPlays(gameId, timestamp)
dao.update(gameId, contentValuesOf(Games.Columns.UPDATED_PLAYS to System.currentTimeMillis()))
playRepository.calculatePlayStats()
}
}
suspend fun refreshPartialPlays(gameId: Int) = withContext(Dispatchers.IO) {
val timestamp = System.currentTimeMillis()
val response = bggService.playsByGame(username, gameId, 1)
val plays = response.plays.mapToEntity(timestamp)
playRepository.saveFromSync(plays, timestamp)
playRepository.calculatePlayStats()
}
suspend fun getPlays(gameId: Int) = playDao.loadPlaysByGame(gameId)
/**
* Returns a map of all game IDs with player colors.
*/
suspend fun getPlayColors() = dao.loadPlayColors().groupBy({ it.first }, { it.second })
suspend fun getPlayColors(gameId: Int) = dao.loadPlayColors(gameId)
suspend fun addPlayColor(gameId: Int, color: String?) {
if (gameId != INVALID_ID && !color.isNullOrBlank()) {
dao.insertColor(gameId, color)
}
}
suspend fun deletePlayColor(gameId: Int, color: String): Int {
return if (gameId != INVALID_ID && color.isNotBlank()) {
dao.deleteColor(gameId, color)
} else 0
}
suspend fun computePlayColors(gameId: Int) {
val colors = playDao.loadPlayerColors(gameId)
dao.insertColors(gameId, colors)
}
suspend fun updateLastViewed(gameId: Int, lastViewed: Long = System.currentTimeMillis()) {
if (gameId != INVALID_ID) {
dao.update(gameId, contentValuesOf(Games.Columns.LAST_VIEWED to lastViewed))
}
}
suspend fun updateGameColors(
gameId: Int,
iconColor: Int,
darkColor: Int,
winsColor: Int,
winnablePlaysColor: Int,
allPlaysColor: Int
) {
if (gameId != INVALID_ID) {
val values = contentValuesOf(
Games.Columns.ICON_COLOR to iconColor,
Games.Columns.DARK_COLOR to darkColor,
Games.Columns.WINS_COLOR to winsColor,
Games.Columns.WINNABLE_PLAYS_COLOR to winnablePlaysColor,
Games.Columns.ALL_PLAYS_COLOR to allPlaysColor,
)
val numberOfRowsModified = dao.update(gameId, values)
Timber.d(numberOfRowsModified.toString())
}
}
suspend fun updateFavorite(gameId: Int, isFavorite: Boolean) {
if (gameId != INVALID_ID) {
dao.update(gameId, contentValuesOf(Games.Columns.STARRED to if (isFavorite) 1 else 0))
}
}
suspend fun delete() = dao.delete()
}
|
gpl-3.0
|
e6541c503718e76026b856eb9b8e5e29
| 38.587879 | 110 | 0.694887 | 4.351765 | false | false | false | false |
Chris-Drake/events
|
app/src/debug/java/nz/co/chrisdrake/events/data/api/model/MockLocationResponse.kt
|
1
|
507
|
package nz.co.chrisdrake.events.data.api.model
object MockLocationResponse {
@JvmField val UNITED_STATES = LocationResource(locations = listOf(Locations.UNITED_STATES))
private object Locations {
val SAN_FRANCISCO = Location(
id = 101,
name = "San Francisco")
val UNITED_STATES = Location(
id = 100,
name = "United States",
children = LocationChildResource(children = listOf(SAN_FRANCISCO)))
}
}
|
apache-2.0
|
f8d4ed94e13e15b25ea74c8c7b0aff72
| 30.6875 | 95 | 0.601578 | 4.225 | false | false | false | false |
jaredsburrows/gradle-license-plugin
|
gradle-license-plugin/src/main/kotlin/com/jaredsburrows/license/internal/report/HtmlReport.kt
|
1
|
8848
|
package com.jaredsburrows.license.internal.report
import com.jaredsburrows.license.internal.LicenseHelper
import kotlinx.html.A
import kotlinx.html.Entities
import kotlinx.html.FlowOrInteractiveOrPhrasingContent
import kotlinx.html.HTML
import kotlinx.html.HtmlTagMarker
import kotlinx.html.TagConsumer
import kotlinx.html.attributesMapOf
import kotlinx.html.body
import kotlinx.html.br
import kotlinx.html.dl
import kotlinx.html.dt
import kotlinx.html.h3
import kotlinx.html.head
import kotlinx.html.hr
import kotlinx.html.li
import kotlinx.html.pre
import kotlinx.html.stream.appendHTML
import kotlinx.html.style
import kotlinx.html.title
import kotlinx.html.ul
import kotlinx.html.unsafe
import kotlinx.html.visit
import kotlinx.html.visitAndFinalize
import org.apache.maven.model.License
import org.apache.maven.model.Model
/**
* Generates HTML report of projects dependencies.
*
* @property projects list of [Model]s for thr HTML report.
*/
class HtmlReport(private val projects: List<Model>) : Report {
override fun toString(): String = report()
override fun name(): String = NAME
override fun extension(): String = EXTENSION
override fun report(): String = if (projects.isEmpty()) emptyReport() else fullReport()
override fun fullReport(): String {
val projectsMap = hashMapOf<String?, List<Model>>()
val licenseMap = LicenseHelper.licenseMap
// Store packages by licenses: build a composite key of all the licenses, sorted in the (probably vain)
// hope that there's more than one project with the same set of multiple licenses.
projects.forEach { project ->
val keys = mutableListOf<String>()
// first check to see if the project's license is in our list of known licenses.
if (project.licenses.isNotEmpty()) {
project.licenses.forEach { license -> keys += getLicenseKey(license) }
}
keys.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it })
var key = ""
if (keys.isNotEmpty()) {
// No Licenses -> empty key, sort first
key = keys.toString()
}
if (!projectsMap.containsKey(key)) {
projectsMap[key] = mutableListOf()
}
(projectsMap[key] as MutableList).add(project)
}
return buildString {
appendLine(DOCTYPE) // createHTMLDocument() add doctype and meta
appendHTML()
.html(lang = "en") {
head {
unsafe { +META }
style {
unsafe { +CSS_STYLE }
}
title { +OPEN_SOURCE_LIBRARIES }
}
body {
h3 {
+NOTICE_LIBRARIES
}
ul {
projectsMap.entries.forEach { entry ->
val sortedProjects = entry.value.sortedWith(
compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }
)
var currentProject: Model? = null
var currentLicense: Int? = null
sortedProjects.forEach { project ->
currentProject = project
currentLicense = entry.key.hashCode()
// Display libraries
li {
a(href = "#$currentLicense") {
+project.name
+" (${project.version})"
}
val copyrightYear = project.inceptionYear.ifEmpty { DEFAULT_YEAR }
dl {
if (project.developers.isNotEmpty()) {
project.developers.forEach { developer ->
dt {
+COPYRIGHT
+Entities.copy
+" $copyrightYear ${developer.id}"
}
}
} else {
dt {
+COPYRIGHT
+Entities.copy
+" $copyrightYear $DEFAULT_AUTHOR"
}
}
}
}
}
// This isn't correctly indented in the html source (but is otherwise correct).
// It appears to be a bug in the DSL implementation from what little I see on the web.
a(name = currentLicense.toString())
// Display associated license text with libraries
val licenses = currentProject?.licenses
if (licenses.isNullOrEmpty()) {
pre {
+NO_LICENSE
}
} else {
licenses.forEach { license ->
val key = getLicenseKey(license)
if (key.isNotEmpty() && licenseMap.values.contains(key)) {
// license from license map
pre {
unsafe { +getLicenseText(key) }
}
} else {
// if not found in the map, just display the info from the POM.xml
val currentLicenseName = license.name.trim()
val currentUrl = license.url.trim()
if (currentLicenseName.isNotEmpty() && currentUrl.isNotEmpty()) {
pre {
unsafe { +"$currentLicenseName\n<a href=\"$currentUrl\">$currentUrl</a>" }
}
} else if (currentUrl.isNotEmpty()) {
pre {
unsafe { +"<a href=\"$currentUrl\">$currentUrl</a>" }
}
} else if (currentLicenseName.isNotEmpty()) {
pre {
unsafe { +"$currentLicenseName\n" }
}
} else {
pre {
+NO_LICENSE
}
}
}
br
}
}
hr {}
}
}
}
}
}
}
override fun emptyReport(): String = buildString {
appendLine(DOCTYPE) // createHTMLDocument() add doctype and meta
appendHTML()
.html(lang = "en") {
head {
unsafe { +META }
style {
unsafe { +CSS_STYLE }
}
title { +OPEN_SOURCE_LIBRARIES }
}
body {
h3 {
+NO_LIBRARIES
}
}
}
}
/**
* See if the license is in our list of known licenses (which coalesces differing URLs to the
* same license text). If not, use the URL if present. Else "".
*/
private fun getLicenseKey(license: License): String {
return when {
// look up by url
LicenseHelper.licenseMap.containsKey(license.url) -> LicenseHelper.licenseMap[license.url]
// then by name
LicenseHelper.licenseMap.containsKey(license.name) -> LicenseHelper.licenseMap[license.name]
// otherwise, use the url as a key
else -> license.url
} as String
}
@HtmlTagMarker private inline fun <T, C : TagConsumer<T>> C.html(
lang: String,
namespace: String? = null,
crossinline block: HTML.() -> Unit = {}
): T = HTML(
mapOf("lang" to lang), this, namespace
).visitAndFinalize(this, block)
@HtmlTagMarker private fun FlowOrInteractiveOrPhrasingContent.a(
href: String? = null,
target: String? = null,
classes: String? = null,
name: String? = null,
block: A.() -> Unit = {}
): Unit = A(
attributesMapOf(
"href",
href,
"target",
target,
"class",
classes,
"name",
name
),
consumer
).visit(block)
private companion object {
private const val EXTENSION = "html"
private const val NAME = "HTML"
const val DOCTYPE = "<!DOCTYPE html>"
const val META = "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
const val CSS_STYLE =
"body { font-family: sans-serif } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; word-break: break-word; display: inline-block }"
const val OPEN_SOURCE_LIBRARIES = "Open source licenses"
const val NO_LIBRARIES = "None"
const val NO_LICENSE = "No license found"
const val NOTICE_LIBRARIES = "Notice for packages:"
const val COPYRIGHT = "Copyright "
const val DEFAULT_AUTHOR = "The original author or authors"
const val DEFAULT_YEAR = "20xx"
private const val MISSING_LICENSE = "Missing standard license text for: "
@JvmStatic fun getLicenseText(fileName: String): String {
return HtmlReport::class.java
.getResource("/license/$fileName")
?.readText()
?: (MISSING_LICENSE + fileName)
}
}
}
|
apache-2.0
|
f53a711069792e356ddef09f902909f7
| 32.138577 | 158 | 0.535827 | 4.842912 | false | false | false | false |
cfig/Android_boot_image_editor
|
helper/src/main/kotlin/cfig/helper/ZipHelper.kt
|
1
|
19251
|
// 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.helper
import cc.cfig.io.Struct
import cfig.helper.Helper.Companion.check_call
import cfig.helper.Helper.Companion.check_output
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.archivers.zip.ZipMethod
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream
import org.apache.commons.compress.compressors.gzip.GzipParameters
import org.apache.commons.compress.compressors.lzma.LZMACompressorInputStream
import org.apache.commons.compress.compressors.lzma.LZMACompressorOutputStream
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
import org.apache.commons.compress.compressors.xz.XZCompressorOutputStream
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.apache.commons.exec.PumpStreamHandler
import org.slf4j.LoggerFactory
import org.tukaani.xz.XZFormatException
import java.io.*
import java.lang.RuntimeException
import java.net.URI
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import java.util.zip.ZipException
import kotlin.reflect.full.declaredFunctions
import kotlin.reflect.jvm.isAccessible
class ZipHelper {
class ZipEntryRecipe(val data: ByteArray, val name: String, val method: ZipMethod)
companion object {
private val log = LoggerFactory.getLogger("ZipHelper")
/*
unzip(): unzip fileName to outDir
*/
fun unzip(fileName: String, outDir: String) {
log.info("unzip: $fileName --> $outDir")
if (File(outDir).exists()) {
if (!File(outDir).isDirectory) {
throw RuntimeException("$outDir exists but is not directory")
}
} else {
log.info("Creating $outDir ...")
File(outDir).mkdirs()
}
ZipArchiveInputStream(FileInputStream(fileName)).use { zis ->
while (true) {
val entry = zis.nextZipEntry ?: break
when {
entry.isDirectory -> {
val entryOut = File(outDir + "/" + entry.name)
entryOut.mkdir()
log.debug("Unzipping[d]: ${entry.name}")
}
entry.isUnixSymlink -> {
throw IllegalArgumentException("this should not happen: Found dir ${entry.name}")
}
else -> {
val entryOut = File(outDir + "/" + entry.name)
log.debug("Unzipping[f]: ${entry.name}")
FileOutputStream(entryOut).use {
zis.copyTo(it)
}
}
}
}
}
log.info("unzip: $fileName --> $outDir Done.")
}
fun zipDelete(zipFile: File, entryName: String) {
val zipProperties = mutableMapOf("create" to "false")
val zipURI = URI.create("jar:file:" + zipFile.canonicalPath)
FileSystems.newFileSystem(zipURI, zipProperties).use { zipfs ->
val entryPath = zipfs.getPath(entryName)
log.info("deleting " + entryPath.toUri() + " from ZIP File ${zipFile.name}")
Files.delete(entryPath)
}
}
fun zipClone(inFile: String, outFile: String) {
ZipFile(inFile).use { zf ->
val zaos = ZipArchiveOutputStream(FileOutputStream(outFile))
val e = zf.entries
while (e.hasMoreElements()) {
val entry = e.nextElement()
zaos.putArchiveEntry(entry)
zf.getInputStream(entry).copyTo(zaos)
zaos.closeArchiveEntry()
}
zaos.finish()
zaos.close()
}
}
fun zipEdit(inFile: String, entryRecipe: ZipEntryRecipe) {
val tmpFile = File.createTempFile("edit.", ".zip")
log.info("transforming $inFile --> $tmpFile ...")
ZipFile(inFile).use { zf ->
val zaos = ZipArchiveOutputStream(tmpFile)
val e = zf.entries
if (zf.getEntry(entryRecipe.name) == null) {
log.info("adding new entry [${entryRecipe.name}(${entryRecipe.method})] into [${tmpFile.canonicalPath}]")
val entry = ZipArchiveEntry(entryRecipe.name)
entry.method = entryRecipe.method.ordinal
zaos.putArchiveEntry(entry)
ByteArrayInputStream(entryRecipe.data).copyTo(zaos)
}
while (e.hasMoreElements()) {
val entry = e.nextElement()
zaos.putArchiveEntry(entry)
if (entry.name == entryRecipe.name) {
log.info("modifying existent entry [${entryRecipe.name}(${entryRecipe.method})] into [${tmpFile.canonicalPath}]")
ByteArrayInputStream(entryRecipe.data).copyTo(zaos)
} else {
log.debug("cloning entry ${entry.name} ...")
zf.getInputStream(entry).copyTo(zaos)
}
zaos.closeArchiveEntry()
}
zaos.finish()
zaos.close()
}
log.info("transforming $inFile --> ${tmpFile.name} done")
Files.move(tmpFile.toPath(), File(inFile).toPath(), StandardCopyOption.REPLACE_EXISTING)
log.info("renaming ${tmpFile.canonicalPath} --> $inFile done")
}
/*
https://github.com/python/cpython/blob/3.8/Lib/zipfile.py
The "local file header" structure, magic number, size, and indices
(section V.A in the format document)
structFileHeader = "<4s2B4HL2L2H"
stringFileHeader = b"PK\003\004"
sizeFileHeader = struct.calcsize(structFileHeader)
*/
fun ZipArchiveEntry.getEntryOffset(): Long {
val zipFileHeaderSize = Struct("<4s2B4HL2L2H").calcSize()
val funGetLocalHeaderOffset = ZipArchiveEntry::class.declaredFunctions.filter { funcItem ->
funcItem.name == "getLocalHeaderOffset"
}[0]
funGetLocalHeaderOffset.isAccessible = true
val headerOffset = funGetLocalHeaderOffset.call(this) as Long
val offset: Long = headerOffset + zipFileHeaderSize + this.localFileDataExtra.size + this.name.length
log.debug("headerOffset = $headerOffset")
log.debug("calcSize: $zipFileHeaderSize")
return offset
}
fun ZipFile.dumpEntry(entryName: String, outFile: File, ignoreError: Boolean = false) {
val entry = this.getEntry(entryName)
if (entry != null) {
log.info("dumping entry: $entryName -> $outFile")
FileOutputStream(outFile).use { outStream ->
this.getInputStream(entry).copyTo(outStream)
}
} else {
if (ignoreError) {
log.info("dumping entry: $entryName : entry not found, skip")
} else {
throw IllegalArgumentException("$entryName doesn't exist")
}
}
}
fun ZipArchiveOutputStream.pack(
inFile: File,
entryName: String,
zipMethod: ZipMethod = ZipMethod.DEFLATED
) {
log.info("packing $entryName($zipMethod) from file $inFile (size=${inFile.length()} ...")
val entry = ZipArchiveEntry(inFile, entryName)
entry.method = zipMethod.ordinal
this.putArchiveEntry(entry)
Files.newInputStream(inFile.toPath()).copyTo(this)
this.closeArchiveEntry()
}
fun ZipArchiveOutputStream.pack(
inStream: InputStream,
entryName: String,
zipMethod: ZipMethod = ZipMethod.DEFLATED
) {
log.info("packing $entryName($zipMethod) from input stream (size=unknown...")
val entry = ZipArchiveEntry(entryName)
entry.method = zipMethod.ordinal
this.putArchiveEntry(entry)
inStream.copyTo(this)
this.closeArchiveEntry()
}
/*
LZMACompressorInputStream() may raise OOM sometimes, like this:
Caused by: java.lang.OutOfMemoryError: Java heap space
at org.tukaani.xz.ArrayCache.getByteArray(Unknown Source)
at org.tukaani.xz.lz.LZDecoder.<init>(Unknown Source)
at org.tukaani.xz.LZMAInputStream.initialize(Unknown Source)
So we catch it explicitly.
*/
fun isLzma(compressedFile: String): Boolean {
return try {
FileInputStream(compressedFile).use { fis ->
LZMACompressorInputStream(fis).use {
}
}
true
} catch (e: IOException) {
false
} catch (e: OutOfMemoryError) {
false
}
}
fun lzma(compressedFile: String, fis: InputStream) {
log.info("Compress(lzma) ... ")
FileOutputStream(compressedFile).use { fos ->
LZMACompressorOutputStream(fos).use { gos ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = fis.read(buffer)
if (bytesRead <= 0) break
gos.write(buffer, 0, bytesRead)
}
}
}
log.info("compress(lzma) done: $compressedFile")
}
/*
@function: lzcat compressedFile > decompressedFile
*/
fun lzcat(compressedFile: String, decompressedFile: String) {
FileInputStream(compressedFile).use { fileIn ->
LZMACompressorInputStream(fileIn).use { lzmaInputStream ->
FileOutputStream(decompressedFile).use { fileOutputStream ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = lzmaInputStream.read(buffer)
if (bytesRead <= 0) break
fileOutputStream.write(buffer, 0, bytesRead)
}
}
}
}
log.info("decompress(lzma) done: $compressedFile -> $decompressedFile")
}
fun isXz(compressedFile: String): Boolean {
return try {
FileInputStream(compressedFile).use { fis ->
XZCompressorInputStream(fis).use {
}
}
true
} catch (e: XZFormatException) {
false
}
}
fun xz(compressedFile: String, fis: InputStream) {
log.info("Compress(xz) ... ")
FileOutputStream(compressedFile).use { fos ->
XZCompressorOutputStream(fos).use { gos ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = fis.read(buffer)
if (bytesRead <= 0) break
gos.write(buffer, 0, bytesRead)
}
}
}
log.info("compress(xz) done: $compressedFile")
}
/*
@function: xzcat compressedFile > decompressedFile
*/
fun xzcat(compressedFile: String, decompressedFile: String) {
FileInputStream(compressedFile).use { fileIn ->
XZCompressorInputStream(fileIn).use { zis ->
FileOutputStream(decompressedFile).use { fileOutputStream ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = zis.read(buffer)
if (bytesRead <= 0) break
fileOutputStream.write(buffer, 0, bytesRead)
}
}
}
}
log.info("decompress(xz) done: $compressedFile -> $decompressedFile")
}
fun isLz4(compressedFile: String): Boolean {
return try {
"lz4 -t $compressedFile".check_call()
true
} catch (e: Exception) {
false
}
}
fun lz4cat(lz4File: String, outFile: String) {
"lz4 -d -fv $lz4File $outFile".check_call()
}
fun lz4(lz4File: String, inputStream: InputStream) {
FileOutputStream(File(lz4File)).use { fos ->
val baosE = ByteArrayOutputStream()
DefaultExecutor().let { exec ->
exec.streamHandler = PumpStreamHandler(fos, baosE, inputStream)
val cmd = CommandLine.parse("lz4 -l -12")
if ("lz4 --version".check_output().contains("r\\d+,".toRegex())) {
log.warn("lz4 version obsolete, needs update")
} else {
cmd.addArgument("--favor-decSpeed")
}
log.info(cmd.toString())
exec.execute(cmd)
}
baosE.toByteArray().let {
if (it.isNotEmpty()) {
log.warn(String(it))
}
}
}
}
fun isAndroidCpio(compressedFile: String): Boolean {
return Dumpling(compressedFile).readFully(0L..5)
.contentEquals(byteArrayOf(0x30, 0x37, 0x30, 0x37, 0x30, 0x31))
}
fun isGZ(compressedFile: String): Boolean {
return try {
FileInputStream(compressedFile).use { fis ->
GZIPInputStream(fis).use {
}
}
true
} catch (e: ZipException) {
false
}
}
/*
@function: zcat compressedFile > decompressedFile
*/
fun zcat(compressedFile: String, decompressedFile: String) {
FileInputStream(compressedFile).use { fileIn ->
GZIPInputStream(fileIn).use { gZIPInputStream ->
FileOutputStream(decompressedFile).use { fileOutputStream ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = gZIPInputStream.read(buffer)
if (bytesRead <= 0) break
fileOutputStream.write(buffer, 0, bytesRead)
}
}
}
}
log.info("decompress(gz) done: $compressedFile -> $decompressedFile")
}
/*
@function: gzip InputStream to file,
using java.util.zip.GZIPOutputStream
caution: about gzip header - OS (Operating System)
According to https://docs.oracle.com/javase/8/docs/api/java/util/zip/package-summary.html
and GZIP spec RFC-1952(http://www.ietf.org/rfc/rfc1952.txt),
gzip files created from java.util.zip.GZIPOutputStream will mark the OS field with
0 - FAT filesystem (MS-DOS, OS/2, NT/Win32)
But default image built from Android source code has the OS field:
3 - Unix
*/
fun gzip(compressedFile: String, fis: InputStream) {
FileOutputStream(compressedFile).use { fos ->
GZIPOutputStream(fos).use { gos ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = fis.read(buffer)
if (bytesRead <= 0) break
gos.write(buffer, 0, bytesRead)
}
}
}
log.info("compress(gz) done: $compressedFile")
}
/*
@function: gzip InputStream to file like Android minigzip,
using commons.compress GzipCompressorOutputStream,
@dependency: commons.compress
*/
fun minigzip(compressedFile: String, fis: InputStream) {
val param = GzipParameters().apply {
operatingSystem = 3 //3: Unix
}
FileOutputStream(compressedFile).use { fos ->
GzipCompressorOutputStream(fos, param).use { gos ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = fis.read(buffer)
if (bytesRead <= 0) break
gos.write(buffer, 0, bytesRead)
}
}
}
log.info("compress(gz) done: $compressedFile")
}
fun isBzip2(compressedFile: String): Boolean {
return try {
FileInputStream(compressedFile).use { fis ->
BZip2CompressorInputStream(fis).use { }
}
true
} catch (e: IOException) {
false
}
}
fun bzip2(compressedFile: String, fis: InputStream) {
log.info("Compress(bzip2) ... ")
FileOutputStream(compressedFile).use { fos ->
BZip2CompressorOutputStream(fos).use { zos ->
val buffer = ByteArray(1024)
while (true) {
val bytesRead = fis.read(buffer)
if (bytesRead <= 0) break
zos.write(buffer, 0, bytesRead)
}
}
}
log.info("compress(bzip2) done: $compressedFile")
}
} // end-of-companion
}
|
apache-2.0
|
75a6d231526fed7aae8ae5439a16e690
| 40.4 | 137 | 0.529063 | 5.060726 | false | false | false | false |
hartwigmedical/hmftools
|
teal/src/main/kotlin/com/hartwig/hmftools/teal/TealUtils.kt
|
1
|
4716
|
package com.hartwig.hmftools.teal
import java.lang.StringBuilder
import java.lang.ThreadLocal
import com.hartwig.hmftools.common.utils.sv.ChrBaseRegion
import com.hartwig.hmftools.teal.telbam.TelbamParams
import htsjdk.samtools.SamReader
import htsjdk.samtools.SamReaderFactory
import org.apache.commons.lang3.StringUtils
import java.io.File
import java.util.regex.Pattern
object TealUtils
{
fun hasTelomericContent(readBases: String): Boolean
{
for (teloSeq in TealConstants.CANONICAL_TELOMERE_SEQUENCES)
{
val matchIndex = readBases.indexOf(teloSeq)
if (matchIndex != -1)
{
return true
}
}
return false
}
// todo: try SequenceUtil.reverseComplement
fun reverseComplementSequence(seq: String): String
{
val builder = StringBuilder()
for (i in seq.length - 1 downTo 0)
{
val b = seq[i]
when (b)
{
'A' ->
{
builder.append('T')
}
'T' ->
{
builder.append('A')
}
'G' ->
{
builder.append('C')
}
'C' ->
{
builder.append('G')
}
}
}
return builder.toString()
}
private const val MIN_CANONICAL_COUNT = 4
private const val MIN_CONSECUTIVE_HEXAMERS = 6
// we match the start of the sequence, must be at least 6 repeats of telomere. The reason we only match the start of the sequence
// is to account for poly G tail that many reads have
private val sGTeloPattern =
Pattern.compile("^[ACGT]{0,2}G{0,3}" + StringUtils.repeat("(?!GGGGGG)([ACGT][ACGT][ACGT]GGG)", MIN_CONSECUTIVE_HEXAMERS))
private val sCTeloPattern =
Pattern.compile("^[ACGT]{0,2}C{0,3}" + StringUtils.repeat("(?!CCCCCC)([ACGT][ACGT][ACGT]CCC)", MIN_CONSECUTIVE_HEXAMERS))
// make matcher thread local since they are not thread safe
private val sGTeloPatternMatcher = ThreadLocal.withInitial { sGTeloPattern.matcher("") }
private val sCTeloPatternMatcher = ThreadLocal.withInitial { sCTeloPattern.matcher("") }
fun isLikelyGTelomeric(readBases: String): Boolean
{
if (StringUtils.countMatches(readBases, "TTAGGG") >= MIN_CANONICAL_COUNT)
{
val m = sGTeloPatternMatcher.get()
m.reset(readBases)
return m.find()
}
return false
}
fun isLikelyCTelomeric(readBases: String): Boolean
{
if (StringUtils.countMatches(readBases, "CCCTAA") >= MIN_CANONICAL_COUNT)
{
val m = sCTeloPatternMatcher.get()
m.reset(readBases)
return m.find()
}
return false
}
// determine if the read is poly G
// note: We must supply this function with the read as is from
// the read
fun isPolyGC(readSeq: String): Boolean
{
// we use threshold of 90%
val numGCs = Math.max(StringUtils.countMatches(readSeq, 'G'), StringUtils.countMatches(readSeq, 'C')).toDouble()
val gcFrac = numGCs / readSeq.length
return gcFrac >= TealConstants.POLY_G_THRESHOLD
}
fun createPartitions(config: TelbamParams): List<ChrBaseRegion>
{
val samReader = openSamReader(config)
val samSequences = samReader.fileHeader.sequenceDictionary.sequences
val partitions: MutableList<ChrBaseRegion> = org.apache.commons.compress.utils.Lists.newArrayList()
val partitionSize = TealConstants.DEFAULT_PARTITION_SIZE
for (seq in samSequences)
{
val chrStr = seq.sequenceName
if (!config.specificChromosomes.isEmpty() && !config.specificChromosomes.contains(chrStr)) continue
val chromosomeLength = seq.sequenceLength
var startPos = 0
while (startPos < chromosomeLength)
{
var endPos = startPos + partitionSize - 1
if (endPos + partitionSize * 0.2 > chromosomeLength) endPos = chromosomeLength
partitions.add(ChrBaseRegion(chrStr, startPos, endPos))
startPos = endPos + 1
}
}
return partitions
}
fun openSamReader(config: TelbamParams): SamReader
{
var factory = SamReaderFactory.makeDefault()
if (config.refGenomeFile != null && !config.refGenomeFile!!.isEmpty())
{
factory = factory.referenceSequence(File(config.refGenomeFile!!))
}
return factory.open(File(config.bamFile))
}
}
|
gpl-3.0
|
0551b7a0067150b330d9a0350bbeab74
| 33.683824 | 133 | 0.596268 | 4.177148 | false | true | false | false |
dafi/photoshelf
|
core/src/main/java/com/ternaryop/photoshelf/util/post/OnPagingScrollListener.kt
|
1
|
1112
|
package com.ternaryop.photoshelf.util.post
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class OnPagingScrollListener(private val onScrollListener: OnScrollListener) : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val layoutManager = recyclerView.layoutManager ?: return
val visibleItemCount = layoutManager.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItem = (layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
// ignore any change after a layout calculation
// see onScrolled documentation
if (dx == 0 && dy == 0) {
return
}
onScrollListener.onScrolled(this, firstVisibleItem, visibleItemCount, totalItemCount)
}
interface OnScrollListener {
fun onScrolled(
onPagingScrollListener: OnPagingScrollListener,
firstVisibleItem: Int,
visibleItemCount: Int,
totalItemCount: Int
)
}
}
|
mit
|
dc9385b59a94baf33e07dea62a0b4e32
| 37.344828 | 112 | 0.705036 | 6.010811 | false | false | false | false |
tasks/tasks
|
app/src/main/java/com/todoroo/astrid/gtasks/api/GtasksInvoker.kt
|
1
|
4156
|
package com.todoroo.astrid.gtasks.api
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.tasks.Tasks
import com.google.api.services.tasks.model.Task
import com.google.api.services.tasks.model.TaskList
import com.google.api.services.tasks.model.TaskLists
import org.tasks.DebugNetworkInterceptor
import org.tasks.googleapis.BaseInvoker
import org.tasks.preferences.Preferences
import java.io.IOException
/**
* Wrapper around the official Google Tasks API to simplify common operations. In the case of an
* exception, each request is tried twice in case of a timeout.
*
* @author Sam Bosley
*/
class GtasksInvoker(
credentials: HttpCredentialsAdapter,
preferences: Preferences,
interceptor: DebugNetworkInterceptor
) : BaseInvoker(credentials, preferences, interceptor) {
private val service =
Tasks.Builder(NetHttpTransport(), GsonFactory(), credentials)
.setApplicationName(APP_NAME)
.build()
@Throws(IOException::class)
suspend fun allGtaskLists(pageToken: String?): TaskLists? =
execute(service!!.tasklists().list().setMaxResults(100).setPageToken(pageToken))
@Throws(IOException::class)
suspend fun getAllGtasksFromListId(
listId: String?, lastSyncDate: Long, pageToken: String?): com.google.api.services.tasks.model.Tasks? =
execute(
service!!
.tasks()
.list(listId)
.setMaxResults(100)
.setShowDeleted(true)
.setShowHidden(true)
.setPageToken(pageToken)
.setUpdatedMin(
GtasksApiUtilities.unixTimeToGtasksCompletionTime(lastSyncDate).toStringRfc3339()))
@Throws(IOException::class)
suspend fun getAllPositions(
listId: String?, pageToken: String?): com.google.api.services.tasks.model.Tasks? =
execute(
service!!
.tasks()
.list(listId)
.setMaxResults(100)
.setShowDeleted(false)
.setShowHidden(false)
.setPageToken(pageToken)
.setFields("items(id,parent,position),nextPageToken"))
@Throws(IOException::class)
suspend fun createGtask(
listId: String?, task: Task?, parent: String?, previous: String?): Task? =
execute(service!!.tasks().insert(listId, task).setParent(parent).setPrevious(previous))
@Throws(IOException::class)
suspend fun updateGtask(listId: String?, task: Task) =
execute(service!!.tasks().update(listId, task.id, task))
@Throws(IOException::class)
suspend fun moveGtask(
listId: String?, taskId: String?, parentId: String?, previousId: String?): Task? =
execute(
service!!
.tasks()
.move(listId, taskId)
.setParent(parentId)
.setPrevious(previousId))
@Throws(IOException::class)
suspend fun deleteGtaskList(listId: String?) {
try {
execute(service!!.tasklists().delete(listId))
} catch (ignored: HttpNotFoundException) {
}
}
@Throws(IOException::class)
suspend fun renameGtaskList(listId: String?, title: String?): TaskList? =
execute(service!!.tasklists().patch(listId, TaskList().setTitle(title)))
@Throws(IOException::class)
suspend fun createGtaskList(title: String?): TaskList? =
execute(service!!.tasklists().insert(TaskList().setTitle(title)))
@Throws(IOException::class)
suspend fun deleteGtask(listId: String?, taskId: String?) {
try {
execute(service!!.tasks().delete(listId, taskId))
} catch (ignored: HttpNotFoundException) {
}
}
}
|
gpl-3.0
|
314d7480f8999f0c46d80081dcbb7720
| 39.359223 | 119 | 0.595765 | 4.760596 | false | false | false | false |
rcgroot/open-gpstracker-ng
|
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/tracklist/TrackViewModel.kt
|
1
|
2447
|
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.tracklist
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import android.net.Uri
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.maps.model.PolylineOptions
import nl.sogeti.android.opengpstrack.ng.features.R
class TrackViewModel(val uri: Uri) {
val name = ObservableField<String>("")
val iconType = ObservableInt(R.drawable.ic_track_type_default)
val startDay = ObservableField<String>("--")
val duration = ObservableField<String>("--")
val distance = ObservableField<String>("--")
val completeBounds = ObservableField<LatLngBounds?>()
val waypoints = ObservableField<List<List<LatLng>>>(listOf())
val polylines = ObservableField<List<PolylineOptions>?>()
val editMode = ObservableBoolean(false)
}
|
gpl-3.0
|
9c8cb3258b7deeb0bdd286a07bf2be6a
| 46.980392 | 81 | 0.651819 | 4.798039 | false | false | false | false |
LarsKrogJensen/graphql-kotlin
|
src/main/kotlin/graphql/language/ObjectValue.kt
|
1
|
617
|
package graphql.language
import java.util.ArrayList
class ObjectValue : AbstractNode(), Value {
val objectFields = ArrayList<ObjectField>()
override val children: List<Node>
get() = objectFields
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
return true
}
override fun toString(): String {
return "ObjectValue{" +
"objectFields=" + objectFields +
'}'
}
fun add(objectField: ObjectField) {
objectFields += objectField
}
}
|
mit
|
570d3cdef085f88c86a789e68b7a0625
| 21.035714 | 53 | 0.602917 | 4.782946 | false | false | false | false |
goodwinnk/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/server/JUnitServerImpl.kt
|
1
|
6600
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.remote.server
import com.intellij.testGuiFramework.remote.transport.MessageType
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import org.apache.log4j.Logger
import java.io.InvalidClassException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
* @author Sergey Karashevich
*/
class JUnitServerImpl : JUnitServer {
private val SEND_THREAD = "JUnit Server Send Thread"
private val RECEIVE_THREAD = "JUnit Server Receive Thread"
private val postingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val receivingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val handlers: ArrayList<ServerHandler> = ArrayList()
private var failHandler: ((Throwable) -> Unit)? = null
private val LOG = Logger.getLogger("#com.intellij.testGuiFramework.remote.server.JUnitServerImpl")
private val serverSocket = ServerSocket(0)
private lateinit var serverSendThread: ServerSendThread
private lateinit var serverReceiveThread: ServerReceiveThread
private lateinit var connection: Socket
private var isStarted = false
private val IDE_STARTUP_TIMEOUT = 180000
private val port: Int
init {
port = serverSocket.localPort
serverSocket.soTimeout = IDE_STARTUP_TIMEOUT
}
override fun start() {
connection = serverSocket.accept()
LOG.info("Server accepted client on port: ${connection.port}")
serverSendThread = ServerSendThread()
serverSendThread.start()
serverReceiveThread = ServerReceiveThread()
serverReceiveThread.start()
isStarted = true
}
override fun isStarted(): Boolean = isStarted
override fun send(message: TransportMessage) {
postingMessages.put(message)
LOG.info("Add message to send pool: $message ")
}
override fun receive(): TransportMessage {
return receivingMessages.poll(IDE_STARTUP_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
?: throw SocketException("Client doesn't respond. Either the test has hanged or IDE crushed.")
}
override fun sendAndWaitAnswer(message: TransportMessage): Unit = sendAndWaitAnswerBase(message)
override fun sendAndWaitAnswer(message: TransportMessage, timeout: Long, timeUnit: TimeUnit): Unit = sendAndWaitAnswerBase(message, timeout, timeUnit)
private fun sendAndWaitAnswerBase(message: TransportMessage, timeout: Long = 0L, timeUnit: TimeUnit = TimeUnit.SECONDS) {
val countDownLatch = CountDownLatch(1)
val waitHandler = createCallbackServerHandler({ countDownLatch.countDown() }, message.id)
addHandler(waitHandler)
send(message)
if (timeout == 0L)
countDownLatch.await()
else
countDownLatch.await(timeout, timeUnit)
removeHandler(waitHandler)
}
override fun addHandler(serverHandler: ServerHandler) {
handlers.add(serverHandler)
}
override fun removeHandler(serverHandler: ServerHandler) {
handlers.remove(serverHandler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun setFailHandler(failHandler: (Throwable) -> Unit) {
this.failHandler = failHandler
}
override fun isConnected(): Boolean {
return try {
connection.isConnected && !connection.isClosed
}
catch (lateInitException: UninitializedPropertyAccessException) {
false
}
}
override fun getPort(): Int = port
override fun stopServer() {
serverSendThread.interrupt()
LOG.info("Server Send Thread joined")
serverReceiveThread.interrupt()
LOG.info("Server Receive Thread joined")
connection.close()
isStarted = false
}
private fun createCallbackServerHandler(handler: (TransportMessage) -> Unit, id: Long)
= object : ServerHandler() {
override fun acceptObject(message: TransportMessage) = message.id == id
override fun handleObject(message: TransportMessage) {
handler(message)
}
}
private inner class ServerSendThread: Thread(SEND_THREAD) {
override fun run() {
LOG.info("Server Send Thread started")
ObjectOutputStream(connection.getOutputStream()).use { outputStream ->
try {
while (!connection.isClosed) {
val message = postingMessages.take()
LOG.info("Sending message: $message ")
outputStream.writeObject(message)
}
}
catch (e: Exception) {
when (e) {
is InterruptedException -> { /* ignore */ }
is InvalidClassException -> LOG.error("Probably client is down:", e)
else -> {
LOG.info(e)
failHandler?.invoke(e)
}
}
}
}
}
}
private inner class ServerReceiveThread: Thread(RECEIVE_THREAD) {
override fun run() {
LOG.info("Server Receive Thread started")
ObjectInputStream(connection.getInputStream()).use { inputStream ->
try {
while (!connection.isClosed) {
val obj = inputStream.readObject()
LOG.debug("Receiving message (DEBUG): $obj")
assert(obj is TransportMessage)
val message = obj as TransportMessage
if (message.type != MessageType.KEEP_ALIVE) LOG.info("Receiving message: $obj")
receivingMessages.put(message)
handlers.filter { it.acceptObject(message) }.forEach { it.handleObject(message) }
}
}
catch (e: Exception) {
when (e) {
is InterruptedException -> { /* ignore */ }
is InvalidClassException -> LOG.error("Probably serialization error:", e)
else -> {
LOG.info(e)
failHandler?.invoke(e)
}
}
}
}
}
}
}
|
apache-2.0
|
6e36b3fdc67299eebee6c4184a863e2d
| 31.840796 | 152 | 0.694697 | 4.772234 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/util/delegates.kt
|
1
|
1085
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import kotlin.reflect.KProperty
class NullableDelegate<T>(supplier: () -> T?) {
private var field: T? = null
private var func: (() -> T?)? = supplier
private val lock = Lock()
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
var f = field
if (f != null) {
return f
}
synchronized(lock) {
f = field
if (f != null) {
return f
}
f = func!!()
// Don't hold on to the supplier after it's used and returned a value
if (f != null) {
field = f
func = null
}
}
return f
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
this.field = value
}
private class Lock
}
fun <T> nullable(supplier: () -> T?): NullableDelegate<T> = NullableDelegate(supplier)
|
mit
|
fbfd163739b40488c9db5416ef0b0c86
| 19.865385 | 86 | 0.517051 | 4.189189 | false | false | false | false |
gameofbombs/kt-postgresql-async
|
postgresql-async/src/test/kotlin/com/github/mauricio/async/db/examples/BasicExample.kt
|
2
|
1773
|
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.examples
import com.github.elizarov.async.async
import com.github.mauricio.async.db.postgresql.PostgreSQLConnection
import com.github.mauricio.async.db.postgresql.util.URLParser
import com.github.mauricio.async.db.util.ExecutorServiceUtils.CachedExecutionContext
import com.github.mauricio.async.db.RowData
import com.github.mauricio.async.db.QueryResult
import com.github.mauricio.async.db.Connection
import io.netty.channel.EventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel
import java.time.Duration
fun main(args: Array<String>) {
val configuration = URLParser.parse("jdbc:postgresql://localhost:5432/testbase?username=postgres&password=postgres")
val connection: Connection = PostgreSQLConnection(configuration)
val TL: Duration? = null; //Duration.ofSeconds(5)
async {
//waitTimeout?
connection.connect()
val queryResult = connection.sendQuery("SELECT 0")
val result = queryResult.rows.let { if (it == null) -1 else it[0][0] }
//waitTimeout
println(result)
connection.disconnect()
}.get()
}
|
apache-2.0
|
0c7a42517d6330ee924c2ead7e73dc64
| 34.42 | 120 | 0.749859 | 4.052632 | false | false | false | false |
rmnn/compiler
|
src/main/kotlin/ru/dageev/compiler/parser/visitor/expression/BinaryOperationVisitor.kt
|
1
|
4055
|
package ru.dageev.compiler.parser.visitor.expression
import ru.dageev.compiler.domain.node.expression.BinaryExpression
import ru.dageev.compiler.domain.node.expression.Expression
import ru.dageev.compiler.domain.type.PrimitiveType
import ru.dageev.compiler.domain.type.Type
import ru.dageev.compiler.grammar.ElaginBaseVisitor
import ru.dageev.compiler.grammar.ElaginParser
import ru.dageev.compiler.parser.CompilationException
/**
* Created by dageev
* on 11/2/16.
*/
class BinaryOperationVisitor(val expressionVisitor: ExpressionVisitor) : ElaginBaseVisitor<BinaryExpression>() {
override fun visitMultDivExpression(ctx: ElaginParser.MultDivExpressionContext): BinaryExpression {
val left = ctx.expression(0).accept(expressionVisitor)
val right = ctx.expression(1).accept(expressionVisitor)
checkForIntType(left, right, ctx.operation.text)
return when (ctx.operation.text) {
"*" -> BinaryExpression.MultiplicationExpression(left, right)
"/" -> BinaryExpression.DivisionalExpression(left, right)
"%" -> BinaryExpression.ModuleExpression(left, right)
else -> throw CompilationException("Wrong operation multiDiv operation ${ctx.operation.text}")
}
}
override fun visitSumExpression(ctx: ElaginParser.SumExpressionContext): BinaryExpression {
val left = ctx.expression(0).accept(expressionVisitor)
val right = ctx.expression(1).accept(expressionVisitor)
checkForIntType(left, right, ctx.operation.text)
return when (ctx.operation.text) {
"+" -> BinaryExpression.AdditionalExpression(left, right)
"-" -> BinaryExpression.SubtractionExpression(left, right)
else -> throw CompilationException("Wrong operation ${ctx.operation.text}")
}
}
override fun visitCompareExpression(ctx: ElaginParser.CompareExpressionContext): BinaryExpression {
val left = ctx.expression(0).accept(expressionVisitor)
val right = ctx.expression(1).accept(expressionVisitor)
return when (ctx.operation.text) {
"<" -> BinaryExpression.LessExpression(left, right)
"<=" -> BinaryExpression.LessEqualsExpression(left, right)
">" -> BinaryExpression.GreaterExpression(left, right)
">=" -> BinaryExpression.GreaterEqualsExpression(left, right)
"==" -> BinaryExpression.EqualityExpression(left, right)
"!=" -> BinaryExpression.NonEqualityExpression(left, right)
else -> throw CompilationException("Wrong operation ${ctx.operation.text}")
}
}
override fun visitLogicalExpression(ctx: ElaginParser.LogicalExpressionContext): BinaryExpression {
val left = ctx.expression(0).accept(expressionVisitor)
val right = ctx.expression(1).accept(expressionVisitor)
checkForBooleanType(left, right, ctx.operation.text)
return when (ctx.operation.text) {
"&&" -> BinaryExpression.LogicalAndExpression(left, right)
"||" -> BinaryExpression.LogicalOrExpression(left, right)
else -> throw CompilationException("Wrong operation ${ctx.operation.text}")
}
}
fun checkForIntType(left: Expression, right: Expression, operation: String) = checkForType(left, right, PrimitiveType.INT, operation)
fun checkForBooleanType(left: Expression, right: Expression, operation: String) = checkForType(left, right, PrimitiveType.BOOLEAN, operation)
fun checkForType(left: Expression, right: Expression, expectedType: Type, operation: String) {
if (left.type != expectedType) {
throw CompilationException("Incorrect left expression type for operation '$operation'. Expected '${expectedType.getTypeName()}', found '${left.type.getTypeName()}'")
}
if (right.type != expectedType) {
throw CompilationException("Incorrect right expression type for operation '$operation'. Expected '${expectedType.getTypeName()}', found '${right.type.getTypeName()}'")
}
}
}
|
apache-2.0
|
62601b5778d54f042fa333fccd142257
| 49.6875 | 179 | 0.703329 | 4.86211 | false | false | false | false |
vondear/RxTools
|
RxArcGisKit/src/main/java/com/tamsiree/rxarcgiskit/model/MapPreview.kt
|
1
|
1360
|
/* Copyright 2017 Esri
*
* 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.tamsiree.rxarcgiskit.model
import java.io.Serializable
/**
* Class which serves as the model in an MVC architecture for setting and getting information
* related to MapPreviews
*/
class MapPreview : Serializable {
var mapNum = 0
var title: String? = null
private var mTransportNetwork = false
private var mGeocoding = false
var desc: String? = null
var thumbnailByteStream: ByteArray? = null
fun hasTransportNetwork(): Boolean {
return mTransportNetwork
}
fun setTransportNetwork(transportNetwork: Boolean) {
mTransportNetwork = transportNetwork
}
fun hasGeocoding(): Boolean {
return mGeocoding
}
fun setGeocoding(geocoding: Boolean) {
mGeocoding = geocoding
}
}
|
apache-2.0
|
3403078deab96d92d13bcf4051133d25
| 27.354167 | 93 | 0.7125 | 4.303797 | false | false | false | false |
deskchanproject/DeskChanJava
|
src/main/kotlin/info/deskchan/external_loader/wrappers/MessageWrapper.kt
|
2
|
3556
|
package info.deskchan.external_loader.wrappers
import org.jetbrains.annotations.Nullable
import org.json.JSONArray
import org.json.JSONObject
abstract class MessageWrapper {
val messageArgsCount = mapOf(
"sendMessage" to 2,
"callNextAlternative" to 4,
"addMessageListener" to 2,
"removeMessageListener" to 2,
"setTimer" to 3,
"cancelTimer" to 1,
"setAlternative" to 3,
"deleteAlternative" to 2,
"getProperty" to 1,
"setProperty" to 2,
"getConfigField" to 1,
"setConfigField" to 2,
"getString" to 1,
"log" to 1,
"error" to 1,
"initializationCompleted" to 0
)
class Message(
val type: String,
val requiredArguments: MutableList<Any?> = mutableListOf(),
val additionalArguments: MutableMap<String, Any?> = mutableMapOf()
){
fun getRequiredAsInt(index: Int) = (requiredArguments[index] as Number).toInt()
fun getRequiredAsLong(index: Int) = (requiredArguments[index] as Number).toLong()
fun getRequiredAsString(index: Int) = requiredArguments[index].toString()
}
abstract fun wrap(message: Message): Any
abstract fun unwrap(text: String): Message
fun serialize(data: Any?): Any {
return when(data)
{
is Collection<*> -> dataToJSON(data)
is Map<*, *> -> dataToJSON(data)
is JSONArray -> dataToJSON(data)
is JSONObject -> dataToJSON(data)
is MessageWrapper.Message -> wrap(data)
is Nullable -> "null"
is Number -> data
else -> data.toString().replace("\n", "\t")
}
}
fun deserialize(data:Any?):Any? {
if (data == null) return null
if (data is List<*> || data is Map<*,*>) return data
if (data is JSONArray) return JSONToData(data)
if (data is JSONObject) return JSONToData(data)
val rdata = data.toString().replace("\t", "\n")
try {
return JSONToData(JSONArray(rdata))
} catch (e:Exception){ }
try {
return JSONToData(JSONObject(rdata))
} catch (e:Exception){ }
try {
if (rdata.contains("."))
return rdata.toDouble()
else
return rdata.toLong()
} catch (e:Exception){ }
try {
val rldata = rdata.toLowerCase()
if (rldata == "true") return true
if (rldata == "false") return false
if (rldata == "null") return null
} catch (e:Exception){ }
return rdata
}
fun dataToJSON(data: Map<*,*>) : JSONObject {
val obj = JSONObject()
data.entries.forEach { obj.put(it.key.toString().replace("\n", "\t"), serialize(it.value)) }
return obj
}
fun dataToJSON(data: Collection<*>) : JSONArray {
val obj = JSONArray()
data.forEach { obj.put(serialize(it)) }
return obj
}
fun dataToJSON(data: JSONObject) : JSONObject = dataToJSON(data.toMap())
fun dataToJSON(data: JSONArray) : JSONArray = dataToJSON(data.toList())
fun JSONToData(data: JSONObject):Any? {
val obj = mutableMapOf<String, Any?>()
data.toMap().forEach { obj.put(it.key.toString().replace("\t", "\n"), deserialize(it.value)) }
return obj
}
fun JSONToData(data: JSONArray):Any? {
val obj = mutableListOf<Any?>()
data.forEach { obj.add(deserialize(it)) }
return obj
}
}
|
lgpl-3.0
|
1f007044fcfa05d1294348b7fc21f098
| 29.393162 | 102 | 0.570022 | 4.268908 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/GlobalAveragePooling.kt
|
1
|
2740
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.linalg.api.buffer.DataType
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
@PreHookRule(nodeNames = [],opNames = ["GlobalAveragePool"],frameworkName = "onnx")
class GlobalAveragePooling: PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
val inputVariable = sd.getVariable(op.inputsToOp[0])
val rankOf = sd.rank(inputVariable)
val range = sd.range(sd.constant(0),rankOf,sd.constant(1),DataType.INT64)
val sizes = sd.concat(0,sd.constant(2).castTo(DataType.INT64),sd.prod(range.shape()).sub(2.0).castTo(DataType.INT64))
val split = sd.splitV(range,sizes,2,0)
val output = sd.math.mean(outputNames[0],inputVariable,split[1],true)
return mapOf(output.name() to listOf(output))
}
}
|
apache-2.0
|
d183c110254042706b1df8ba8ac4b359
| 49.759259 | 184 | 0.709489 | 4.145234 | false | false | false | false |
jk1/youtrack-idea-plugin
|
src/main/kotlin/com/github/jk1/ytplugin/timeTracker/TimerWidget.kt
|
1
|
2484
|
package com.github.jk1.ytplugin.timeTracker
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.logger
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.CustomStatusBarWidget
import com.intellij.openapi.wm.StatusBar
import java.awt.Font
import java.util.concurrent.TimeUnit
import javax.swing.JLabel
import javax.swing.Timer
class TimerWidget(val timeTracker: TimeTracker, private val parentDisposable: Disposable, override val project: Project) : CustomStatusBarWidget, ComponentAware {
private val label = JLabel(time())
private val timer = Timer(1000) { label.text = time() }
private val logsTimer = Timer(120000) {
logger.debug(
"\nSystem.currentTimeMillis: ${System.currentTimeMillis()} \n" +
"timeTracker.startTime: ${timeTracker.startTime} \n" +
"timeTracker.pausedTime: ${timeTracker.pausedTime} \n")
}
private var trackingDisposable: Disposable? = null
fun time(): String {
val savedTime = spentTimePerTaskStorage.getSavedTimeForLocalTask(taskManagerComponent.getActiveTask().id)
val recordedTime = if (timeTracker.isPaused) {
timeTracker.getRecordedTimeInMills() + savedTime
} else {
System.currentTimeMillis() - timeTracker.startTime - timeTracker.pausedTime + savedTime
}
logger.debug("\nsavedTime: $savedTime \nrecordedTime: $recordedTime \n \n")
val time = String.format("%02dh %02dm",
TimeUnit.MILLISECONDS.toHours(recordedTime),
TimeUnit.MILLISECONDS.toMinutes(recordedTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(recordedTime)))
return "Time spent on issue ${timeTracker.issueId}: $time"
}
override fun install(statusBar: StatusBar) {
val f: Font = label.font
label.font = f.deriveFont(f.style or Font.BOLD)
trackingDisposable = ActivityTracker.newDisposable(parentDisposable)
timer.start()
logsTimer.start()
}
override fun dispose() {
if (trackingDisposable != null) {
Disposer.dispose(trackingDisposable!!)
trackingDisposable = null
}
}
override fun getComponent(): JLabel {
return label
}
override fun ID(): String {
return "Time Tracking Clock"
}
}
|
apache-2.0
|
e2f6df9f0e051eb3a37c40cc0697a9c7
| 34.5 | 162 | 0.680757 | 4.491863 | false | false | false | false |
petropavel13/2photo-android
|
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/db/DatabaseOpenHelper.kt
|
1
|
2382
|
package com.github.petropavel13.twophoto.db
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.github.petropavel13.twophoto.model.*
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper
import com.j256.ormlite.dao.Dao
import com.j256.ormlite.support.ConnectionSource
import com.j256.ormlite.table.TableUtils
/**
* Created by petropavel on 07/05/15.
*/
class DatabaseOpenHelper(ctx: Context): OrmLiteSqliteOpenHelper(ctx, "2photo-db", null, 1) {
override fun onUpgrade(database: SQLiteDatabase?, connectionSource: ConnectionSource?, oldVersion: Int, newVersion: Int) {
//
}
override fun onCreate(database: SQLiteDatabase?, connectionSource: ConnectionSource?) {
TableUtils.createTableIfNotExists(connectionSource, Post.Artist::class.java)
TableUtils.createTableIfNotExists(connectionSource, Post.Author::class.java)
TableUtils.createTableIfNotExists(connectionSource, Post.Category::class.java)
TableUtils.createTableIfNotExists(connectionSource, Post.Entry::class.java)
TableUtils.createTableIfNotExists(connectionSource, Post.Tag::class.java)
TableUtils.createTableIfNotExists(connectionSource, PostDetail.Comment::class.java)
TableUtils.createTableIfNotExists(connectionSource, PostDetail::class.java)
TableUtils.createTableIfNotExists(connectionSource, PostCategory::class.java)
TableUtils.createTableIfNotExists(connectionSource, PostTag::class.java)
TableUtils.createTableIfNotExists(connectionSource, PostArtist::class.java)
}
fun artistsDao(): Dao<Post.Artist, Int> = getDao(Post.Artist::class.java)
fun postArtistDao(): Dao<PostArtist, Int> = getDao(PostArtist::class.java)
fun authorsDao(): Dao<Post.Author, Int> = getDao(Post.Author::class.java)
fun categoriesDao(): Dao<Post.Category, Int> = getDao(Post.Category::class.java)
fun postCategoryDao(): Dao<PostCategory, Int> = getDao(PostCategory::class.java)
fun entriesDao(): Dao<Post.Entry, Int> = getDao(Post.Entry::class.java)
fun tagsDao(): Dao<Post.Tag, Int> = getDao(Post.Tag::class.java)
fun postTagsDao(): Dao<PostTag, Int> = getDao(PostTag::class.java)
fun commentsDao(): Dao<PostDetail.Comment, Int> = getDao(PostDetail.Comment::class.java)
fun postsDao(): Dao<PostDetail, Int> = getDao(PostDetail::class.java)
}
|
mit
|
bcb88c27a49a1a9b47f522933845f7c3
| 54.395349 | 126 | 0.759866 | 4.099828 | false | false | false | false |
saschpe/PlanningPoker
|
common/src/main/java/saschpe/poker/util/PlanningPoker.kt
|
1
|
1907
|
/*
* Copyright 2016 Sascha Peilicke
*
* 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 saschpe.poker.util
import android.util.SparseIntArray
import androidx.annotation.IntDef
object PlanningPoker {
const val FIBONACCI = 1
const val T_SHIRT_SIZES = 2
const val IDEAL_DAYS = 3
const val POWERS_OF_TWO = 4
const val REAL_FIBONACCI = 5
val values = androidx.collection.SimpleArrayMap<Int, List<String>>(3)
val defaults = SparseIntArray(5)
@IntDef(FIBONACCI, T_SHIRT_SIZES, IDEAL_DAYS, POWERS_OF_TWO)
annotation class Flavor
init {
// Use an "@" for coffee, because "☕" doesn't render correctly on most devices
values.put(FIBONACCI, listOf("0", "½", "1", "2", "3", "5", "8", "13", "20", "40", "100", "?", "@"))
values.put(T_SHIRT_SIZES, listOf("XS", "S", "M", "L", "XL", "XXL"))
values.put(IDEAL_DAYS, listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11+"))
values.put(POWERS_OF_TWO, listOf("0", "1", "2", "4", "8", "16", "32", "64"))
values.put(REAL_FIBONACCI, listOf("0", "1", "2", "3", "5", "8", "13", "21", "34", "55", "89", "144", "?", "☕"))
}
init {
defaults.append(FIBONACCI, 5)
defaults.append(T_SHIRT_SIZES, 2)
defaults.append(IDEAL_DAYS, 5)
defaults.append(POWERS_OF_TWO, 2)
defaults.append(REAL_FIBONACCI, 5)
}
}
|
apache-2.0
|
839d00a31afd1832741150267735c8d9
| 35.576923 | 119 | 0.620925 | 3.138614 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua
|
src/main/java/com/tang/intellij/lua/stubs/LuaTableFieldStub.kt
|
2
|
4284
|
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.BitUtil
import com.intellij.util.io.StringRef
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.psi.impl.LuaTableFieldImpl
import com.tang.intellij.lua.stubs.index.LuaClassMemberIndex
import com.tang.intellij.lua.stubs.index.StubKeys
import com.tang.intellij.lua.ty.ITy
import com.tang.intellij.lua.ty.getTableTypeName
class LuaTableFieldType : LuaStubElementType<LuaTableFieldStub, LuaTableField>("TABLE_FIELD") {
override fun createPsi(luaTableFieldStub: LuaTableFieldStub): LuaTableField {
return LuaTableFieldImpl(luaTableFieldStub, this)
}
override fun shouldCreateStub(node: ASTNode): Boolean {
val tableField = node.psi as LuaTableField
return tableField.shouldCreateStub
}
private fun findTableExprTypeName(field: LuaTableField): String? {
val table = PsiTreeUtil.getParentOfType(field, LuaTableExpr::class.java)
var ty: String? = null
if (table != null)
ty = getTableTypeName(table)
return ty
}
override fun createStub(field: LuaTableField, parentStub: StubElement<*>): LuaTableFieldStub {
val ty = field.comment?.docTy
val flags = BitUtil.set(0, FLAG_DEPRECATED, field.isDeprecated)
return LuaTableFieldStubImpl(ty,
field.fieldName,
findTableExprTypeName(field),
flags,
parentStub,
this)
}
override fun serialize(fieldStub: LuaTableFieldStub, stubOutputStream: StubOutputStream) {
stubOutputStream.writeTyNullable(fieldStub.docTy)
stubOutputStream.writeName(fieldStub.name)
stubOutputStream.writeName(fieldStub.typeName)
stubOutputStream.writeShort(fieldStub.flags)
}
override fun deserialize(stream: StubInputStream, stubElement: StubElement<*>): LuaTableFieldStub {
val ty = stream.readTyNullable()
val fieldName = stream.readName()
val typeName = stream.readName()
val flags = stream.readShort()
return LuaTableFieldStubImpl(ty,
StringRef.toString(fieldName),
StringRef.toString(typeName),
flags.toInt(),
stubElement,
this)
}
override fun indexStub(fieldStub: LuaTableFieldStub, indexSink: IndexSink) {
val fieldName = fieldStub.name
val typeName = fieldStub.typeName
if (fieldName != null && typeName != null) {
LuaClassMemberIndex.indexStub(indexSink, typeName, fieldName)
indexSink.occurrence(StubKeys.SHORT_NAME, fieldName)
}
}
companion object {
const val FLAG_DEPRECATED = 0x20
}
}
/**
* table field stub
* Created by tangzx on 2017/1/14.
*/
interface LuaTableFieldStub : LuaClassMemberStub<LuaTableField> {
val typeName: String?
val name: String?
val flags: Int
}
class LuaTableFieldStubImpl(
override val docTy: ITy?,
override val name: String?,
override val typeName: String?,
override val flags: Int,
parent: StubElement<*>,
elementType: LuaStubElementType<*, *>
) : LuaStubBase<LuaTableField>(parent, elementType), LuaTableFieldStub {
override val isDeprecated: Boolean
get() = BitUtil.isSet(flags, LuaTableFieldType.FLAG_DEPRECATED)
override val visibility = Visibility.PUBLIC
}
|
apache-2.0
|
307ad3fe9d17fb54f67aa5679795f1cd
| 34.413223 | 103 | 0.697712 | 4.434783 | false | false | false | false |
CruGlobal/android-gto-support
|
gto-support-androidx-collection/src/main/kotlin/org/ccci/gto/android/common/androidx/collection/LongSparseArray.kt
|
2
|
670
|
package org.ccci.gto.android.common.androidx.collection
import androidx.collection.LongSparseArray
fun <T> LongSparseArray<T>.mutableKeyIterator(): MutableIterator<Long> =
object : LongIterator(), MutableIterator<Long> {
var index = 0
var nextCalled = false
override fun hasNext() = index < size()
override fun nextLong() = keyAt(index++).also { nextCalled = true }
override fun remove() {
check(nextCalled) {
"next() was not called or remove() was called more than once for the most recent next() call"
}
removeAt(--index)
nextCalled = false
}
}
|
mit
|
bb70e89c524da32866ca959a17afbe76
| 34.263158 | 109 | 0.613433 | 4.685315 | false | false | false | false |
inorichi/tachiyomi-extensions
|
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/wpcomics/WPComics.kt
|
1
|
11157
|
package eu.kanade.tachiyomi.multisrc.wpcomics
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
abstract class WPComics(
override val name: String,
override val baseUrl: String,
override val lang: String,
private val dateFormat: SimpleDateFormat = SimpleDateFormat("HH:mm - dd/MM/yyyy Z", Locale.US),
private val gmtOffset: String? = "+0500"
) : ParsedHttpSource() {
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0")
.add("Referer", baseUrl)
private fun List<String>.doesInclude(thisWord: String): Boolean = this.any { it.contains(thisWord, ignoreCase = true) }
// Popular
open val popularPath = "hot"
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/$popularPath" + if (page > 1) "?page=$page" else "", headers)
}
override fun popularMangaSelector() = "div.items div.item"
override fun popularMangaFromElement(element: Element): SManga {
return SManga.create().apply {
element.select("h3 a").let {
title = it.text()
setUrlWithoutDomain(it.attr("abs:href"))
}
thumbnail_url = imageOrNull(element.select("div.image:first-of-type img").first())
}
}
override fun popularMangaNextPageSelector() = "a.next-page, a[rel=next]"
// Latest
override fun latestUpdatesRequest(page: Int): Request {
return GET(baseUrl + if (page > 1) "?page=$page" else "", headers)
}
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
// Search
protected open val searchPath = "tim-truyen"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val filterList = filters.let { if (it.isEmpty()) getFilterList() else it }
return if (filterList.isEmpty()) {
GET("$baseUrl/?s=$query&post_type=comics&page=$page")
} else {
val url = "$baseUrl/$searchPath".toHttpUrlOrNull()!!.newBuilder()
filterList.forEach { filter ->
when (filter) {
is GenreFilter -> filter.toUriPart()?.let { url.addPathSegment(it) }
is StatusFilter -> filter.toUriPart()?.let { url.addQueryParameter("status", it) }
}
}
url.apply {
addQueryParameter("keyword", query)
addQueryParameter("page", page.toString())
addQueryParameter("sort", "0")
}
GET(url.toString().replace("www.nettruyen.com/tim-truyen?status=2&", "www.nettruyen.com/truyen-full?"), headers)
}
}
override fun searchMangaSelector() = "div.items div.item div.image a"
override fun searchMangaFromElement(element: Element): SManga {
return SManga.create().apply {
title = element.attr("title")
setUrlWithoutDomain(element.attr("href"))
thumbnail_url = imageOrNull(element.select("img").first())
}
}
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
// Details
override fun mangaDetailsParse(document: Document): SManga {
return SManga.create().apply {
document.select("article#item-detail").let { info ->
author = info.select("li.author p.col-xs-8").text()
status = info.select("li.status p.col-xs-8").text().toStatus()
genre = info.select("li.kind p.col-xs-8 a").joinToString { it.text() }
description = info.select("div.detail-content p").text()
thumbnail_url = imageOrNull(info.select("div.col-image img").first())
}
}
}
open fun String?.toStatus(): Int {
val ongoingWords = listOf("Ongoing", "Updating", "Đang tiến hành")
val completedWords = listOf("Complete", "Hoàn thành")
return when {
this == null -> SManga.UNKNOWN
ongoingWords.doesInclude(this) -> SManga.ONGOING
completedWords.doesInclude(this) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
}
// Chapters
override fun chapterListSelector() = "div.list-chapter li.row:not(.heading)"
override fun chapterFromElement(element: Element): SChapter {
return SChapter.create().apply {
element.select("a").let {
name = it.text()
setUrlWithoutDomain(it.attr("href"))
}
date_upload = element.select("div.col-xs-4").text().toDate()
}
}
private val currentYear by lazy { Calendar.getInstance(Locale.US)[1].toString().takeLast(2) }
private fun String?.toDate(): Long {
this ?: return 0
val secondWords = listOf("second", "giây")
val minuteWords = listOf("minute", "phút")
val hourWords = listOf("hour", "giờ")
val dayWords = listOf("day", "ngày")
val agoWords = listOf("ago", "trước")
return try {
if (agoWords.any { this.contains(it, ignoreCase = true) }) {
val trimmedDate = this.substringBefore(" ago").removeSuffix("s").split(" ")
val calendar = Calendar.getInstance()
when {
dayWords.doesInclude(trimmedDate[1]) -> calendar.apply { add(Calendar.DAY_OF_MONTH, -trimmedDate[0].toInt()) }
hourWords.doesInclude(trimmedDate[1]) -> calendar.apply { add(Calendar.HOUR_OF_DAY, -trimmedDate[0].toInt()) }
minuteWords.doesInclude(trimmedDate[1]) -> calendar.apply { add(Calendar.MINUTE, -trimmedDate[0].toInt()) }
secondWords.doesInclude(trimmedDate[1]) -> calendar.apply { add(Calendar.SECOND, -trimmedDate[0].toInt()) }
}
calendar.timeInMillis
} else {
(if (gmtOffset == null) this.substringAfterLast(" ") else "$this $gmtOffset").let {
// timestamp has year
if (Regex("""\d+/\d+/\d\d""").find(it)?.value != null) {
dateFormat.parse(it)?.time ?: 0
} else {
// MangaSum - timestamp sometimes doesn't have year (current year implied)
dateFormat.parse("$it/$currentYear")?.time ?: 0
}
}
}
} catch (_: Exception) {
0L
}
}
// Pages
// sources sometimes have an image element with an empty attr that isn't really an image
open fun imageOrNull(element: Element): String? {
fun Element.hasValidAttr(attr: String): Boolean {
val regex = Regex("""https?://.*""", RegexOption.IGNORE_CASE)
return when {
this.attr(attr).isNullOrBlank() -> false
this.attr("abs:$attr").matches(regex) -> true
else -> false
}
}
return when {
element.hasValidAttr("data-original") -> element.attr("abs:data-original")
element.hasValidAttr("data-src") -> element.attr("abs:data-src")
element.hasValidAttr("src") -> element.attr("abs:src")
else -> null
}
}
open val pageListSelector = "div.page-chapter > img, li.blocks-gallery-item img"
override fun pageListParse(document: Document): List<Page> {
return document.select(pageListSelector).mapNotNull { img -> imageOrNull(img) }
.distinct()
.mapIndexed { i, image -> Page(i, "", image) }
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
// Filters
protected class StatusFilter(vals: Array<Pair<String?, String>>) : UriPartFilter("Status", vals)
protected class GenreFilter(vals: Array<Pair<String?, String>>) : UriPartFilter("Genre", vals)
protected open fun getStatusList(): Array<Pair<String?, String>> = arrayOf(
Pair(null, "Tất cả"),
Pair("1", "Đang tiến hành"),
Pair("2", "Đã hoàn thành"),
Pair("3", "Tạm ngừng")
)
protected open fun getGenreList(): Array<Pair<String?, String>> = arrayOf(
null to "Tất cả",
"action" to "Action",
"adult" to "Adult",
"adventure" to "Adventure",
"anime" to "Anime",
"chuyen-sinh" to "Chuyển Sinh",
"comedy" to "Comedy",
"comic" to "Comic",
"cooking" to "Cooking",
"co-dai" to "Cổ Đại",
"doujinshi" to "Doujinshi",
"drama" to "Drama",
"dam-my" to "Đam Mỹ",
"ecchi" to "Ecchi",
"fantasy" to "Fantasy",
"gender-bender" to "Gender Bender",
"harem" to "Harem",
"historical" to "Historical",
"horror" to "Horror",
"josei" to "Josei",
"live-action" to "Live action",
"manga" to "Manga",
"manhua" to "Manhua",
"manhwa" to "Manhwa",
"martial-arts" to "Martial Arts",
"mature" to "Mature",
"mecha" to "Mecha",
"mystery" to "Mystery",
"ngon-tinh" to "Ngôn Tình",
"one-shot" to "One shot",
"psychological" to "Psychological",
"romance" to "Romance",
"school-life" to "School Life",
"sci-fi" to "Sci-fi",
"seinen" to "Seinen",
"shoujo" to "Shoujo",
"shoujo-ai" to "Shoujo Ai",
"shounen" to "Shounen",
"shounen-ai" to "Shounen Ai",
"slice-of-life" to "Slice of Life",
"smut" to "Smut",
"soft-yaoi" to "Soft Yaoi",
"soft-yuri" to "Soft Yuri",
"sports" to "Sports",
"supernatural" to "Supernatural",
"thieu-nhi" to "Thiếu Nhi",
"tragedy" to "Tragedy",
"trinh-tham" to "Trinh Thám",
"truyen-scan" to "Truyện scan",
"truyen-mau" to "Truyện Màu",
"webtoon" to "Webtoon",
"xuyen-khong" to "Xuyên Không"
)
protected open class UriPartFilter(displayName: String, val vals: Array<Pair<String?, String>>) :
Filter.Select<String>(displayName, vals.map { it.second }.toTypedArray()) {
fun toUriPart() = vals[state].first
}
}
|
apache-2.0
|
db62b5140b6b81055c13c71d73708c0d
| 37.017123 | 130 | 0.591118 | 4.087261 | false | false | false | false |
java-opengl-labs/learn-OpenGL
|
src/main/kotlin/learnOpenGL/a_gettingStarted/6.1 coordinate systems.kt
|
1
|
7192
|
package learnOpenGL.a_gettingStarted
/**
* Created by GBarbieri on 25.04.2017.
*/
import glm_.func.rad
import glm_.glm
import glm_.mat4x4.Mat4
import glm_.vec2.Vec2
import glm_.vec3.Vec3
import gln.draw.glDrawElements
import gln.get
import gln.glClearColor
import gln.glf.semantic
import gln.program.usingProgram
import gln.texture.glTexImage2D
import gln.texture.plus
import gln.uniform.glUniform
import gln.vertexArray.glBindVertexArray
import gln.vertexArray.glVertexAttribPointer
import learnOpenGL.common.flipY
import learnOpenGL.common.readImage
import learnOpenGL.common.toBuffer
import org.lwjgl.opengl.EXTABGR
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL12.GL_BGR
import org.lwjgl.opengl.GL13.GL_TEXTURE0
import org.lwjgl.opengl.GL13.glActiveTexture
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.*
import org.lwjgl.opengl.GL30.*
import uno.buffer.destroyBuf
import uno.buffer.floatBufferBig
import uno.buffer.intBufferBig
import uno.buffer.use
import uno.glsl.Program
import uno.glsl.glDeleteProgram
import uno.glsl.usingProgram
fun main(args: Array<String>) {
with(CoordinateSystems()) {
run()
end()
}
}
private class CoordinateSystems {
val window = initWindow("Coordinate Systems")
val program = ProgramA()
enum class Buffer { Vertex, Element }
val buffers = intBufferBig<Buffer>()
val vao = intBufferBig(1)
val vertices = floatArrayOf(
// positions | texture coords
+0.5f, +0.5f, 0f, 1f, 1f, // top right
+0.5f, -0.5f, 0f, 1f, 0f, // bottom right
-0.5f, -0.5f, 0f, 0f, 0f, // bottom left
-0.5f, +0.5f, 0f, 0f, 1f // top left
)
val indices = intArrayOf(
0, 1, 3, // first triangle
1, 2, 3 // second triangle
)
enum class Texture { A, B }
val textures = intBufferBig<Texture>()
val matBuffer = floatBufferBig(16)
inner class ProgramA : Program("shaders/a/_6_1", "coordinate-systems.vert", "coordinate-systems.frag") {
val model = glGetUniformLocation(name, "model")
val view = glGetUniformLocation(name, "view")
val proj = glGetUniformLocation(name, "projection")
init {
usingProgram(name) {
"textureA".unitE = Texture.A
"textureB".unitE = Texture.B
}
}
}
init {
// set up vertex data (and buffer(s)) and configure vertex attributes
glGenVertexArrays(vao)
glGenBuffers(buffers)
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(vao)
glBindBuffer(GL_ARRAY_BUFFER, buffers[Buffer.Vertex])
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Buffer.Element])
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW)
// position attribute
glVertexAttribPointer(semantic.attr.POSITION, Vec3.length, GL_FLOAT, false, Vec3.size + Vec2.size, 0)
glEnableVertexAttribArray(semantic.attr.POSITION)
// texture coord attribute
glVertexAttribPointer(semantic.attr.TEX_COORD, Vec2.length, GL_FLOAT, false, Vec3.size + Vec2.size, Vec3.size)
glEnableVertexAttribArray(semantic.attr.TEX_COORD)
// load and create a texture
glGenTextures(textures)
// texture A
glBindTexture(GL_TEXTURE_2D, textures[Texture.A])
// set the texture wrapping parameters to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
// load image, create texture and generate mipmaps
var image = readImage("textures/container.jpg").flipY()
image.toBuffer().use {
glTexImage2D(GL_RGB, image.width, image.height, GL_BGR, GL_UNSIGNED_BYTE, it)
glGenerateMipmap(GL_TEXTURE_2D)
}
// texture B
glBindTexture(GL_TEXTURE_2D, textures[Texture.B])
// set the texture wrapping parameters to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
// load image, create texture and generate mipmaps
image = readImage("textures/awesomeface.png").flipY()
image.toBuffer().use {
glTexImage2D(GL_RGB, image.width, image.height, EXTABGR.GL_ABGR_EXT, GL_UNSIGNED_BYTE, it)
glGenerateMipmap(GL_TEXTURE_2D)
}
/* You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens.
Modifying other VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs)
when it's not directly necessary. */
//glBindVertexArray()
}
fun run() {
while (window.open) {
window.processInput()
// render
glClearColor(clearColor)
glClear(GL_COLOR_BUFFER_BIT)
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0 + Texture.A)
glBindTexture(GL_TEXTURE_2D, textures[Texture.A])
glActiveTexture(GL_TEXTURE0 + Texture.B)
glBindTexture(GL_TEXTURE_2D, textures[Texture.B])
usingProgram(program) {
// create transformations
val model = glm.rotate(Mat4(), -55f.rad, 1f, 0f, 0f)
val view = glm.translate(Mat4(), 0f, 0f, -3f)
val projection = glm.perspective(45f.rad, window.aspect, 0.1f, 100f)
// pass them to the shaders (3 different ways)
glUniformMatrix4fv(program.model, false, model to matBuffer)
glUniform(program.view, view)
/* note: currently we set the projection matrix each frame, but since the projection matrix rarely
changes it's often best practice to set it outside the main loop only once. Best place is the
framebuffer size callback */
projection to program.proj
// render container
glBindVertexArray(vao)
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT)
}
window.swapAndPoll()
}
}
fun end() {
// optional: de-allocate all resources once they've outlived their purpose:
glDeleteProgram(program)
glDeleteVertexArrays(vao)
glDeleteBuffers(buffers)
glDeleteTextures(textures)
destroyBuf(vao, buffers, textures, matBuffer)
window.end()
}
}
|
mit
|
3b5c59a9ecaa76593cb2fa8587cd9a9c
| 33.252381 | 125 | 0.647108 | 4.024622 | false | false | false | false |
geckour/Glyph
|
app/src/main/java/jp/org/example/geckour/glyph/ui/view/DotsView.kt
|
1
|
5689
|
package jp.org.example.geckour.glyph.ui.view
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import jp.org.example.geckour.glyph.R
class DotsView : View {
companion object {
const val DOTS_SIZE = 11
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context) : super(context)
private val paint = Paint()
private var offsetWidth = 0f
private var offsetHeight = 0f
private var radius = 0f
private var dotDiam = 0
private val dotBitmapTrue: Bitmap by lazy {
BitmapFactory.decodeResource(resources, R.drawable.dot_t).let {
Bitmap.createScaledBitmap(it, dotDiam, dotDiam, false)
}
}
private val dotBitmapFalse: Bitmap by lazy {
BitmapFactory.decodeResource(resources, R.drawable.dot_f).let {
Bitmap.createScaledBitmap(it, dotDiam, dotDiam, false)
}
}
private val dots = Array(DOTS_SIZE) { PointF() }
private val isThrough = Array(DOTS_SIZE) { false }
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
offsetWidth = (right - left) * 0.5f
offsetHeight = (bottom - top) * 0.5f
radius = offsetWidth * 0.45f
dotDiam = (offsetWidth * 0.15).toInt()
val uAngle = Math.PI / 3.0
dots.forEachIndexed { i, pointF ->
val c = when (i) {
1 -> 1
2 -> 3
3 -> 4
4 -> 6
in 5..10 -> i
else -> 0
}
if (i == 0) pointF.set(offsetWidth, offsetHeight * 1.2f)
else {
pointF.set(
Math.cos(uAngle * (c - 0.5)).toFloat()
* (if (i < 5) radius else radius * 2f) + offsetWidth,
Math.sin(uAngle * (c - 0.5)).toFloat()
* (if (i < 5) radius else radius * 2f) + offsetHeight * 1.2f
)
}
}
paint.isAntiAlias = true
invalidate()
}
override fun onDraw(canvas: Canvas) {
isThrough.forEachIndexed { i, b ->
if (b) {
canvas.drawBitmap(dotBitmapTrue,
dots[i].x - dotDiam / 2,
dots[i].y - dotDiam / 2, paint)
} else {
canvas.drawBitmap(dotBitmapFalse,
dots[i].x - dotDiam / 2,
dots[i].y - dotDiam / 2, paint)
}
}
}
fun setDotState(index: Int, b: Boolean) {
if (index in 0 until DOTS_SIZE) isThrough[index] = b
invalidate()
}
fun setDotsState(predicate: (Int) -> Boolean) {
isThrough.forEachIndexed { i, _ ->
isThrough[i] = predicate(i)
}
invalidate()
}
fun setDotsState(indices: List<Pair<Int, Boolean>>) {
indices.forEach {
if (it.first in 0 until DOTS_SIZE) {
isThrough[it.first] = it.second
}
}
invalidate()
}
fun getDots(): Array<PointF> = dots
fun getCollision(fromX: Float, fromY: Float, toX: Float, toY: Float,
onCollision: (List<Int>) -> Unit = {}): List<Int> {
val collisionDots: ArrayList<Int> = ArrayList()
val tol = dotDiam
for (i in 0 until DOTS_SIZE) {
if (fromX == toX && fromY == toY) {
//円の方程式にて当たり判定
val diffX = fromX - dots[i].x
val diffY = fromY - dots[i].y
if (diffX * diffX + diffY * diffY < tol * tol) {
isThrough[i] = true
collisionDots.add(i)
}
} else {
//線分と円の当たり判定
val a = fromY - toY
val b = toX - fromX
val c = fromX * toY - toX * fromY
val d = (a * dots[i].x + b * dots[i].y + c) / Math.sqrt((a * a + b * b).toDouble())
if (-tol <= d && d <= tol) {
//線分への垂線と半径
val diffFromX = fromX - dots[i].x
val diffToX = toX - dots[i].x
val diffFromY = fromY - dots[i].y
val diffToY = toY - dots[i].y
val difXA = toX - fromX
val difYB = toY - fromY
val innerA = (diffFromX * difXA + diffFromY * difYB).toDouble()
val innerB = (diffToX * difXA + diffToY * difYB).toDouble()
val dA = Math.sqrt((diffFromX * diffFromX + diffFromY * diffFromY).toDouble())
val dB = Math.sqrt((diffToX * diffToX + diffToY * diffToY).toDouble())
if (innerA * innerB <= 0) {
//内積
isThrough[i] = true
collisionDots.add(i)
} else if (dA < tol || dB < tol) {
isThrough[i] = true
collisionDots.add(i)
}
}
}
}
return collisionDots.distinct().apply { if (this.isNotEmpty()) onCollision(this) }
}
}
|
gpl-2.0
|
5c184928c44be6517bac29eae8139b1d
| 33.286585 | 99 | 0.490663 | 4.030824 | false | false | false | false |
YinChangSheng/wx-event-broadcast
|
src/main/kotlin/com/qq/weixin/wx3rd/Apis.kt
|
1
|
2226
|
package com.qq.weixin.wx3rd
import com.google.gson.Gson
import feign.*
import feign.gson.GsonDecoder
import feign.gson.GsonEncoder
import feign.okhttp.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
/**
* 作者: [email protected]
* 创建于: 2017/9/18
* 微信: yin80871901
*/
@Headers("Accept: application/json", "Content-Type: application/json")
interface WXComponentApi {
/**
* response => {
* "component_access_token": "61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA",
* "expires_in": 7200
* }
*/
@RequestLine("POST /api_component_token")
@Throws(WXException::class)
@Body("%7B\"component_appid\": \"{component_appid}\", \"component_appsecret\": \"{component_appsecret}\", \"component_verify_ticket\": \"{component_verify_ticket}\"%7D")
fun apiComponentToken(
@Param("component_appid") componentAppId: String,
@Param("component_appsecret") componentAppSecret: String,
@Param("component_verify_ticket") verifyTicket: String
) : WXComponentToken
}
val WorkModeProd = 1
val WorkModeMock = 2
class WXComponentClient {
private val logger = LoggerFactory.getLogger(WXComponentClient::class.java)
private val baseUrl = "https://api.weixin.qq.com/cgi-bin/component"
private val mockBaseUrl = "http://127.0.0.1:9800/cgi-bin/component"
private val gson = Gson()
private val okhttp : okhttp3.OkHttpClient
init {
okhttp = okhttp3.OkHttpClient
.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.addInterceptor(HttpLoggingInterceptor(logger::debug))
.build()
}
fun build(mode: Int) : WXComponentApi {
return Feign.builder()
.decoder(GsonDecoder(gson))
.encoder(GsonEncoder(gson))
.client(OkHttpClient())
// 使用 mock server
.target(WXComponentApi::class.java, if ( mode == 1 ) baseUrl else mockBaseUrl)
}
}
|
apache-2.0
|
311f347e96d08ebf890b3ed5d2f75edc
| 29.680556 | 173 | 0.653986 | 3.698492 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/CachingMapDataWithGeometry.kt
|
1
|
2002
|
package de.westnordost.streetcomplete.data.osm.osmquest
import de.westnordost.osmapi.map.MapDataWithGeometry
import de.westnordost.osmapi.map.MutableMapData
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometry
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryCreator
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPointGeometry
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
/** MapDataWithGeometry that lazily creates the element geometry. Will create incomplete (relation)
* geometry */
class CachingMapDataWithGeometry @Inject constructor(
private val elementGeometryCreator: ElementGeometryCreator
) : MutableMapData(), MapDataWithGeometry {
private val nodeGeometriesById: ConcurrentHashMap<Long, Optional<ElementPointGeometry>> = ConcurrentHashMap()
private val wayGeometriesById: ConcurrentHashMap<Long, Optional<ElementGeometry>> = ConcurrentHashMap()
private val relationGeometriesById: ConcurrentHashMap<Long, Optional<ElementGeometry>> = ConcurrentHashMap()
override fun getNodeGeometry(id: Long): ElementPointGeometry? {
val node = nodesById[id] ?: return null
return nodeGeometriesById.getOrPut(id, {
Optional(elementGeometryCreator.create(node))
}).value
}
override fun getWayGeometry(id: Long): ElementGeometry? {
val way = waysById[id] ?: return null
return wayGeometriesById.getOrPut(id, {
Optional(elementGeometryCreator.create(way, this, true))
}).value
}
override fun getRelationGeometry(id: Long): ElementGeometry? {
val relation = relationsById[id] ?: return null
return relationGeometriesById.getOrPut(id, {
Optional(elementGeometryCreator.create(relation, this, true))
}).value
}
}
// workaround the limitation of ConcurrentHashMap that it cannot store null values by wrapping it
private class Optional<T>(val value: T?)
|
gpl-3.0
|
6aacfd35b116bcf008ede107c59d9ff0
| 44.522727 | 113 | 0.765734 | 4.800959 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/execution/ui/QueryServerComboBoxModel.kt
|
1
|
2139
|
/*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.processor.query.execution.ui
import uk.co.reecedunn.intellij.plugin.processor.query.QueryServer
import javax.swing.AbstractListModel
import javax.swing.ComboBoxModel
class QueryServerComboBoxModel : AbstractListModel<String>(), ComboBoxModel<String> {
// region ComboBoxModel
var defaultSelection: String? = null
set(value) {
field = value
fireContentsChanged(this, -1, -1)
}
private var selected: Any? = null
override fun setSelectedItem(anItem: Any?) {
if (anItem?.let { selected == it } ?: selected == null) return
selected = anItem
fireContentsChanged(this, -1, -1)
}
override fun getSelectedItem(): Any? {
val selected = selected ?: defaultSelection
return when {
items.isEmpty() -> selected
items.contains(selected) -> selected
else -> items.first()
}
}
// endregion
// region ListModel
private var items = listOf<String>()
override fun getSize(): Int = items.size
override fun getElementAt(index: Int): String = items[index]
fun update(items: List<String>) {
this.items = items
this.selected = when {
items.isEmpty() -> defaultSelection
defaultSelection == QueryServer.NONE -> items.first()
items.contains(defaultSelection) -> defaultSelection
else -> items.first()
}
fireContentsChanged(this, -1, -1)
}
// endregion
}
|
apache-2.0
|
c57ed387b45c5fbd945753bf9fd3b203
| 30 | 85 | 0.654511 | 4.522199 | false | false | false | false |
WillowChat/Hopper
|
src/main/kotlin/chat/willow/hopper/routes/JsonRouteHandler.kt
|
1
|
2813
|
package chat.willow.hopper.routes
import chat.willow.hopper.auth.BasicAuthSparkFilter
import chat.willow.hopper.routes.shared.ErrorResponseBody
import spark.Request
import spark.Response
import spark.Route
object EmptyContext {
object Builder: IContextBuilder<EmptyContext> {
override fun build(request: Request): EmptyContext? {
return EmptyContext
}
}
}
interface IContextBuilder<out ContextType> {
fun build(request: Request): ContextType?
}
data class AuthenticatedContext(val user: String) {
object Builder: IContextBuilder<AuthenticatedContext> {
override fun build(request: Request): AuthenticatedContext? {
val authenticatedUser = BasicAuthSparkFilter.authenticatedUser(request)
if (authenticatedUser == null || authenticatedUser.username.isEmpty()) {
return null
} else {
return AuthenticatedContext(user = authenticatedUser.username)
}
}
}
}
abstract class JsonRouteHandler<RequestType, SuccessType, ContextType>
(val requestAdapter: IStringParser<RequestType>,
val successAdapter: IStringSerialiser<SuccessType>,
val failureAdapter: IStringSerialiser<ErrorResponseBody>,
val contextBuilder: IContextBuilder<ContextType>)
: IRoute<RequestType, RouteResult<SuccessType, ErrorResponseBody>, ContextType>, Route {
override fun handle(request: Request, response: Response): Any? {
val body = try { request.body() } catch (e: Exception) { return "" }
val requestTyped = requestAdapter.parse(body)
if (requestTyped == null) {
response.status(400)
return ""
}
val context = contextBuilder.build(request)
if (context == null) {
// todo: cleanup - context builder should be able to provide some sort of error
response.status(500)
return failureAdapter.serialise(unauthenticatedError.failure!!)
}
val result = this.handle(requestTyped, context)
response.status(result.code)
if (result.success != null) {
return successAdapter.serialise(result.success)
} else if (result.failure != null) {
return failureAdapter.serialise(result.failure)
}
return failureAdapter.serialise(serverError.failure!!)
}
val unauthenticatedError = jsonFailure<SuccessType>(401, "not authenticated")
val serverError = jsonFailure<SuccessType>(500, "server error")
}
fun <T>jsonSuccess(success: T): RouteResult<T, ErrorResponseBody> {
return RouteResult.success(value = success)
}
fun <T>jsonFailure(code: Int, message: String): RouteResult<T, ErrorResponseBody> {
return RouteResult.failure(code, error = ErrorResponseBody(code, message))
}
|
isc
|
502a7d4f33e84a11f7204759ac8b8574
| 32.105882 | 92 | 0.684678 | 4.566558 | false | false | false | false |
jiaminglu/kotlin-native
|
samples/html5Canvas/src/main/kotlin/main.kt
|
1
|
1192
|
import html5.minimal.*
import kotlinx.wasm.jsinterop.*
import konan.internal.ExportForCppRuntime
fun main(args: Array<String>) {
val html5 = html5()
val document = html5.document
val canvas = document.getElementById("myCanvas").asCanvas;
val ctx = canvas.getContext("2d");
val rect = canvas.getBoundingClientRect();
val rectLeft = rect.getInt("left")
val rectTop = rect.getInt("top")
var mouseX: Int = 0;
var mouseY: Int = 0;
var draw: Boolean = false;
document.setter("onmousemove") { args: ArrayList<JsValue> ->
val event = args[0];
mouseX = event.getInt("clientX") - rectLeft
mouseY = event.getInt("clientY") - rectTop
if (mouseX < 0) mouseX = 0;
if (mouseX > 639) mouseX = 639;
if (mouseY < 0) mouseY = 0;
if (mouseY > 479) mouseY = 479;
}
document.setter("onmousedown") {
draw = true;
}
document.setter("onmouseup") {
draw = false;
}
setInterval(10) {
if (draw) {
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
} else {
ctx.moveTo(mouseX, mouseY);
ctx.stroke();
}
}
}
|
apache-2.0
|
cd0125a9bfcf50c1bcb89e3cbcba8b79
| 24.361702 | 64 | 0.57047 | 3.784127 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/injection/search/CatalogSearchSuggestionsPresentationModule.kt
|
2
|
1391
|
package org.stepik.android.view.injection.search
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.core.presenters.SearchSuggestionsPresenter
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.storage.operations.DatabaseFacade
import org.stepik.android.cache.search.SearchCacheDataSourceImpl
import org.stepik.android.data.search.source.SearchCacheDataSource
import org.stepik.android.domain.search.repository.SearchRepository
@Module
object CatalogSearchSuggestionsPresentationModule {
@Provides
internal fun provideSearchSuggestionsPresenter(
searchRepository: SearchRepository,
analytic: Analytic,
@BackgroundScheduler
scheduler: Scheduler,
@MainScheduler
mainScheduler: Scheduler
): SearchSuggestionsPresenter =
SearchSuggestionsPresenter(
courseId = -1L,
searchRepository = searchRepository,
analytic = analytic,
scheduler = scheduler,
mainScheduler = mainScheduler
)
@Provides
internal fun provideSearchCacheDataSource(databaseFacade: DatabaseFacade): SearchCacheDataSource =
SearchCacheDataSourceImpl(dbElementsCount = 2, databaseFacade = databaseFacade)
}
|
apache-2.0
|
756a57ccc64d37cf2d79a3a24ad5bcdb
| 36.621622 | 102 | 0.76995 | 5.391473 | false | false | false | false |
jakubveverka/SportApp
|
app/src/main/java/com/example/jakubveverka/sportapp/Utils/ButterKnife.kt
|
1
|
6873
|
package com.example.jakubveverka.sportapp.Utils
import android.app.Activity
import android.app.Dialog
import android.app.DialogFragment
import android.app.Fragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import android.support.v4.app.DialogFragment as SupportDialogFragment
import android.support.v4.app.Fragment as SupportFragment
public fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, viewFinder)
public fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, viewFinder)
public fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, viewFinder)
public fun <V : View> DialogFragment.bindView(id: Int)
: ReadOnlyProperty<DialogFragment, V> = required(id, viewFinder)
public fun <V : View> SupportDialogFragment.bindView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V> = required(id, viewFinder)
public fun <V : View> Fragment.bindView(id: Int)
: ReadOnlyProperty<Fragment, V> = required(id, viewFinder)
public fun <V : View> SupportFragment.bindView(id: Int)
: ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder)
public fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
public fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, viewFinder)
public fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
public fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder)
public fun <V : View> DialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<DialogFragment, V?> = optional(id, viewFinder)
public fun <V : View> SupportDialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V?> = optional(id, viewFinder)
public fun <V : View> Fragment.bindOptionalView(id: Int)
: ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder)
public fun <V : View> SupportFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder)
public fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
public fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, viewFinder)
public fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder)
public fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder)
public fun <V : View> DialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<DialogFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> SupportDialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> Fragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder)
public fun <V : View> SupportFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder)
public fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder)
public fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder)
public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder)
public fun <V : View> DialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<DialogFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> SupportDialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder)
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Dialog.viewFinder: Dialog.(Int) -> View?
get() = { findViewById(it) }
private val DialogFragment.viewFinder: DialogFragment.(Int) -> View?
get() = { dialog.findViewById(it) }
private val SupportDialogFragment.viewFinder: SupportDialogFragment.(Int) -> View?
get() = { dialog.findViewById(it) }
private val Fragment.viewFinder: Fragment.(Int) -> View?
get() = { view.findViewById(it) }
private val SupportFragment.viewFinder: SupportFragment.(Int) -> View?
get() = { view!!.findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
private fun viewNotFound(id:Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
}
|
mit
|
b98131a3bbf5e6ab661fc8a8b06df4db
| 51.869231 | 100 | 0.703914 | 3.943201 | false | false | false | false |
apollostack/apollo-android
|
apollo-runtime/src/main/java/com/apollographql/apollo3/internal/interceptor/ApolloParseInterceptor.kt
|
1
|
4563
|
package com.apollographql.apollo3.internal.interceptor
import com.apollographql.apollo3.CacheInfo
import com.apollographql.apollo3.api.ResponseAdapterCache
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.cache.http.HttpCache
import com.apollographql.apollo3.api.internal.ApolloLogger
import com.apollographql.apollo3.api.fromResponse
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.exception.ApolloHttpException
import com.apollographql.apollo3.exception.ApolloParseException
import com.apollographql.apollo3.http.OkHttpExecutionContext
import com.apollographql.apollo3.interceptor.ApolloInterceptor
import com.apollographql.apollo3.interceptor.ApolloInterceptor.CallBack
import com.apollographql.apollo3.interceptor.ApolloInterceptor.FetchSourceType
import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorRequest
import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorResponse
import com.apollographql.apollo3.interceptor.ApolloInterceptorChain
import com.apollographql.apollo3.withCacheInfo
import okhttp3.Headers
import okhttp3.Response
import java.io.Closeable
import java.util.concurrent.Executor
/**
* ApolloParseInterceptor is a concrete [ApolloInterceptor] responsible for inflating the http responses into
* models. To get the http responses, it hands over the control to the next interceptor in the chain and proceeds to
* then parse the returned response.
*/
class ApolloParseInterceptor(private val httpCache: HttpCache?,
private val responseAdapterCache: ResponseAdapterCache,
private val logger: ApolloLogger) : ApolloInterceptor {
@Volatile
var disposed = false
override fun interceptAsync(request: InterceptorRequest, chain: ApolloInterceptorChain,
dispatcher: Executor, callBack: CallBack) {
if (disposed) return
chain.proceedAsync(request, dispatcher, object : CallBack {
override fun onResponse(response: InterceptorResponse) {
try {
if (disposed) return
val result = parse(request.operation as Operation<Operation.Data>, response.httpResponse.get())
callBack.onResponse(result)
callBack.onCompleted()
} catch (e: ApolloException) {
onFailure(e)
}
}
override fun onFailure(e: ApolloException) {
if (disposed) return
callBack.onFailure(e)
}
override fun onCompleted() {
// call onCompleted in onResponse in case of error
}
override fun onFetch(sourceType: FetchSourceType) {
callBack.onFetch(sourceType)
}
})
}
override fun dispose() {
disposed = true
}
@Throws(ApolloHttpException::class, ApolloParseException::class)
fun parse(operation: Operation<Operation.Data>, httpResponse: Response): InterceptorResponse {
val cacheKey = httpResponse.request().header(HttpCache.CACHE_KEY_HEADER)
return if (httpResponse.isSuccessful) {
try {
val httpExecutionContext = OkHttpExecutionContext(httpResponse)
var parsedResponse = operation.fromResponse(httpResponse.body()!!.source(), responseAdapterCache)
parsedResponse = parsedResponse.copy(
executionContext = parsedResponse.executionContext.plus(httpExecutionContext) + CacheInfo(httpResponse.cacheResponse() != null)
)
if (parsedResponse.hasErrors() && httpCache != null) {
httpCache.removeQuietly(cacheKey!!)
}
InterceptorResponse(httpResponse, parsedResponse)
} catch (rethrown: Exception) {
logger.e(rethrown, "Failed to parse network response for operation: %s", operation.name())
closeQuietly(httpResponse)
httpCache?.removeQuietly(cacheKey!!)
throw ApolloParseException("Failed to parse http response", rethrown)
}
} else {
logger.e("Failed to parse network response: %s", httpResponse)
throw ApolloHttpException(
statusCode = httpResponse.code(),
headers = httpResponse.headers().toMap(),
message = httpResponse.body()?.string() ?: "",
cause = null
)
}
}
companion object {
private fun Headers.toMap(): Map<String, String> = this.names().map {
it to get(it)!!
}.toMap()
private fun closeQuietly(closeable: Closeable?) {
if (closeable != null) {
try {
closeable.close()
} catch (ignored: Exception) {
}
}
}
}
}
|
mit
|
52c570e94e0d3522440f049bd185a191
| 38 | 139 | 0.7151 | 4.880214 | false | false | false | false |
exponentjs/exponent
|
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/modules/PedometerModule.kt
|
2
|
2007
|
// Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.sensors.modules
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.SensorEvent
import android.os.Bundle
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi44_0_0.expo.modules.interfaces.sensors.services.PedometerServiceInterface
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
class PedometerModule(reactContext: Context?) : BaseSensorModule(reactContext) {
private var stepsAtTheBeginning: Int? = null
override val eventName: String = "Exponent.pedometerUpdate"
override fun getName(): String {
return "ExponentPedometer"
}
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(PedometerServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
if (stepsAtTheBeginning == null) {
stepsAtTheBeginning = sensorEvent.values[0].toInt() - 1
}
return Bundle().apply {
putDouble("steps", (sensorEvent.values[0] - stepsAtTheBeginning!!).toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
stepsAtTheBeginning = null
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
stepsAtTheBeginning = null
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
promise.resolve(context.packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER))
}
@ExpoMethod
fun getStepCountAsync(startDate: Int?, endDate: Int?, promise: Promise) {
promise.reject("E_NOT_AVAILABLE", "Getting step count for date range is not supported on Android yet.")
}
}
|
bsd-3-clause
|
329b82c5255aa142386b98ddf2b86b53
| 30.857143 | 107 | 0.758346 | 4.1639 | false | false | false | false |
esqr/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/InputToolbar.kt
|
1
|
4483
|
package io.github.feelfreelinux.wykopmobilny.ui.widgets
import android.content.Context
import android.net.Uri
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.api.entries.TypedInputStream
import io.github.feelfreelinux.wykopmobilny.ui.widgets.markdown_toolbar.MarkdownToolbarListener
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import kotlinx.android.synthetic.main.input_toolbar.view.*
import javax.inject.Inject
import android.R.attr.data
import android.support.annotation.ColorInt
import android.content.res.Resources.Theme
import android.util.TypedValue
interface InputToolbarListener {
fun sendPhoto(photo : TypedInputStream, body : String)
fun sendPhoto(photo : String?, body : String)
fun openGalleryImageChooser()
}
class InputToolbar : ConstraintLayout, MarkdownToolbarListener {
override var selectionPosition: Int
get() = body.selectionStart
set(value) { body.setSelection(value) }
override var textBody: String
get() = body.text.toString()
set(value) { body.setText(value) }
@Inject lateinit var userManager : UserManagerApi
var defaultText = ""
override fun openGalleryImageChooser() {
inputToolbarListener?.openGalleryImageChooser()
}
fun setPhoto(photo : Uri?) {
markdownToolbar.photo = photo
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
var inputToolbarListener : InputToolbarListener? = null
init {
WykopApp.uiInjector.inject(this)
val typedValue = TypedValue()
val theme = context.theme
theme.resolveAttribute(R.attr.cardViewColor, typedValue, true)
setBackgroundColor(typedValue.data)
show()
// Inflate view
View.inflate(context, R.layout.input_toolbar, this)
markdownToolbar.markdownListener = this
// Setup listeners
show_markdown_menu.setOnClickListener {
showMarkdownToolbar()
}
markdown_close.setOnClickListener {
closeMarkdownToolbar()
}
body.setOnFocusChangeListener {
_, focused ->
if (focused && !hasUserEditedContent()) {
textBody = defaultText
}
}
send.setOnClickListener {
showProgress(true)
val typedInputStream = markdownToolbar.getPhotoTypedInputStream()
if (typedInputStream != null) {
inputToolbarListener?.sendPhoto(typedInputStream, body.text.toString())
} else {
inputToolbarListener?.sendPhoto(markdownToolbar.photoUrl, body.text.toString())
}
}
}
fun showMarkdownToolbar() {
markdownToolbarHolder.isVisible = true
show_markdown_menu.isVisible = false
}
fun closeMarkdownToolbar() {
markdownToolbarHolder.isVisible = false
show_markdown_menu.isVisible = true
}
fun showProgress(shouldShowProgress : Boolean) {
progressBar.isVisible = shouldShowProgress
send.isVisible = !shouldShowProgress
}
fun resetState() {
textBody = defaultText
selectionPosition = textBody.length
markdownToolbar.apply {
photo = null
photoUrl = null
}
closeMarkdownToolbar()
body.clearFocus()
}
fun setDefaultAddressant(user : String) {
if (userManager.isUserAuthorized() && userManager.getUserCredentials()!!.login != user) {
defaultText = "@$user: "
}
}
fun addAddressant(user : String) {
body.requestFocus()
textBody += "@$user: "
selectionPosition = textBody.length
}
fun setCustomHint(hint : String) {
body.hint = hint
}
fun hasUserEditedContent() = textBody != defaultText && markdownToolbar.hasUserEditedContent()
fun hide() {
isVisible = false
}
fun show() {
// Only show if user's logged in
isVisible = userManager.isUserAuthorized()
}
}
|
mit
|
823e163dbae970bd9ee13334ad1f33c3
| 28.695364 | 111 | 0.672318 | 5.065537 | false | false | false | false |
sdoward/AwarenessApiPlayGround
|
app/src/main/java/com/sdoward/awareness/android/AwarenesRxExtensions.kt
|
1
|
1393
|
package com.sdoward.awareness.android
import com.google.android.gms.awareness.SnapshotApi
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.places.PlaceLikelihood
import io.reactivex.Single
fun SnapshotApi.getActivityObservable(client: GoogleApiClient): Single<List<Activity>> {
return Single.create { emitter ->
getDetectedActivity(client).setResultCallback {
if (it.activityRecognitionResult == null) {
emitter.onSuccess(listOf())
} else if (it.activityRecognitionResult.probableActivities == null) {
emitter.onSuccess(listOf())
} else {
emitter.onSuccess(it.activityRecognitionResult.probableActivities.map { it.map() })
}
}
}
}
fun SnapshotApi.getLocationObservable(client: GoogleApiClient): Single<Location> {
return Single.create { emitter ->
getLocation(client).setResultCallback {
emitter.onSuccess(it.location.map())
}
}
}
fun SnapshotApi.getPlacesObservable(client: GoogleApiClient): Single<List<Place>> {
return Single.create { emitter ->
getPlaces(client).setResultCallback {
val placeList = if (it.placeLikelihoods == null) listOf<PlaceLikelihood>() else it.placeLikelihoods
emitter.onSuccess(placeList.map { it.map() })
}
}
}
|
apache-2.0
|
f1961848da9ff9139fd98fd56c897528
| 36.675676 | 111 | 0.67911 | 4.422222 | false | false | false | false |
Maccimo/intellij-community
|
platform/vcs-impl/src/com/intellij/vcs/commit/ChangesViewCommitPanel.kt
|
2
|
8877
|
// 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.vcs.commit
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.*
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode.UNVERSIONED_FILES_TAG
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData.*
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindow
import com.intellij.ui.EditorTextComponent
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.JBColor
import com.intellij.ui.SideBorder
import com.intellij.util.ui.JBUI.Borders.*
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.tree.TreeUtil.*
import com.intellij.vcsUtil.VcsUtil.getFilePath
import javax.swing.JComponent
import javax.swing.SwingConstants
import kotlin.properties.Delegates.observable
internal fun ChangesBrowserNode<*>.subtreeRootObject(): Any? = (path.getOrNull(1) as? ChangesBrowserNode<*>)?.userObject
class ChangesViewCommitPanel(private val changesViewHost: ChangesViewPanel, private val rootComponent: JComponent) :
NonModalCommitPanel(changesViewHost.changesView.project), ChangesViewCommitWorkflowUi {
val changesView get() = changesViewHost.changesView
private val toolbarPanel = simplePanel().apply {
isOpaque = false
border = emptyLeft(1)
}
private val progressPanel = ChangesViewCommitProgressPanel(this, commitMessage.editorField)
private var isHideToolWindowOnDeactivate = false
var isToolbarHorizontal: Boolean by observable(false) { _, oldValue, newValue ->
if (oldValue != newValue) {
addToolbar(newValue) // this also removes toolbar from previous parent
}
}
init {
Disposer.register(this, commitMessage)
bottomPanel = {
add(progressPanel.apply { border = empty(6) })
add(commitAuthorComponent.apply { border = empty(0, 5, 4, 0) })
add(commitActionsPanel)
}
buildLayout()
addToolbar(isToolbarHorizontal)
for (support in EditChangelistSupport.EP_NAME.getExtensions(project)) {
support.installSearch(commitMessage.editorField, commitMessage.editorField)
}
with(changesView) {
setInclusionListener { fireInclusionChanged() }
isShowCheckboxes = true
}
changesViewHost.statusComponent =
CommitStatusPanel(this).apply {
border = emptyRight(6)
background = changesView.background
addToLeft(toolbarPanel)
}
ChangesViewCommitTabTitleUpdater(this).start()
commitActionsPanel.setupShortcuts(rootComponent, this)
commitActionsPanel.isCommitButtonDefault = {
!progressPanel.isDumbMode &&
IdeFocusManager.getInstance(project).getFocusedDescendantFor(rootComponent) != null
}
}
private fun addToolbar(isHorizontal: Boolean) {
if (isHorizontal) {
toolbar.setOrientation(SwingConstants.HORIZONTAL)
toolbar.setReservePlaceAutoPopupIcon(false)
centerPanel.border = null
toolbarPanel.addToCenter(toolbar.component)
}
else {
toolbar.setOrientation(SwingConstants.VERTICAL)
toolbar.setReservePlaceAutoPopupIcon(true)
centerPanel.border = createBorder(JBColor.border(), SideBorder.LEFT)
addToLeft(toolbar.component)
}
}
override var editedCommit by observable<EditedCommitDetails?>(null) { _, _, newValue ->
refreshData()
newValue?.let { expand(it) }
}
override val isActive: Boolean get() = isVisible
override fun activate(): Boolean {
val toolWindow = getVcsToolWindow() ?: return false
val contentManager = ChangesViewContentManager.getInstance(project)
saveToolWindowState()
changesView.isShowCheckboxes = true
isVisible = true
commitActionsPanel.isActive = true
contentManager.selectContent(LOCAL_CHANGES)
toolWindow.activate({ commitMessage.requestFocusInMessage() }, false)
return true
}
override fun deactivate(isRestoreState: Boolean) {
if (isRestoreState) restoreToolWindowState()
clearToolWindowState()
changesView.isShowCheckboxes = false
isVisible = false
commitActionsPanel.isActive = false
}
private fun saveToolWindowState() {
if (!isActive) {
isHideToolWindowOnDeactivate = getVcsToolWindow()?.isVisible != true
}
}
private fun restoreToolWindowState() {
if (isHideToolWindowOnDeactivate) {
getVcsToolWindow()?.hide(null)
}
}
private fun clearToolWindowState() {
isHideToolWindowOnDeactivate = false
}
private fun getVcsToolWindow(): ToolWindow? = getToolWindowFor(project, LOCAL_CHANGES)
override fun expand(item: Any) {
val node = changesView.findNodeInTree(item)
node?.let { changesView.expandSafe(it) }
}
override fun select(item: Any) {
val path = changesView.findNodePathInTree(item)
path?.let { selectPath(changesView, it, false) }
}
override fun selectFirst(items: Collection<Any>) {
if (items.isEmpty()) return
val path = treePathTraverser(changesView).preOrderDfsTraversal().find { getLastUserObject(it) in items }
path?.let { selectPath(changesView, it, false) }
}
override fun showCommitOptions(popup: JBPopup, isFromToolbar: Boolean, dataContext: DataContext) =
if (isFromToolbar && !isToolbarHorizontal) popup.showAbove(this@ChangesViewCommitPanel)
else super.showCommitOptions(popup, isFromToolbar, dataContext)
override fun setCompletionContext(changeLists: List<LocalChangeList>) {
commitMessage.setChangesSupplier(ChangeListChangesSupplier(changeLists))
}
override fun refreshData() = ChangesViewManager.getInstanceEx(project).refreshImmediately()
override fun getDisplayedChanges(): List<Change> = all(changesView).userObjects(Change::class.java)
override fun getIncludedChanges(): List<Change> = included(changesView).userObjects(Change::class.java)
override fun getDisplayedUnversionedFiles(): List<FilePath> =
allUnderTag(changesView, UNVERSIONED_FILES_TAG).userObjects(FilePath::class.java)
override fun getIncludedUnversionedFiles(): List<FilePath> =
includedUnderTag(changesView, UNVERSIONED_FILES_TAG).userObjects(FilePath::class.java)
override var inclusionModel: InclusionModel?
get() = changesView.inclusionModel
set(value) {
changesView.setInclusionModel(value)
}
override fun includeIntoCommit(items: Collection<*>) = changesView.includeChanges(items)
override val commitProgressUi: CommitProgressUi get() = progressPanel
override fun endExecution() = closeEditorPreviewIfEmpty()
private fun closeEditorPreviewIfEmpty() {
val changesViewManager = ChangesViewManager.getInstance(project) as? ChangesViewManager ?: return
if (!ChangesViewManager.isEditorPreview(project)) return
refreshData()
changesViewManager.closeEditorPreview(true)
}
override fun dispose() {
changesViewHost.statusComponent = null
with(changesView) {
isShowCheckboxes = false
setInclusionListener(null)
}
}
}
private class ChangesViewCommitProgressPanel(
private val commitWorkflowUi: ChangesViewCommitWorkflowUi,
commitMessage: EditorTextComponent
) : CommitProgressPanel() {
private var oldInclusion: Set<Any> = emptySet()
init {
setup(commitWorkflowUi, commitMessage)
}
override fun inclusionChanged() {
val newInclusion = commitWorkflowUi.inclusionModel?.getInclusion().orEmpty()
if (oldInclusion != newInclusion) super.inclusionChanged()
oldInclusion = newInclusion
}
}
private class ChangesViewCommitTabTitleUpdater(private val commitPanel: ChangesViewCommitPanel) :
CommitTabTitleUpdater(commitPanel.changesView, LOCAL_CHANGES, { message("local.changes.tab") }),
ChangesViewContentManagerListener {
init {
Disposer.register(commitPanel, this)
pathsProvider = {
val singleRoot = ProjectLevelVcsManager.getInstance(project).allVersionedRoots.singleOrNull()
if (singleRoot != null) listOf(getFilePath(singleRoot)) else commitPanel.getDisplayedPaths()
}
}
override fun start() {
super.start()
project.messageBus.connect(this).subscribe(ChangesViewContentManagerListener.TOPIC, this)
}
override fun toolWindowMappingChanged() = updateTab()
override fun updateTab() {
if (!project.isCommitToolWindowShown) return
super.updateTab()
}
}
|
apache-2.0
|
32ebd14a6f341c7d9d7cdfe1965cf3d8
| 33.406977 | 158 | 0.759941 | 4.652516 | false | false | false | false |
Hexworks/zircon
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/graphics/ThreadSafeLayer.kt
|
1
|
4927
|
package org.hexworks.zircon.internal.graphics
import org.hexworks.cobalt.core.api.UUID
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.zircon.api.DrawSurfaces
import org.hexworks.zircon.api.behavior.Clearable
import org.hexworks.zircon.api.behavior.Movable
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Rect
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.extensions.toTileGraphics
import org.hexworks.zircon.api.graphics.Layer
import org.hexworks.zircon.api.graphics.StyleSet
import org.hexworks.zircon.api.graphics.TileComposite
import org.hexworks.zircon.api.graphics.TileGraphics
import org.hexworks.zircon.api.graphics.impl.SubTileGraphics
import org.hexworks.zircon.internal.behavior.impl.DefaultMovable
import kotlin.jvm.Synchronized
open class ThreadSafeLayer internal constructor(
initialPosition: Position, initialContents: TileGraphics, private val movable: Movable = DefaultMovable(
position = initialPosition, size = initialContents.size
), private val backend: InternalTileGraphics = FastTileGraphics(
initialSize = initialContents.size,
initialTileset = initialContents.tileset,
initialTiles = initialContents.tiles
)
) : Clearable, InternalLayer, Movable by movable, TileGraphics by backend {
final override val id: UUID = UUID.randomUUID()
final override val size: Size
get() = backend.size
final override val width: Int
get() = backend.size.width
final override val height: Int
get() = backend.size.height
final override val rect: Rect
get() = movable.rect
final override val hiddenProperty = false.toProperty()
final override var isHidden: Boolean by hiddenProperty.asDelegate()
override fun asInternalLayer() = this
@Synchronized
override fun getAbsoluteTileAtOrNull(position: Position): Tile? {
return backend.getTileAtOrNull(position)
}
@Synchronized
override fun getAbsoluteTileAtOrElse(position: Position, orElse: (position: Position) -> Tile): Tile {
return getAbsoluteTileAtOrNull(position) ?: orElse(position)
}
@Synchronized
final override fun drawAbsoluteTileAt(position: Position, tile: Tile) {
backend.draw(tile, position - this.position)
}
@Synchronized
override fun moveTo(position: Position): Boolean {
return movable.moveTo(position)
}
@Synchronized
final override fun draw(tileMap: Map<Position, Tile>, drawPosition: Position, drawArea: Size) {
backend.draw(tileMap, drawPosition, drawArea)
}
@Synchronized
final override fun draw(tile: Tile, drawPosition: Position) {
backend.draw(tile, drawPosition)
}
@Synchronized
final override fun draw(tileComposite: TileComposite) {
backend.draw(tileComposite)
}
@Synchronized
final override fun draw(tileComposite: TileComposite, drawPosition: Position) {
backend.draw(tileComposite, drawPosition)
}
@Synchronized
final override fun draw(tileComposite: TileComposite, drawPosition: Position, drawArea: Size) {
backend.draw(tileComposite, drawPosition, drawArea)
}
@Synchronized
final override fun draw(tileMap: Map<Position, Tile>) {
backend.draw(tileMap)
}
@Synchronized
final override fun draw(tileMap: Map<Position, Tile>, drawPosition: Position) {
backend.draw(tileMap, drawPosition)
}
@Synchronized
final override fun fill(filler: Tile) {
backend.fill(filler)
}
@Synchronized
final override fun transform(transformer: (Position, Tile) -> Tile) {
backend.transform(transformer)
}
@Synchronized
final override fun applyStyle(styleSet: StyleSet) {
backend.applyStyle(styleSet)
}
@Synchronized
final override fun clear() {
backend.clear()
}
@Synchronized
final override fun createCopy(): Layer {
return ThreadSafeLayer(
initialPosition = position, initialContents = tiles.toTileGraphics(size, tileset)
).apply {
isHidden = isHidden
}
}
@Synchronized
override fun render(graphics: TileGraphics) {
graphics.draw(backend)
}
final override fun toTileImage() = backend.toTileImage()
final override fun toLayer(offset: Position) = createCopy().apply {
moveTo(offset)
}
final override fun toResized(newSize: Size) = backend.toResized(newSize)
final override fun toResized(newSize: Size, filler: Tile) = backend.toResized(newSize, filler)
final override fun toSubTileGraphics(rect: Rect) = SubTileGraphics(rect, backend)
override fun toString(): String {
return DrawSurfaces.tileGraphicsBuilder().withSize(size).withTiles(tiles).build().toString()
}
}
|
apache-2.0
|
144c626a576c1085de95697fc0765c7e
| 30.993506 | 108 | 0.715243 | 4.442741 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/jetpack/java/org/wordpress/android/ui/accounts/login/components/LoopingText.kt
|
1
|
2676
|
package org.wordpress.android.ui.accounts.login.components
import android.content.res.Configuration
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import org.wordpress.android.R
import org.wordpress.android.ui.accounts.login.LocalPosition
import org.wordpress.android.ui.compose.theme.AppTheme
import org.wordpress.android.util.extensions.isOdd
private const val FIXED_FONT_SIZE = 40
@Composable
private fun LargeTexts() {
val fontSize = (FIXED_FONT_SIZE / LocalDensity.current.fontScale).sp
val lineHeight = fontSize * 1.05 // calculate line height to 5% larger than the font size
val texts = stringArrayResource(R.array.login_prologue_revamped_jetpack_feature_texts)
val secondaryColor = colorResource(R.color.text_color_jetpack_login_label_secondary)
val primaryColor = colorResource(R.color.text_color_jetpack_login_label_primary)
val styledText = buildAnnotatedString {
texts.forEachIndexed { index, text ->
withStyle(ParagraphStyle(lineHeight = lineHeight)) {
when ((index + 1).isOdd) {
true -> withStyle(SpanStyle(color = secondaryColor)) {
append(text)
}
false -> withStyle(SpanStyle(color = primaryColor)) {
append(text)
}
}
}
}
}
Text(
text = styledText,
style = TextStyle(
fontSize = fontSize,
fontWeight = FontWeight.Bold,
letterSpacing = (-0.03).sp,
),
)
}
@Composable
fun LoopingText(modifier: Modifier = Modifier) {
RepeatingColumn(
position = LocalPosition.current,
modifier = modifier
) {
LargeTexts()
}
}
@Preview(showBackground = true, device = Devices.PIXEL_4)
@Preview(showBackground = true, device = Devices.PIXEL_4, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewLoopingText() {
AppTheme {
LoopingText()
}
}
|
gpl-2.0
|
51e63b25a332975770db0edc59c66b73
| 33.307692 | 99 | 0.683857 | 4.386885 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/reader/repository/ReaderTagRepository.kt
|
1
|
4840
|
package org.wordpress.android.ui.reader.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.wordpress.android.datasets.wrappers.ReaderTagTableWrapper
import org.wordpress.android.models.ReaderTag
import org.wordpress.android.models.ReaderTagList
import org.wordpress.android.models.ReaderTagType
import org.wordpress.android.models.ReaderTagType.DEFAULT
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.IO_THREAD
import org.wordpress.android.ui.reader.ReaderConstants
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.Success
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.SuccessWithData
import org.wordpress.android.ui.reader.repository.usecases.ShouldAutoUpdateTagUseCase
import org.wordpress.android.ui.reader.repository.usecases.tags.FetchFollowedTagsUseCase
import org.wordpress.android.ui.reader.repository.usecases.tags.FetchInterestTagsUseCase
import org.wordpress.android.ui.reader.repository.usecases.tags.FollowInterestTagsUseCase
import org.wordpress.android.ui.reader.repository.usecases.tags.GetFollowedTagsUseCase
import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
/**
* ReaderTagRepository is middleware that encapsulates data related business related data logic
* Handle communicate with ReaderServices and Actions
*/
class ReaderTagRepository @Inject constructor(
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
@Named(IO_THREAD) private val ioDispatcher: CoroutineDispatcher,
private val readerUtilsWrapper: ReaderUtilsWrapper,
private val fetchInterestTagUseCase: FetchInterestTagsUseCase,
private val followInterestTagsUseCase: FollowInterestTagsUseCase,
private val fetchFollowedTagUseCase: FetchFollowedTagsUseCase,
private val getFollowedTagsUseCase: GetFollowedTagsUseCase,
private val shouldAutoUpdateTagUseCase: ShouldAutoUpdateTagUseCase,
private val readerTagTableWrapper: ReaderTagTableWrapper
) {
private val mutableRecommendedInterests = MutableLiveData<ReaderTagList>()
private val recommendedInterests: LiveData<ReaderTagList> = mutableRecommendedInterests
private val followingReaderTag = readerUtilsWrapper.getTagFromTagName(ReaderConstants.KEY_FOLLOWING, DEFAULT)
suspend fun getInterests(): ReaderRepositoryCommunication {
return withContext(ioDispatcher) {
fetchInterestTagUseCase.fetch()
}
}
suspend fun getUserTags(): ReaderRepositoryCommunication {
return withContext(ioDispatcher) {
val userTags = getFollowedTagsUseCase.get()
if (userTags.isNotEmpty()) {
SuccessWithData(userTags)
} else {
val refresh = shouldAutoUpdateTagUseCase.get(followingReaderTag)
var result: ReaderRepositoryCommunication = Success
if (refresh) {
result = fetchFollowedTagUseCase.fetch()
}
if (result is Success) {
SuccessWithData(getFollowedTagsUseCase.get())
} else {
result
}
}
}
}
suspend fun saveInterests(tags: List<ReaderTag>): ReaderRepositoryCommunication {
return withContext(ioDispatcher) {
followInterestTagsUseCase.followInterestTags(tags)
}
}
suspend fun clearTagLastUpdated(tag: ReaderTag) {
withContext(ioDispatcher) {
readerTagTableWrapper.clearTagLastUpdated(tag)
}
}
suspend fun getRecommendedInterests(): LiveData<ReaderTagList> =
withContext(bgDispatcher) {
delay(TimeUnit.SECONDS.toMillis(5))
getMockRecommendedInterests()
}
private suspend fun getMockRecommendedInterests(): LiveData<ReaderTagList> {
return withContext(ioDispatcher) {
mutableRecommendedInterests.postValue(getMockInterests())
recommendedInterests
}
}
// todo: remove method post implementation
@Suppress("ForbiddenComment")
private fun getMockInterests() =
ReaderTagList().apply {
for (c in 'A'..'Z')
(add(
ReaderTag(
c.toString(), c.toString(), c.toString(),
"https://public-api.wordpress.com/rest/v1.2/read/tags/$c/posts",
ReaderTagType.DEFAULT
)
))
}
}
|
gpl-2.0
|
72578e71b1bcbe968c17ce16545313b1
| 42.603604 | 113 | 0.708678 | 5.24377 | false | false | false | false |
KotlinNLP/SimpleDNN
|
src/test/kotlin/core/layers/recurrent/tpr/TPRLayerParametersSpec.kt
|
1
|
3684
|
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.recurrent.tpr
import com.kotlinnlp.simplednn.core.functionalities.initializers.ConstantInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.RandomInitializer
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.RandomGenerator
import com.kotlinnlp.simplednn.core.layers.models.recurrent.tpr.TPRLayerParameters
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
class TPRLayerParametersSpec: Spek({
describe("a TPRLayerParameters") {
context("initialization") {
context("dense input") {
var k = 0
val initValues = doubleArrayOf(
0.1, 0.2, 0.3, 0.4, 0.5, 0.6,
0.7, 0.8, 0.9, 1.0, 1.1, 1.2,
1.3, 1.4, 1.5, 1.6, 1.7, 1.8,
1.9, 2.0, 2.1, 2.2, 2.3, 2.4,
2.5, 2.6, 2.7, 2.8, 2.9, 3.0,
3.1, 3.2, 3.3, 3.4, 3.5, 3.6,
3.7, 3.8, 3.9, 4.0, 4.1, 4.2,
4.3, 4.4, 4.5, 4.6, 4.7, 4.8)
val randomGenerator = mock<RandomGenerator>()
whenever(randomGenerator.next()).thenAnswer { initValues[k++] }
val params = TPRLayerParameters(
inputSize = 3,
dRoles = 2,
dSymbols = 2,
nRoles = 2,
nSymbols = 3,
weightsInitializer = RandomInitializer(randomGenerator),
biasesInitializer = ConstantInitializer(0.9))
val wInS = params.wInS.values
val wInR = params.wInR.values
val wRecS = params.wRecS.values
val wRecR = params.wRecR.values
val bS = params.bS.values
val bR = params.bR.values
val s = params.s.values
val r = params.r.values
it("should contain the expected initialized weights of the input -> Symbols matrix") {
(0 until wInS.length).forEach { i -> assertEquals(initValues[i], wInS[i]) }
}
it("should contain the expected initialized weights of the input -> Roles matrix") {
(0 until wInR.length).forEach { i -> assertEquals(initValues[i + 9], wInR[i]) }
}
it("should contain the expected initialized weights of the recurrent -> Symbols matrix") {
(0 until wRecS.length).forEach { i -> assertEquals(initValues[i + 15], wRecS[i]) }
}
it("should contain the expected initialized weights of the recurrent -> Roles matrix") {
(0 until wRecR.length).forEach { i -> assertEquals(initValues[i + 27], wRecR[i]) }
}
it("should contain the expected initialized biases of Symbols") {
(0 until bS.length).forEach { i -> assertEquals(0.9, bS[i]) }
}
it("should contain the expected initialized biases of Roles") {
(0 until bR.length).forEach { i -> assertEquals(0.9, bR[i]) }
}
it("should contain the expected initialized weights of the Symbols embeddings matrix") {
(0 until s.length).forEach { i -> assertEquals(initValues[i + 35], s[i]) }
}
it("should contain the expected initialized weights of the Role embeddings matrix") {
(0 until r.length).forEach { i -> assertEquals(initValues[i + 41], r[i]) }
}
}
}
}
})
|
mpl-2.0
|
3e456a3a045b24e3ddc89061c2aad5cc
| 38.612903 | 98 | 0.612106 | 3.740102 | false | false | false | false |
mdaniel/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/WorkspaceModuleImporter.kt
|
1
|
16544
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.importing.workspaceModel
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addJavaModuleSettingsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addModuleEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.idea.maven.importing.MavenImportUtil
import org.jetbrains.idea.maven.importing.MavenModuleType
import org.jetbrains.idea.maven.importing.tree.MavenModuleImportData
import org.jetbrains.idea.maven.importing.tree.MavenTreeModuleImportData
import org.jetbrains.idea.maven.importing.tree.dependency.*
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.project.MavenImportingSettings
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.utils.MavenLog
class WorkspaceModuleImporter(
private val project: Project,
private val importData: MavenTreeModuleImportData,
private val virtualFileUrlManager: VirtualFileUrlManager,
private val builder: MutableEntityStorage,
private val importingSettings: MavenImportingSettings,
private val dependenciesImportingContext: DependenciesImportingContext,
private val folderImportingContext: WorkspaceFolderImporter.FolderImportingContext
) {
private val externalSource = ExternalProjectSystemRegistry.getInstance().getSourceById(EXTERNAL_SOURCE_ID)
fun importModule(): ModuleEntity {
val baseModuleDirPath = importingSettings.dedicatedModuleDir.ifBlank { null } ?: importData.mavenProject.directory
val baseModuleDir = virtualFileUrlManager.fromPath(baseModuleDirPath)
val moduleLibrarySource = JpsEntitySourceFactory.createEntitySourceForModule(project, baseModuleDir, externalSource)
val projectLibrarySource = dependenciesImportingContext.getCachedProjectLibraryEntitySource {
JpsEntitySourceFactory.createEntitySourceForProjectLibrary(project, externalSource)
}
val moduleName = importData.moduleData.moduleName
val dependencies = collectDependencies(moduleName, importData.dependencies, moduleLibrarySource, projectLibrarySource)
val moduleEntity = createModuleEntity(moduleName, importData.mavenProject, importData.moduleData.type, dependencies,
moduleLibrarySource)
configureModuleEntity(importData, moduleEntity, folderImportingContext)
return moduleEntity
}
private fun createModuleEntity(moduleName: String,
mavenProject: MavenProject,
mavenModuleType: MavenModuleType,
dependencies: List<ModuleDependencyItem>,
entitySource: EntitySource): ModuleEntity {
val moduleEntity = builder.addModuleEntity(moduleName, dependencies, entitySource, ModuleTypeId.JAVA_MODULE)
val externalSystemModuleOptionsEntity = ExternalSystemModuleOptionsEntity(entitySource) {
ExternalSystemData(moduleEntity, mavenProject.file.path, mavenModuleType).write(this)
}
builder.addEntity(externalSystemModuleOptionsEntity)
return moduleEntity
}
private fun configureModuleEntity(importData: MavenModuleImportData,
moduleEntity: ModuleEntity,
folderImportingContext: WorkspaceFolderImporter.FolderImportingContext) {
val folderImporter = WorkspaceFolderImporter(builder, virtualFileUrlManager, importingSettings, folderImportingContext)
val importFolderHolder = folderImporter.createContentRoots(importData.mavenProject, importData.moduleData.type, moduleEntity)
when (importData.moduleData.type) {
MavenModuleType.MAIN_ONLY -> importJavaSettingsMain(moduleEntity, importData, importFolderHolder)
MavenModuleType.TEST_ONLY -> importJavaSettingsTest(moduleEntity, importData, importFolderHolder)
MavenModuleType.COMPOUND_MODULE -> importJavaSettingsMainAndTestAggregator(moduleEntity, importData)
MavenModuleType.AGGREGATOR -> importJavaSettingsAggregator(moduleEntity, importData)
else -> importJavaSettings(moduleEntity, importData, importFolderHolder)
}
}
private fun collectDependencies(moduleName: String,
dependencies: List<Any>,
moduleLibrarySource: EntitySource,
projectLibrarySource: EntitySource): List<ModuleDependencyItem> {
val result = mutableListOf(ModuleDependencyItem.InheritedSdkDependency, ModuleDependencyItem.ModuleSourceDependency)
for (dependency in dependencies) {
if (dependency is SystemDependency) {
result.add(createSystemDependency(moduleName, dependency.artifact, moduleLibrarySource))
}
else if (dependency is LibraryDependency) {
result.add(createLibraryDependency(dependency.artifact, projectLibrarySource))
}
else if (dependency is AttachedJarDependency) {
result.add(createLibraryDependency(
dependency.artifact,
toScope(dependency.scope),
classUrls = dependency.classes.map(::pathToUrl),
sourceUrls = dependency.sources.map(::pathToUrl),
javadocUrls = dependency.javadocs.map(::pathToUrl),
projectLibrarySource
))
}
else if (dependency is ModuleDependency) {
result.add(ModuleDependencyItem.Exportable
.ModuleDependency(ModuleId(dependency.artifact), false, toScope(dependency.scope), dependency.isTestJar))
}
else if (dependency is BaseDependency) {
result.add(createLibraryDependency(dependency.artifact, projectLibrarySource))
}
}
return result
}
private fun pathToUrl(it: String) = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, it) + JarFileSystem.JAR_SEPARATOR
private fun toScope(scope: DependencyScope): ModuleDependencyItem.DependencyScope =
when (scope) {
DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME
DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST
DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED
else -> ModuleDependencyItem.DependencyScope.COMPILE
}
private fun createSystemDependency(moduleName: String,
artifact: MavenArtifact,
entitySource: EntitySource): ModuleDependencyItem.Exportable.LibraryDependency {
assert(MavenConstants.SCOPE_SYSTEM == artifact.scope)
val libraryId = LibraryId(artifact.libraryName, LibraryTableId.ModuleLibraryTableId(moduleId = ModuleId(moduleName)))
addLibraryEntity(libraryId,
classUrls = listOf(
MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)),
sourceUrls = emptyList(),
javadocUrls = emptyList(),
entitySource)
return ModuleDependencyItem.Exportable.LibraryDependency(libraryId, false, artifact.dependencyScope)
}
private fun createLibraryDependency(artifact: MavenArtifact,
entitySource: EntitySource): ModuleDependencyItem.Exportable.LibraryDependency {
assert(MavenConstants.SCOPE_SYSTEM != artifact.scope)
return createLibraryDependency(artifact.libraryName,
artifact.dependencyScope,
classUrls = listOf(
MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)),
sourceUrls = listOf(
MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")),
javadocUrls = listOf(
MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")),
entitySource)
}
private fun createLibraryDependency(
libraryName: String,
scope: ModuleDependencyItem.DependencyScope,
classUrls: List<String>,
sourceUrls: List<String>,
javadocUrls: List<String>,
source: EntitySource
): ModuleDependencyItem.Exportable.LibraryDependency {
val libraryId = LibraryId(libraryName, LibraryTableId.ProjectLibraryTableId)
addLibraryEntity(libraryId, classUrls, sourceUrls, javadocUrls, source)
return ModuleDependencyItem.Exportable.LibraryDependency(libraryId, false, scope)
}
private fun addLibraryEntity(
libraryId: LibraryId,
classUrls: List<String>,
sourceUrls: List<String>,
javadocUrls: List<String>,
source: EntitySource) {
if (builder.resolve(libraryId) != null) return
val roots = mutableListOf<LibraryRoot>()
roots.addAll(classUrls.map { LibraryRoot(virtualFileUrlManager.fromUrl(it), LibraryRootTypeId.COMPILED) })
roots.addAll(sourceUrls.map { LibraryRoot(virtualFileUrlManager.fromUrl(it), LibraryRootTypeId.SOURCES) })
roots.addAll(javadocUrls.map { LibraryRoot(virtualFileUrlManager.fromUrl(it), JAVADOC_TYPE) })
builder.addLibraryEntity(libraryId.name,
libraryId.tableId,
roots,
emptyList(),
source)
}
private val MavenArtifact.dependencyScope: ModuleDependencyItem.DependencyScope
get() = when (scope) {
MavenConstants.SCOPE_RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME
MavenConstants.SCOPE_TEST -> ModuleDependencyItem.DependencyScope.TEST
MavenConstants.SCOPE_PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED
else -> ModuleDependencyItem.DependencyScope.COMPILE
}
private fun importJavaSettings(moduleEntity: ModuleEntity,
importData: MavenModuleImportData,
importFolderHolder: WorkspaceFolderImporter.CachedProjectFolders) {
val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel }
val inheritCompilerOutput: Boolean
val compilerOutputUrl: VirtualFileUrl?
val compilerOutputUrlForTests: VirtualFileUrl?
if (importingSettings.isUseMavenOutput) {
inheritCompilerOutput = false
compilerOutputUrl = virtualFileUrlManager.fromPath(importFolderHolder.outputPath)
compilerOutputUrlForTests = virtualFileUrlManager.fromPath(importFolderHolder.testOutputPath)
}
else {
inheritCompilerOutput = true
compilerOutputUrl = null
compilerOutputUrlForTests = null
}
builder.addJavaModuleSettingsEntity(inheritCompilerOutput, false, compilerOutputUrl, compilerOutputUrlForTests,
languageLevel.name, moduleEntity, moduleEntity.entitySource)
}
private fun importJavaSettingsMainAndTestAggregator(moduleEntity: ModuleEntity, importData: MavenModuleImportData) {
val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel }
builder.addJavaModuleSettingsEntity(true, false, null, null, languageLevel.name, moduleEntity, moduleEntity.entitySource)
}
private fun importJavaSettingsAggregator(moduleEntity: ModuleEntity, importData: MavenModuleImportData) {
val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel }
builder.addJavaModuleSettingsEntity(true, false, null, null, languageLevel.name, moduleEntity, moduleEntity.entitySource)
}
private fun importJavaSettingsMain(moduleEntity: ModuleEntity,
importData: MavenModuleImportData,
importFolderHolder: WorkspaceFolderImporter.CachedProjectFolders) {
val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel }
val inheritCompilerOutput: Boolean
val compilerOutputUrl: VirtualFileUrl?
if (importingSettings.isUseMavenOutput) {
inheritCompilerOutput = false
compilerOutputUrl = virtualFileUrlManager.fromPath(importFolderHolder.outputPath)
}
else {
inheritCompilerOutput = true
compilerOutputUrl = null
}
builder.addJavaModuleSettingsEntity(inheritCompilerOutput, false, compilerOutputUrl, null,
languageLevel.name, moduleEntity, moduleEntity.entitySource)
}
private fun importJavaSettingsTest(moduleEntity: ModuleEntity,
importData: MavenModuleImportData,
importFolderHolder: WorkspaceFolderImporter.CachedProjectFolders) {
val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel }
val inheritCompilerOutput: Boolean
val compilerOutputUrlForTests: VirtualFileUrl?
if (importingSettings.isUseMavenOutput) {
inheritCompilerOutput = false
compilerOutputUrlForTests = virtualFileUrlManager.fromPath(importFolderHolder.testOutputPath)
}
else {
inheritCompilerOutput = true
compilerOutputUrlForTests = null
}
builder.addJavaModuleSettingsEntity(inheritCompilerOutput, false, null, compilerOutputUrlForTests,
languageLevel.name, moduleEntity, moduleEntity.entitySource)
}
class DependenciesImportingContext {
private var projectLibrarySourceCache: EntitySource? = null
internal fun getCachedProjectLibraryEntitySource(compute: () -> EntitySource): EntitySource {
return projectLibrarySourceCache ?: compute().also { projectLibrarySourceCache = it }
}
}
companion object {
internal val JAVADOC_TYPE: LibraryRootTypeId = LibraryRootTypeId("JAVADOC")
val EXTERNAL_SOURCE_ID get() = ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID
}
class ExternalSystemData(val moduleEntity: ModuleEntity, val mavenProjectFilePath: String, val mavenModuleType: MavenModuleType) {
fun write(entity: ExternalSystemModuleOptionsEntity.Builder) {
entity.externalSystemModuleVersion = VERSION
entity.module = moduleEntity
entity.externalSystem = EXTERNAL_SOURCE_ID
// Can't use 'entity.linkedProjectPath' since it implies directory (and used to set working dir for Run Configurations).
entity.linkedProjectId = FileUtil.toSystemIndependentName(mavenProjectFilePath)
entity.externalSystemModuleType = mavenModuleType.name
}
companion object {
const val VERSION = "223-2"
fun tryRead(entity: ExternalSystemModuleOptionsEntity): ExternalSystemData? {
if (entity.externalSystem != EXTERNAL_SOURCE_ID || entity.externalSystemModuleVersion != VERSION) return null
val id = entity.linkedProjectId
if (id == null) {
MavenLog.LOG.debug("ExternalSystemModuleOptionsEntity.linkedProjectId must not be null")
return null
}
val mavenProjectFilePath = FileUtil.toSystemIndependentName(id)
val typeName = entity.externalSystemModuleType
if (typeName == null) {
MavenLog.LOG.debug("ExternalSystemModuleOptionsEntity.externalSystemModuleType must not be null")
return null
}
val moduleType = try {
MavenModuleType.valueOf(typeName)
}
catch (e: Exception) {
MavenLog.LOG.debug(e)
return null
}
return ExternalSystemData(entity.module, mavenProjectFilePath, moduleType)
}
}
}
}
|
apache-2.0
|
924ccd53ec6b7b319e2e73f8c3503dd8
| 49.59633 | 132 | 0.731867 | 6.1479 | false | true | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/tampere/TampereTransitData.kt
|
1
|
7389
|
/*
* TampereTransitData.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.tampere
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.desfire.DesfireApplication
import au.id.micolous.metrodroid.card.desfire.DesfireCard
import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory
import au.id.micolous.metrodroid.card.desfire.files.RecordDesfireFile
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.*
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.ImmutableByteArray
private val EPOCH = Epoch.utc(1900, MetroTimeZone.HELSINKI)
private fun parseTimestamp(day: Int, minute: Int): TimestampFull = EPOCH.dayMinute(day,
minute)
private fun parseDaystamp(day: Int): Daystamp = EPOCH.days(day)
@Parcelize
class TampereTrip(private val mDay: Int, private val mMinute: Int,
private val mFare: Int,
private val mMinutesSinceFirstStamp: Int,
private val mTransport: Int,
private val mA: Int, // 0x8b for first trip in a day, 0xb otherwise, 0 for refills
private val mB: Int, // Always 4
private val mC: Int, // Always 0
private val mRoute: Int,
private val mEventCode: Int, // 3 = topup, 5 = first tap, 11 = transfer
private val mFlags: Int
): Trip() {
override val startTimestamp: Timestamp?
get() = parseTimestamp(mDay, mMinute)
override val fare: TransitCurrency?
get() = TransitCurrency.EUR(mFare)
override val mode: Mode
get() = when (mTransport) {
0xba, 0xde -> Mode.BUS // ba = bus. de = ?? (used for subscriptions)
0x4c -> Mode.TICKET_MACHINE // 4c is ASCII for 'L' from Finnish "lataa" = "top-up"
else -> Mode.OTHER
}
override val isTransfer: Boolean
get() = (mFlags and 0x40000) != 0
override val humanReadableRouteID get() = mRoute.toString()
override val routeName get() = TampereTransitData.getRouteName(mRoute)
override fun getRawFields(level: TransitData.RawLevel) = "A=0x${mA.toString(16)}/B=$mB/C=$mC" +
(if (level != TransitData.RawLevel.UNKNOWN_ONLY) "/EventCode=$mEventCode/flags=0x${mFlags.toString(16)}/sinceFirstStamp=$mMinutesSinceFirstStamp/transport=0x${mTransport.toString(16)}" else "")
companion object {
fun parse(raw: ImmutableByteArray): TampereTrip? {
val type = raw.byteArrayToIntReversed(4, 1)
val fare = raw.byteArrayToIntReversed(8, 2).let {
if (type == 0x4c)
-it
else
it
}
val minuteField = raw.byteArrayToIntReversed(6, 2)
val cField = raw.byteArrayToIntReversed(10, 2)
return TampereTrip(mDay = raw.byteArrayToIntReversed(0, 2),
mMinute = minuteField shr 5,
mFare = fare,
mMinutesSinceFirstStamp = raw.byteArrayToIntReversed(2, 1),
mTransport = type,
mA = raw.byteArrayToIntReversed(3, 1),
mB = raw.byteArrayToIntReversed(5, 1),
mC = cField and 3,
mRoute = cField shr 2,
mEventCode = minuteField and 0x1f,
mFlags = raw.byteArrayToIntReversed(12, 3)
// Last byte: CRC-8-maxim checksum of the record
)
}
}
}
@Parcelize
class TampereTransitData (
override val serialNumber: String?,
private val mBalance: Int?,
override val trips: List<Trip>?,
private val mHolderName: String?,
private val mHolderBirthDate: Int?,
private val mIssueDate: Int?): TransitData() {
override val cardName: String
get() = Localizer.localizeString(NAME)
public override val balance: TransitCurrency?
get() = mBalance?.let { TransitCurrency.EUR(it) }
override val info: List<ListItem>?
get() = listOf(
ListItem(R.string.card_holders_name, mHolderName),
ListItem(R.string.date_of_birth, mHolderBirthDate?.let { parseDaystamp(it) }?.format()),
ListItem(R.string.issue_date, mIssueDate?.let { parseDaystamp(it) }?.format())
)
companion object {
// Finish for "Tampere travel card". It doesn't seem to have a more specific
// brand name.
val NAME = R.string.card_name_tampere
const val APP_ID = 0x121ef
private fun getSerialNumber(app: DesfireApplication?) = app?.getFile(0x07)?.data?.toHexString()?.substring(2, 20)
private fun parse(desfireCard: DesfireCard): TampereTransitData? {
val app = desfireCard.getApplication(APP_ID)
val file4 = app?.getFile(0x04)?.data
val holderName = file4?.sliceOffLen(6, 24)?.readASCII()
val holderBirthDate = file4?.byteArrayToIntReversed(0x22, 2)
val issueDate = file4?.byteArrayToIntReversed(0x2a, 2)
return TampereTransitData(
serialNumber = getSerialNumber(app),
mBalance = app?.getFile(0x01)?.data?.byteArrayToIntReversed(),
trips = (app?.getFile(0x03) as? RecordDesfireFile)?.records?.mapNotNull { TampereTrip.parse(it) },
mHolderName = holderName,
mHolderBirthDate = holderBirthDate,
mIssueDate = issueDate
)
}
private val CARD_INFO = CardInfo(
name = NAME,
locationId = R.string.location_tampere,
imageId = R.drawable.tampere,
imageAlphaId = R.drawable.iso7810_id1_alpha,
region = TransitRegion.FINLAND,
cardType = CardType.MifareDesfire)
fun getRouteName(routeNumber: Int) = FormattedString("${routeNumber/100}/${routeNumber%100}")
val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory {
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun earlyCheck(appIds: IntArray) = APP_ID in appIds
override fun parseTransitData(card: DesfireCard) = parse(card)
override fun parseTransitIdentity(card: DesfireCard) = TransitIdentity(NAME,
getSerialNumber(card.getApplication(APP_ID)))
}
}
}
|
gpl-3.0
|
68637118748351cb312a3ea8d2110418
| 42.464706 | 205 | 0.630938 | 4.239243 | false | false | false | false |
JetBrains/kotlin-spec
|
grammar/src/test/org/jetbrains/kotlin/spec/grammar/parsetree/ParseTreeUtil.kt
|
1
|
4704
|
package org.jetbrains.kotlin.spec.grammar.parsetree
import org.antlr.v4.runtime.*
import org.antlr.v4.runtime.atn.PredictionContext
import org.antlr.v4.runtime.tree.ParseTree
import org.antlr.v4.runtime.tree.TerminalNodeImpl
import org.jetbrains.kotlin.spec.grammar.KotlinLexer
import org.jetbrains.kotlin.spec.grammar.KotlinParser
import org.jetbrains.kotlin.spec.grammar.util.TestUtil
import java.util.HashMap
data class SyntaxError(val message: String?, val line: Int, val charPosition: Int) {
override fun toString() = "Line $line:$charPosition $message"
}
class KotlinParserWithLimitedCache(input: TokenStream): KotlinParser(input) {
companion object {
private const val MAX_CACHE_SIZE = 10000
private val cacheField = _sharedContextCache.javaClass.declaredFields.find { it.name == "cache" }!!.apply { isAccessible = true }
private val cache = cacheField.get(_sharedContextCache) as HashMap<PredictionContext, PredictionContext>
}
init {
if (_sharedContextCache.size() > MAX_CACHE_SIZE) {
cache.clear()
reset()
interpreter.clearDFA()
}
}
}
class KotlinLexerWithLimitedCache(input: CharStream): KotlinLexer(input) {
companion object {
private const val MAX_CACHE_SIZE = 10000
private val cacheField = _sharedContextCache.javaClass.declaredFields.find { it.name == "cache" }!!.apply { isAccessible = true }
private val cache = cacheField.get(_sharedContextCache) as HashMap<PredictionContext, PredictionContext>
}
init {
if (_sharedContextCache.size() > MAX_CACHE_SIZE) {
cache.clear()
reset()
interpreter.clearDFA()
}
}
}
object ParseTreeUtil {
private const val ROOT_RULE = "kotlinFile"
private fun buildTree(
parser: KotlinParser,
tokenTypeMap: Map<String, Int>,
antlrParseTree: ParseTree,
kotlinParseTree: KotlinParseTree
): KotlinParseTree {
for (i in 0..antlrParseTree.childCount) {
val antlrParseTreeNode = antlrParseTree.getChild(i) ?: continue
val kotlinParseTreeNode = when (antlrParseTreeNode) {
is TerminalNodeImpl ->
KotlinParseTree(
KotlinParseTreeNodeType.TERMINAL,
KotlinLexer.VOCABULARY.getSymbolicName(antlrParseTreeNode.symbol.type),
antlrParseTreeNode.symbol.text.replace(TestUtil.ls, "\\n")
)
else ->
KotlinParseTree(
KotlinParseTreeNodeType.RULE,
parser.ruleNames[(antlrParseTreeNode as RuleContext).ruleIndex]
)
}
kotlinParseTree.children.add(kotlinParseTreeNode)
buildTree(parser, tokenTypeMap, antlrParseTreeNode, kotlinParseTreeNode)
}
return kotlinParseTree
}
private fun getErrorListener(errors: MutableList<SyntaxError>) =
object : BaseErrorListener() {
override fun syntaxError(
recognizer: Recognizer<*, *>?,
offendingSymbol: Any?,
line: Int,
charPositionInLine: Int,
msg: String?,
e: RecognitionException?
) {
errors.add(SyntaxError(msg, line, charPositionInLine))
}
}
fun parse(sourceCode: String): Pair<KotlinParseTree, Pair<List<SyntaxError>, List<SyntaxError>>> {
val lexerErrors = mutableListOf<SyntaxError>()
val parserErrors = mutableListOf<SyntaxError>()
val lexer = KotlinLexerWithLimitedCache(ANTLRInputStream(sourceCode))
val tokens = CommonTokenStream(
lexer.apply {
removeErrorListeners()
addErrorListener(getErrorListener(lexerErrors))
}
)
val kotlinParser = KotlinParserWithLimitedCache(tokens)
val parseTree = kotlinParser.apply {
removeErrorListeners()
addErrorListener(getErrorListener(parserErrors))
}.kotlinFile() as ParseTree
val kotlinParseTree = buildTree(
kotlinParser,
lexer.tokenTypeMap,
parseTree,
KotlinParseTree(
KotlinParseTreeNodeType.RULE,
kotlinParser.ruleNames[kotlinParser.ruleIndexMap[ROOT_RULE]!!]
)
)
return Pair(kotlinParseTree, Pair(lexerErrors, parserErrors))
}
}
|
apache-2.0
|
e8b200a013b738ae138374efc4f18405
| 37.243902 | 137 | 0.605017 | 4.889813 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewRenderer.kt
|
8
|
2950
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.projectView.impl
import com.intellij.ide.projectView.ProjectViewNode
import com.intellij.ide.ui.UISettings
import com.intellij.ide.util.treeView.NodeRenderer
import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.text.JBDateFormat
import com.intellij.util.ui.tree.TreeUtil
import java.nio.file.Files
import java.nio.file.attribute.BasicFileAttributes
import javax.swing.JTree
open class ProjectViewRenderer : NodeRenderer() {
init {
isOpaque = false
isIconOpaque = false
isTransparentIconBackground = true
}
override fun customizeCellRenderer(tree: JTree,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean) {
super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus)
val userObject = TreeUtil.getUserObject(value)
if (userObject is ProjectViewNode<*> && UISettings.getInstance().showInplaceComments) {
appendInplaceComments(userObject)
}
}
// used in Rider
@Suppress("MemberVisibilityCanBePrivate")
fun appendInplaceComments(project: Project?, file: VirtualFile?) {
val ioFile = if (file == null || file.isDirectory || !file.isInLocalFileSystem) null else file.toNioPath()
val fileAttributes = try {
if (ioFile == null) null else Files.readAttributes(ioFile, BasicFileAttributes::class.java)
}
catch (ignored: Exception) {
null
}
if (fileAttributes != null) {
append(" ")
val attributes = SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES
append(JBDateFormat.getFormatter().formatDateTime(fileAttributes.lastModifiedTime().toMillis()), attributes)
append(", " + StringUtil.formatFileSize(fileAttributes.size()), attributes)
}
if (Registry.`is`("show.last.visited.timestamps") && file != null && project != null) {
IdeDocumentHistoryImpl.appendTimestamp(project, this, file)
}
}
private fun appendInplaceComments(node: ProjectViewNode<*>) {
val parentNode = node.parent
val content = node.value
if (content is PsiFileSystemItem || content !is PsiElement || parentNode != null && parentNode.value is PsiDirectory) {
appendInplaceComments(node.project, node.virtualFile)
}
}
}
|
apache-2.0
|
5e41b1ebce64f89dbabc0433216052aa
| 38.878378 | 123 | 0.69661 | 4.727564 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinWordSelectionFilter.kt
|
4
|
1186
|
// 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.editor.wordSelection
import com.intellij.openapi.util.Condition
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.KtNodeTypes.BLOCK
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.kdoc.parser.KDocElementTypes
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtContainerNode
class KotlinWordSelectionFilter : Condition<PsiElement> {
override fun value(e: PsiElement): Boolean {
if (e.language != KotlinLanguage.INSTANCE) return true
if (KotlinListSelectioner.canSelect(e)) return false
if (KotlinCodeBlockSelectioner.canSelect(e)) return false
val elementType = e.node.elementType
if (elementType == KtTokens.REGULAR_STRING_PART || elementType == KtTokens.ESCAPE_SEQUENCE) return true
if (e is KtContainerNode) return false
return when (e.node.elementType) {
BLOCK, KDocElementTypes.KDOC_SECTION -> false
else -> true
}
}
}
|
apache-2.0
|
605e39d28c16b69eaa408e81e410920c
| 38.533333 | 158 | 0.742833 | 4.376384 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/composer/StoryReplyComposer.kt
|
1
|
5454
|
package org.thoughtcrime.securesms.stories.viewer.reply.composer
import android.app.Dialog
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.ViewSwitcher
import androidx.core.widget.doAfterTextChanged
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.ComposeText
import org.thoughtcrime.securesms.components.InputAwareLayout
import org.thoughtcrime.securesms.components.QuoteView
import org.thoughtcrime.securesms.components.emoji.EmojiPageView
import org.thoughtcrime.securesms.components.emoji.EmojiToggle
import org.thoughtcrime.securesms.components.emoji.MediaKeyboard
import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord
import org.thoughtcrime.securesms.database.model.Mention
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.mms.QuoteModel
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.visible
class StoryReplyComposer @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val inputAwareLayout: InputAwareLayout
private val quoteView: QuoteView
private val privacyChrome: TextView
private val emojiDrawerToggle: EmojiToggle
private val emojiDrawer: MediaKeyboard
val reactionButton: View
val input: ComposeText
var isRequestingEmojiDrawer: Boolean = false
private set
var callback: Callback? = null
val emojiPageView: EmojiPageView?
get() = findViewById(R.id.emoji_page_view)
init {
inflate(context, R.layout.stories_reply_to_story_composer, this)
inputAwareLayout = findViewById(R.id.input_aware_layout)
emojiDrawerToggle = findViewById(R.id.emoji_toggle)
quoteView = findViewById(R.id.quote_view)
input = findViewById(R.id.compose_text)
reactionButton = findViewById(R.id.reaction)
privacyChrome = findViewById(R.id.private_reply_recipient)
emojiDrawer = findViewById(R.id.emoji_drawer)
val viewSwitcher: ViewSwitcher = findViewById(R.id.reply_reaction_switch)
val reply: View = findViewById(R.id.reply)
reply.setOnClickListener {
callback?.onSendActionClicked()
}
input.setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_SEND -> {
callback?.onSendActionClicked()
true
}
else -> false
}
}
input.doAfterTextChanged {
if (it.isNullOrEmpty()) {
viewSwitcher.displayedChild = 0
} else {
viewSwitcher.displayedChild = 1
}
}
reactionButton.setOnClickListener {
callback?.onPickReactionClicked()
}
emojiDrawerToggle.setOnClickListener {
onEmojiToggleClicked()
}
inputAwareLayout.addOnKeyboardShownListener {
if (inputAwareLayout.currentInput == emojiDrawer && !emojiDrawer.isEmojiSearchMode) {
onEmojiToggleClicked()
}
}
}
fun setQuote(messageRecord: MediaMmsMessageRecord) {
quoteView.setQuote(
GlideApp.with(this),
messageRecord.dateSent,
messageRecord.recipient,
messageRecord.body,
false,
messageRecord.slideDeck,
null,
null,
QuoteModel.Type.NORMAL
)
quoteView.visible = true
}
fun displayPrivacyChrome(recipient: Recipient) {
privacyChrome.text = context.getString(R.string.StoryReplyComposer__replying_privately_to_s, recipient.getDisplayName(context))
privacyChrome.visible = true
}
fun consumeInput(): Pair<CharSequence, List<Mention>> {
val trimmedText = input.textTrimmed.toString()
val mentions = input.mentions
input.setText("")
return trimmedText to mentions
}
fun openEmojiSearch() {
emojiDrawer.onOpenEmojiSearch()
}
fun onEmojiSelected(emoji: String?) {
input.insertEmoji(emoji)
}
fun closeEmojiSearch() {
emojiDrawer.onCloseEmojiSearch()
}
private fun onEmojiToggleClicked() {
if (!emojiDrawer.isInitialised) {
callback?.onInitializeEmojiDrawer(emojiDrawer)
emojiDrawerToggle.attach(emojiDrawer)
}
if (inputAwareLayout.currentInput == emojiDrawer) {
isRequestingEmojiDrawer = false
inputAwareLayout.showSoftkey(input)
callback?.onHideEmojiKeyboard()
} else {
isRequestingEmojiDrawer = true
inputAwareLayout.hideSoftkey(input) {
inputAwareLayout.post {
inputAwareLayout.show(input, emojiDrawer)
emojiDrawer.post { callback?.onShowEmojiKeyboard() }
}
}
}
}
interface Callback {
fun onSendActionClicked()
fun onPickReactionClicked()
fun onInitializeEmojiDrawer(mediaKeyboard: MediaKeyboard)
fun onShowEmojiKeyboard() = Unit
fun onHideEmojiKeyboard() = Unit
}
companion object {
fun installIntoBottomSheet(context: Context, dialog: Dialog): StoryReplyComposer {
val container: ViewGroup = dialog.findViewById(R.id.container)
val oldComposer: StoryReplyComposer? = container.findViewById(R.id.input)
if (oldComposer != null) {
return oldComposer
}
val composer = StoryReplyComposer(context)
composer.id = R.id.input
container.addView(composer)
return composer
}
}
}
|
gpl-3.0
|
bb5324e59c7b5bb7e8366e7419974afd
| 27.857143 | 131 | 0.731573 | 4.492586 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/yoga/src/templates/kotlin/yoga/yogaTypes.kt
|
4
|
9411
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package yoga
import org.lwjgl.generator.*
val YGNodeRef = "YGNodeRef".handle
val YGNodeConstRef = "YGNodeConstRef".handle
val YGConfigRef = "YGConfigRef".handle
val YGAlign = "YGAlign".enumType
val YGDimension = "YGDimension".enumType
val YGDirection = "YGDirection".enumType
val YGDisplay = "YGDisplay".enumType
val YGEdge = "YGEdge".enumType
val YGExperimentalFeature = "YGExperimentalFeature".enumType
val YGFlexDirection = "YGFlexDirection".enumType
val YGJustify = "YGJustify".enumType
val YGLogLevel = "YGLogLevel".enumType
val YGMeasureMode = "YGMeasureMode".enumType
val YGNodeType = "YGNodeType".enumType
val YGOverflow = "YGOverflow".enumType
val YGPositionType = "YGPositionType".enumType
val YGUnit = "YGUnit".enumType
val YGWrap = "YGWrap".enumType
val YGSize = struct(Module.YOGA, "YGSize") {
float("width", "")
float("height", "")
}
val YGValue = struct(Module.YOGA, "YGValue") {
float("value", "")
YGUnit("unit", "")
}
val YGMeasureFunc = Module.YOGA.callback {
YGSize(
"YGMeasureFunc",
"",
YGNodeRef("node", ""),
float("width", ""),
YGMeasureMode("widthMode", ""),
float("height", ""),
YGMeasureMode("heightMode", ""),
nativeType = "YGMeasureFunc"
)
}
val YGBaselineFunc = Module.YOGA.callback {
float(
"YGBaselineFunc",
"",
YGNodeRef("node", ""),
float("width", ""),
float("height", ""),
nativeType = "YGBaselineFunc"
)
}
val YGDirtiedFunc = Module.YOGA.callback {
void(
"YGDirtiedFunc",
"",
YGNodeRef("node", ""),
nativeType = "YGDirtiedFunc"
)
}
val YGPrintFunc = Module.YOGA.callback {
void(
"YGPrintFunc",
"",
YGNodeRef("node", ""),
nativeType = "YGPrintFunc"
)
}
val YGNodeCleanupFunc = Module.YOGA.callback {
void(
"YGNodeCleanupFunc",
"",
YGNodeRef("node", ""),
nativeType = "YGNodeCleanupFunc"
)
}
val YGLogger = Module.YOGA.callback {
int(
"YGLogger",
"",
YGConfigRef("config", ""),
YGNodeRef("node", ""),
YGLogLevel("level", ""),
charUTF8.const.p("format", ""),
va_list("args", ""),
nativeType = "YGLogger"
)
}
val YGCloneNodeFunc = Module.YOGA.callback {
YGNodeRef(
"YGCloneNodeFunc",
"",
YGNodeRef("oldNode", ""),
YGNodeRef("owner", ""),
int("childIndex", ""),
nativeType = "YGCloneNodeFunc"
)
}
// Internal API, exposed for efficiency.
val CompactValue = struct(Module.YOGA, "CompactValue", mutable = false) {
javaImport("static org.lwjgl.util.yoga.Yoga.*")
documentation = "Unstable/private API."
union {
float("value", "")
uint32_t("repr", "")
}
customMethod("""
private static final int BIAS = 0x20000000;
private static final int PERCENT_BIT = 0x40000000;
private static final int AUTO_BITS = 0x7faaaaaa;
private static final int ZERO_BITS_POINT = 0x7f8f0f0f;
private static final int ZERO_BITS_PERCENT = 0x7f80f0f0;
public float decode() {
int repr = repr();
switch (repr) {
case AUTO_BITS:
return Float.NaN;
case ZERO_BITS_POINT:
case ZERO_BITS_PERCENT:
return 0.0f;
}
if (Float.isNaN(value())) {
return Float.NaN;
}
repr &= ~PERCENT_BIT;
repr += BIAS;
return Float.intBitsToFloat(repr);
}
public YGValue decode(YGValue __result) {
int repr = repr();
switch (repr) {
case AUTO_BITS:
return __result
.value(YGUndefined)
.unit(YGUnitAuto);
case ZERO_BITS_POINT:
return __result
.value(0.0f)
.unit(YGUnitPoint);
case ZERO_BITS_PERCENT:
return __result
.value(0.0f)
.unit(YGUnitPercent);
}
if (Float.isNaN(value())) {
return __result
.value(YGUndefined)
.unit(YGUnitUndefined);
}
int data = repr;
data &= ~PERCENT_BIT;
data += BIAS;
return __result
.value(Float.intBitsToFloat(data))
.unit((repr & PERCENT_BIT) != 0 ? YGUnitPercent : YGUnitPoint);
}
""")
}
val YGCachedMeasurement = struct(Module.YOGA, "YGCachedMeasurement", mutable = false) {
documentation = "Unstable/private API."
float("availableWidth", "")
float("availableHeight", "")
YGMeasureMode("widthMeasureMode", "")
YGMeasureMode("heightMeasureMode", "")
float("computedWidth", "")
float("computedHeight", "")
}
val YGFloatOptional = struct(Module.YOGA, "YGFloatOptional", mutable = false) {
float("value", "")
customMethod("""
public boolean isUndefined() {
return Float.isNaN(value());
}""")
}
const val YG_MAX_CACHED_RESULT_COUNT = 16
val YGLayout = struct(Module.YOGA, "YGLayout", mutable = false) {
documentation = "Unstable/private API."
NativeName("position")..float("positions", "")[4]
float("dimensions", "")[2]
float("margin", "")[4]
float("border", "")[4]
float("padding", "")[4]
uint8_t("flags", "").virtual()
YGDirection("direction", "", bits = 2).getter("nflags(struct) & 0b11")
bool("didUseLegacyFlag", "", bits = 1).getter("((nflags(struct) >>> 2) & 0b1) != 0")
bool("doesLegacyStretchFlagAffectsLayout", "", bits = 1).getter("((nflags(struct) >>> 3) & 0b1) != 0")
bool("hadOverflow", "", bits = 1).getter("((nflags(struct) >>> 4) & 0b1) != 0")
uint32_t("computedFlexBasisGeneration", "")
YGFloatOptional("computedFlexBasis", "")
uint32_t("generationCount", "")
YGDirection("lastOwnerDirection", "")
uint32_t("nextCachedMeasurementsIndex", "")
YGCachedMeasurement("cachedMeasurements", "")[YG_MAX_CACHED_RESULT_COUNT]
float("measuredDimensions", "")[2]
YGCachedMeasurement("cachedLayout", "")
}
const val YGEdgeCount = 9
val YGStyle = struct(Module.YOGA, "YGStyle", mutable = false) {
documentation = "Unstable/private API."
uint32_t("flags", "").virtual()
YGDirection("direction", "", bits = 2).getter("nflags(struct) & 0b11")
YGFlexDirection("flexDirection", "", bits = 2).getter("(nflags(struct) >>> 2) & 0b11")
YGJustify("justifyContent", "", bits = 3).getter("(nflags(struct) >>> 4) & 0b111")
YGAlign("alignContent", "", bits = 3).getter("(nflags(struct) >>> 7) & 0b111")
YGAlign("alignItems", "", bits = 3).getter("(nflags(struct) >>> 10) & 0b111")
YGAlign("alignSelf", "", bits = 3).getter("(nflags(struct) >>> 13) & 0b111")
YGPositionType("positionType", "", bits = 2).getter("(nflags(struct) >>> 16) & 0b11")
YGWrap("flexWrap", "", bits = 2).getter("(nflags(struct) >>> 18) & 0b11")
YGOverflow("overflow", "", bits = 2).getter("(nflags(struct) >>> 20) & 0b11")
YGDisplay("display", "", bits = 1).getter("(nflags(struct) >>> 22) & 0b1")
YGFloatOptional("flex", "")
YGFloatOptional("flexGrow", "")
YGFloatOptional("flexShrink", "")
CompactValue("flexBasis", "")
CompactValue("margin", "")[YGEdgeCount]
NativeName("position")..CompactValue("positions", "")[YGEdgeCount]
CompactValue("padding", "")[YGEdgeCount]
CompactValue("border", "")[YGEdgeCount]
CompactValue("dimensions", "")[2]
CompactValue("minDimensions", "")[2]
CompactValue("maxDimensions", "")[2]
YGFloatOptional("aspectRatio", "")
}
val YGNode = struct(Module.YOGA, "YGNode") {
documentation = "Unstable/private API."
nullable..opaque_p("context", "")
uint8_t("flags", "").virtual()
bool("hasNewLayout", "", bits = 1).getter("(nflags(struct) & 0b1) != 0")
bool("isReferenceBaseline", "", bits = 1).getter("((nflags(struct) >>> 1) & 0b1) != 0")
bool("isDirty", "", bits = 1).getter("((nflags(struct) >>> 2) & 0b1) != 0")
YGNodeType("nodeType", "", bits = 1).getter("(nflags(struct) >>> 3) & 0b1")
bool("measureUsesContext", "", bits = 1).getter("((nflags(struct) >>> 4) & 0b1) != 0")
bool("baselineUsesContext", "", bits = 1).getter("((nflags(struct) >>> 5) & 0b1) != 0")
bool("printUsesContext", "", bits = 1).getter("((nflags(struct) >>> 6) & 0b1) != 0")
bool("useWebDefaults", "", bits = 1).getter("((nflags(struct) >>> 7) & 0b1) != 0")
padding(1)
union {
nullable..YGMeasureFunc("noContext", "")
nullable.."MeasureWithContextFn".handle("withContext", "")
}("measure", "")
union {
nullable..YGBaselineFunc("noContext", "")
nullable.."BaselineWithContextFn".handle("withContext", "")
}("baseline", "")
union {
nullable..YGPrintFunc("noContext", "")
nullable.."PrintWithContextFn".handle("withContext", "")
}("print", "")
nullable..YGDirtiedFunc("dirtied", "")
YGStyle("style", "")
YGLayout("layout", "")
uint32_t("lineIndex", "")
nullable..YGNodeRef("owner", "")
nullable.."YGVector".handle("children", "").private() // std:vector<YGNodeRef>
nullable..YGConfigRef("config", "")
YGValue("resolvedDimensions", "")[2]
}
|
bsd-3-clause
|
b2f6bbf5fad8566f2daf4e25a9f485f3
| 27.871166 | 106 | 0.581235 | 3.548643 | false | false | false | false |
DemonWav/MinecraftDev
|
src/main/kotlin/com/demonwav/mcdev/util/reference/PackageNameReferenceProvider.kt
|
1
|
6043
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util.reference
import com.demonwav.mcdev.util.manipulator
import com.demonwav.mcdev.util.packageName
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiPackage
import com.intellij.psi.PsiQualifiedNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.ResolveResult
import com.intellij.util.IncorrectOperationException
import com.intellij.util.PlatformIcons
import com.intellij.util.ProcessingContext
abstract class PackageNameReferenceProvider : PsiReferenceProvider() {
protected open val description
get() = "package '%s'"
protected open fun getBasePackage(element: PsiElement): String? = null
protected open fun canBindTo(element: PsiElement) = element is PsiPackage
protected open fun resolve(qualifiedName: String, element: PsiElement, facade: JavaPsiFacade): Array<ResolveResult> {
facade.findPackage(qualifiedName)?.let { return arrayOf(PsiElementResolveResult(it)) }
return ResolveResult.EMPTY_ARRAY
}
protected abstract fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any>
protected fun collectSubpackages(context: PsiPackage, classes: Iterable<PsiClass>): Array<Any> {
return collectPackageChildren(context, classes) {}
}
protected inline fun collectPackageChildren(context: PsiPackage, classes: Iterable<PsiClass>,
classFunc: (PsiClass) -> Any?): Array<Any> {
val parentPackage = context.qualifiedName
val subPackageStart = parentPackage.length + 1
val packages = HashSet<String>()
val list = ArrayList<Any>()
for (psiClass in classes) {
val packageName = psiClass.packageName ?: continue
if (!packageName.startsWith(parentPackage)) {
continue
}
if (packageName.length < subPackageStart) {
classFunc(psiClass)?.let { list.add(it) }
continue
}
val end = packageName.indexOf('.', subPackageStart)
val nextName = if (end == -1) packageName.substring(subPackageStart) else packageName.substring(subPackageStart, end)
if (packages.add(nextName)) {
list.add(LookupElementBuilder.create(nextName).withIcon(PlatformIcons.PACKAGE_ICON))
}
}
return list.toArray()
}
fun resolve(element: PsiElement): PsiElement? {
val range = element.manipulator!!.getRangeInElement(element)
return Reference(element, range, range.startOffset, null).multiResolve(false).firstOrNull()?.element
}
final override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
val baseRange = element.manipulator!!.getRangeInElement(element)
val text = element.text!!
val start = baseRange.startOffset
val end = baseRange.endOffset
var pos = start
var current: Reference? = null
val list = ArrayList<PsiReference>()
while (true) {
val separatorPos = text.indexOf('.', pos)
if (separatorPos == -1) {
list.add(Reference(element, TextRange(pos, end), start, current))
break
}
if (separatorPos >= end) {
break
}
current = Reference(element, TextRange(pos, separatorPos), start, current)
list.add(current)
pos = separatorPos + 1
if (pos == end) {
list.add(Reference(element, TextRange(end, end), start, current))
break
}
}
return list.toTypedArray()
}
private inner class Reference(element: PsiElement, range: TextRange, start: Int, val previous: Reference?)
: PsiReferenceBase.Poly<PsiElement>(element, range, false), InspectionReference {
override val description: String
get() = [email protected]
private val qualifiedRange = TextRange(start, range.endOffset)
private val qualifiedName: String
get() {
val name = qualifiedRange.substring(element.text)
return getBasePackage(element)?.let { it + '.' + name } ?: name
}
override val unresolved: Boolean
get() = multiResolve(false).isEmpty()
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
return resolve(qualifiedName, element, JavaPsiFacade.getInstance(element.project))
}
override fun getVariants(): Array<Any> {
return collectVariants(element, previous?.multiResolve(false)?.firstOrNull()?.element)
}
private fun getNewName(newTarget: PsiQualifiedNamedElement): String {
val newName = newTarget.qualifiedName!!
return getBasePackage(element)?.let { newName.removePrefix(it + '.') } ?: newName
}
override fun bindToElement(newTarget: PsiElement): PsiElement? {
if (!canBindTo(newTarget)) {
throw IncorrectOperationException("Cannot bind to $newTarget")
}
if (super.isReferenceTo(newTarget)) {
return element
}
val newName = getNewName(newTarget as PsiQualifiedNamedElement)
return element.manipulator?.handleContentChange(element, qualifiedRange, newName)
}
override fun isReferenceTo(element: PsiElement) = canBindTo(element) && super.isReferenceTo(element)
}
}
|
mit
|
370313b78900bea83a22e6a060d4ee59
| 35.403614 | 129 | 0.6558 | 5.164957 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/nanovg/src/templates/kotlin/nanovg/NVGTypes.kt
|
4
|
2480
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package nanovg
import org.lwjgl.generator.*
fun GeneratorTargetNative.includeNanoVGAPI(directives: String) = nativeDirective(
"""#include "lwjgl_malloc.h"
#define NVG_MALLOC(sz) org_lwjgl_malloc(sz)
#define NVG_REALLOC(p,sz) org_lwjgl_realloc(p,sz)
#define NVG_FREE(p) org_lwjgl_free(p)
DISABLE_WARNINGS()
$directives
ENABLE_WARNINGS()""")
val NVGcontext = "NVGcontext".opaque
val NVGcolor = struct(Module.NANOVG, "NVGColor", nativeName = "NVGcolor") {
documentation = "A NanoVG color."
union {
float("rgba", "an array of 4 color components")[4]
struct {
float("r", "the color red component")
float("g", "the color green component")
float("b", "the color blue component")
float("a", "the color alpha component")
}
}
}
val NVGpaint = struct(Module.NANOVG, "NVGPaint", nativeName = "NVGpaint") {
documentation = "A NanoVG paint."
float("xform", "the transformation matrix")[6]
float("extent", "the extent")[2]
float("radius", "the radius")
float("feather", "the feather amount")
NVGcolor("innerColor", "the inner color")
NVGcolor("outerColor", "the outer color")
int("image", "the image handle")
}
val charptr = "char".opaque // address, not data
val NVGglyphPosition = struct(Module.NANOVG, "NVGGlyphPosition", nativeName = "NVGglyphPosition", mutable = false) {
documentation = "A glyph position."
charptr.p("str", "position of the glyph in the input string")
float("x", "the x-coordinate of the logical glyph position")
float("minx", "the left bound of the glyph shape")
float("maxx", "the right bound of the glyph shape")
}
val NVGtextRow = struct(Module.NANOVG, "NVGTextRow", nativeName = "NVGtextRow", mutable = false) {
documentation = "A text row."
charptr.p("start", "pointer to the input text where the row starts")
charptr.p("end", "pointer to the input text where the row ends (one past the last character")
charptr.p("next", "pointer to the beginning of the next row")
float("width", "logical width of the row")
float("minx", "actual left bound of the row. Logical width and bounds can differ because of kerning and some parts over extending.")
float("maxx", "actual right bound of the row. Logical width and bounds can differ because of kerning and some parts over extending.")
}
|
bsd-3-clause
|
aaba293180c20202b8ec2e111c929e87
| 36.575758 | 137 | 0.67379 | 3.604651 | false | false | false | false |
jovr/imgui
|
core/src/main/kotlin/imgui/api/tabBarsTabs.kt
|
2
|
5406
|
package imgui.api
import glm_.max
import imgui.*
import imgui.ImGui.popID
import imgui.ImGui.pushOverrideID
import imgui.ImGui.style
import imgui.internal.classes.PtrOrIndex
import imgui.internal.classes.Rect
import imgui.internal.classes.TabBar
import kotlin.reflect.KMutableProperty0
/** Tab Bars, Tabs */
interface tabBarsTabs {
/** create and append into a TabBar */
fun beginTabBar(strId: String, flags: TabBarFlags = 0): Boolean {
val window = g.currentWindow!!
if (window.skipItems) return false
val id = window.getID(strId)
val tabBar = g.tabBars.getOrAddByKey(id)
val tabBarBb = Rect(window.dc.cursorPos.x,
window.dc.cursorPos.y,
window.innerClipRect.max.x,
window.dc.cursorPos.y + g.fontSize + style.framePadding.y * 2)
tabBar.id = id
return tabBar.beginEx(tabBarBb, flags or TabBarFlag._IsFocused)
}
/** only call EndTabBar() if BeginTabBar() returns true! */
fun endTabBar() {
val window = g.currentWindow!!
if (window.skipItems) return
val tabBar = g.currentTabBar ?: error("Mismatched BeginTabBar()/EndTabBar()!")
// Fallback in case no TabItem have been submitted
if (tabBar.wantLayout)
tabBar.layout()
// Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
val tabBarAppearing = tabBar.prevFrameVisible + 1 < g.frameCount
if (tabBar.visibleTabWasSubmitted || tabBar.visibleTabId == 0 || tabBarAppearing) {
tabBar.currTabsContentsHeight = (window.dc.cursorPos.y - tabBar.barRect.max.y) max tabBar.currTabsContentsHeight
window.dc.cursorPos.y = tabBar.barRect.max.y + tabBar.currTabsContentsHeight
}
else
window.dc.cursorPos.y = tabBar.barRect.max.y + tabBar.prevTabsContentsHeight
if (tabBar.beginCount > 1)
window.dc.cursorPos put tabBar.backupCursorPos
if (tabBar.flags hasnt TabBarFlag._DockNode) popID()
g.currentTabBarStack.pop()
g.currentTabBar = g.currentTabBarStack.lastOrNull()?.tabBar
}
/** create a Tab. Returns true if the Tab is selected. */
fun beginTabItem(label: String, pOpen: BooleanArray, index: Int, flags: TabItemFlags = 0) =
withBoolean(pOpen, index) { beginTabItem(label, it, flags) }
/** create a Tab. Returns true if the Tab is selected. */
fun beginTabItem(label: String, pOpen: KMutableProperty0<Boolean>? = null, flags: TabItemFlags = 0): Boolean {
val window = g.currentWindow!!
if (window.skipItems) return false
val tabBar = g.currentTabBar ?: error("Needs to be called between BeginTabBar() and EndTabBar()!")
assert(flags hasnt TabItemFlag._Button) { "BeginTabItem() Can't be used with button flags, use TabItemButton() instead!" }
return tabBar.tabItemEx(label, pOpen, flags).also {
if (it && flags hasnt TabItemFlag.NoPushId) {
val tab = tabBar.tabs[tabBar.lastTabItemIdx]
pushOverrideID(tab.id) // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
}
}
}
/** only call EndTabItem() if BeginTabItem() returns true! */
fun endTabItem() {
val window = g.currentWindow!!
if (window.skipItems) return
val tabBar = g.currentTabBar ?: error("Needs to be called between BeginTabBar() and EndTabBar()!")
assert(tabBar.lastTabItemIdx >= 0)
val tab = tabBar.tabs[tabBar.lastTabItemIdx]
if (tab.flags hasnt TabItemFlag.NoPushId)
popID()
}
/** create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. */
fun tabItemButton(label: String, flags: TabItemFlags = TabItemFlag.None.i): Boolean {
val window = g.currentWindow!!
if (window.skipItems)
return false
val tabBar = g.currentTabBar ?: error("Needs to be called between BeginTabBar() and EndTabBar()!")
return tabBar.tabItemEx(label, null, flags or TabItemFlag._Button or TabItemFlag.NoReorder)
}
/** notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars).
* For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.
*
* [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
* To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar().
* Tabs closed by the close button will automatically be flagged to avoid this issue. */
fun setTabItemClosed(tabOrDockedWindowLabel: String) {
val isWithinManualTabBar = g.currentTabBar?.flags?.hasnt(TabBarFlag._DockNode) == true
if (isWithinManualTabBar) {
val tabBar = g.currentTabBar!!
val tabId = tabBar calcTabID tabOrDockedWindowLabel
tabBar.findTabByID(tabId)?.let {
it.wantClose = true // Will be processed by next call to TabBarLayout()
}
}
}
// comfortable util
val PtrOrIndex.tabBar: TabBar?
get() = ptr ?: g.tabBars[index]
}
|
mit
|
245e089777b2b6ae1e90046304600bfb
| 41.574803 | 163 | 0.666297 | 4.019331 | false | false | false | false |
nlgcoin/guldencoin-official
|
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/ui/monitor/PeerListFragment.kt
|
2
|
3244
|
// Copyright (c) 2018 The Gulden developers
// Authored by: Willem de Jonge ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
package com.gulden.unity_wallet.ui.monitor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.gulden.jniunifiedbackend.ILibraryController
import com.gulden.jniunifiedbackend.IP2pNetworkController
import com.gulden.unity_wallet.R
import com.gulden.unity_wallet.UnityCore
import com.gulden.unity_wallet.util.AppBaseFragment
import kotlinx.android.synthetic.main.peer_list_fragment.*
import kotlinx.android.synthetic.main.peer_list_fragment.view.*
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
class PeerListFragment : AppBaseFragment(), CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob()
private var peerUpdateJob: Job? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val adapter = PeerListAdapter()
adapter.setHasStableIds(true)
val viewModel = ViewModelProviders.of(this).get(PeerListViewModel::class.java)
// observe peer changes
viewModel.getPeers().observe(this, Observer { peers ->
if (peers.isEmpty()) {
peer_list_group.displayedChild = 1
} else {
peer_list_group.displayedChild = 2
adapter.submitList(peers)
}
})
// periodically update peers
peerUpdateJob = launch(Dispatchers.Main) {
try {
UnityCore.instance.walletReady.await()
while (isActive) {
val peers = withContext(Dispatchers.IO) {
IP2pNetworkController.getPeerInfo()
}
viewModel.setPeers(peers)
delay(3000)
}
}
catch (e: Throwable) {
// silently ignore walletReady failure (deferred was cancelled or completed with exception)
}
}
val view = inflater.inflate(R.layout.peer_list_fragment, container, false)
view.peer_list.let { recycler ->
recycler.layoutManager = LinearLayoutManager(context)
recycler.adapter = adapter
recycler.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
// Turn off item animation as it causes annoying flicker every time we do an update (every 3000ms)
recycler.itemAnimator = null
// Turn off scroll bar fading as otherwise the scroll bar annoyingly keeps appearing and re-appearing when we do an update (every 3000ms)
recycler.isScrollbarFadingEnabled = false
}
return view
}
override fun onDestroy() {
super.onDestroy()
peerUpdateJob?.cancel()
}
}
|
mit
|
0a77c9ff08fe48178fdde165b50cc4a0
| 36.287356 | 149 | 0.669544 | 5.006173 | false | false | false | false |
dhis2/dhis2-android-sdk
|
core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/ProgramIndicatorEvaluatorHelper.kt
|
1
|
18506
|
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator
import java.util.*
import org.hisp.dhis.android.core.analytics.AnalyticsException
import org.hisp.dhis.android.core.analytics.aggregated.Dimension
import org.hisp.dhis.android.core.analytics.aggregated.DimensionItem
import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem
import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.helpers.DateUtils
import org.hisp.dhis.android.core.common.AggregationType
import org.hisp.dhis.android.core.common.AnalyticsType
import org.hisp.dhis.android.core.enrollment.EnrollmentTableInfo
import org.hisp.dhis.android.core.event.EventTableInfo
import org.hisp.dhis.android.core.program.*
import org.hisp.dhis.android.core.program.programindicatorengine.internal.AnalyticsBoundaryParser
import org.hisp.dhis.android.core.program.programindicatorengine.internal.AnalyticsBoundaryTarget
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.enrollment
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.event
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo
@Suppress("TooManyFunctions")
internal object ProgramIndicatorEvaluatorHelper {
fun getProgramIndicator(
evaluationItem: AnalyticsServiceEvaluationItem,
metadata: Map<String, MetadataItem>
): ProgramIndicator {
val programIndicatorItem = evaluationItem.allDimensionItems
.find { it is DimensionItem.DataItem.ProgramIndicatorItem }
?: throw AnalyticsException.InvalidArguments("Invalid arguments: no program indicator dimension provided.")
return (metadata[programIndicatorItem.id] as MetadataItem.ProgramIndicatorItem).item
}
private fun hasDefaultBoundaries(programIndicator: ProgramIndicator): Boolean {
return programIndicator.analyticsPeriodBoundaries()?.let { boundaries ->
boundaries.size == 2 &&
(
hasDefaultTargetBoundaries(
programIndicator,
AnalyticsType.EVENT,
BoundaryTargetType.EventDate
) ||
hasDefaultTargetBoundaries(
programIndicator,
AnalyticsType.ENROLLMENT,
BoundaryTargetType.EnrollmentDate
)
)
} ?: false
}
private fun hasDefaultTargetBoundaries(
programIndicator: ProgramIndicator,
type: AnalyticsType,
targetType: BoundaryTargetType
): Boolean {
val hasTargetTypeAndNoOffset = programIndicator.analyticsPeriodBoundaries()!!.all {
it.boundaryTargetType() == targetType &&
(it.offsetPeriods() == null || it.offsetPeriods() == 0 || it.offsetPeriodType() == null)
}
val hasStartBoundary =
programIndicator.analyticsPeriodBoundaries()!!.any {
it.analyticsPeriodBoundaryType() == AnalyticsPeriodBoundaryType.AFTER_START_OF_REPORTING_PERIOD
}
val hasEndBoundary =
programIndicator.analyticsPeriodBoundaries()!!.any {
it.analyticsPeriodBoundaryType() == AnalyticsPeriodBoundaryType.BEFORE_END_OF_REPORTING_PERIOD
}
return programIndicator.analyticsType() == type &&
hasTargetTypeAndNoOffset &&
hasStartBoundary &&
hasEndBoundary
}
fun getEventWhereClause(
programIndicator: ProgramIndicator,
evaluationItem: AnalyticsServiceEvaluationItem,
metadata: Map<String, MetadataItem>
): String {
val items = AnalyticsDimensionHelper.getItemsByDimension(evaluationItem)
return WhereClauseBuilder().apply {
appendComplexQuery(
WhereClauseBuilder().apply {
appendOrKeyNumberValue(EventTableInfo.Columns.DELETED, 0)
appendOrIsNullValue(EventTableInfo.Columns.DELETED)
}.build()
)
appendInSubQuery(
EventTableInfo.Columns.PROGRAM_STAGE,
"SELECT ${ProgramStageTableInfo.Columns.UID} " +
"FROM ${ProgramStageTableInfo.TABLE_INFO.name()} " +
"WHERE ${ProgramStageTableInfo.Columns.PROGRAM} = '${programIndicator.program()?.uid()}'"
)
items.entries.forEach { entry ->
when (entry.key) {
is Dimension.Period -> {
appendProgramIndicatorPeriodClauses(
defaultColumn = "$event.${EventTableInfo.Columns.EVENT_DATE}",
programIndicator = programIndicator,
dimensions = entry.value,
builder = this,
metadata = metadata
)
}
is Dimension.OrganisationUnit ->
AnalyticsEvaluatorHelper.appendOrgunitWhereClause(
columnName = EventTableInfo.Columns.ORGANISATION_UNIT,
items = entry.value,
builder = this,
metadata = metadata
)
is Dimension.Category ->
AnalyticsEvaluatorHelper.appendCategoryWhereClause(
attributeColumnName = EventTableInfo.Columns.ATTRIBUTE_OPTION_COMBO,
disaggregationColumnName = null,
items = entry.value,
builder = this,
metadata = metadata
)
else -> {
}
}
}
}.build()
}
fun getEnrollmentWhereClause(
programIndicator: ProgramIndicator,
evaluationItem: AnalyticsServiceEvaluationItem,
metadata: Map<String, MetadataItem>
): String {
val items = AnalyticsDimensionHelper.getItemsByDimension(evaluationItem)
return WhereClauseBuilder().apply {
appendComplexQuery(
WhereClauseBuilder().apply {
appendOrKeyNumberValue(EnrollmentTableInfo.Columns.DELETED, 0)
appendOrIsNullValue(EnrollmentTableInfo.Columns.DELETED)
}.build()
)
appendKeyStringValue(EnrollmentTableInfo.Columns.PROGRAM, programIndicator.program()?.uid())
items.entries.forEach { entry ->
when (entry.key) {
is Dimension.Period ->
appendProgramIndicatorPeriodClauses(
defaultColumn = "$enrollment.${EnrollmentTableInfo.Columns.ENROLLMENT_DATE}",
programIndicator = programIndicator,
dimensions = entry.value,
builder = this,
metadata = metadata
)
is Dimension.OrganisationUnit ->
AnalyticsEvaluatorHelper.appendOrgunitWhereClause(
columnName = EnrollmentTableInfo.Columns.ORGANISATION_UNIT,
items = entry.value,
builder = this,
metadata = metadata
)
is Dimension.Category -> TODO()
else -> {
}
}
}
}.build()
}
private fun appendProgramIndicatorPeriodClauses(
dimensions: List<DimensionItem>,
metadata: Map<String, MetadataItem>,
programIndicator: ProgramIndicator,
defaultColumn: String,
builder: WhereClauseBuilder,
) {
if (hasDefaultBoundaries(programIndicator)) {
builder.appendComplexQuery(
buildDefaultBoundariesClause(
column = defaultColumn,
dimensions = dimensions,
metadata = metadata
)
)
} else {
buildNonDefaultBoundariesClauses(programIndicator, dimensions, metadata).forEach {
builder.appendComplexQuery(it)
}
}
}
private fun buildDefaultBoundariesClause(
column: String,
dimensions: List<DimensionItem>,
metadata: Map<String, MetadataItem>
): String {
val reportingPeriods = AnalyticsEvaluatorHelper.getReportingPeriods(dimensions, metadata)
return WhereClauseBuilder().apply {
reportingPeriods.forEach { period ->
appendOrComplexQuery(
AnalyticsEvaluatorHelper.getPeriodWhereClause(
columnStart = column,
columnEnd = column,
period = period
)
)
}
}.build()
}
private fun buildNonDefaultBoundariesClauses(
programIndicator: ProgramIndicator,
dimensions: List<DimensionItem>,
metadata: Map<String, MetadataItem>
): List<String> {
val startDate: Date? = AnalyticsEvaluatorHelper.getStartDate(dimensions, metadata)
val endDate: Date? = AnalyticsEvaluatorHelper.getEndDate(dimensions, metadata)
return if (startDate != null && endDate != null) {
val boundariesByTarget = programIndicator.analyticsPeriodBoundaries()?.groupBy {
AnalyticsBoundaryParser.parseBoundaryTarget(it.boundaryTarget())
}
boundariesByTarget?.mapNotNull { (target, list) ->
target?.let {
getBoundaryTargetClauses(target, list, programIndicator, startDate, endDate)
}
}?.flatten() ?: emptyList()
} else {
emptyList()
}
}
@Suppress("LongMethod", "ComplexMethod")
private fun getBoundaryTargetClauses(
target: AnalyticsBoundaryTarget,
boundaries: List<AnalyticsPeriodBoundary>,
programIndicator: ProgramIndicator,
startDate: Date,
endDate: Date
): List<String> {
val analyticsType = programIndicator.analyticsType() ?: AnalyticsType.ENROLLMENT
return when (target) {
AnalyticsBoundaryTarget.EventDate -> {
val column = EventTableInfo.Columns.EVENT_DATE
val targetColumn = when (analyticsType) {
AnalyticsType.EVENT -> "$event.$column"
AnalyticsType.ENROLLMENT -> ProgramIndicatorSQLUtils.getEventColumnForEnrollmentWhereClause(column)
}
boundaries.map { getBoundaryCondition(targetColumn, it, startDate, endDate) }
}
AnalyticsBoundaryTarget.EnrollmentDate -> {
val column = EnrollmentTableInfo.Columns.ENROLLMENT_DATE
val targetColumn = when (analyticsType) {
AnalyticsType.EVENT -> ProgramIndicatorSQLUtils.getEnrollmentColumnForEventWhereClause(column)
AnalyticsType.ENROLLMENT -> "$enrollment.$column"
}
boundaries.map { getBoundaryCondition(targetColumn, it, startDate, endDate) }
}
AnalyticsBoundaryTarget.IncidentDate -> {
val column = EnrollmentTableInfo.Columns.INCIDENT_DATE
val targetColumn = when (analyticsType) {
AnalyticsType.EVENT -> ProgramIndicatorSQLUtils.getEnrollmentColumnForEventWhereClause(column)
AnalyticsType.ENROLLMENT -> "$enrollment.$column"
}
boundaries.map { getBoundaryCondition(targetColumn, it, startDate, endDate) }
}
is AnalyticsBoundaryTarget.Custom.DataElement -> {
val targetColumn = ProgramIndicatorSQLUtils.getTrackerDataValueWhereClause(
column = TrackedEntityDataValueTableInfo.Columns.VALUE,
programStageUid = target.programStageUid,
dataElementUid = target.dataElementUid,
programIndicator = programIndicator
)
boundaries.map { getBoundaryCondition(targetColumn, it, startDate, endDate) }
}
is AnalyticsBoundaryTarget.Custom.Attribute -> {
val targetColumn = ProgramIndicatorSQLUtils.getAttributeWhereClause(
column = TrackedEntityAttributeValueTableInfo.Columns.VALUE,
attributeUid = target.attributeUid,
programIndicator = programIndicator
)
boundaries.map { getBoundaryCondition(targetColumn, it, startDate, endDate) }
}
is AnalyticsBoundaryTarget.Custom.PSEventDate ->
when (analyticsType) {
AnalyticsType.EVENT ->
throw AnalyticsException.InvalidArguments("PS_EVENTDATE not supported for EVENT analytics")
AnalyticsType.ENROLLMENT -> {
val whereClauses = boundaries.map {
getBoundaryCondition(
column = EventTableInfo.Columns.EVENT_DATE,
boundary = it,
startDate = startDate,
endDate = endDate
)
}
val whereClause = ProgramIndicatorSQLUtils.getExistsEventForEnrollmentWhere(
programStageUid = target.programStageUid,
whereClause = WhereClauseBuilder().apply {
whereClauses.forEach { appendComplexQuery(it) }
}.build()
)
listOf(whereClause)
}
}
}
}
private fun getBoundaryCondition(
column: String,
boundary: AnalyticsPeriodBoundary,
startDate: Date,
endDate: Date
): String {
val operator = when (boundary.analyticsPeriodBoundaryType()) {
AnalyticsPeriodBoundaryType.AFTER_START_OF_REPORTING_PERIOD,
AnalyticsPeriodBoundaryType.AFTER_END_OF_REPORTING_PERIOD -> ">="
else -> "<="
}
val date = when (boundary.analyticsPeriodBoundaryType()) {
AnalyticsPeriodBoundaryType.AFTER_START_OF_REPORTING_PERIOD,
AnalyticsPeriodBoundaryType.BEFORE_START_OF_REPORTING_PERIOD -> startDate
else -> endDate
}
val dateWithOffset = if (boundary.offsetPeriods() != null && boundary.offsetPeriodType() != null) {
DateUtils.dateWithOffset(date, boundary.offsetPeriods()!!, boundary.offsetPeriodType()!!)
} else {
date
}
return "julianday($column) $operator julianday('${DateUtils.DATE_FORMAT.format(dateWithOffset)}')"
}
fun getAggregator(
evaluationItem: AnalyticsServiceEvaluationItem,
programIndicator: ProgramIndicator
): AggregationType {
val aggregationType =
if (evaluationItem.aggregationType != AggregationType.DEFAULT) {
evaluationItem.aggregationType
} else {
programIndicator.aggregationType()
}
return when (aggregationType) {
null -> AggregationType.AVERAGE
AggregationType.AVERAGE,
AggregationType.SUM,
AggregationType.COUNT,
AggregationType.MIN,
AggregationType.MAX -> aggregationType
AggregationType.AVERAGE_SUM_ORG_UNIT,
AggregationType.FIRST,
AggregationType.LAST,
AggregationType.LAST_IN_PERIOD -> AggregationType.SUM
AggregationType.FIRST_AVERAGE_ORG_UNIT,
AggregationType.LAST_AVERAGE_ORG_UNIT,
AggregationType.LAST_IN_PERIOD_AVERAGE_ORG_UNIT,
AggregationType.DEFAULT -> AggregationType.AVERAGE
AggregationType.VARIANCE,
AggregationType.STDDEV,
AggregationType.CUSTOM,
AggregationType.NONE ->
throw AnalyticsException.UnsupportedAggregationType(programIndicator.aggregationType()!!)
}
}
}
|
bsd-3-clause
|
82cadbc6c414f5078ce8df769cf8ad16
| 43.378897 | 119 | 0.605749 | 5.88239 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/ModuleImlFileEntitiesSerializer.kt
|
2
|
39406
|
// 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.ide.impl.jps.serialization
import com.intellij.diagnostic.AttachmentFactory
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.impl.ModulePath
import com.intellij.openapi.project.ExternalStorageConfigurationManager
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.util.JDOMUtil
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.io.exists
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jdom.Attribute
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.model.serialization.JpsProjectLoader
import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer
import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension.*
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.*
import org.jetbrains.jps.util.JpsPathUtil
import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity
import java.io.StringReader
import java.nio.file.Path
import java.util.*
internal const val DEPRECATED_MODULE_MANAGER_COMPONENT_NAME = "DeprecatedModuleOptionManager"
private const val MODULE_ROOT_MANAGER_COMPONENT_NAME = "NewModuleRootManager"
private const val URL_ATTRIBUTE = "url"
private val STANDARD_MODULE_OPTIONS = setOf(
"type", "external.system.id", "external.system.module.version", "external.linked.project.path", "external.linked.project.id",
"external.root.project.path", "external.system.module.group", "external.system.module.type"
)
private val MODULE_OPTIONS_TO_CHECK = setOf(
"external.system.module.version", "external.linked.project.path", "external.linked.project.id",
"external.root.project.path", "external.system.module.group", "external.system.module.type"
)
internal open class ModuleImlFileEntitiesSerializer(internal val modulePath: ModulePath,
override val fileUrl: VirtualFileUrl,
override val internalEntitySource: JpsFileEntitySource,
private val virtualFileManager: VirtualFileUrlManager,
internal val internalModuleListSerializer: JpsModuleListSerializer? = null,
internal val externalModuleListSerializer: JpsModuleListSerializer? = null,
private val externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null)
: JpsFileEntitiesSerializer<ModuleEntity> {
override val mainEntityClass: Class<ModuleEntity>
get() = ModuleEntity::class.java
protected open val skipLoadingIfFileDoesNotExist
get() = false
override fun equals(other: Any?) = other?.javaClass == javaClass && (other as ModuleImlFileEntitiesSerializer).modulePath == modulePath
override fun hashCode() = modulePath.hashCode()
override fun loadEntities(builder: MutableEntityStorage,
reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) {
val externalStorageEnabled = externalStorageConfigurationManager?.isEnabled ?: false
if (!externalStorageEnabled) {
val moduleEntity = loadModuleEntity(reader, builder, errorReporter, virtualFileManager)
if (moduleEntity != null) createFacetSerializer().loadFacetEntities(builder, moduleEntity, reader)
} else {
val externalSerializer = externalModuleListSerializer?.createSerializer(internalEntitySource, fileUrl, modulePath.group) as ModuleImlFileEntitiesSerializer?
val moduleEntity = externalSerializer?.loadModuleEntity(reader, builder, errorReporter, virtualFileManager)
?: loadModuleEntity(reader, builder, errorReporter, virtualFileManager)
if (moduleEntity != null) {
// "res" is a temporal solution to catch the root cause of https://ea.jetbrains.com/browser/ea_problems/239676
var res = true
res = res && createFacetSerializer().loadFacetEntities(builder, moduleEntity, reader)
res = res && externalSerializer?.createFacetSerializer()?.loadFacetEntities(builder, moduleEntity, reader) ?: true
if (!res) {
LOG.error(
"Facets are loaded with issues",
fileUrl.virtualFile?.let { AttachmentFactory.createAttachment(it).also { att -> att.isIncluded = true } },
externalSerializer?.fileUrl?.virtualFile?.let { AttachmentFactory.createAttachment(it).also { att -> att.isIncluded = true } },
)
}
}
}
}
private fun loadModuleEntity(reader: JpsFileContentReader,
builder: MutableEntityStorage,
errorReporter: ErrorReporter,
virtualFileManager: VirtualFileUrlManager): ModuleEntity? {
if (skipLoadingIfFileDoesNotExist && !fileUrl.toPath().exists()) return null
val moduleOptions: Map<String?, String?>
val customRootsSerializer: CustomModuleRootsSerializer?
val customDir: String?
val externalSystemOptions: Map<String?, String?>
val externalSystemId: String?
val entitySourceForModuleAndOtherEntities = try {
moduleOptions = readModuleOptions(reader)
val pair = readExternalSystemOptions(reader, moduleOptions)
externalSystemOptions = pair.first
externalSystemId = pair.second
customRootsSerializer = moduleOptions[JpsProjectLoader.CLASSPATH_ATTRIBUTE]?.let { customSerializerId ->
val serializer = CustomModuleRootsSerializer.EP_NAME.extensions().filter { it.id == customSerializerId }.findAny().orElse(null)
if (serializer == null) {
errorReporter.reportError(ProjectModelBundle.message("error.message.unknown.classpath.provider", fileUrl.fileName, customSerializerId), fileUrl)
}
return@let serializer
}
customDir = moduleOptions[JpsProjectLoader.CLASSPATH_DIR_ATTRIBUTE]
val externalSystemEntitySource = createEntitySource(externalSystemId)
val moduleEntitySource = customRootsSerializer?.createEntitySource(fileUrl, internalEntitySource, customDir, virtualFileManager)
?: externalSystemEntitySource
if (moduleEntitySource is DummyParentEntitySource)
Pair(moduleEntitySource, externalSystemEntitySource)
else
Pair(moduleEntitySource, moduleEntitySource)
}
catch (e: JDOMException) {
builder.addModuleEntity(modulePath.moduleName, listOf(ModuleDependencyItem.ModuleSourceDependency), internalEntitySource)
throw e
}
val moduleEntity = builder.addModuleEntity(modulePath.moduleName, listOf(ModuleDependencyItem.ModuleSourceDependency),
entitySourceForModuleAndOtherEntities.first)
val entitySource = entitySourceForModuleAndOtherEntities.second
val moduleGroup = modulePath.group
if (moduleGroup != null) {
builder.addModuleGroupPathEntity(moduleGroup.split('/'), moduleEntity, entitySource)
}
val moduleType = moduleOptions["type"]
if (moduleType != null) {
builder.modifyEntity(moduleEntity) {
type = moduleType
}
}
@Suppress("UNCHECKED_CAST")
val customModuleOptions =
moduleOptions.filter { (key, value) -> key != null && value != null && key !in STANDARD_MODULE_OPTIONS } as Map<String, String>
if (customModuleOptions.isNotEmpty()) {
builder.addModuleCustomImlDataEntity(null, customModuleOptions, moduleEntity, entitySource)
}
CUSTOM_MODULE_COMPONENT_SERIALIZER_EP.extensions().forEach {
it.loadComponent(builder, moduleEntity, reader, fileUrl, errorReporter, virtualFileManager)
}
// Don't forget to load external system options even if custom root serializer exist
loadExternalSystemOptions(builder, moduleEntity, reader, externalSystemOptions, externalSystemId, entitySource)
if (customRootsSerializer != null) {
customRootsSerializer.loadRoots(builder, moduleEntity, reader, customDir, fileUrl, internalModuleListSerializer, errorReporter, virtualFileManager)
}
else {
val rootManagerElement = reader.loadComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, getBaseDirPath())?.clone()
if (rootManagerElement != null) {
loadRootManager(rootManagerElement, moduleEntity, builder, virtualFileManager)
}
}
return moduleEntity
}
protected open fun getBaseDirPath(): String? = null
protected open fun readExternalSystemOptions(reader: JpsFileContentReader,
moduleOptions: Map<String?, String?>): Pair<Map<String?, String?>, String?> {
val externalSystemId = moduleOptions["external.system.id"]
?: if (moduleOptions[ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY] == true.toString()) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID
else null
return Pair(moduleOptions, externalSystemId)
}
private fun readModuleOptions(reader: JpsFileContentReader): Map<String?, String?> {
val component = reader.loadComponent(fileUrl.url, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, getBaseDirPath()) ?: return emptyMap()
return component.getChildren("option").associateBy({ it.getAttributeValue("key") },
{ it.getAttributeValue("value") })
}
protected open fun loadExternalSystemOptions(builder: MutableEntityStorage,
module: ModuleEntity,
reader: JpsFileContentReader,
externalSystemOptions: Map<String?, String?>,
externalSystemId: String?,
entitySource: EntitySource) {
if (!shouldCreateExternalSystemModuleOptions(externalSystemId, externalSystemOptions, MODULE_OPTIONS_TO_CHECK)) return
val optionsEntity = builder.getOrCreateExternalSystemModuleOptions(module, entitySource)
builder.modifyEntity(optionsEntity) {
externalSystem = externalSystemId
externalSystemModuleVersion = externalSystemOptions["external.system.module.version"]
linkedProjectPath = externalSystemOptions["external.linked.project.path"]
linkedProjectId = externalSystemOptions["external.linked.project.id"]
rootProjectPath = externalSystemOptions["external.root.project.path"]
externalSystemModuleGroup = externalSystemOptions["external.system.module.group"]
externalSystemModuleType = externalSystemOptions["external.system.module.type"]
}
}
internal fun shouldCreateExternalSystemModuleOptions(externalSystemId: String?,
externalSystemOptions: Map<String?, String?>,
moduleOptionsToCheck: Set<String>): Boolean {
if (externalSystemId != null) return true
return externalSystemOptions.any { (key, value) -> value != null && key in moduleOptionsToCheck }
}
private fun loadRootManager(rootManagerElement: Element,
moduleEntity: ModuleEntity,
builder: MutableEntityStorage,
virtualFileManager: VirtualFileUrlManager) {
val entitySource = moduleEntity.entitySource
for (contentElement in rootManagerElement.getChildrenAndDetach(CONTENT_TAG)) {
val orderOfItems = mutableListOf<VirtualFileUrl>()
val excludeRootsUrls = contentElement.getChildren(EXCLUDE_FOLDER_TAG)
.map { virtualFileManager.fromUrl(it.getAttributeValueStrict(URL_ATTRIBUTE)) }
val excludePatterns = contentElement.getChildren(EXCLUDE_PATTERN_TAG)
.map { it.getAttributeValue(EXCLUDE_PATTERN_ATTRIBUTE) }
val contentRootUrl = contentElement.getAttributeValueStrict(URL_ATTRIBUTE)
.let { virtualFileManager.fromUrl(it) }
val contentRootEntity = builder.addContentRootEntity(contentRootUrl, excludeRootsUrls, excludePatterns, moduleEntity)
for (sourceRootElement in contentElement.getChildren(SOURCE_FOLDER_TAG)) {
val url = sourceRootElement.getAttributeValueStrict(URL_ATTRIBUTE)
val isTestSource = sourceRootElement.getAttributeValue(IS_TEST_SOURCE_ATTRIBUTE)?.toBoolean() == true
val type = sourceRootElement.getAttributeValue(SOURCE_ROOT_TYPE_ATTRIBUTE)
?: (if (isTestSource) JAVA_TEST_ROOT_TYPE_ID else JAVA_SOURCE_ROOT_TYPE_ID)
val virtualFileUrl = virtualFileManager.fromUrl(url)
orderOfItems += virtualFileUrl
val sourceRoot = builder.addSourceRootEntity(contentRootEntity, virtualFileUrl,
type, entitySource)
if (type == JAVA_SOURCE_ROOT_TYPE_ID || type == JAVA_TEST_ROOT_TYPE_ID) {
builder.addJavaSourceRootEntity(sourceRoot, sourceRootElement.getAttributeValue(IS_GENERATED_ATTRIBUTE)?.toBoolean() ?: false,
sourceRootElement.getAttributeValue(PACKAGE_PREFIX_ATTRIBUTE) ?: "")
}
else if (type == JAVA_RESOURCE_ROOT_ID || type == JAVA_TEST_RESOURCE_ROOT_ID) {
builder.addJavaResourceRootEntity(sourceRoot, sourceRootElement.getAttributeValue(IS_GENERATED_ATTRIBUTE)?.toBoolean() ?: false,
sourceRootElement.getAttributeValue(RELATIVE_OUTPUT_PATH_ATTRIBUTE) ?: "")
}
else {
val elem = sourceRootElement.clone()
elem.removeAttribute(URL_ATTRIBUTE)
elem.removeAttribute(SOURCE_ROOT_TYPE_ATTRIBUTE)
if (!JDOMUtil.isEmpty(elem)) {
builder.addCustomSourceRootPropertiesEntity(sourceRoot, JDOMUtil.write(elem))
}
}
}
storeSourceRootsOrder(orderOfItems, contentRootEntity, builder)
}
fun Element.readScope(): ModuleDependencyItem.DependencyScope {
val attributeValue = getAttributeValue(SCOPE_ATTRIBUTE) ?: return ModuleDependencyItem.DependencyScope.COMPILE
return try {
ModuleDependencyItem.DependencyScope.valueOf(attributeValue)
}
catch (e: IllegalArgumentException) {
ModuleDependencyItem.DependencyScope.COMPILE
}
}
fun Element.isExported() = getAttributeValue(EXPORTED_ATTRIBUTE) != null
val moduleLibraryNames = mutableSetOf<String>()
var nextUnnamedLibraryIndex = 1
val dependencyItems = rootManagerElement.getChildrenAndDetach(ORDER_ENTRY_TAG).mapTo(ArrayList()) { dependencyElement ->
when (val orderEntryType = dependencyElement.getAttributeValue(TYPE_ATTRIBUTE)) {
SOURCE_FOLDER_TYPE -> ModuleDependencyItem.ModuleSourceDependency
JDK_TYPE -> ModuleDependencyItem.SdkDependency(dependencyElement.getAttributeValueStrict(JDK_NAME_ATTRIBUTE),
dependencyElement.getAttributeValue(JDK_TYPE_ATTRIBUTE))
INHERITED_JDK_TYPE -> ModuleDependencyItem.InheritedSdkDependency
LIBRARY_TYPE -> {
val level = dependencyElement.getAttributeValueStrict(LEVEL_ATTRIBUTE)
val parentId = LibraryNameGenerator.getLibraryTableId(level)
val libraryId = LibraryId(dependencyElement.getAttributeValueStrict(NAME_ATTRIBUTE), parentId)
ModuleDependencyItem.Exportable.LibraryDependency(libraryId, dependencyElement.isExported(), dependencyElement.readScope())
}
MODULE_LIBRARY_TYPE -> {
val libraryElement = dependencyElement.getChild(LIBRARY_TAG)!!
// TODO. Probably we want a fixed name based on hashed library roots
val nameAttributeValue = libraryElement.getAttributeValue(NAME_ATTRIBUTE)
val originalName = nameAttributeValue ?: "${LibraryNameGenerator.UNNAMED_LIBRARY_NAME_PREFIX}${nextUnnamedLibraryIndex++}"
val name = LibraryNameGenerator.generateUniqueLibraryName(originalName) { it in moduleLibraryNames }
moduleLibraryNames.add(name)
val tableId = LibraryTableId.ModuleLibraryTableId(moduleEntity.persistentId)
loadLibrary(name, libraryElement, tableId, builder, entitySource, virtualFileManager, false)
val libraryId = LibraryId(name, tableId)
ModuleDependencyItem.Exportable.LibraryDependency(libraryId, dependencyElement.isExported(), dependencyElement.readScope())
}
MODULE_TYPE -> {
val depModuleName = dependencyElement.getAttributeValueStrict(MODULE_NAME_ATTRIBUTE)
ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(depModuleName), dependencyElement.isExported(),
dependencyElement.readScope(),
dependencyElement.getAttributeValue("production-on-test") != null)
}
else -> throw JDOMException("Unexpected '$TYPE_ATTRIBUTE' attribute in '$ORDER_ENTRY_TAG' tag: $orderEntryType")
}
}
if (dependencyItems.none { it is ModuleDependencyItem.ModuleSourceDependency }) {
dependencyItems.add(ModuleDependencyItem.ModuleSourceDependency)
}
val inheritedCompilerOutput = rootManagerElement.getAttributeAndDetach(INHERIT_COMPILER_OUTPUT_ATTRIBUTE)
val languageLevel = rootManagerElement.getAttributeAndDetach(MODULE_LANGUAGE_LEVEL_ATTRIBUTE)
val excludeOutput = rootManagerElement.getChildAndDetach(EXCLUDE_OUTPUT_TAG) != null
val compilerOutput = rootManagerElement.getChildAndDetach(OUTPUT_TAG)?.getAttributeValue(URL_ATTRIBUTE)
val compilerOutputForTests = rootManagerElement.getChildAndDetach(TEST_OUTPUT_TAG)?.getAttributeValue(URL_ATTRIBUTE)
builder.addJavaModuleSettingsEntity(
inheritedCompilerOutput = inheritedCompilerOutput?.toBoolean() ?: false,
excludeOutput = excludeOutput,
compilerOutput = compilerOutput?.let { virtualFileManager.fromUrl(it) },
compilerOutputForTests = compilerOutputForTests?.let { virtualFileManager.fromUrl(it) },
languageLevelId = languageLevel,
module = moduleEntity,
source = entitySource
)
if (!JDOMUtil.isEmpty(rootManagerElement)) {
val customImlData = moduleEntity.customImlData
if (customImlData == null) {
builder.addModuleCustomImlDataEntity(
rootManagerTagCustomData = JDOMUtil.write(rootManagerElement),
customModuleOptions = emptyMap(),
module = moduleEntity,
source = entitySource
)
}
else {
builder.modifyEntity(customImlData) {
rootManagerTagCustomData = JDOMUtil.write(rootManagerElement)
}
}
}
builder.modifyEntity(moduleEntity) {
dependencies = dependencyItems
}
}
private fun Element.getChildrenAndDetach(cname: String): List<Element> {
val result = getChildren(cname).toList()
result.forEach { it.detach() }
return result
}
private fun Element.getAttributeAndDetach(name: String): String? {
val result = getAttributeValue(name)
removeAttribute(name)
return result
}
private fun Element.getChildAndDetach(cname: String): Element? =
getChild(cname)?.also { it.detach() }
override fun saveEntities(mainEntities: Collection<ModuleEntity>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
storage: EntityStorage,
writer: JpsFileContentWriter) {
val module = mainEntities.singleOrNull()
if (module != null && acceptsSource(module.entitySource)) {
saveModuleEntities(module, entities, storage, writer)
}
else {
writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, null)
writer.saveComponent(fileUrl.url, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null)
}
@Suppress("UNCHECKED_CAST")
val facets = (entities[FacetEntity::class.java] as List<FacetEntity>?)?.filter { acceptsSource(it.entitySource) } ?: emptyList()
createFacetSerializer().saveFacetEntities(facets, writer)
}
protected open fun createFacetSerializer(): FacetEntitiesSerializer {
return FacetEntitiesSerializer(fileUrl, internalEntitySource, JpsFacetSerializer.FACET_MANAGER_COMPONENT_NAME, null, false)
}
protected open fun acceptsSource(entitySource: EntitySource): Boolean {
return entitySource is JpsFileEntitySource ||
entitySource is CustomModuleEntitySource ||
entitySource is JpsFileDependentEntitySource && (entitySource as? JpsImportedEntitySource)?.storedExternally != true
}
private fun saveModuleEntities(module: ModuleEntity,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
storage: EntityStorage,
writer: JpsFileContentWriter) {
val externalSystemOptions = module.exModuleOptions
val customImlData = module.customImlData
saveModuleOptions(externalSystemOptions, module.type, customImlData, writer)
val moduleOptions = customImlData?.customModuleOptions
val customSerializerId = moduleOptions?.get(JpsProjectLoader.CLASSPATH_ATTRIBUTE)
if (customSerializerId != null) {
val serializer = CustomModuleRootsSerializer.EP_NAME.extensions().filter { it.id == customSerializerId }.findAny().orElse(null)
if (serializer != null) {
val customDir = moduleOptions[JpsProjectLoader.CLASSPATH_DIR_ATTRIBUTE]
serializer.saveRoots(module, entities, writer, customDir, fileUrl, storage, virtualFileManager)
writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, null)
}
else {
LOG.warn("Classpath storage provider $customSerializerId not found")
}
}
else {
saveRootManagerElement(module, customImlData, entities, writer)
}
CUSTOM_MODULE_COMPONENT_SERIALIZER_EP.extensions().forEach {
it.saveComponent(module, fileUrl, writer)
}
}
private fun saveRootManagerElement(module: ModuleEntity,
customImlData: ModuleCustomImlDataEntity?,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
writer: JpsFileContentWriter) {
val rootManagerElement = JDomSerializationUtil.createComponentElement(MODULE_ROOT_MANAGER_COMPONENT_NAME)
saveJavaSettings(module.javaSettings, rootManagerElement)
if (customImlData != null) {
val rootManagerTagCustomData = customImlData.rootManagerTagCustomData
if (rootManagerTagCustomData != null) {
val element = JDOMUtil.load(StringReader(rootManagerTagCustomData))
JDOMUtil.merge(rootManagerElement, element)
}
}
rootManagerElement.attributes.sortWith(knownAttributesComparator)
//todo ensure that custom data is written in proper order
val contentEntities = module.contentRoots.filter { it.entitySource == module.entitySource }.sortedBy { it.url.url }
contentEntities.forEach { contentEntry ->
val contentRootTag = Element(CONTENT_TAG)
contentRootTag.setAttribute(URL_ATTRIBUTE, contentEntry.url.url)
contentEntry.sourceRoots.sortedWith(contentEntry.getSourceRootsComparator()).forEach {
contentRootTag.addContent(saveSourceRoot(it))
}
contentEntry.excludedUrls.forEach {
contentRootTag.addContent(Element(EXCLUDE_FOLDER_TAG).setAttribute(URL_ATTRIBUTE, it.url))
}
contentEntry.excludedPatterns.forEach {
contentRootTag.addContent(Element(EXCLUDE_PATTERN_TAG).setAttribute(EXCLUDE_PATTERN_ATTRIBUTE, it))
}
rootManagerElement.addContent(contentRootTag)
}
@Suppress("UNCHECKED_CAST")
val moduleLibraries = (entities[LibraryEntity::class.java] as List<LibraryEntity>? ?: emptyList()).associateBy { it.name }
module.dependencies.forEach {
rootManagerElement.addContent(saveDependencyItem(it, moduleLibraries))
}
writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, rootManagerElement)
}
private fun createEntitySource(externalSystemId: String?): EntitySource {
if (externalSystemId == null) return internalEntitySource
return createExternalEntitySource(externalSystemId)
}
protected open fun createExternalEntitySource(externalSystemId: String): EntitySource
= JpsImportedEntitySource(internalEntitySource, externalSystemId, false)
private fun javaPluginPresent() = PluginManagerCore.getPlugin(PluginId.findId("com.intellij.java")) != null
private fun saveJavaSettings(javaSettings: JavaModuleSettingsEntity?,
rootManagerElement: Element) {
if (javaSettings == null) {
if (javaPluginPresent()) {
rootManagerElement.setAttribute(INHERIT_COMPILER_OUTPUT_ATTRIBUTE, true.toString())
rootManagerElement.addContent(Element(EXCLUDE_OUTPUT_TAG))
}
return
}
if (javaSettings.inheritedCompilerOutput) {
rootManagerElement.setAttribute(INHERIT_COMPILER_OUTPUT_ATTRIBUTE, true.toString())
}
else {
val outputUrl = javaSettings.compilerOutput?.url
if (outputUrl != null) {
rootManagerElement.addContent(Element(OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, outputUrl))
}
val testOutputUrl = javaSettings.compilerOutputForTests?.url
if (testOutputUrl != null) {
rootManagerElement.addContent(Element(TEST_OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, testOutputUrl))
}
}
if (javaSettings.excludeOutput) {
rootManagerElement.addContent(Element(EXCLUDE_OUTPUT_TAG))
}
javaSettings.languageLevelId?.let {
rootManagerElement.setAttribute(MODULE_LANGUAGE_LEVEL_ATTRIBUTE, it)
}
}
private fun saveDependencyItem(dependencyItem: ModuleDependencyItem, moduleLibraries: Map<String, LibraryEntity>)
= when (dependencyItem) {
is ModuleDependencyItem.ModuleSourceDependency -> createOrderEntryTag(SOURCE_FOLDER_TYPE).setAttribute("forTests", "false")
is ModuleDependencyItem.SdkDependency -> createOrderEntryTag(JDK_TYPE).apply {
setAttribute(JDK_NAME_ATTRIBUTE, dependencyItem.sdkName)
val sdkType = dependencyItem.sdkType
setAttribute(JDK_TYPE_ATTRIBUTE, sdkType)
}
is ModuleDependencyItem.InheritedSdkDependency -> createOrderEntryTag(INHERITED_JDK_TYPE)
is ModuleDependencyItem.Exportable.LibraryDependency -> {
val library = dependencyItem.library
if (library.tableId is LibraryTableId.ModuleLibraryTableId) {
createOrderEntryTag(MODULE_LIBRARY_TYPE).apply {
setExportedAndScopeAttributes(dependencyItem)
addContent(saveLibrary(moduleLibraries.getValue(library.name), null, false))
}
} else {
createOrderEntryTag(LIBRARY_TYPE).apply {
setExportedAndScopeAttributes(dependencyItem)
setAttribute(NAME_ATTRIBUTE, library.name)
setAttribute(LEVEL_ATTRIBUTE, library.tableId.level)
}
}
}
is ModuleDependencyItem.Exportable.ModuleDependency -> createOrderEntryTag(MODULE_TYPE).apply {
setAttribute(MODULE_NAME_ATTRIBUTE, dependencyItem.module.name)
setExportedAndScopeAttributes(dependencyItem)
if (dependencyItem.productionOnTest) {
setAttribute("production-on-test", "")
}
}
}
protected open fun saveModuleOptions(externalSystemOptions: ExternalSystemModuleOptionsEntity?,
moduleType: String?,
customImlData: ModuleCustomImlDataEntity?,
writer: JpsFileContentWriter) {
val optionsMap = TreeMap<String, String?>()
if (externalSystemOptions != null) {
if (externalSystemOptions.externalSystem == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID) {
optionsMap[ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY] = true.toString()
}
else {
optionsMap["external.system.id"] = externalSystemOptions.externalSystem
}
optionsMap["external.root.project.path"] = externalSystemOptions.rootProjectPath
optionsMap["external.linked.project.id"] = externalSystemOptions.linkedProjectId
optionsMap["external.linked.project.path"] = externalSystemOptions.linkedProjectPath
optionsMap["external.system.module.type"] = externalSystemOptions.externalSystemModuleType
optionsMap["external.system.module.group"] = externalSystemOptions.externalSystemModuleGroup
optionsMap["external.system.module.version"] = externalSystemOptions.externalSystemModuleVersion
}
optionsMap["type"] = moduleType
if (customImlData != null) {
optionsMap.putAll(customImlData.customModuleOptions)
}
val componentTag = JDomSerializationUtil.createComponentElement(DEPRECATED_MODULE_MANAGER_COMPONENT_NAME)
for ((name, value) in optionsMap) {
if (value != null) {
componentTag.addContent(Element("option").setAttribute("key", name).setAttribute("value", value))
}
}
if (componentTag.children.isNotEmpty()) {
writer.saveComponent(fileUrl.url, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, componentTag)
}
}
private fun Element.setExportedAndScopeAttributes(item: ModuleDependencyItem.Exportable) {
if (item.exported) {
setAttribute(EXPORTED_ATTRIBUTE, "")
}
if (item.scope != ModuleDependencyItem.DependencyScope.COMPILE) {
setAttribute(SCOPE_ATTRIBUTE, item.scope.name)
}
}
private fun createOrderEntryTag(type: String) = Element(ORDER_ENTRY_TAG).setAttribute(TYPE_ATTRIBUTE, type)
private fun saveSourceRoot(sourceRoot: SourceRootEntity): Element {
val sourceRootTag = Element(SOURCE_FOLDER_TAG)
sourceRootTag.setAttribute(URL_ATTRIBUTE, sourceRoot.url.url)
val rootType = sourceRoot.rootType
if (rootType !in listOf(JAVA_SOURCE_ROOT_TYPE_ID, JAVA_TEST_ROOT_TYPE_ID)) {
sourceRootTag.setAttribute(SOURCE_ROOT_TYPE_ATTRIBUTE, rootType)
}
val javaRootProperties = sourceRoot.asJavaSourceRoot()
if (javaRootProperties != null) {
sourceRootTag.setAttribute(IS_TEST_SOURCE_ATTRIBUTE, (rootType == JAVA_TEST_ROOT_TYPE_ID).toString())
val packagePrefix = javaRootProperties.packagePrefix
if (packagePrefix.isNotEmpty()) {
sourceRootTag.setAttribute(PACKAGE_PREFIX_ATTRIBUTE, packagePrefix)
}
if (javaRootProperties.generated) {
sourceRootTag.setAttribute(IS_GENERATED_ATTRIBUTE, true.toString())
}
}
val javaResourceRootProperties = sourceRoot.asJavaResourceRoot()
if (javaResourceRootProperties != null) {
val relativeOutputPath = javaResourceRootProperties.relativeOutputPath
if (relativeOutputPath.isNotEmpty()) {
sourceRootTag.setAttribute(RELATIVE_OUTPUT_PATH_ATTRIBUTE, relativeOutputPath)
}
if (javaResourceRootProperties.generated) {
sourceRootTag.setAttribute(IS_GENERATED_ATTRIBUTE, true.toString())
}
}
val customProperties = sourceRoot.asCustomSourceRoot()
if (customProperties != null) {
val element = JDOMUtil.load(StringReader(customProperties.propertiesXmlTag))
JDOMUtil.merge(sourceRootTag, element)
}
return sourceRootTag
}
override val additionalEntityTypes: List<Class<out WorkspaceEntity>>
get() = listOf(SourceRootOrderEntity::class.java)
override fun toString(): String = "ModuleImlFileEntitiesSerializer($fileUrl)"
companion object {
private val LOG = logger<ModuleImlFileEntitiesSerializer>()
// The comparator has reversed priority. So, the last entry of this list will be printed as a first attribute in the xml tag.
private val orderOfKnownAttributes = listOf(
INHERIT_COMPILER_OUTPUT_ATTRIBUTE,
MODULE_LANGUAGE_LEVEL_ATTRIBUTE,
URL_ATTRIBUTE,
"name"
)
// Reversed comparator for attributes. Unknown attributes will be pushed to the end (since they return -1 in the [indexOf]).
private val knownAttributesComparator = Comparator<Attribute> { o1, o2 ->
orderOfKnownAttributes.indexOf(o1.name).compareTo(orderOfKnownAttributes.indexOf(o2.name))
}.reversed()
private val CUSTOM_MODULE_COMPONENT_SERIALIZER_EP = ExtensionPointName.create<CustomModuleComponentSerializer>("com.intellij.workspaceModel.customModuleComponentSerializer")
}
}
internal open class ModuleListSerializerImpl(override val fileUrl: String,
private val virtualFileManager: VirtualFileUrlManager,
private val externalModuleListSerializer: JpsModuleListSerializer? = null,
private val externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null)
: JpsModuleListSerializer {
companion object {
internal fun createModuleEntitiesSerializer(fileUrl: VirtualFileUrl,
moduleGroup: String?,
source: JpsFileEntitySource,
virtualFileManager: VirtualFileUrlManager,
internalModuleListSerializer: JpsModuleListSerializer? = null,
externalModuleListSerializer: JpsModuleListSerializer? = null,
externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null) =
ModuleImlFileEntitiesSerializer(ModulePath(JpsPathUtil.urlToPath(fileUrl.url), moduleGroup),
fileUrl, source, virtualFileManager,
internalModuleListSerializer,
externalModuleListSerializer,
externalStorageConfigurationManager)
}
override val isExternalStorage: Boolean
get() = false
open val componentName: String
get() = "ProjectModuleManager"
override val entitySourceFilter: (EntitySource) -> Boolean
get() = { it is JpsFileEntitySource || it is CustomModuleEntitySource ||
it is JpsFileDependentEntitySource && (it as? JpsImportedEntitySource)?.storedExternally != true }
override fun getFileName(entity: ModuleEntity): String {
return "${entity.name}.iml"
}
override fun createSerializer(internalSource: JpsFileEntitySource, fileUrl: VirtualFileUrl, moduleGroup: String?): JpsFileEntitiesSerializer<ModuleEntity> {
return createModuleEntitiesSerializer(fileUrl, moduleGroup, internalSource, virtualFileManager, this, externalModuleListSerializer,
externalStorageConfigurationManager)
}
override fun loadFileList(reader: JpsFileContentReader, virtualFileManager: VirtualFileUrlManager): List<Pair<VirtualFileUrl, String?>> {
val moduleManagerTag = reader.loadComponent(fileUrl, componentName) ?: return emptyList()
return ModuleManagerBridgeImpl.getPathsToModuleFiles(moduleManagerTag).map {
Path.of(it.path).toVirtualFileUrl(virtualFileManager) to it.group
}
}
override fun saveEntitiesList(entities: Sequence<ModuleEntity>, writer: JpsFileContentWriter) {
val entitiesToSave = entities
.filter { entitySourceFilter(it.entitySource) }
.mapNotNullTo(ArrayList()) { module -> getSourceToSave(module)?.let { Pair(it, module) } }
.sortedBy { it.second.name }
val componentTag: Element?
if (entitiesToSave.isNotEmpty()) {
val modulesTag = Element("modules")
entitiesToSave
.forEach { (source, module) ->
val moduleTag = Element("module")
val fileUrl = getModuleFileUrl(source, module)
moduleTag.setAttribute("fileurl", fileUrl)
moduleTag.setAttribute("filepath", JpsPathUtil.urlToPath(fileUrl))
module.groupPath?.let {
moduleTag.setAttribute("group", it.path.joinToString("/"))
}
modulesTag.addContent(moduleTag)
}
componentTag = JDomSerializationUtil.createComponentElement(componentName)
componentTag.addContent(modulesTag)
}
else {
componentTag = null
}
writer.saveComponent(fileUrl, componentName, componentTag)
}
protected open fun getSourceToSave(module: ModuleEntity): JpsFileEntitySource.FileInDirectory? {
val entitySource = module.entitySource
if (entitySource is CustomModuleEntitySource) {
return entitySource.internalSource as? JpsFileEntitySource.FileInDirectory
}
if (entitySource is JpsFileDependentEntitySource) {
return entitySource.originalSource as? JpsFileEntitySource.FileInDirectory
}
return entitySource as? JpsFileEntitySource.FileInDirectory
}
override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) {
writer.saveComponent(fileUrl, JpsFacetSerializer.FACET_MANAGER_COMPONENT_NAME, null)
writer.saveComponent(fileUrl, MODULE_ROOT_MANAGER_COMPONENT_NAME, null)
writer.saveComponent(fileUrl, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null)
}
private fun getModuleFileUrl(source: JpsFileEntitySource.FileInDirectory,
module: ModuleEntity) = source.directory.url + "/" + module.name + ".iml"
override fun toString(): String = "ModuleListSerializerImpl($fileUrl)"
}
fun storeSourceRootsOrder(orderOfItems: List<VirtualFileUrl>,
contentRootEntity: ContentRootEntity,
builder: MutableEntityStorage) {
if (orderOfItems.size > 1) {
// Save the order in which sourceRoots appear in the module
val orderingEntity = contentRootEntity.sourceRootOrder
if (orderingEntity == null) {
builder.addEntity(SourceRootOrderEntity(contentRootEntity.entitySource, orderOfItems) {
this.contentRootEntity = contentRootEntity
})
}
else {
builder.modifyEntity(orderingEntity) {
orderOfSourceRoots = orderOfItems
}
}
}
}
fun ContentRootEntity.getSourceRootsComparator(): Comparator<SourceRootEntity> {
val order = (sourceRootOrder?.orderOfSourceRoots ?: emptyList()).withIndex().associateBy({ it.value }, { it.index })
return compareBy<SourceRootEntity> { order[it.url] ?: order.size }.thenBy { it.url.url }
}
|
apache-2.0
|
b4fd0d7fd2cd4aec1ece4eeca42a1f47
| 50.44517 | 177 | 0.706923 | 5.718473 | false | false | false | false |
zeapo/Android-Password-Store
|
app/src/main/java/com/zeapo/pwdstore/git/GitOperation.kt
|
1
|
12670
|
package com.zeapo.pwdstore.git
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.LinearLayout
import androidx.preference.PreferenceManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.KeyPair
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.UserPreference
import com.zeapo.pwdstore.git.config.GitConfigSessionFactory
import com.zeapo.pwdstore.git.config.SshApiSessionFactory
import com.zeapo.pwdstore.git.config.SshConfigSessionFactory
import com.zeapo.pwdstore.utils.PasswordRepository
import org.eclipse.jgit.api.GitCommand
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.transport.SshSessionFactory
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider
import java.io.File
/**
* Creates a new git operation
*
* @param fileDir the git working tree directory
* @param callingActivity the calling activity
*/
abstract class GitOperation(fileDir: File, internal val callingActivity: Activity) {
protected val repository: Repository? = PasswordRepository.getRepository(fileDir)
internal var provider: UsernamePasswordCredentialsProvider? = null
internal var command: GitCommand<*>? = null
/**
* Sets the authentication using user/pwd scheme
*
* @param username the username
* @param password the password
* @return the current object
*/
internal open fun setAuthentication(username: String, password: String): GitOperation {
SshSessionFactory.setInstance(GitConfigSessionFactory())
this.provider = UsernamePasswordCredentialsProvider(username, password)
return this
}
/**
* Sets the authentication using ssh-key scheme
*
* @param sshKey the ssh-key file
* @param username the username
* @param passphrase the passphrase
* @return the current object
*/
internal open fun setAuthentication(sshKey: File, username: String, passphrase: String): GitOperation {
val sessionFactory = SshConfigSessionFactory(sshKey.absolutePath, username, passphrase)
SshSessionFactory.setInstance(sessionFactory)
this.provider = null
return this
}
/**
* Sets the authentication using OpenKeystore scheme
*
* @param identity The identiy to use
* @return the current object
*/
private fun setAuthentication(username: String, identity: SshApiSessionFactory.ApiIdentity?): GitOperation {
SshSessionFactory.setInstance(SshApiSessionFactory(username, identity))
this.provider = null
return this
}
/**
* Executes the GitCommand in an async task
*/
abstract fun execute()
/**
* Executes the GitCommand in an async task after creating the authentication
*
* @param connectionMode the server-connection mode
* @param username the username
* @param sshKey the ssh-key file to use in ssh-key connection mode
* @param identity the api identity to use for auth in OpenKeychain connection mode
*/
fun executeAfterAuthentication(connectionMode: String,
username: String,
sshKey: File?,
identity: SshApiSessionFactory.ApiIdentity?) {
executeAfterAuthentication(connectionMode, username, sshKey, identity, false)
}
/**
* Executes the GitCommand in an async task after creating the authentication
*
* @param connectionMode the server-connection mode
* @param username the username
* @param sshKey the ssh-key file to use in ssh-key connection mode
* @param identity the api identity to use for auth in OpenKeychain connection mode
* @param showError show the passphrase edit text in red
*/
private fun executeAfterAuthentication(connectionMode: String,
username: String,
sshKey: File?,
identity: SshApiSessionFactory.ApiIdentity?,
showError: Boolean) {
if (connectionMode.equals("ssh-key", ignoreCase = true)) {
if (sshKey == null || !sshKey.exists()) {
MaterialAlertDialogBuilder(callingActivity)
.setMessage(callingActivity.resources.getString(R.string.ssh_preferences_dialog_text))
.setTitle(callingActivity.resources.getString(R.string.ssh_preferences_dialog_title))
.setPositiveButton(callingActivity.resources.getString(R.string.ssh_preferences_dialog_import)) { _, _ ->
try {
// Ask the UserPreference to provide us with the ssh-key
// onResult has to be handled by the callingActivity
val intent = Intent(callingActivity.applicationContext, UserPreference::class.java)
intent.putExtra("operation", "get_ssh_key")
callingActivity.startActivityForResult(intent, GET_SSH_KEY_FROM_CLONE)
} catch (e: Exception) {
println("Exception caught :(")
e.printStackTrace()
}
}
.setNegativeButton(callingActivity.resources.getString(R.string.ssh_preferences_dialog_generate)) { _, _ ->
try {
// Duplicated code
val intent = Intent(callingActivity.applicationContext, UserPreference::class.java)
intent.putExtra("operation", "make_ssh_key")
callingActivity.startActivityForResult(intent, GET_SSH_KEY_FROM_CLONE)
} catch (e: Exception) {
println("Exception caught :(")
e.printStackTrace()
}
}
.setNeutralButton(callingActivity.resources.getString(R.string.dialog_cancel)) { _, _ ->
// Finish the blank GitActivity so user doesn't have to press back
callingActivity.finish()
}.show()
} else {
val layoutInflater = LayoutInflater.from(callingActivity.applicationContext)
@SuppressLint("InflateParams") val dialogView = layoutInflater.inflate(R.layout.git_passphrase_layout, null)
val passphrase = dialogView.findViewById<EditText>(R.id.sshkey_passphrase)
val settings = PreferenceManager.getDefaultSharedPreferences(callingActivity.applicationContext)
val sshKeyPassphrase = settings.getString("ssh_key_passphrase", null)
if (showError) {
passphrase.error = "Wrong passphrase"
}
val jsch = JSch()
try {
val keyPair = KeyPair.load(jsch, callingActivity.filesDir.toString() + "/.ssh_key")
if (keyPair.isEncrypted) {
if (sshKeyPassphrase != null && sshKeyPassphrase.isNotEmpty()) {
if (keyPair.decrypt(sshKeyPassphrase)) {
// Authenticate using the ssh-key and then execute the command
setAuthentication(sshKey, username, sshKeyPassphrase).execute()
} else {
// call back the method
executeAfterAuthentication(connectionMode, username, sshKey, identity, true)
}
} else {
MaterialAlertDialogBuilder(callingActivity)
.setTitle(callingActivity.resources.getString(R.string.passphrase_dialog_title))
.setMessage(callingActivity.resources.getString(R.string.passphrase_dialog_text))
.setView(dialogView)
.setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ ->
if (keyPair.decrypt(passphrase.text.toString())) {
val rememberPassphrase = (dialogView.findViewById<View>(R.id.sshkey_remember_passphrase) as CheckBox).isChecked
if (rememberPassphrase) {
settings.edit().putString("ssh_key_passphrase", passphrase.text.toString()).apply()
}
// Authenticate using the ssh-key and then execute the command
setAuthentication(sshKey, username, passphrase.text.toString()).execute()
} else {
settings.edit().putString("ssh_key_passphrase", null).apply()
// call back the method
executeAfterAuthentication(connectionMode, username, sshKey, identity, true)
}
}.setNegativeButton(callingActivity.resources.getString(R.string.dialog_cancel)) { _, _ ->
// Do nothing.
}.show()
}
} else {
setAuthentication(sshKey, username, "").execute()
}
} catch (e: JSchException) {
e.printStackTrace()
MaterialAlertDialogBuilder(callingActivity)
.setTitle("Unable to open the ssh-key")
.setMessage("Please check that it was imported.")
.setPositiveButton("Ok") { _, _ -> callingActivity.finish() }
.show()
}
}
} else if (connectionMode.equals("OpenKeychain", ignoreCase = true)) {
setAuthentication(username, identity).execute()
} else {
val password = EditText(callingActivity)
password.hint = "Password"
password.width = LinearLayout.LayoutParams.MATCH_PARENT
password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
MaterialAlertDialogBuilder(callingActivity)
.setTitle(callingActivity.resources.getString(R.string.passphrase_dialog_title))
.setMessage(callingActivity.resources.getString(R.string.password_dialog_text))
.setView(password)
.setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ ->
// authenticate using the user/pwd and then execute the command
setAuthentication(username, password.text.toString()).execute()
}
.setNegativeButton(callingActivity.resources.getString(R.string.dialog_cancel)) { _, _ ->
callingActivity.finish()
}
.show()
}
}
/**
* Action to execute on error
*/
open fun onError(errorMessage: String) {
MaterialAlertDialogBuilder(callingActivity)
.setTitle(callingActivity.resources.getString(R.string.jgit_error_dialog_title))
.setMessage(callingActivity.resources.getString(R.string.jgit_error_dialog_text) + errorMessage)
.setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ ->
callingActivity.setResult(Activity.RESULT_CANCELED)
callingActivity.finish()
}
.show()
}
/**
* Action to execute on success
*/
open fun onSuccess() {}
companion object {
const val GET_SSH_KEY_FROM_CLONE = 201
}
}
|
gpl-3.0
|
303a78312af8535422529c316dd4f725
| 49.68 | 155 | 0.568508 | 5.686715 | false | false | false | false |
securityfirst/Umbrella_android
|
app/src/main/java/org/secfirst/umbrella/data/database/lesson/LessonDao.kt
|
1
|
3052
|
package org.secfirst.umbrella.data.database.lesson
import com.raizlabs.android.dbflow.sql.language.SQLite
import kotlinx.coroutines.withContext
import org.secfirst.umbrella.data.database.difficulty.Difficulty
import org.secfirst.umbrella.data.database.difficulty.DifficultyPreferred
import org.secfirst.umbrella.data.database.difficulty.DifficultyPreferred_Table
import org.secfirst.umbrella.data.database.difficulty.Difficulty_Table
import org.secfirst.umbrella.data.database.segment.Markdown
import org.secfirst.umbrella.data.database.segment.Markdown_Table
import org.secfirst.umbrella.misc.AppExecutors.Companion.ioContext
interface LessonDao {
suspend fun getAllLesson(): List<Module> = withContext(ioContext) {
val modules = SQLite.select()
.from(ModuleModelView::class.java)
.orderBy(ModuleModelView_ViewTable.index, true)
.queryList()
val subjects = SQLite.select()
.from(SubjectModelView::class.java)
.where(SubjectModelView_ViewTable.module_id.`in`(modules.map { it.id }))
.orderBy(SubjectModelView_ViewTable.index, true)
.queryList()
val markdowns = SQLite.select()
.from(Markdown::class.java)
.where(Markdown_Table.module_id.`in`(modules.map { it.id }))
.orderBy(Markdown_Table.index, true)
.queryList()
modules.map {
it.toModule().apply {
this.subjects = subjects.filter { it.module_id == this.id }.map { it.toSubject() }.toMutableList()
this.markdowns = markdowns.filter { it.module!!.id == this.id }.toMutableList()
}
}
}
suspend fun getDifficultyBySubject(subjectId: String): List<Difficulty> = withContext(ioContext) {
SQLite.select()
.from(Difficulty::class.java)
.where(Difficulty_Table.subject_id.`is`(subjectId))
.queryList()
}
suspend fun getMarkdownBySubject(subjectId: String): List<Markdown> = withContext(ioContext) {
SQLite.select()
.from(Markdown::class.java)
.where(Markdown_Table.subject_id.`is`(subjectId))
.queryList()
}
suspend fun getDifficultyPreferred(subjectId: String): DifficultyPreferred? = withContext(ioContext) {
SQLite.select()
.from(DifficultyPreferred::class.java)
.where(DifficultyPreferred_Table.subjectId.`is`(subjectId))
.querySingle()
}
suspend fun getLessonBy(moduleId: String): Module? = withContext(ioContext) {
SQLite.select()
.from(Module::class.java)
.where(Module_Table.id.`is`(moduleId))
.querySingle()
}
suspend fun getFavoriteMarkdown(): List<Markdown> = withContext(ioContext) {
SQLite.select()
.from(Markdown::class.java)
.where(Markdown_Table.favorite.`is`(true))
.queryList()
}
}
|
gpl-3.0
|
0959d23018d1921376f9ddf3a19af36b
| 41.402778 | 114 | 0.631717 | 4.455474 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/dialog/DlgDateTime.kt
|
1
|
3197
|
package jp.juggler.subwaytooter.dialog
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.DatePicker
import android.widget.TimePicker
import jp.juggler.subwaytooter.R
import jp.juggler.util.dismissSafe
import java.util.*
class DlgDateTime(
val activity: Activity,
) : DatePicker.OnDateChangedListener, View.OnClickListener {
private lateinit var datePicker: DatePicker
private lateinit var timePicker: TimePicker
private lateinit var btnCancel: Button
private lateinit var btnOk: Button
private lateinit var dialog: Dialog
private lateinit var callback: (Long) -> Unit
@SuppressLint("InflateParams")
fun open(initialValue: Long, callback: (Long) -> Unit) {
this.callback = callback
val view = activity.layoutInflater.inflate(R.layout.dlg_date_time, null, false)
datePicker = view.findViewById(R.id.datePicker)
timePicker = view.findViewById(R.id.timePicker)
btnCancel = view.findViewById(R.id.btnCancel)
btnOk = view.findViewById(R.id.btnOk)
val c = GregorianCalendar.getInstance(TimeZone.getDefault())
c.timeInMillis = when (initialValue) {
0L -> System.currentTimeMillis() + 10 * 60000L
else -> initialValue
}
datePicker.firstDayOfWeek = Calendar.MONDAY
datePicker.init(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH),
this
)
timePicker.hour = c.get(Calendar.HOUR_OF_DAY)
timePicker.minute = c.get(Calendar.MINUTE)
timePicker.setIs24HourView(
when (Settings.System.getString(activity.contentResolver, Settings.System.TIME_12_24)) {
"12" -> false
else -> true
}
)
btnCancel.setOnClickListener(this)
btnOk.setOnClickListener(this)
dialog = Dialog(activity)
dialog.setContentView(view)
dialog.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
dialog.show()
}
override fun onClick(v: View) {
when (v.id) {
R.id.btnCancel -> dialog.cancel()
R.id.btnOk -> {
dialog.dismissSafe()
callback(getTime())
}
}
}
override fun onDateChanged(
view: DatePicker,
year: Int,
monthOfYear: Int,
dayOfMonth: Int,
) {
// nothing to do
}
private fun getTime(): Long {
val c = GregorianCalendar.getInstance(TimeZone.getDefault())
c.set(
datePicker.year,
datePicker.month,
datePicker.dayOfMonth,
timePicker.hour,
timePicker.minute,
0,
)
c.set(Calendar.MILLISECOND, 0)
return c.timeInMillis
}
}
|
apache-2.0
|
06d406a1cd4a56890112f76622dec659
| 27.878505 | 100 | 0.603065 | 4.667153 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary
|
app/src/main/java/co/smartreceipts/android/workers/EmailAssistant.kt
|
1
|
7628
|
package co.smartreceipts.android.workers
import android.content.Context
import android.content.Intent
import android.net.Uri
import co.smartreceipts.analytics.log.Logger
import co.smartreceipts.android.R
import co.smartreceipts.android.date.DateFormatter
import co.smartreceipts.android.model.Distance
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.android.model.Trip
import co.smartreceipts.android.persistence.DatabaseHelper
import co.smartreceipts.android.settings.UserPreferenceManager
import co.smartreceipts.android.settings.catalog.UserPreference
import co.smartreceipts.android.utils.IntentUtils
import co.smartreceipts.android.workers.reports.formatting.SmartReceiptsFormattableString
import co.smartreceipts.android.workers.widget.EmailResult
import co.smartreceipts.android.workers.widget.GenerationErrors
import co.smartreceipts.core.di.scopes.ApplicationScope
import com.hadisatrio.optional.Optional
import io.reactivex.Single
import io.reactivex.functions.BiFunction
import java.io.File
import java.util.*
import javax.inject.Inject
@ApplicationScope
class EmailAssistant @Inject constructor(
private val context: Context,
private val databaseHelper: DatabaseHelper,
private val preferenceManager: UserPreferenceManager,
private val attachmentFilesWriter: AttachmentFilesWriter,
private val dateFormatter: DateFormatter,
private val intentUtils: IntentUtils
) {
enum class EmailOptions(val index: Int) {
PDF_FULL(0), PDF_IMAGES_ONLY(1), CSV(2), ZIP(3), ZIP_WITH_METADATA(4);
}
companion object {
private const val DEVELOPER_EMAIL = "supp" + "or" + "t@" + "smart" + "receipts" + "." + "co"
private fun getEmailDeveloperIntent(): Intent {
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:$DEVELOPER_EMAIL")
return intent
}
@JvmStatic
fun getEmailDeveloperIntent(subject: String): Intent {
val intent = getEmailDeveloperIntent()
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
return intent
}
@JvmStatic
fun getEmailDeveloperIntent(subject: String, body: String): Intent {
val intent = getEmailDeveloperIntent(subject)
intent.putExtra(Intent.EXTRA_TEXT, body)
return intent
}
@JvmStatic
fun getEmailDeveloperIntent(context: Context, subject: String, body: String, files: List<File>): Intent {
val intent = IntentUtils().getSendIntent(context, files)
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(DEVELOPER_EMAIL))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, body)
return intent
}
}
fun emailTrip(trip: Trip, options: EnumSet<EmailOptions>): Single<EmailResult> {
if (options.isEmpty()) {
return Single.just(EmailResult.Error(GenerationErrors.ERROR_NO_SELECTION))
}
return Single.zip(
databaseHelper.receiptsTable.get(trip, true),
databaseHelper.distanceTable.get(trip, true),
BiFunction<List<Receipt>, List<Distance>, EmailResult> { receipts, distances ->
val preGenerationIssues = checkPreGenerationIssues(receipts, distances, options)
when {
preGenerationIssues.isPresent -> preGenerationIssues.get()
else -> writeReport(trip, receipts, distances, options)
}
})
}
private fun checkPreGenerationIssues(
receipts: List<Receipt>,
distances: List<Distance>,
options: EnumSet<EmailOptions>
): Optional<EmailResult.Error> {
if (receipts.isEmpty()) {
if (distances.isEmpty() || !(options.contains(EmailOptions.CSV) || options.contains(EmailOptions.PDF_FULL))) {
// Only allow report processing to continue with no receipts if we're doing a full pdf or CSV report with distances
return Optional.of(EmailResult.Error(GenerationErrors.ERROR_NO_RECEIPTS))
} else {
if ((options.contains(EmailOptions.CSV) || options.contains(EmailOptions.PDF_FULL))
&& !preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)) {
// user wants to create CSV or PDF report with just distances but this option is disabled
return Optional.of(EmailResult.Error(GenerationErrors.ERROR_DISABLED_DISTANCES))
}
}
}
return Optional.absent()
}
private fun writeReport(trip: Trip, receipts: List<Receipt>, distances: List<Distance>, options: EnumSet<EmailOptions>): EmailResult {
val writerResults = attachmentFilesWriter.write(trip, receipts, distances, options)
return when {
writerResults.didMemoryErrorOccure -> EmailResult.Error(GenerationErrors.ERROR_MEMORY)
writerResults.didPDFFailCompletely -> {
if (writerResults.didPDFFailTooManyColumns) {
EmailResult.Error(GenerationErrors.ERROR_TOO_MANY_COLUMNS)
} else {
EmailResult.Error(GenerationErrors.ERROR_PDF_GENERATION)
}
}
else -> {
val sendIntent = prepareSendAttachmentsIntent(writerResults.files.filterNotNull(), trip, receipts, distances)
EmailResult.Success(sendIntent)
}
}
}
private fun prepareSendAttachmentsIntent(
attachments: List<File>, trip: Trip, receipts: List<Receipt>, distances: List<Distance>
): Intent {
val bodyBuilder = StringBuilder()
for (attachment in attachments) {
if (attachment.length() > 5000000) { //Technically, this should be 5,242,880 but I'd rather give a warning buffer
bodyBuilder.append("\n")
bodyBuilder.append(context.getString(R.string.email_body_subject_5mb_warning, attachment.absolutePath))
}
}
Logger.info(this, "Built the following files [{}].", attachments)
var body = bodyBuilder.toString()
if (body.isNotEmpty()) {
body = "\n\n" + body
}
when {
attachments.size == 1 -> body = context.getString(R.string.report_attached).toString() + body
attachments.size > 1 -> body =
context.getString(R.string.reports_attached, Integer.toString(attachments.size)).toString() + body
}
val emailIntent: Intent = intentUtils.getSendIntent(context, attachments)
val to = preferenceManager.get(UserPreference.Email.ToAddresses).split(";".toRegex()).toTypedArray()
val cc = preferenceManager.get(UserPreference.Email.CcAddresses).split(";".toRegex()).toTypedArray()
val bcc = preferenceManager.get(UserPreference.Email.BccAddresses).split(";".toRegex()).toTypedArray()
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
emailIntent.putExtra(Intent.EXTRA_CC, cc)
emailIntent.putExtra(Intent.EXTRA_BCC, bcc)
emailIntent.putExtra(
Intent.EXTRA_SUBJECT,
SmartReceiptsFormattableString(
preferenceManager.get(UserPreference.Email.Subject), trip, preferenceManager, dateFormatter, receipts, distances
).toString()
)
emailIntent.putExtra(Intent.EXTRA_TEXT, body)
Logger.debug(this, "Built the send intent {} with extras {}.", emailIntent, emailIntent.extras)
return emailIntent
}
}
|
agpl-3.0
|
65e3563f00495711f9a1eb24b8f3c672
| 41.383333 | 138 | 0.665574 | 4.846252 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary
|
app/src/main/java/co/smartreceipts/android/identity/apis/organizations/Error.kt
|
2
|
313
|
package co.smartreceipts.android.identity.apis.organizations
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Error(
@Json(name = "has_error") val hasError: Boolean = false,
@Json(name = "errors") val errors: List<String> = emptyList()
)
|
agpl-3.0
|
2ae6691329f0d3cc842e763f7686038d
| 27.454545 | 65 | 0.747604 | 3.682353 | false | false | false | false |
paplorinc/intellij-community
|
python/src/com/jetbrains/python/lexer/PyFStringLiteralLexer.kt
|
3
|
948
|
// 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.lexer
import com.intellij.util.text.CharArrayUtil
import com.jetbrains.python.PyTokenTypes
class PyFStringLiteralLexer: PyStringLiteralLexerBase(PyTokenTypes.FSTRING_TEXT) {
override fun locateToken(start: Int): Int {
if (start >= myBufferEnd) {
return myBufferEnd
}
if (myBuffer[start] == '\\') {
return locateEscapeSequence(start)
}
else {
val nextBackslashOffset = CharArrayUtil.indexOf(myBuffer, "\\", start + 1, myBufferEnd)
return if (nextBackslashOffset >= 0) nextBackslashOffset else myBufferEnd
}
}
// TODO actually keep track of "raw" prefixes of f-strings somehow
override fun isRaw(): Boolean = false
override fun isUnicodeMode(): Boolean = true
override fun getState(): Int = myBaseLexerState
}
|
apache-2.0
|
29913bf3017b78aa8c3b7083da847b5f
| 32.857143 | 140 | 0.721519 | 4.086207 | false | false | false | false |
paplorinc/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrUnaryOperatorReference.kt
|
2
|
1603
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.references
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.*
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrUnaryExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.HardcodedGroovyMethodConstants.*
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMethodCallReferenceBase
import org.jetbrains.plugins.groovy.lang.resolve.impl.resolveImpl2
class GrUnaryOperatorReference(element: GrUnaryExpression) : GroovyMethodCallReferenceBase<GrUnaryExpression>(element) {
override fun getRangeInElement(): TextRange = element.operationToken.textRangeInParent
override val receiver: PsiType? get() = element.operand?.type
override val methodName: String get() = unaryOperatorMethodNames[element.operationTokenType]!!
override val arguments: Arguments? get() = emptyList()
override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> = resolveImpl2(incomplete)
companion object {
private val unaryOperatorMethodNames = mapOf(
T_NOT to AS_BOOLEAN,
T_PLUS to POSITIVE,
T_MINUS to NEGATIVE,
T_DEC to PREVIOUS,
T_INC to NEXT,
T_BNOT to BITWISE_NEGATE
)
}
}
|
apache-2.0
|
53ffddbc1b092f3b340e27c0fbd9b5bd
| 43.527778 | 140 | 0.797879 | 4.286096 | false | false | false | false |
georocket/georocket
|
src/main/kotlin/io/georocket/cli/SpinnerRenderer.kt
|
1
|
2127
|
package io.georocket.cli
import io.vertx.core.Vertx
import org.fusesource.jansi.Ansi
import org.jline.terminal.Terminal
import org.jline.terminal.TerminalBuilder
import java.io.Closeable
import java.io.IOException
class SpinnerRenderer(private val vertx: Vertx, private val message: String) : Closeable {
companion object {
// copied from https://github.com/sindresorhus/cli-spinners, released under
// the MIT license by Sindre Sorhus
private val frames = listOf("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
/**
* Default refresh interval in milliseconds
*/
private const val DEFAULT_INTERVAL = 75L
/**
* Slower refresh interval in milliseconds (for dumb terminals)
*/
private const val DEFAULT_INTERVAL_SLOW = 1000L
}
/**
* ID of the refresh timer
*/
private val timerId: Long
/**
* `true` if this is a dumb terminal
*/
private val dumb: Boolean = try {
TerminalBuilder.terminal().use { terminal ->
Terminal.TYPE_DUMB.equals(terminal.type, true) ||
Terminal.TYPE_DUMB_COLOR.equals(terminal.type, true)
}
} catch (e: IOException) {
true
}
/**
* The character currently being rendered
*/
private var currentFrame = 0
init {
// determine refresh interval
val interval = if (dumb) {
DEFAULT_INTERVAL_SLOW
} else {
DEFAULT_INTERVAL
}
// render once and then start periodic timer
if (dumb) {
print("$message ")
}
render()
timerId = vertx.setPeriodic(interval) { render() }
}
/**
* Dispose this renderer and do not print progress anymore
*/
override fun close() {
vertx.cancelTimer(timerId)
if (dumb) {
println()
} else {
val ansi = Ansi.ansi()
print(ansi.cursorToColumn(0).eraseLine().a("\u001B[?25h"))
}
}
private fun render() {
if (dumb) {
print(".")
} else {
val ansi = Ansi.ansi()
print(ansi.a("\u001B[?25l").cursorToColumn(0).eraseLine().a("${frames[currentFrame]} $message "))
currentFrame = (currentFrame + 1) % frames.size
}
}
}
|
apache-2.0
|
dba27ad77343eba7a1423b7124e1c7f5
| 23.218391 | 103 | 0.620313 | 3.709507 | false | false | false | false |
RuneSuite/client
|
api/src/main/java/org/runestar/client/api/util/Lists.kt
|
1
|
660
|
package org.runestar.client.api.util
import java.util.*
fun <T> MutableList<T>.addNotNull(t: T?) {
t?.let { add(it) }
}
fun <T> cascadingListOf(a: T?): List<T> {
val m1 = a ?: return emptyList()
return Collections.singletonList(m1)
}
fun <T> cascadingListOf(a: T?, b: T?): List<T> {
val m1 = a ?: return emptyList()
val m2 = b ?: return Collections.singletonList(m1)
return Arrays.asList(m1, m2)
}
fun <T> cascadingListOf(a: T?, b: T?, c: T?): List<T> {
val m1 = a ?: return emptyList()
val m2 = b ?: return Collections.singletonList(m1)
val m3 = c ?: return Arrays.asList(m1, m2)
return Arrays.asList(m1, m2, m3)
}
|
mit
|
92db7a0edcea5f7028b055ede688ba06
| 25.44 | 55 | 0.622727 | 2.79661 | false | false | false | false |
cdiamon/AutoColorist
|
app/src/main/java/com/cdiamon/autocolorist/fragments/MapsFragment.kt
|
1
|
1365
|
package com.cdiamon.autocolorist.fragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.cdiamon.autocolorist.databinding.FragmentMapsBinding
import com.cdiamon.autocolorist.maps.MapsActivity
class MapsFragment : Fragment() {
private var _binding: FragmentMapsBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
_binding = FragmentMapsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.mapsGoButton.setOnClickListener {
val intent = Intent(activity, MapsActivity::class.java)
Toast.makeText(activity, "Go to alpha maps activity", Toast.LENGTH_SHORT).show()
startActivity(intent)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
fun newInstance(): MapsFragment {
return MapsFragment()
}
}
}
|
apache-2.0
|
e153d9cfc40ea1dcf18289d72b8e4a43
| 29.333333 | 92 | 0.693773 | 4.642857 | false | false | false | false |
Atsky/haskell-idea-plugin
|
plugin/src/org/jetbrains/cabal/highlight/ErrorMessage.kt
|
1
|
351
|
package org.jetbrains.cabal.highlight
import com.intellij.psi.PsiElement
class ErrorMessage(errorPlace: PsiElement, errorText: String, errorType: String, isAfterNodeError: Boolean = false) {
val text: String = errorText
val place: PsiElement = errorPlace
val severity: String = errorType
val isAfterNode: Boolean = isAfterNodeError
}
|
apache-2.0
|
29188ae3237cc8a61c549540d651259b
| 34.2 | 117 | 0.77208 | 4.443038 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/JavaClassOnCompanionFixes.kt
|
1
|
2478
|
// 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object JavaClassOnCompanionFixes : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val expression = diagnostic.psiElement.parent as? KtDotQualifiedExpression ?: return emptyList()
val companionName = expression.receiverExpression.mainReference?.resolve()?.safeAs<KtObjectDeclaration>()?.name
?: SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.identifier
return listOf(
ReplaceWithCompanionClassJavaFix(expression, companionName),
ReplaceWithClassJavaFix(expression)
)
}
}
class ReplaceWithCompanionClassJavaFix(
expression: KtDotQualifiedExpression,
private val companionName: String
) : KotlinQuickFixAction<KtDotQualifiedExpression>(expression) {
override fun getText(): String = KotlinBundle.message("replace.with.0", "$companionName::class.java")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.replace("$0.$companionName::class.java")
}
}
class ReplaceWithClassJavaFix(
expression: KtDotQualifiedExpression
) : KotlinQuickFixAction<KtDotQualifiedExpression>(expression), LowPriorityAction {
override fun getText(): String = KotlinBundle.message("replace.with.0", "::class.java")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.replace("$0::class.java")
}
}
private fun KtDotQualifiedExpression.replace(pattern: String) {
replace(KtPsiFactory(project).createExpressionByPattern(pattern, receiverExpression))
}
|
apache-2.0
|
76e5d422fb3bcfcaf1d4887a91537256
| 42.473684 | 158 | 0.776029 | 4.916667 | false | false | false | false |
Hexworks/snap
|
src/main/kotlin/org/codetome/snap/model/rest/ResponseParamType.kt
|
1
|
1419
|
package org.codetome.snap.model.rest
enum class ResponseParamType(val text: String, val validatorFn: (value: String) -> Boolean) {
STATUS("Status", {
SUPPORTED_STATUSES.contains(it)
}),
LOCATION("Location", {
val firstPathIndex = it.indexOf(PATH_SEPARATOR)
val lastPathIndex = it.lastIndexOf(PATH_SEPARATOR)
val paramOpenIndex = it.indexOf(PARAM_OPEN_PAREN)
val paramCloseIndex = it.indexOf(PARAM_CLOSE_PAREN)
it.startsWith(PATH_SEPARATOR)
.and(lastPathIndex > firstPathIndex)
.and(paramCloseIndex > paramOpenIndex)
.and(paramOpenIndex > 0)
.and(paramCloseIndex > 0)
}),
PRODUCES("Produces", {
VALID_PRODUCES_VALUES.contains(it)
});
companion object {
private val VALID_PRODUCES_VALUES = listOf("application/json")
private val SUPPORTED_STATUSES = listOf("200", "201")
private val PATH_SEPARATOR = "/"
private val PARAM_OPEN_PAREN = "{"
private val PARAM_CLOSE_PAREN = "}"
fun fetchByText(text: String): ResponseParamType {
val enum = ResponseParamType.values().filter { it.text == text }
if (enum.isEmpty()) {
throw IllegalArgumentException("No request param type found by text: '$text'.")
} else {
return enum.first()
}
}
}
}
|
agpl-3.0
|
1b6f2106b907b0693d857cc8a9820735
| 35.410256 | 95 | 0.596195 | 4.352761 | false | false | false | false |
allotria/intellij-community
|
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab3.kt
|
2
|
14882
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.ui
import com.intellij.debugger.ui.DebuggerContentInfo
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.layout.LayoutAttractionPolicy
import com.intellij.execution.ui.layout.PlaceInGrid
import com.intellij.execution.ui.layout.impl.RunnerLayoutUiImpl
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.TabListAction
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.PersistentThreeComponentSplitter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Pair.create
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ToolWindowType
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.JBColor
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.intellij.util.Producer
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.*
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActions
import com.intellij.xdebugger.impl.frame.*
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree
import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode
import java.awt.Component
import java.awt.Container
import javax.swing.Icon
import javax.swing.LayoutFocusTraversalPolicy
import javax.swing.event.AncestorEvent
import javax.swing.event.AncestorListener
//TODO: unify with XDebugSessionTab2
class XDebugSessionTab3(
session: XDebugSessionImpl,
icon: Icon?,
environment: ExecutionEnvironment?
) : XDebugSessionTab(session, icon, environment, false) {
companion object {
private const val threadsIsVisibleKey = "threadsIsVisibleKey"
private const val debuggerContentId = "DebuggerView"
}
private val project = session.project
private var threadsIsVisible
get() = PropertiesComponent.getInstance(project).getBoolean(threadsIsVisibleKey, true)
set(value) = PropertiesComponent.getInstance(project).setValue(threadsIsVisibleKey, value, true)
private val lifetime = Disposer.newDisposable()
private val splitter = PersistentThreeComponentSplitter(false, true, "DebuggerViewTab", lifetime, project, 0.35f, 0.3f)
private val xThreadsFramesView = XFramesView(myProject)
private var variables: XVariablesView? = null
private val toolWindow get() = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.DEBUG)
private val focusTraversalPolicy = MyFocusTraversalPolicy()
init {
// value from com.intellij.execution.ui.layout.impl.GridImpl
splitter.setMinSize(48)
splitter.isFocusCycleRoot = true
splitter.isFocusTraversalPolicyProvider = true
splitter.focusTraversalPolicy = focusTraversalPolicy
session.addSessionListener(object : XDebugSessionListener {
override fun sessionStopped() {
UIUtil.invokeLaterIfNeeded {
splitter.saveProportions()
Disposer.dispose(lifetime)
}
}
})
project.messageBus.connect(lifetime).subscribe(XDebuggerManager.TOPIC, object : XDebuggerManagerListener {
override fun processStarted(debugProcess: XDebugProcess) {
UIUtil.invokeLaterIfNeeded {
if (debugProcess.session != null && debugProcess.session != session) {
splitter.saveProportions()
}
}
}
override fun currentSessionChanged(previousSession: XDebugSession?, currentSession: XDebugSession?) {
UIUtil.invokeLaterIfNeeded {
if (previousSession == session) {
splitter.saveProportions()
//xThreadsFramesView.saveUiState()
}
else if (currentSession == session)
splitter.restoreProportions()
}
}
override fun processStopped(debugProcess: XDebugProcess) {
UIUtil.invokeLaterIfNeeded {
splitter.saveProportions()
//xThreadsFramesView.saveUiState()
if (debugProcess.session == session)
Disposer.dispose(lifetime)
}
}
})
val ancestorListener = object : AncestorListener {
override fun ancestorAdded(event: AncestorEvent?) {
if (XDebuggerManager.getInstance(project).currentSession == session) {
splitter.restoreProportions()
}
}
override fun ancestorRemoved(event: AncestorEvent?) {
if (XDebuggerManager.getInstance(project).currentSession == session) {
splitter.saveProportions()
//xThreadsFramesView.saveUiState()
}
}
override fun ancestorMoved(event: AncestorEvent?) {
}
}
toolWindow?.component?.addAncestorListener(ancestorListener)
Disposer.register(lifetime, Disposable {
toolWindow?.component?.removeAncestorListener(ancestorListener)
})
var oldToolWindowType: ToolWindowType? = null
project.messageBus.connect(lifetime).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
if (oldToolWindowType == toolWindow?.type) return
setHeaderState()
oldToolWindowType = toolWindow?.type
}
})
}
override fun getWatchesContentId() = debuggerContentId
override fun getFramesContentId() = debuggerContentId
override fun addVariablesAndWatches(session: XDebugSessionImpl) {
val variablesView: XVariablesView?
val watchesView: XVariablesView?
if (isWatchesInVariables) {
variablesView = XWatchesViewImpl(session, true, true, false)
registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView)
variables = variablesView
watchesView = null
myWatchesView = variablesView
} else {
variablesView = XVariablesView(session)
registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView)
variables = variablesView
watchesView = XWatchesViewImpl(session, false, true, false)
registerView(DebuggerContentInfo.WATCHES_CONTENT, watchesView)
myWatchesView = watchesView
}
splitter.apply {
innerComponent = variablesView.panel
lastComponent = watchesView?.panel
}
UIUtil.removeScrollBorder(splitter)
splitter.revalidate()
splitter.repaint()
updateTraversalPolicy()
}
private fun updateTraversalPolicy() {
focusTraversalPolicy.components = getComponents().asSequence().toList()
}
override fun initDebuggerTab(session: XDebugSessionImpl) {
val framesView = xThreadsFramesView
registerView(DebuggerContentInfo.FRAME_CONTENT, framesView)
//framesView.setThreadsVisible(threadsIsVisible)
splitter.firstComponent = xThreadsFramesView.mainPanel
addVariablesAndWatches(session)
val name = debuggerContentId
val content = myUi.createContent(name, splitter, XDebuggerBundle.message("xdebugger.debugger.tab.title"), null, framesView.defaultFocusedComponent).apply {
isCloseable = false
}
myUi.addContent(content, 0, PlaceInGrid.left, false)
ui.defaults.initContentAttraction(debuggerContentId, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION, LayoutAttractionPolicy.FocusOnce())
toolWindow?.let {
val contentManager = it.contentManager
val listener = object : ContentManagerListener {
override fun contentAdded(event: ContentManagerEvent) {
setHeaderState()
}
override fun contentRemoved(event: ContentManagerEvent) {
setHeaderState()
}
}
contentManager.addContentManagerListener(listener)
Disposer.register(lifetime, Disposable {
contentManager.removeContentManagerListener(listener)
})
}
setHeaderState()
}
private fun getComponents(): Iterator<Component> {
return iterator {
//if (threadsIsVisible)
// yield(xThreadsFramesView.threads)
yield(xThreadsFramesView.mainPanel)
val vars = variables ?: return@iterator
yield(vars.defaultFocusedComponent)
if (!isWatchesInVariables)
yield(myWatchesView.defaultFocusedComponent)
}
}
override fun initToolbars(session: XDebugSessionImpl) {
(myUi as? RunnerLayoutUiImpl)?.setLeftToolbarVisible(false)
val toolbar = DefaultActionGroup()
toolbar.addAll(getCustomizedActionGroup(XDebuggerActions.TOOL_WINDOW_TOP_TOOLBAR_3_GROUP))
myUi.options.setTopLeftToolbar(toolbar, ActionPlaces.DEBUGGER_TOOLBAR)
myUi.options.setTitleProducer(Producer {
val icon = if (session.isStopped) session.runProfile?.icon else ExecutionUtil.getLiveIndicator(session.runProfile?.icon)
return@Producer create(icon, StringUtil.shortenTextWithEllipsis(session.sessionName, 15, 0) + ":")
})
}
private fun setHeaderState() {
toolWindow?.let { toolWindow ->
if (toolWindow !is ToolWindowEx) return@let
val singleContent = toolWindow.contentManager.contents.singleOrNull()
val headerVisible = toolWindow.isHeaderVisible
val topRightToolbar = DefaultActionGroup().apply {
if (headerVisible) return@apply
addAll(toolWindow.decorator.headerToolbar.actions.filter { it != null && it !is TabListAction })
}
myUi.options.setTopRightToolbar(topRightToolbar, ActionPlaces.DEBUGGER_TOOLBAR)
val topMiddleToolbar = DefaultActionGroup().apply {
if (singleContent == null || headerVisible) return@apply
add(object : AnAction(XDebuggerBundle.message("session.tab.close.debug.session"), null, AllIcons.Actions.Cancel) {
override fun actionPerformed(e: AnActionEvent) {
toolWindow.contentManager.removeContent(singleContent, true)
}
})
}
myUi.options.setTopMiddleToolbar(topMiddleToolbar, ActionPlaces.DEBUGGER_TOOLBAR)
toolWindow.decorator.isHeaderVisible = headerVisible
if (toolWindow.decorator.isHeaderVisible) {
toolWindow.component.border = null
toolWindow.component.invalidate()
toolWindow.component.repaint()
} else if (toolWindow.component.border == null) {
UIUtil.addBorder(toolWindow.component, JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0))
}
}
}
private val ToolWindowEx.isHeaderVisible get() = (type != ToolWindowType.DOCKED) || contentManager.contents.singleOrNull() == null
override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topLeftToolbar: DefaultActionGroup, settings: DefaultActionGroup) {
leftToolbar.apply {
val constraints = Constraints(Anchor.BEFORE, XDebuggerActions.VIEW_BREAKPOINTS)
add(object : ToggleAction() {
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (threadsIsVisible != state) {
threadsIsVisible = state
updateTraversalPolicy()
}
//xThreadsFramesView.setThreadsVisible(state)
Toggleable.setSelected(e.presentation, state)
}
override fun isSelected(e: AnActionEvent) = threadsIsVisible
override fun update(e: AnActionEvent) {
e.presentation.icon = AllIcons.Actions.SplitVertically
if (threadsIsVisible) {
e.presentation.text = XDebuggerBundle.message("session.tab.hide.threads.view")
}
else {
e.presentation.text = XDebuggerBundle.message("session.tab.show.threads.view")
}
setSelected(e, threadsIsVisible)
}
}, constraints)
add(ActionManager.getInstance().getAction(XDebuggerActions.FRAMES_TOP_TOOLBAR_GROUP), constraints)
add(Separator.getInstance(), constraints)
}
super.registerAdditionalActions(leftToolbar, settings, topLeftToolbar)
}
override fun dispose() {
Disposer.dispose(lifetime)
super.dispose()
}
class MyFocusTraversalPolicy : LayoutFocusTraversalPolicy() {
var components: List<Component> = listOf()
override fun getLastComponent(aContainer: Container?): Component {
if (components.isNotEmpty())
return components.last().prepare()
return super.getLastComponent(aContainer)
}
override fun getFirstComponent(aContainer: Container?): Component {
if (components.isNotEmpty())
return components.first().prepare()
return super.getFirstComponent(aContainer)
}
override fun getComponentAfter(aContainer: Container?, aComponent: Component?): Component {
if (aComponent == null)
return super.getComponentAfter(aContainer, aComponent)
val index = components.indexOf(aComponent)
if (index < 0 || index > components.lastIndex)
return super.getComponentAfter(aContainer, aComponent)
for (i in components.indices) {
val component = components[(index + i + 1) % components.size]
if (isEmpty(component)) continue
return component.prepare()
}
return components[index + 1].prepare()
}
override fun getComponentBefore(aContainer: Container?, aComponent: Component?): Component {
if (aComponent == null)
return super.getComponentBefore(aContainer, aComponent)
val index = components.indexOf(aComponent)
if (index < 0 || index > components.lastIndex)
return super.getComponentBefore(aContainer, aComponent)
for (i in components.indices) {
val component = components[(components.size + index - i - 1) % components.size]
if (isEmpty(component)) continue
return component.prepare()
}
return components[index - 1].prepare()
}
private fun Component.prepare(): Component {
if (this is XDebuggerTree && this.selectionCount == 0){
val child = root.children.firstOrNull() as? XDebuggerTreeNode ?: return this
selectionPath = child.path
}
return this
}
private fun isEmpty(component: Component): Boolean {
return when (component) {
is XDebuggerThreadsList -> component.isEmpty
is XDebuggerFramesList -> component.isEmpty
is XDebuggerTree -> component.isEmpty
else -> false
}
}
}
}
internal class MorePopupGroup : DefaultActionGroup(), DumbAware {
init {
isPopup = true
templatePresentation.icon = AllIcons.Actions.More
templatePresentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true)
}
}
|
apache-2.0
|
184eb863fc28b0b71136ddedad1c07bf
| 35.03632 | 159 | 0.722887 | 5.115847 | false | false | false | false |
allotria/intellij-community
|
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesInGitLogUiFactoryProvider.kt
|
3
|
1340
|
// 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 git4idea.ui.branch.dashboard
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsRoot
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.impl.CustomVcsLogUiFactoryProvider
import com.intellij.vcs.log.impl.VcsLogManager
import com.intellij.vcs.log.ui.MainVcsLogUi
import git4idea.GitVcs
class BranchesInGitLogUiFactoryProvider(private val project: Project) : CustomVcsLogUiFactoryProvider {
override fun isActive(vcsLogManager: VcsLogManager) = hasGitRoots(project, vcsLogManager)
override fun createLogUiFactory(logId: String,
vcsLogManager: VcsLogManager,
filters: VcsLogFilterCollection?): VcsLogManager.VcsLogUiFactory<out MainVcsLogUi> =
BranchesVcsLogUiFactory(vcsLogManager, logId, filters)
private fun hasGitRoots(project: Project, logManager: VcsLogManager) =
ProjectLevelVcsManager.getInstance(project).allVcsRoots.asSequence()
.filter { it.vcs?.keyInstanceMethod == GitVcs.getKey() }
.map(VcsRoot::getPath)
.toSet()
.containsAll(logManager.dataManager.roots)
}
|
apache-2.0
|
c6c096e672d83eda0d81a8b4c93e11ae
| 46.892857 | 140 | 0.768657 | 4.685315 | false | false | false | false |
DmytroTroynikov/aemtools
|
aem-intellij-core/src/main/kotlin/com/aemtools/completion/clientlib/provider/ClientlibDeclarationIncludeCompletionProvider.kt
|
1
|
4714
|
package com.aemtools.completion.clientlib.provider
import com.aemtools.common.util.findParentByType
import com.aemtools.common.util.getPsi
import com.aemtools.common.util.relativeTo
import com.aemtools.common.util.toPsiFile
import com.aemtools.lang.clientlib.CdLanguage
import com.aemtools.lang.clientlib.psi.CdBasePath
import com.aemtools.lang.clientlib.psi.CdInclude
import com.aemtools.lang.clientlib.psi.CdPsiFile
import com.aemtools.lang.util.basePathElement
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.project.DumbAware
import com.intellij.psi.PsiDirectory
import com.intellij.util.ProcessingContext
import javax.swing.Icon
/**
* @author Dmytro_Troynikov
*/
object ClientlibDeclarationIncludeCompletionProvider : CompletionProvider<CompletionParameters>(), DumbAware {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
if (result.isStopped) {
return
}
val currentElement = parameters.position.findParentByType(CdInclude::class.java)
?: return
val basePath = currentElement.basePathElement()?.include?.text
val startDir = findStartDirectory(parameters.originalFile.containingDirectory, basePath)
?: return
val rawVariants = collectRawVariants(parameters, startDir, basePath)
val file = parameters.originalFile.getPsi(CdLanguage) as? CdPsiFile
?: return
val presentVariants = extractPresentVariants(file)
val filteredVariants = rawVariants.filterNot {
presentVariants.any { present -> present.realPath == it.realPath }
}
result.addAllElements(filteredVariants.map {
LookupElementBuilder.create(it.relativePath)
.withIcon(it.icon)
})
result.stopHere()
}
private fun extractPresentVariants(cdFile: CdPsiFile): Collection<CdImport> {
val elements = cdFile.children.filter {
it is CdBasePath
|| it is CdInclude
}
val realPath: String = cdFile.containingDirectory
?.virtualFile
?.path
?: return emptyList()
val result: ArrayList<CdImport> = ArrayList()
var currentBasePath: String? = null
elements.forEach {
if (it is CdBasePath) {
currentBasePath = it.include?.text
} else if (it is CdInclude) {
if (currentBasePath == null) {
result.add(CdImport(
realPath = "$realPath/${it.text}",
relativePath = it.text
))
} else {
result.add(CdImport(
realPath = "$realPath/$currentBasePath/${it.text}",
relativePath = it.text,
basePath = currentBasePath
))
}
}
}
return result
}
private fun collectRawVariants(parameters: CompletionParameters,
startDir: PsiDirectory,
basePath: String?): List<CdImport> {
val currentFile = parameters.originalFile
fun variantsCollector(dir: PsiDirectory): List<CdImport> {
val result = ArrayList<CdImport>()
dir.files.filter {
accept(currentFile.name, it.name)
}
.forEach {
result.add(CdImport(
it.virtualFile.path,
it.virtualFile.path.relativeTo(startDir.virtualFile.path),
basePath,
it.virtualFile.toPsiFile(parameters.position.project)?.getIcon(0)
))
}
result.addAll(dir.subdirectories.flatMap(::variantsCollector))
return result
}
return variantsCollector(startDir)
}
private fun findStartDirectory(directory: PsiDirectory, basePath: String?): PsiDirectory? {
if (basePath == null) {
return directory
}
val parts = basePath.split("\\", "/")
var result: PsiDirectory? = directory
parts.forEach {
when (it) {
".." -> result = result?.parentDirectory
"." -> {
}
else -> result = result?.subdirectories?.find { subdirectory -> subdirectory.name == it }
}
}
return result
}
private fun accept(currentFileName: String, fileToCheck: String): Boolean = if (currentFileName == "js.txt") {
fileToCheck.endsWith(".js")
} else {
fileToCheck.endsWith(".css") || fileToCheck.endsWith(".less")
}
/**
* File import data class.
*/
data class CdImport(
val realPath: String,
val relativePath: String,
val basePath: String? = null,
val icon: Icon? = null)
}
|
gpl-3.0
|
36adc44c2bff7b15e016f258da0b446d
| 30.637584 | 112 | 0.666101 | 4.621569 | false | false | false | false |
fluidsonic/fluid-json
|
coding/sources-jvm/JsonDecoderCodec.kt
|
1
|
1376
|
package io.fluidsonic.json
import kotlin.reflect.*
public interface JsonDecoderCodec<Value : Any, in Context : JsonCodingContext> : JsonCodecProvider<Context> {
public val decodableType: JsonCodingType<Value>
public fun JsonDecoder<Context>.decode(valueType: JsonCodingType<Value>): Value
@Suppress("UNCHECKED_CAST")
override fun <ActualValue : Any> decoderCodecForType(decodableType: JsonCodingType<ActualValue>): JsonDecoderCodec<ActualValue, Context>? =
if (this.decodableType.satisfiesType(decodableType))
this as JsonDecoderCodec<ActualValue, Context>
else
null
override fun <ActualValue : Any> encoderCodecForClass(encodableClass: KClass<ActualValue>): JsonEncoderCodec<ActualValue, Context>? =
null
public companion object {
private fun JsonCodingType<*>.satisfiesType(requestedType: JsonCodingType<*>): Boolean {
if (isUnconstrainedUpperBoundInGenericContext) {
return true
}
if (requestedType.rawClass != rawClass) {
return false
}
val decodableArguments = arguments
val requestedArguments = requestedType.arguments
check(decodableArguments.size == requestedArguments.size)
@Suppress("LoopToCallChain")
for ((index, decodableArgument) in decodableArguments.withIndex()) {
if (!decodableArgument.satisfiesType(requestedArguments[index])) {
return false
}
}
return true
}
}
}
|
apache-2.0
|
e914b7a427ef123e3b8a0f548a3e8794
| 26.52 | 140 | 0.758721 | 4.144578 | false | false | false | false |
allotria/intellij-community
|
plugins/git4idea/src/git4idea/config/NotificationErrorNotifier.kt
|
2
|
2629
|
// 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 git4idea.config
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vcs.VcsNotifier
import git4idea.config.GitExecutableProblemsNotifier.BadGitExecutableNotification
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NotNull
internal class NotificationErrorNotifier(val project: Project) : ErrorNotifier {
override fun showError(@Nls(capitalization = Nls.Capitalization.Sentence) text: String,
@Nls(capitalization = Nls.Capitalization.Sentence) description: String?,
fixOption: ErrorNotifier.FixOption?) {
val notification = createNotification(text, description)
if (fixOption != null) {
notification.addAction(NotificationAction.createSimpleExpiring(fixOption.text) {
fixOption.fix()
})
}
GitExecutableProblemsNotifier.notify(project, notification)
}
private fun createNotification(text: String, description: String?): BadGitExecutableNotification {
return BadGitExecutableNotification(VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.displayId, null,
getErrorTitle(text, description), null, getErrorMessage(text, description),
NotificationType.ERROR, NotificationListener.UrlOpeningListener(false))
}
override fun showError(@Nls(capitalization = Nls.Capitalization.Sentence) text: String) {
GitExecutableProblemsNotifier.notify(project, createNotification(text, null))
}
override fun executeTask(@NlsContexts.ProgressTitle title: String, cancellable: Boolean, action: () -> Unit) {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, title, cancellable) {
override fun run(indicator: ProgressIndicator) {
action()
}
})
}
override fun changeProgressTitle(@NlsContexts.ProgressTitle text: String) {
ProgressManager.getInstance().progressIndicator?.text = text
}
override fun showMessage(@NlsContexts.NotificationContent text: String) {
VcsNotifier.getInstance(project).notifyInfo(null, "", text)
}
override fun hideProgress() {
}
}
|
apache-2.0
|
189e3d7b2237781b842d70baf612cf79
| 44.327586 | 140 | 0.753138 | 5.085106 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-core/jvm/test/scheduling/BlockingCoroutineDispatcherLivenessStressTest.kt
|
1
|
2072
|
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.scheduling
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import java.util.concurrent.atomic.*
import kotlin.test.*
/**
* Test that ensures implementation correctness of [LimitingDispatcher] and
* designed to stress its particular implementation details.
*/
class BlockingCoroutineDispatcherLivenessStressTest : SchedulerTestBase() {
private val concurrentWorkers = AtomicInteger(0)
@Before
fun setUp() {
// In case of starvation test will hang
idleWorkerKeepAliveNs = Long.MAX_VALUE
}
@Test
fun testAddPollRace() = runBlocking {
val limitingDispatcher = blockingDispatcher(1)
val iterations = 25_000 * stressTestMultiplier
// Stress test for specific case (race #2 from LimitingDispatcher). Shouldn't hang.
for (i in 1..iterations) {
val tasks = (1..2).map {
async(limitingDispatcher) {
try {
val currentlyExecuting = concurrentWorkers.incrementAndGet()
assertEquals(1, currentlyExecuting)
} finally {
concurrentWorkers.decrementAndGet()
}
}
}
tasks.forEach { it.await() }
}
}
@Test
fun testPingPongThreadsCount() = runBlocking {
corePoolSize = CORES_COUNT
val iterations = 100_000 * stressTestMultiplier
val completed = AtomicInteger(0)
for (i in 1..iterations) {
val tasks = (1..2).map {
async(dispatcher) {
// Useless work
concurrentWorkers.incrementAndGet()
concurrentWorkers.decrementAndGet()
completed.incrementAndGet()
}
}
tasks.forEach { it.await() }
}
assertEquals(2 * iterations, completed.get())
}
}
|
apache-2.0
|
4583c47b64a833781e860b23e06e38af
| 31.375 | 102 | 0.584459 | 5.090909 | false | true | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-debug/test/junit4/CoroutinesTimeoutDisabledTracesTest.kt
|
1
|
1420
|
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.debug.junit4
import kotlinx.coroutines.*
import org.junit.*
import org.junit.runners.model.*
class CoroutinesTimeoutDisabledTracesTest : TestBase(disableOutCheck = true) {
@Rule
@JvmField
public val validation = TestFailureValidation(
500, true, false,
TestResultSpec(
"hangingTest", expectedOutParts = listOf(
"Coroutines dump",
"Test hangingTest timed out after 500 milliseconds",
"BlockingCoroutine{Active}",
"at kotlinx.coroutines.debug.junit4.CoroutinesTimeoutDisabledTracesTest.hangForever",
"at kotlinx.coroutines.debug.junit4.CoroutinesTimeoutDisabledTracesTest.waitForHangJob"
),
notExpectedOutParts = listOf("Coroutine creation stacktrace"),
error = TestTimedOutException::class.java
)
)
private val job = GlobalScope.launch(Dispatchers.Unconfined) { hangForever() }
private suspend fun hangForever() {
suspendCancellableCoroutine<Unit> { }
expectUnreached()
}
@Test
fun hangingTest() = runBlocking<Unit> {
waitForHangJob()
expectUnreached()
}
private suspend fun waitForHangJob() {
job.join()
expectUnreached()
}
}
|
apache-2.0
|
85b8040b8004e3749cfbf46685549870
| 29.212766 | 103 | 0.652817 | 4.733333 | false | true | false | false |
jenetics/jenetics
|
buildSrc/src/main/kotlin/Env.kt
|
1
|
2368
|
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
import java.time.Year
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
/**
* Common environment values.
*/
object Env {
val NOW = ZonedDateTime.now()
val YEAR = Year.now();
val COPYRIGHT_YEAR = "2007-${YEAR}"
val DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
val BUILD_DATE = DATE_FORMAT.format(NOW)
val BUILD_JDK = System.getProperty("java.version")
val BUILD_OS_NAME = System.getProperty("os.name")
val BUILD_OS_ARCH = System.getProperty("os.arch")
val BUILD_OS_VERSION = System.getProperty("os.version")
val BUILD_BY = System.getProperty("user.name")
}
/**
* Information about the library and author.
*/
object Jenetics {
const val VERSION = "7.1.1"
const val ID = "jenetics"
const val NAME = "Jenetics"
const val GROUP = "io.jenetics"
const val AUTHOR = "Franz Wilhelmstötter"
const val EMAIL = "[email protected]"
const val URL = "https://jenetics.io"
val PROJECT_TO_MODULE = mapOf(
"jenetics" to "io.jenetics.base",
"jenetics.ext" to "io.jenetics.ext",
"jenetics.prog" to "io.jenetics.prog",
"jenetics.xml" to "io.jenetics.xml"
)
}
/**
* Environment variables for publishing to Maven Central.
*/
object Maven {
const val SNAPSHOT_URL = "https://oss.sonatype.org/content/repositories/snapshots/"
const val RELEASE_URL = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
const val SCM_URL = "https://github.com/jenetics/jenetics"
const val SCM_CONNECTION = "scm:git:https://github.com/jenetics/jenetics.git"
const val DEVELOPER_CONNECTION = "scm:git:https://github.com/jenetics/jenetics.git"
}
|
apache-2.0
|
aceb0b5622f03c08871dbb8eb9486edb
| 27.841463 | 88 | 0.720085 | 3.136605 | false | false | false | false |
chromeos/video-composition-sample
|
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/domain/entity/Settings.kt
|
1
|
1717
|
/*
* Copyright (c) 2021 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 dev.chromeos.videocompositionsample.domain.entity
import java.io.Serializable
data class Settings(
val trackList: List<Track>,
val encoderCodecType: EncoderCodecType,
val isEnableDecoderFallback: Boolean,
val isSummaryVisible: Boolean,
val isTestCaseMode: Boolean,
val isTestExportEnabled: Boolean = true,
val selectedTestCaseIds: List<Int> = listOf(),
val selectedExportCaseIds: List<Int> = listOf()
) : Serializable
data class Track(
val clip: Clip,
val effect: Effect
)
enum class Effect(val effectId: Int) {
Effect1(1),
Effect2(2),
Effect3(3),
Effect4(4);
companion object {
fun fromEffectId(value: Int): Effect? = values().find { it.effectId == value }
}
}
enum class Clip(val clipId: Int) {
Video_3840x2160_30fps(1),
Video_1080x1920_30fps(2),
Video_3840x2160_60fps(3),
Video_1920x1080_120fps(4);
companion object {
fun fromClipId(value: Int): Clip? = values().find { it.clipId == value }
}
}
enum class EncoderCodecType {
h264,
h265
}
|
apache-2.0
|
b3a3bbea5e7f337e2b0def5a7027c145
| 26.709677 | 86 | 0.676179 | 3.815556 | false | false | false | false |
exponent/exponent
|
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/splashscreen/SplashScreenModule.kt
|
2
|
2002
|
package abi42_0_0.expo.modules.splashscreen
import android.content.Context
import abi42_0_0.org.unimodules.core.ExportedModule
import abi42_0_0.org.unimodules.core.ModuleRegistry
import abi42_0_0.org.unimodules.core.Promise
import abi42_0_0.org.unimodules.core.errors.CurrentActivityNotFoundException
import abi42_0_0.org.unimodules.core.interfaces.ActivityProvider
import abi42_0_0.org.unimodules.core.interfaces.ExpoMethod
// Below import must be kept unversioned even in versioned code to provide a redirection from
// versioned code realm to unversioned code realm.
// Without this import any `SplashScreen.anyMethodName(...)` invocation on JS side ends up
// in versioned SplashScreen kotlin object that stores no information about the ExperienceActivity.
import expo.modules.splashscreen.singletons.SplashScreen
class SplashScreenModule(context: Context) : ExportedModule(context) {
companion object {
private const val NAME = "ExpoSplashScreen"
private const val ERROR_TAG = "ERR_SPLASH_SCREEN"
}
private lateinit var activityProvider: ActivityProvider
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
activityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
}
@ExpoMethod
fun preventAutoHideAsync(promise: Promise) {
val activity = activityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
SplashScreen.preventAutoHide(
activity,
{ hasEffect -> promise.resolve(hasEffect) },
{ m -> promise.reject(ERROR_TAG, m) }
)
}
@ExpoMethod
fun hideAsync(promise: Promise) {
val activity = activityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
SplashScreen.hide(
activity,
{ hasEffect -> promise.resolve(hasEffect) },
{ m -> promise.reject(ERROR_TAG, m) }
)
}
}
|
bsd-3-clause
|
4fa9880941def4b5f6830fc9ad50ed4b
| 31.819672 | 99 | 0.744256 | 4.419426 | false | false | false | false |
smmribeiro/intellij-community
|
platform/testFramework/src/com/intellij/util/io/DirectoryContentSpec.kt
|
2
|
5960
|
// 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.util.io
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.impl.*
import org.junit.rules.ErrorCollector
import java.io.File
import java.nio.file.Path
/**
* Builds a data structure specifying content (files, their content, sub-directories, archives) of a directory. It can be used to either check
* that a given directory matches this specification or to generate files in a directory accordingly to the specification.
*/
inline fun directoryContent(content: DirectoryContentBuilder.() -> Unit): DirectoryContentSpec {
val builder = DirectoryContentBuilderImpl(DirectorySpec())
builder.content()
return builder.result
}
/**
* Builds a data structure specifying content (files, their content, sub-directories, archives) of a zip file. It can be used to either check
* that a given zip file matches this specification or to generate a zip file accordingly to the specification.
*/
inline fun zipFile(content: DirectoryContentBuilder.() -> Unit): DirectoryContentSpec {
val builder = DirectoryContentBuilderImpl(ZipSpec())
builder.content()
return builder.result
}
/**
* Builds [DirectoryContentSpec] structure by an existing directory. Can be used to check that generated directory matched expected data
* from testData directory.
* @param originalDir point to an original directory located in the project sources from which [dir] was built; will be used to allow fixing
* the original files directly from 'Comparison Failure' dialog
*/
@JvmOverloads
fun directoryContentOf(dir: Path, originalDir: Path = dir): DirectoryContentSpec {
return DirectorySpec().also { fillSpecFromDirectory(it, dir, originalDir) }
}
abstract class DirectoryContentBuilder {
/**
* File with name [name] and any content
*/
abstract fun file(name: String)
abstract fun file(name: String, text: String)
abstract fun file(name: String, content: ByteArray)
inline fun dir(name: String, content: DirectoryContentBuilder.() -> Unit) {
val dirDefinition = DirectorySpec()
DirectoryContentBuilderImpl(dirDefinition).content()
addChild(name, dirDefinition)
}
inline fun zip(name: String, content: DirectoryContentBuilder.() -> Unit) {
val zipDefinition = ZipSpec()
DirectoryContentBuilderImpl(zipDefinition).content()
addChild(name, zipDefinition)
}
/**
* This method isn't supposed to be called directly, use other methods instead.
*/
abstract fun addChild(name: String, spec: DirectoryContentSpecImpl)
}
interface DirectoryContentSpec {
/**
* Generates files, directories and archives accordingly to this specification in [target] directory
*/
fun generate(target: File)
/**
* Generates files, directories and archives accordingly to this specification in a temp directory and return that directory.
*/
fun generateInTempDir(): Path
/**
* Returns specification for a directory which contain all data from this instance and data from [other]. If the both instance have
* specification for the same file, data from [other] wins.
*/
fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpec
}
/**
* Checks that contents of the given directory matches [spec].
* @param filePathFilter determines which relative paths should be checked
* @param errorCollector will be used to report all errors at once if provided, otherwise only the first error will be reported
*/
@JvmOverloads
fun File.assertMatches(spec: DirectoryContentSpec, fileTextMatcher: FileTextMatcher = FileTextMatcher.exact(),
filePathFilter: (String) -> Boolean = { true }, errorCollector: ErrorCollector? = null) {
assertContentUnderFileMatches(toPath(), spec as DirectoryContentSpecImpl, fileTextMatcher, filePathFilter, errorCollector,
expectedDataIsInSpec = true)
}
/**
* Checks that contents of the given directory matches [spec].
* @param filePathFilter determines which relative paths should be checked
* @param errorCollector will be used to report all errors at once if provided, otherwise only the first error will be reported
*/
@JvmOverloads
fun Path.assertMatches(spec: DirectoryContentSpec, fileTextMatcher: FileTextMatcher = FileTextMatcher.exact(),
filePathFilter: (String) -> Boolean = { true }, errorCollector: ErrorCollector? = null) {
assertContentUnderFileMatches(this, spec as DirectoryContentSpecImpl, fileTextMatcher, filePathFilter, errorCollector,
expectedDataIsInSpec = true)
}
/**
* Checks that contents of [path] matches this spec. The same as [Path.assertMatches], but in case of comparison failure the data
* from the spec will be shown as actual, and the data from the file will be shown as expected.
*/
@JvmOverloads
fun DirectoryContentSpec.assertIsMatchedBy(path: Path, fileTextMatcher: FileTextMatcher = FileTextMatcher.exact(),
filePathFilter: (String) -> Boolean = { true }, errorCollector: ErrorCollector? = null) {
assertContentUnderFileMatches(path, this as DirectoryContentSpecImpl, fileTextMatcher, filePathFilter, errorCollector,
expectedDataIsInSpec = false)
}
interface FileTextMatcher {
companion object {
@JvmStatic
fun ignoreBlankLines(): FileTextMatcher = FileTextMatchers.ignoreBlankLines
@JvmStatic
fun exact(): FileTextMatcher = FileTextMatchers.exact
@JvmStatic
fun ignoreLineSeparators(): FileTextMatcher = FileTextMatchers.lines
@JvmStatic
fun ignoreXmlFormatting(): FileTextMatcher = FileTextMatchers.ignoreXmlFormatting
}
fun matches(actualText: String, expectedText: String): Boolean
}
fun DirectoryContentSpec.generateInVirtualTempDir(): VirtualFile {
return LocalFileSystem.getInstance().refreshAndFindFileByNioFile(generateInTempDir())!!
}
|
apache-2.0
|
14b996676fbb319c116d026ad741868d
| 40.103448 | 158 | 0.761913 | 5.042301 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfo.kt
|
2
|
4818
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("UpdateData")
package com.intellij.openapi.updateSettings.impl
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.*
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
@Throws(IOException::class, JDOMException::class)
fun parseUpdateData(
text: String,
productCode: String = ApplicationInfo.getInstance().build.productCode,
): Product? = parseUpdateData(JDOMUtil.load(text), productCode)
fun parseUpdateData(node: Element, productCode: String = ApplicationInfo.getInstance().build.productCode): Product? =
node.getChildren("product")
.find { it.getChildren("code").any { code -> code.value.trim() == productCode } }
?.let { Product(it, productCode) }
class Product internal constructor(node: Element, private val productCode: String) {
val name: @NlsSafe String = node.getMandatoryAttributeValue("name")
val channels: List<UpdateChannel> = node.getChildren("channel").map { UpdateChannel(it, productCode) }
val disableMachineId: Boolean = node.getAttributeValue("disableMachineId", "false") == "true"
override fun toString(): String = productCode
}
class UpdateChannel internal constructor(node: Element, productCode: String) {
enum class Licensing { EAP, RELEASE; }
val id: String = node.getMandatoryAttributeValue("id")
val status: ChannelStatus = ChannelStatus.fromCode(node.getAttributeValue("status"))
val licensing: Licensing = if (node.getAttributeValue("licensing") == "eap") Licensing.EAP else Licensing.RELEASE
val evalDays: Int = node.getAttributeValue("evalDays")?.toInt() ?: 30
val url: String? = node.getAttributeValue("url")
val builds: List<BuildInfo> = node.getChildren("build").map { BuildInfo(it, productCode) }
override fun toString(): String = id
}
class BuildInfo internal constructor(node: Element, productCode: String) {
val number: BuildNumber = parseBuildNumber(node.getMandatoryAttributeValue("fullNumber", "number"), productCode)
val apiVersion: BuildNumber = node.getAttributeValue("apiVersion")?.let { BuildNumber.fromStringWithProductCode(it, number.productCode) } ?: number
val version: String = node.getAttributeValue("version") ?: ""
val message: @NlsSafe String = node.getChild("message")?.value ?: ""
val blogPost: String? = node.getChild("blogPost")?.getAttributeValue("url")
val releaseDate: Date? = parseDate(node.getAttributeValue("releaseDate"))
val target: BuildRange? = BuildRange.fromStrings(node.getAttributeValue("targetSince"), node.getAttributeValue("targetUntil"))
val patches: List<PatchInfo> = node.getChildren("patch").map(::PatchInfo)
val downloadUrl: String? = node.getChildren("button").find { it.getAttributeValue("download") != null }?.getMandatoryAttributeValue("url")
private fun parseBuildNumber(value: String, productCode: String): BuildNumber {
val buildNumber = BuildNumber.fromString(value)!!
return if (buildNumber.productCode.isNotEmpty()) buildNumber else BuildNumber(productCode, *buildNumber.components)
}
private fun parseDate(value: String?): Date? =
if (value == null) null
else try {
SimpleDateFormat("yyyyMMdd", Locale.US).parse(value) // same as the 'majorReleaseDate' in ApplicationInfo.xml
}
catch (e: ParseException) {
logger<BuildInfo>().info("invalid build release date: ${value}")
null
}
override fun toString(): String = "${number}/${version}"
}
class PatchInfo internal constructor(node: Element) {
companion object {
val OS_SUFFIX = if (SystemInfo.isWindows) "win" else if (SystemInfo.isMac) "mac" else if (SystemInfo.isUnix) "unix" else "unknown"
}
val fromBuild: BuildNumber = BuildNumber.fromString(node.getMandatoryAttributeValue("fullFrom", "from"))!!
val size: String? = node.getAttributeValue("size")
val isAvailable: Boolean = node.getAttributeValue("exclusions")?.splitToSequence(",")?.none { it.trim() == OS_SUFFIX } ?: true
}
private fun Element.getMandatoryAttributeValue(attribute: String) =
getAttributeValue(attribute) ?: throw JDOMException("${name}@${attribute} missing")
private fun Element.getMandatoryAttributeValue(attribute: String, fallback: String) =
getAttributeValue(attribute) ?: getMandatoryAttributeValue(fallback)
//<editor-fold desc="Deprecated stuff.">
@Deprecated("Please use `parseUpdateData` instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
class UpdatesInfo(node: Element) {
val product: Product? = parseUpdateData(node)
}
//</editor-fold>
|
apache-2.0
|
21b0f9863b8ca415cd5d896f01243c8d
| 47.666667 | 149 | 0.752802 | 4.469388 | false | false | false | false |
LouisCAD/Splitties
|
modules/intents/src/androidMain/kotlin/splitties/intents/PendingIntents.kt
|
1
|
2168
|
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.intents
import android.app.PendingIntent
import android.content.Intent
import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import splitties.init.appCtx
/**
* @param reqCode Can be left to default (0) if this [PendingIntent] is unique as defined from
* [Intent.filterEquals].
* @param options are ignored below API 16.
*/
fun Intent.toPendingActivity(
reqCode: Int = 0,
flags: Int = 0,
options: Bundle? = null
): PendingIntent = if (SDK_INT >= 16) {
PendingIntent.getActivity(appCtx, reqCode, this, flags, options)
} else PendingIntent.getActivity(appCtx, reqCode, this, flags)
/**
* @param reqCode Can be left to default (0) if this [PendingIntent] is unique as defined from
* [Intent.filterEquals].
* @param options are ignored below API 16.
*/
fun Array<Intent>.toPendingActivities(
reqCode: Int = 0,
flags: Int = 0,
options: Bundle? = null
): PendingIntent = if (SDK_INT >= 16) {
PendingIntent.getActivities(appCtx, reqCode, this, flags, options)
} else PendingIntent.getActivities(appCtx, reqCode, this, flags)
/**
* @param reqCode Can be left to default (0) if this [PendingIntent] is unique as defined from
* [Intent.filterEquals].
*/
fun Intent.toPendingForegroundService(
reqCode: Int = 0,
flags: Int = 0
): PendingIntent = if (SDK_INT >= 26) {
PendingIntent.getForegroundService(appCtx, reqCode, this, flags)
} else toPendingService(reqCode, flags)
/**
* @param reqCode Can be left to default (0) if this [PendingIntent] is unique as defined from
* [Intent.filterEquals].
*/
inline fun Intent.toPendingService(
reqCode: Int = 0,
flags: Int = 0
): PendingIntent = PendingIntent.getService(appCtx, reqCode, this, flags)
/**
* @param reqCode Can be left to default (0) if this [PendingIntent] is unique as defined from
* [Intent.filterEquals].
*/
inline fun Intent.toPendingBroadcast(
reqCode: Int = 0,
flags: Int = 0
): PendingIntent = PendingIntent.getBroadcast(appCtx, reqCode, this, flags)
|
apache-2.0
|
ab3f71011817836c960a29e7f24f6c65
| 31.358209 | 109 | 0.717251 | 3.693356 | false | false | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/libs/utils/extensions/SpannableExt.kt
|
1
|
1765
|
@file:JvmName("SpannableExt")
package com.kickstarter.libs.utils.extensions
import android.graphics.Color
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.text.style.BulletSpan
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import android.view.View
fun Spannable.size(size: Int) {
val span = AbsoluteSizeSpan(size)
this.setSpan(span, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun SpannableString.color() {
val span = ForegroundColorSpan(Color.BLACK)
this.setSpan(span, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun SpannableString.boldStyle() {
val span = StyleSpan(Typeface.BOLD)
this.setSpan(span, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun SpannableString.italicStyle() {
val span = StyleSpan(Typeface.ITALIC)
this.setSpan(span, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun SpannableString.linkStyle(clickCallback: () -> Unit) {
val span = UnderlineSpan()
val colorSpan = ForegroundColorSpan(Color.GREEN)
val clickableSpan = object : ClickableSpan() {
override fun onClick(view: View) {
clickCallback()
}
}
this.setSpan(span, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
this.setSpan(colorSpan, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
this.setSpan(clickableSpan, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun SpannableString.bulletStyle() {
val span = BulletSpan(30, Color.BLACK)
this.setSpan(span, 0, this.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
|
apache-2.0
|
8699303e982153ce7327db9e9b51f57b
| 32.942308 | 83 | 0.75864 | 3.904867 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt
|
1
|
5931
|
package info.nightscout.androidaps.activities
import android.os.Bundle
import android.widget.ArrayAdapter
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.defaultProfile.DefaultProfile
import info.nightscout.androidaps.databinding.ActivitySurveyBinding
import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.ActivityMonitor
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.InstanceId
import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.stats.TddCalculator
import info.nightscout.androidaps.utils.stats.TirCalculator
import javax.inject.Inject
class SurveyActivity : NoSplashAppCompatActivity() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var tddCalculator: TddCalculator
@Inject lateinit var tirCalculator: TirCalculator
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activityMonitor: ActivityMonitor
@Inject lateinit var defaultProfile: DefaultProfile
private lateinit var binding: ActivitySurveyBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySurveyBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.id.text = InstanceId.instanceId()
val profileStore = activePlugin.activeProfileInterface.profile
val profileList = profileStore?.getProfileList() ?: return
binding.spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList)
binding.tdds.text = tddCalculator.stats()
binding.tir.text = tirCalculator.stats()
binding.activity.text = activityMonitor.stats()
binding.profile.setOnClickListener {
val age = SafeParse.stringToDouble(binding.age.text.toString())
val weight = SafeParse.stringToDouble(binding.weight.text.toString())
val tdd = SafeParse.stringToDouble(binding.tdd.text.toString())
if (age < 1 || age > 120) {
ToastUtils.showToastInUiThread(this, R.string.invalidage)
return@setOnClickListener
}
if ((weight < 5 || weight > 150) && tdd == 0.0) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
if ((tdd < 5 || tdd > 150) && weight == 0.0) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
profileFunction.getProfile()?.let { runningProfile ->
defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())?.let { profile ->
ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also {
it.putLong("time", DateUtil.now())
it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal)
it.putString("customProfile", runningProfile.data.toString())
it.putString("customProfile2", profile.data.toString())
it.putString("customProfileUnits", profile.units)
it.putString("customProfileName", "Age: $age TDD: $tdd Weight: $weight")
}
}.show(supportFragmentManager, "ProfileViewDialog")
}
}
}
binding.submit.setOnClickListener {
val r = FirebaseRecord()
r.id = InstanceId.instanceId()
r.age = SafeParse.stringToInt(binding.age.text.toString())
r.weight = SafeParse.stringToInt(binding.weight.text.toString())
if (r.age < 1 || r.age > 120) {
ToastUtils.showToastInUiThread(this, R.string.invalidage)
return@setOnClickListener
}
if (r.weight < 5 || r.weight > 150) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
if (binding.spinner.selectedItem == null)
return@setOnClickListener
val profileName = binding.spinner.selectedItem.toString()
val specificProfile = profileStore.getSpecificProfile(profileName)
r.profileJson = specificProfile.toString()
val auth = FirebaseAuth.getInstance()
auth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
aapsLogger.debug(LTag.CORE, "signInAnonymously:success")
//val user = auth.currentUser // TODO: do we need this, seems unused?
val database = FirebaseDatabase.getInstance().reference
database.child("survey").child(r.id).setValue(r)
} else {
aapsLogger.error("signInAnonymously:failure", task.exception!!)
ToastUtils.showToastInUiThread(this, "Authentication failed.")
//updateUI(null)
}
// ...
}
finish()
}
}
inner class FirebaseRecord {
var id = ""
var age: Int = 0
var weight: Int = 0
var profileJson = "ghfg"
}
}
|
agpl-3.0
|
697c7f9ff99ee01926dbfb30caa4fff8
| 43.593985 | 102 | 0.636318 | 5.112931 | false | false | false | false |
cout970/Modeler
|
src/main/kotlin/com/cout970/modeler/gui/rcomponents/Root.kt
|
1
|
2331
|
package com.cout970.modeler.gui.rcomponents
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.gui.leguicomp.onCmd
import com.cout970.modeler.gui.rcomponents.left.LeftPanel
import com.cout970.modeler.gui.rcomponents.left.LeftPanelProps
import com.cout970.modeler.gui.rcomponents.popup.PopUp
import com.cout970.modeler.gui.rcomponents.popup.PopUpProps
import com.cout970.modeler.gui.rcomponents.right.RightPanel
import com.cout970.modeler.gui.rcomponents.right.RightPanelProps
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RComponent
import com.cout970.reactive.core.RProps
import com.cout970.reactive.core.RState
import com.cout970.reactive.dsl.*
import com.cout970.reactive.nodes.child
import com.cout970.reactive.nodes.div
import com.cout970.reactive.nodes.style
data class RootState(
var leftVisible: Boolean = true,
var rightVisible: Boolean = true,
var bottomVisible: Boolean = false
) : RState
data class RootProps(val gui: Gui) : RProps
class RootComp : RComponent<RootProps, RootState>() {
override fun getInitialState() = RootState()
override fun RBuilder.render() = div("Root") {
style {
transparent()
borderless()
}
postMount {
sizeX = parent.sizeX
sizeY = parent.sizeY
}
child(CenterPanel::class, CenterPanelProps(props.gui.canvasContainer, props.gui.timer))
child(LeftPanel::class, LeftPanelProps(state.leftVisible, props.gui.state,
props.gui.gridLines, props.gui.animator, props.gui.canvasContainer) { props.gui.root.reRender() })
child(RightPanel::class, RightPanelProps(state.rightVisible, props.gui.programState,
props.gui.state, props.gui.input))
child(BottomPanel::class, BottomPanelProps(state.bottomVisible, props.gui.animator,
props.gui.programState, props.gui.input))
child(TopBar::class, TopBarProps(props.gui))
child(Search::class)
child(PopUp::class, PopUpProps(props.gui.state, props.gui.propertyHolder))
onCmd("toggleLeft") { setState { copy(leftVisible = !leftVisible) } }
onCmd("toggleRight") { setState { copy(rightVisible = !rightVisible) } }
onCmd("toggleBottom") { setState { copy(bottomVisible = !bottomVisible) } }
}
}
|
gpl-3.0
|
96297649dcec29604a0b8029485a6b00
| 34.861538 | 110 | 0.720721 | 3.723642 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt
|
1
|
6292
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.highlighter.AbstractKotlinHighlightVisitor
import org.jetbrains.kotlin.idea.quickfix.CleanupFix
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.ReplaceObsoleteLabelSyntaxFix
import org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class KotlinCleanupInspection : LocalInspectionTool(), CleanupLocalInspectionTool {
// required to simplify the inspection registration in tests
override fun getDisplayName(): String = KotlinBundle.message("usage.of.redundant.or.deprecated.syntax.or.deprecated.symbols")
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? {
if (isOnTheFly || file !is KtFile || !ProjectRootsUtil.isInProjectSource(file)) {
return null
}
val analysisResult = file.analyzeWithAllCompilerChecks()
if (analysisResult.isError()) {
return null
}
val diagnostics = analysisResult.bindingContext.diagnostics
val problemDescriptors = arrayListOf<ProblemDescriptor>()
val importsToRemove = DeprecatedSymbolUsageFix.importDirectivesToBeRemoved(file)
for (import in importsToRemove) {
val removeImportFix = RemoveImportFix(import)
val problemDescriptor = createProblemDescriptor(import, removeImportFix.text, listOf(removeImportFix), file, manager)
problemDescriptors.add(problemDescriptor)
}
file.forEachDescendantOfType<PsiElement> { element ->
for (diagnostic in diagnostics.forElement(element)) {
if (diagnostic.isCleanup()) {
val fixes = diagnostic.toCleanupFixes()
if (fixes.isNotEmpty()) {
problemDescriptors.add(diagnostic.toProblemDescriptor(fixes, file, manager))
}
}
}
}
return problemDescriptors.toTypedArray()
}
private fun Diagnostic.isCleanup() = factory in cleanupDiagnosticsFactories || isObsoleteLabel()
private val cleanupDiagnosticsFactories = setOf(
Errors.MISSING_CONSTRUCTOR_KEYWORD,
Errors.UNNECESSARY_NOT_NULL_ASSERTION,
Errors.UNNECESSARY_SAFE_CALL,
Errors.USELESS_CAST,
Errors.USELESS_ELVIS,
ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION,
Errors.DEPRECATION,
Errors.DEPRECATION_ERROR,
Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION,
Errors.OPERATOR_MODIFIER_REQUIRED,
Errors.INFIX_MODIFIER_REQUIRED,
Errors.DEPRECATED_TYPE_PARAMETER_SYNTAX,
Errors.MISPLACED_TYPE_PARAMETER_CONSTRAINTS,
Errors.COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT,
ErrorsJs.WRONG_EXTERNAL_DECLARATION,
Errors.YIELD_IS_RESERVED,
Errors.DEPRECATED_MODIFIER_FOR_TARGET,
Errors.DEPRECATED_MODIFIER
)
private fun Diagnostic.isObsoleteLabel(): Boolean {
val annotationEntry = psiElement.getNonStrictParentOfType<KtAnnotationEntry>() ?: return false
return ReplaceObsoleteLabelSyntaxFix.looksLikeObsoleteLabel(annotationEntry)
}
private fun Diagnostic.toCleanupFixes(): Collection<CleanupFix> {
return AbstractKotlinHighlightVisitor.createQuickFixes(this).filterIsInstance<CleanupFix>()
}
private class Wrapper(val intention: IntentionAction, file: KtFile) : IntentionWrapper(intention, file) {
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (intention.isAvailable(
project,
editor,
file
)
) { // we should check isAvailable here because some elements may get invalidated (or other conditions may change)
super.invoke(project, editor, file)
}
}
}
private fun Diagnostic.toProblemDescriptor(fixes: Collection<CleanupFix>, file: KtFile, manager: InspectionManager): ProblemDescriptor =
createProblemDescriptor(psiElement, DefaultErrorMessages.render(this), fixes, file, manager)
private fun createProblemDescriptor(
element: PsiElement,
message: String,
fixes: Collection<CleanupFix>,
file: KtFile,
manager: InspectionManager
): ProblemDescriptor {
return manager.createProblemDescriptor(
element,
message,
false,
fixes.map { Wrapper(it, file) }.toTypedArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
private class RemoveImportFix(import: KtImportDirective) : KotlinQuickFixAction<KtImportDirective>(import), CleanupFix {
override fun getFamilyName() = KotlinBundle.message("remove.deprecated.symbol.import")
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
}
}
|
apache-2.0
|
a2b9291637832ca8d3b56d2205a4549d
| 43.309859 | 158 | 0.717578 | 5.221577 | false | false | false | false |
jwren/intellij-community
|
platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.kt
|
2
|
4571
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("HardCodedStringLiteral")
package org.jetbrains.builtInWebServer
import com.intellij.ide.browsers.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.http.HttpVirtualFile
import com.intellij.psi.PsiFile
import com.intellij.util.SmartList
import com.intellij.util.Url
import com.intellij.util.Urls
import org.jetbrains.builtInWebServer.liveReload.WebServerPageConnectionService
import org.jetbrains.ide.BuiltInServerManager
open class BuiltInWebBrowserUrlProvider : WebBrowserUrlProvider(), DumbAware {
override fun canHandleElement(request: OpenInBrowserRequest): Boolean {
if (request.virtualFile is HttpVirtualFile) {
return true
}
// we must use base language because we serve file - not part of file, but the whole file
// handlebars, for example, contains HTML and HBS psi trees, so, regardless of context, we should not handle such file
return request.isPhysicalFile() && isFileOfMyLanguage(request.file)
}
protected open fun isFileOfMyLanguage(psiFile: PsiFile): Boolean = WebBrowserXmlService.getInstance().isHtmlOrXmlFile(psiFile)
override fun getUrl(request: OpenInBrowserRequest, file: VirtualFile): Url? {
if (file is HttpVirtualFile) {
return Urls.newFromVirtualFile(file)
}
else {
return getBuiltInServerUrls(file, request.project, null, request.isAppendAccessToken, request.reloadMode).firstOrNull()
}
}
}
@JvmOverloads
fun getBuiltInServerUrls(file: VirtualFile,
project: Project,
currentAuthority: String?,
appendAccessToken: Boolean = true,
reloadMode: ReloadMode? = null): List<Url> {
if (currentAuthority != null && !compareAuthority(currentAuthority)) {
return emptyList()
}
val info = WebServerPathToFileManager.getInstance(project).getPathInfo(file) ?: return emptyList()
return getBuiltInServerUrls(info, project, currentAuthority, appendAccessToken, reloadMode)
}
fun getBuiltInServerUrls(info: PathInfo,
project: Project,
currentAuthority: String? = null,
appendAccessToken: Boolean = true,
preferredReloadMode: ReloadMode? = null): SmartList<Url> {
val effectiveBuiltInServerPort = BuiltInServerOptions.getInstance().effectiveBuiltInServerPort
val path = info.path
val authority = currentAuthority ?: "localhost:$effectiveBuiltInServerPort"
val reloadMode = preferredReloadMode ?: WebBrowserManager.getInstance().webServerReloadMode
val appendReloadOnSave = reloadMode != ReloadMode.DISABLED
val queryBuilder = StringBuilder()
if (appendAccessToken || appendReloadOnSave) queryBuilder.append('?')
if (appendAccessToken) queryBuilder.append(TOKEN_PARAM_NAME).append('=').append(acquireToken())
if (appendAccessToken && appendReloadOnSave) queryBuilder.append('&')
if (appendReloadOnSave) queryBuilder.append(WebServerPageConnectionService.RELOAD_URL_PARAM).append('=').append(reloadMode.name)
val query = queryBuilder.toString()
val urls = SmartList(Urls.newHttpUrl(authority, "/${project.name}/$path", query))
val path2 = info.rootLessPathIfPossible
if (path2 != null) {
urls.add(Urls.newHttpUrl(authority, '/' + project.name + '/' + path2, query))
}
val defaultPort = BuiltInServerManager.getInstance().port
if (currentAuthority == null && defaultPort != effectiveBuiltInServerPort) {
val defaultAuthority = "localhost:$defaultPort"
urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path", query))
if (path2 != null) {
urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path2", query))
}
}
return urls
}
fun compareAuthority(currentAuthority: String?): Boolean {
if (currentAuthority.isNullOrEmpty()) {
return false
}
val portIndex = currentAuthority!!.indexOf(':')
if (portIndex < 0) {
return false
}
val host = currentAuthority.substring(0, portIndex)
if (!isOwnHostName(host)) {
return false
}
val port = StringUtil.parseInt(currentAuthority.substring(portIndex + 1), -1)
return port == BuiltInServerOptions.getInstance().effectiveBuiltInServerPort || port == BuiltInServerManager.getInstance().port
}
|
apache-2.0
|
1f5ebc7a56e16f186f07d78bcb2c8c01
| 40.563636 | 140 | 0.731569 | 4.575576 | false | false | false | false |
jwren/intellij-community
|
java/java-features-trainer/src/com/intellij/java/ift/JavaProjectUtil.kt
|
1
|
1518
|
// 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.java.ift
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.ui.configuration.SdkLookup
import com.intellij.openapi.roots.ui.configuration.SdkLookupDecision
import com.intellij.util.lang.JavaVersion
object JavaProjectUtil {
fun findJavaSdkAsync(project: Project, onSdkSearchCompleted: (Sdk?) -> Unit) {
val javaSdkType = JavaSdk.getInstance()
SdkLookup.newLookupBuilder()
.withProject(project)
.withSdkType(javaSdkType)
.withVersionFilter {
JavaVersion.tryParse(it)?.isAtLeast(6) == true
}
.onDownloadableSdkSuggested {
onSdkSearchCompleted(null)
SdkLookupDecision.STOP
}
.onSdkResolved { sdk ->
if (sdk != null && sdk.sdkType === javaSdkType) {
onSdkSearchCompleted(sdk)
}
}
.executeLookup()
}
fun getProjectJdk(project: Project): Sdk? {
val projectJdk = ProjectRootManager.getInstance(project).projectSdk
val module = ModuleManager.getInstance(project).modules.first()
val moduleJdk = ModuleRootManager.getInstance(module).sdk
return moduleJdk ?: projectJdk
}
}
|
apache-2.0
|
da36475054684f7fd6e9d5f923dcd57a
| 36.04878 | 120 | 0.741107 | 4.4 | false | false | false | false |
JetBrains/kotlin-native
|
backend.native/tests/codegen/coroutines/controlFlow_inline2.kt
|
4
|
920
|
/*
* Copyright 2010-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 codegen.coroutines.controlFlow_inline2
import kotlin.test.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resumeWith(result: Result<Any?>) { result.getOrThrow() }
}
suspend fun s1(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
inline suspend fun inline_s2(): Int {
var x = s1()
return x
}
@Test fun runTest() {
var result = 0
builder {
result = inline_s2()
}
println(result)
}
|
apache-2.0
|
671c22da59712029e2f7b09fba456d2b
| 21.439024 | 115 | 0.696739 | 3.982684 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.