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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Qihoo360/RePlugin | replugin-sample/plugin/plugin-demo3-kotlin/app/src/main/java/com/qihoo360/replugin/sample/demo3/MainActivity.kt | 4 | 4783 | /*
* Copyright (C) 2005-2017 Qihoo 360 Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed To in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.qihoo360.replugin.sample.demo3
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.Toast
import com.qihoo360.replugin.RePlugin
import com.qihoo360.replugin.sample.demo3.activity.theme.ThemeBlackNoTitleBarActivity
import java.util.ArrayList
/**
* @author RePlugin Team
*/
class MainActivity : Activity() {
private val mItems = ArrayList<TestItem>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
initData()
val lv = findViewById(R.id.list_view) as ListView
lv.adapter = TestAdapter()
Toast.makeText(this, "Hello Kotlin ! Hello RePlugin !", Toast.LENGTH_SHORT).show()
}
private fun initData() {
// TODO UI丑是丑了点儿,但能说明问题。以后会优化的
// =========
// Activity
// =========
mItems.add(TestItem("Kotlin Activity: Theme BlackNoTitleBar", View.OnClickListener { v ->
val intent = Intent(v.context, ThemeBlackNoTitleBarActivity::class.java)
v.context.startActivity(intent)
}))
// =========
// Other Components
// =========
mItems.add(TestItem("Kotlin Broadcast: Send (to All)", View.OnClickListener { v ->
val intent = Intent()
intent.action = "com.qihoo360.repluginapp.replugin.receiver.ACTION3"
intent.putExtra("name", "jerry")
v.context.sendBroadcast(intent)
}))
// =========
// Communication
// =========
mItems.add(TestItem("Kotlin ClassLoader: Reflection (to Demo2, Recommend)", View.OnClickListener { v ->
// 这是RePlugin的推荐玩法:反射调用Demo2,这样"天然的"做好了"版本控制"
// 避免出现我们当年2013年的各种问题
val cl = RePlugin.fetchClassLoader("demo2")
if (cl == null) {
Toast.makeText(v.context, "Not install Demo2", Toast.LENGTH_SHORT).show()
return@OnClickListener
}
try {
val clz = cl.loadClass("com.qihoo360.replugin.sample.demo2.MainApp")
val m = clz.getDeclaredMethod("helloFromDemo1", Context::class.java, String::class.java)
m.invoke(null, v.context, "Demo3")
} catch (e: Exception) {
// 有可能Demo2根本没有这个类,也有可能没有相应方法(通常出现在"插件版本升级"的情况)
Toast.makeText(v.context, "", Toast.LENGTH_SHORT).show()
e.printStackTrace()
}
}))
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
if (requestCode == REQUEST_CODE_DEMO2 && resultCode == RESULT_CODE_DEMO2) {
Toast.makeText(this, data.getStringExtra("data"), Toast.LENGTH_SHORT).show()
}
}
private inner class TestAdapter : BaseAdapter() {
override fun getCount(): Int {
return mItems.size
}
override fun getItem(position: Int): TestItem {
return mItems[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
if (convertView == null) {
convertView = Button(this@MainActivity)
}
val item = getItem(position)
(convertView as Button).text = item.title
convertView.setOnClickListener(item.mClickListener)
return convertView
}
}
companion object {
private val REQUEST_CODE_DEMO2 = 0x021
private val RESULT_CODE_DEMO2 = 0x022
}
}
| apache-2.0 | 90d1502f9fa8dfc0e0327820ee4c4d41 | 30.881944 | 111 | 0.625354 | 4.188869 | false | false | false | false |
VerifAPS/verifaps-lib | ide/src/main/kotlin/edu/kit/iti/formal/automation/ide/editor.kt | 1 | 10911 | package edu.kit.iti.formal.automation.ide
import bibliothek.gui.dock.common.DefaultMultipleCDockable
import bibliothek.gui.dock.common.MultipleCDockableFactory
import bibliothek.gui.dock.common.MultipleCDockableLayout
import bibliothek.util.xml.XElement
import edu.kit.iti.formal.automation.ide.editors.IECLanguageSupport
import edu.kit.iti.formal.automation.ide.editors.SmvLanguageSupport
import edu.kit.iti.formal.automation.ide.editors.TestTableLanguageSupport
import edu.kit.iti.formal.automation.plcopenxml.IECXMLFacade
import org.fife.rsta.ui.CollapsibleSectionPanel
import org.fife.rsta.ui.search.FindToolBar
import org.fife.rsta.ui.search.ReplaceToolBar
import org.fife.ui.rsyntaxtextarea.ErrorStrip
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities
import org.fife.ui.rtextarea.Gutter
import org.fife.ui.rtextarea.RTextScrollPane
import java.awt.BorderLayout
import java.awt.Font
import java.awt.event.KeyEvent
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.JFileChooser
import javax.swing.KeyStroke
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import kotlin.properties.Delegates
interface Saveable {
fun saveAs()
fun save()
}
interface Closeable {
fun close()
}
interface HasFont {
var textFont: Font
}
data class CodeEditorData(var file: File?) : MultipleCDockableLayout {
override fun writeStream(p0: DataOutputStream) {
(file?.absolutePath ?: "").let {
p0.writeUTF(it)
}
}
override fun readXML(p0: XElement) {
file = File(p0.getAttribute("file").value)
//type = p0.getAttribute("type").value
}
override fun writeXML(p0: XElement) {
p0.getAttribute("file").value = file?.absolutePath
//p0.getAttribute("type").value = type
}
override fun readStream(p0: DataInputStream) {
file = File(p0.readUTF())
//type = p0.readUTF()
}
}
interface EditorFactory {
fun get(file: File): CodeEditor?
fun getLanguage(it: File): LanguageSupport?
fun getSupportedSuffixes(): Collection<String>
}
class EditorFactoryImpl(val lookup: Lookup,
private val factory: MultipleCDockableFactory<*, *>)
: EditorFactory {
override fun getSupportedSuffixes(): Collection<String> {
return (ttSupport.extension
+ iecSupport.extension
+ smvSupport.extension
+ NoneLanguageSupport.extension + listOf("xml")).toSet()
}
val ttSupport = TestTableLanguageSupport(lookup)
val iecSupport = IECLanguageSupport(lookup)
val smvSupport = SmvLanguageSupport(lookup)
val languageSupports = mutableListOf(
ttSupport, smvSupport, iecSupport)
val editorFactories = arrayListOf<(File) -> CodeEditor?>()
override fun getLanguage(it: File): LanguageSupport? {
for (language in languageSupports) {
for (ext in language.extension)
if (it.toString().endsWith(ext))
return language
}
return null
}
fun default(file: File): CodeEditor? {
return getLanguage(file)?.let { createCodeEditor(file, it) }
}
fun createCodeEditor(it: File, language: LanguageSupport): CodeEditor {
val codeEditor = CodeEditor(lookup, factory)
codeEditor.languageSupport = language
codeEditor.file = it
codeEditor.textArea.text = try {
it.readText()
} catch (e: Exception) {
""
}
codeEditor.dirty = false
codeEditor.textArea.foldManager.reparse()
return codeEditor
}
init {
editorFactories.add(this::default)
editorFactories.add(this::pclOpenXml)
editorFactories.add(this::fallback)
}
fun fallback(it: File): CodeEditor = createCodeEditor(it, NoneLanguageSupport)
fun pclOpenXml(it: File): CodeEditor? {
return if (it.name.endsWith("xml")) {
val stCode = IECXMLFacade.extractPLCOpenXml(it)
val f = File(it.parentFile, it.nameWithoutExtension + ".st")
f.writeText(stCode)
createCodeEditor(f, IECLanguageSupport(lookup))
} else null
}
override fun get(file: File): CodeEditor? {
for (it in editorFactories) {
val p = it(file)
if (p != null) {
return p
}
}
return null
}
}
class DockableCodeEditorFactory(var lookup: Lookup)
: MultipleCDockableFactory<CodeEditor, CodeEditorData> {
override fun write(p0: CodeEditor): CodeEditorData = CodeEditorData(p0.file)
override fun create(): CodeEditorData = CodeEditorData(File("empty"))
override fun read(p0: CodeEditorData): CodeEditor? {
return p0.file?.let {
lookup.get<EditorFactory>().get(it)
}
}
override fun match(p0: CodeEditor?, p1: CodeEditorData?): Boolean = p0?.file == p1?.file
}
class CodeEditor(val lookup: Lookup, factory: MultipleCDockableFactory<*, *>)
: DefaultMultipleCDockable(factory), Saveable, HasFont, Closeable {
private val colors: Colors by lookup.with()
var text: String
get() = textArea.text
set(value) {
textArea.text = value
}
var languageSupport by Delegates.observable<LanguageSupport>(NoneLanguageSupport) { prop, old, new ->
if (old != new) {
textArea.clearParsers()
textArea.syntaxEditingStyle = new.mimeType
(textArea.document as RSyntaxDocument).setSyntaxStyle(AntlrTokenMakerFactory(new.antlrLexerFactory))
textArea.syntaxScheme = new.syntaxScheme
textArea.addParser(new.createParser(this, lookup))
textArea.isCodeFoldingEnabled = new.isCodeFoldingEnabled
}
}
val textArea = RSyntaxTextArea(20, 60)
val viewPort = RTextScrollPane(textArea)
val gutter: Gutter = RSyntaxUtilities.getGutter(textArea)
val code: String
get() = textArea.document.getText(0, textArea.document.length)
var file: File? by Delegates.observable<File?>(null) { prop, old, new ->
titleText = title
}
var dirty: Boolean by Delegates.observable(false) { prop, old, new ->
titleText = title
}
private val DIRTY_MARKER = '*'
private val title: String
get() = (file?.name ?: "EMPTY") + (if (dirty) DIRTY_MARKER else "")
override var textFont: Font
get() = textArea.font
set(value) {
textArea.font = value
gutter.lineNumberFont = value
}
val rootPanel = CollapsibleSectionPanel()
val errorStrip = ErrorStrip(textArea)
val searchListener = DefaultSearchListener(textArea)
val findToolBar = FindToolBar(searchListener)
val replaceToolBar = ReplaceToolBar(searchListener)
val actionShowFindToolBar = rootPanel.addBottomComponent(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_DOWN_MASK), findToolBar)
val actionShowReplaceToolBar = rootPanel.addBottomComponent(KeyStroke.getKeyStroke("ctrl R"), replaceToolBar)
init {
textFont = lookup.get<Colors>().defaultFont
contentPane.layout = BorderLayout()
(textArea.document as RSyntaxDocument).setSyntaxStyle(AntlrTokenMakerFactory(languageSupport.antlrLexerFactory))
textArea.syntaxScheme = languageSupport.syntaxScheme
textArea.isCodeFoldingEnabled = true
textArea.currentLineHighlightColor = colors.highLightLine
textArea.background = colors.background
textArea.document.addDocumentListener(object : DocumentListener {
override fun changedUpdate(e: DocumentEvent?) {
dirty = true
}
override fun insertUpdate(e: DocumentEvent?) {
dirty = true
}
override fun removeUpdate(e: DocumentEvent?) {
dirty = true
}
})
/*textArea.addParser(object : AbstractParser() {
override fun parse(doc: RSyntaxDocument, style: String): ParseResult {
val kolasuParseResult =
languageSupport.parser.parse(doc.getText(0, doc.length))
if (kolasuParseResult.root != null) {
cachedRoot = kolasuParseResult.root
}
val validator = languageSupport.validator
val issues = validator.validate(kolasuParseResult, context)
val kanvasParseResult = DefaultParseResult(this)
issues.forEach { kanvasParseResult.addNotice(DefaultParserNotice(this, it.message, it.line, it.offset, it.length)) }
return kanvasParseResult
}
override fun isEnabled(): Boolean = true
})
*/
//val provider = createCompletionProvider(languageSupport, context, { cachedRoot })
/*val provider = object : DefaultCompletionProvider() {
override fun getCompletionByInputText(inputText: String?): MutableList<Completion> {
println(inputText)
return super.getCompletionByInputText(inputText)
}
}
val ac = AutoCompletion(provider)
ac.install(textArea)*/
contentPane.layout = BorderLayout()
titleText = "EMPTY"
isCloseable = true
rootPanel.add(viewPort)
contentPane.add(errorStrip, BorderLayout.LINE_END)
contentPane.add(rootPanel)
actionShowFindToolBar.activateKeystroke(contentPane as JComponent)
actionShowReplaceToolBar.activateKeystroke(contentPane as JComponent)
//org.fife.rsta.ui.DocumentMap docMap = new org.fife.rsta.ui.DocumentMap(textArea);
//contentPane.add(docMap, BorderLayout.LINE_END);
}
override fun close() {
//DockingManager.undock(dockable)
}
override fun save() {
val file = file
if (file == null) saveAs() else file.writeText(code)
file?.also {
lookup.get<EditorFactory>().getLanguage(it)?.also {
languageSupport = it
}
}
dirty = false
}
override fun saveAs() {
val fc = lookup.get<GetFileChooser>().fileChooser
val res = fc.showSaveDialog(contentPane)
if (res == JFileChooser.APPROVE_OPTION) {
file = fc.selectedFile
save()
}
}
}
fun Action.activateKeystroke(comp: JComponent) {
(getValue(Action.ACCELERATOR_KEY) as? KeyStroke)?.also { activateKeystroke(comp, it) }
}
fun Action.activateKeystroke(comp: JComponent, ks: KeyStroke) {
comp.registerKeyboardAction(this, ks,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or JComponent.WHEN_FOCUSED)
}
| gpl-3.0 | f0629e0250b0fc557fff023e7a76e4a9 | 32.675926 | 137 | 0.659518 | 4.360911 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/physics/TickleWeldJoint.kt | 1 | 2404 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.physics
import org.jbox2d.dynamics.joints.WeldJoint
import org.jbox2d.dynamics.joints.WeldJointDef
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.Actor
import uk.co.nickthecoder.tickle.util.Angle
/**
* Join two actors together, as if welded together.
*
* NOTE. It is up to you to destroy the joint (for example, if actorA or actorB dies before the scene is over).
*
* @param pointA The position of the pin, relative to [actorA].
* This is (0,0), if you want them welded at the "middle" of actorA.
* Note, you do NOT have to account for the actor's rotation (if it is rotated),
* but you DO have to take account of its scale (if it has been scaled).
*
* @param pointB The position of the pin, relative to [actorB].
* This is (0,0), if you want them welded at the "middle" of actorB.
* Note, you do NOT have to account for the actor's rotation (if it is rotated),
* but you DO have to take account of its scale (if it has been scaled).
*/
class TickleWeldJoint(actorA: Actor, actorB: Actor, pointA: Vector2d, pointB: Vector2d)
: TickleJoint<WeldJoint, WeldJointDef>(actorA, actorB, pointA, pointB) {
var referenceAngle: Angle = Angle.radians(0.0)
set(v) {
field = v
replace()
}
override fun createDef(): WeldJointDef {
val jointDef = WeldJointDef()
jointDef.bodyA = actorA.body!!.jBox2DBody
jointDef.bodyB = actorB.body!!.jBox2DBody
tickleWorld.pixelsToWorld(jointDef.localAnchorA, pointA)
tickleWorld.pixelsToWorld(jointDef.localAnchorB, pointB)
jointDef.referenceAngle = referenceAngle.radians.toFloat()
return jointDef
}
}
| gpl-3.0 | 0fd42929c81bc434502855806d7cc793 | 37.15873 | 111 | 0.712562 | 3.664634 | false | false | false | false |
zingmars/Cbox-bot | src/CLI.kt | 1 | 24326 | /**
* CLI manager daemon
* Created by zingmars on 03.10.2015.
*/
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.ServerSocket
public class CLI (private val Settings :Settings, private val Logger :Logger, private val Box :Box, private val Plugins :Plugins, private val ThreadController :ThreadController)
{
private var port :Int = Settings.GetSetting("daemonPort").toInt()
private var Daemon = Thread()
private var enabled = false
private var active = false
init
{
enabled = Settings.GetSetting("daemonEnabled").toBoolean()
if(enabled) {
this.start()
} else {
Logger.LogMessage(13)
}
}
//Daemon functions
public fun isActive() :Boolean
{
return active
}
public fun start()
{
if(enabled) {
this.active = true
Daemon = Thread(Runnable () { this.Demon() })
Daemon.isDaemon = true
Logger.LogMessage(14, port.toString())
Daemon.start()
ThreadController.ConnectCLI(Daemon)
}
}
public fun stop()
{
this.active = false;
ThreadController.DisconnectCLI()
Daemon.stop()
Logger.LogMessage(60)
}
public fun Reload() :Boolean
{
try {
Logger.LogMessage(59)
this.stop()
this.start()
return true
} catch (e: Exception) {
Logger.LogMessage(65)
this.active = false
return false
}
}
private fun Demon()
{
// Create a simple daemon listening on a specified port
val socket = ServerSocket(port)
while(active) {
val client = socket.accept() // Only allow one at a time since it's not supposed to be a public interface
if(client.isConnected) {
this.ActiveConnectionHandler(client)
}
}
}
private fun ActiveConnectionHandler(client :java.net.Socket)
{
val SessionStartTime = Settings.getCurrentTime()
val out = PrintWriter(client.outputStream, true)
val _in = BufferedReader(InputStreamReader(client.inputStream))
var connectionActive = true
Logger.LogMessage(15, client.remoteSocketAddress.toString())
out.println("Cbox.ws bot CLI interface - Welcome! Type :help for help. Please note that commands are not checked for correctness, and will accept any input. Use this interface at your own risk.") //Welcome message
// Await input and react to it
var input :String
// Listen for input
while(true) {
for(msg in ThreadController.GetCLIBuffer()) {
out.println(msg)
}
out.printf(">> ")
try {
input = _in.readLine() //My major gripe with kotlin - you can't have expression within if, while etc. Sort of annoying.
} catch(e: Exception) {
break; //Client has disconnected, close socket.
}
// Separate command from parameters and log it
var command :List<String> = input.split(" ")
if(command.size > 1) {
Logger.LogCommands(command[0], input.substring(input.indexOf(" ")+1))
} else {
Logger.LogCommands(input)
}
try {
// Execute commands
when(command[0].toLowerCase()) {
":quit" -> { // Disconnect
if(ConfirmAction(out, _in)) {
Logger.LogMessage(16, "Session lasted " + (Settings.getCurrentTime() - SessionStartTime).toString() + " seconds")
client.close()
connectionActive = false
}
else {
Logger.LogMessage(17)
}
}
":shutdowncli" -> { // Shut down the CLI interface. Warn - can't bring it up without restarting the server.
if(ConfirmAction(out, _in)) {
Logger.LogMessage(16, "Session lasted " + (Settings.getCurrentTime() - SessionStartTime).toString() + " seconds")
Logger.LogMessage(29)
client.close()
this.stop()
this.enabled = false
connectionActive = false
} else {
Logger.LogMessage(17)
}
}
":ping" -> {
out.println("Pong!")
}
":shutdown" -> {
if(ConfirmAction(out, _in)) {
try {
Logger.LogMessage(16, "Session lasted " + (Settings.getCurrentTime() - SessionStartTime).toString() + " seconds")
Logger.LogMessage(55)
out.println("Shutdown initiated. Good bye!")
connectionActive = false
Box.stop()
Plugins.stop()
this.stop()
} catch (e :Exception){
System.exit(0);
}
}
}
":reload" -> {
if(ConfirmAction(out, _in)) {
if(this.Reload()) out.println("Reload successful!")
else out.println("Error while reloading the CLI module (how can you still see this?)")
}
}
":help" -> {
out.println("Please refer to https://github.com/zingmars/Cbox-bot/blob/master/misc/cli.txt for full command list.")
}
"settings.savesettings" -> {
Settings.SaveSettings()
out.println("Changes saved successfully.")
}
"settings.loadsettings" -> {
if(ConfirmAction(out, _in)) Settings.LoadSettings()
out.println("Settings reloaded successfully. Please reload modules for the changes to have an effect.")
}
"settings.getsetting" -> {
if(command[1] != "") out.println(command[1] + ":" + Settings.GetSetting(command[1]))
else out.println("Syntax: settings.getsetting <settingname>. All trailing arguments will be ignored");
}
"settings.setsetting" -> {
if(command[1] != "" && command[2] != "") {
Settings.SetSetting(command[1], command[2])
out.println(command[1] + " set to " + command[2])
} else {
out.println("Syntax: settings.setsetting <name> <value>. All trailing arguments will be ignored, setting values mustn't contain any spaces.")
}
}
"settings.changesettingsfile" -> {
if(command[1] != "") {
if(ConfirmAction(out, _in)) Settings.ChangeSettingsFile(command[1])
out.println("Settings reloaded successfully. Please reload modules for the changes to have an effect.")
} else {
out.println("Syntax: settings.changesettingsfile <filename>. All trailing arguments will be ignored.")
}
}
"settings.getSettings" -> {
out.println(Settings.GetAllSettings())
}
"logger.disable" -> {
if(ConfirmAction(out, _in)) {
var pam1 = true
var pam2 = true
var pam3 = true
try{
pam1 = command[1].toBoolean()
pam2 = command[2].toBoolean()
pam3 = command[3].toBoolean()
} catch (ex: Exception) {
}
if(Logger.Disable(pam1, pam2, pam3)) {
out.println("Logging disabled")
} else {
out.println("Either an error occurred, or logging was already disabled");
}
}
}
"logger.enable" -> {
var pam1 = true
var pam2 = true
var pam3 = true
try{
pam1 = command[1].toBoolean()
pam2 = command[2].toBoolean()
pam3 = command[3].toBoolean()
} catch (ex: Exception) {
}
if(Logger.Enable(pam1, pam2, pam3)) {
out.println("Logging enabled")
} else {
out.println("Either an error occurred, or logging was already enabled");
}
}
"logger.archive" -> {
if(ConfirmAction(out,_in)) {
Logger.ArchiveOldLogs()
out.println("Logs archived successfully")
}
}
"logger.toconsole" -> {
if(command[1] != "") {
Logger.ChangeConsoleLoggingState(command[1].toBoolean())
out.println("Changed console logging behaviour")
} else {
out.println("Syntax: logger.toconsole <true:false>")
}
}
"logger.tofile" -> {
if(command[1] != "") {
Logger.ChangeFileLoggingState(command[1].toBoolean())
out.println("Changed file logging behaviour")
} else {
out.println("Syntax: logger.tofile <true:false>")
}
}
"logger.chattofile" -> {
if(command[1] != "") {
Logger.ChangeChatLoggingState(command[1].toBoolean())
out.println("Changed chat logging behaviour")
} else {
out.println("Syntax: logger.chattofile <true:false>")
}
}
"logger.changelogfile" -> {
if(ConfirmAction(out, _in)) {
var pam1 = if(command[1] == "") Settings.GetSetting("logFile") else command[1]
var pam2 = if(command[2] == "") Settings.GetSetting("logFolder") else command[2]
if(Logger.ChangeLogFile(pam1, pam2)) {
out.println("Changed currently active log file")
} else {
out.println("Could not change the log file. Logging disabled.")
}
}
}
"logger.changechatlogfile" -> {
if(ConfirmAction(out, _in)) {
var pam1 = if(command[1] == "") Settings.GetSetting("chatLogFile") else command[1]
var pam2 = if(command[2] == "") Settings.GetSetting("logFolder") else command[2]
if(Logger.ChangeChatLogFile(pam1, pam2)) {
out.println("Changed currently active chat log file")
} else {
out.println("Could not change the log file. Chat logging disabled.")
}
}
}
"logger.changepluginlogfile" -> {
if(ConfirmAction(out, _in)) {
var pam1 = if(command[1] == "") Settings.GetSetting("chatLogFile") else command[1]
var pam2 = if(command[2] == "") Settings.GetSetting("logFolder") else command[2]
if(Logger.ChangePluginLogFile(pam1, pam2)) {
out.println("Changed currently active plugin log file")
} else {
out.println("Could not change the log file. Plugin logging disabled.")
}
}
}
"logger.reload" -> {
ThreadController.AddToMainBuffer("Restart,Logger")
}
"global.reload" -> {
out.println("This will initiate a global reload. You might be disconnected and the app might not reload successfully.")
if(ConfirmAction(out, _in)) {
Logger.LogMessage(54)
ThreadController.AddToMainBuffer("Restart,Logger")
ThreadController.AddToMainBuffer("Restart,Box")
ThreadController.AddToMainBuffer("Restart,Plugins")
out.println("Please wait...")
Thread.sleep(Settings.GetSetting("refreshRate").toLong()*3) //wait for the main process to sync and the other processes to do their thing
out.println("Modules reloaded")
}
}
"box.reload" -> {
ThreadController.AddToMainBuffer("Restart.Box")
out.println("Please wait...")
Thread.sleep(Settings.GetSetting("refreshRate").toLong()*3)
}
"box.tocli" -> {
this.CLIChat(out, _in, client)
}
"box.relog" -> {
out.println("Relogging with given credentials (username, password, avatarURL) and reloading the box")
if(command[1] != "" && command[2] != "") {
try {
Box.ChangeCredentials(command[1], command[2], command[3])
} catch (e: Exception) {
Box.ChangeCredentials(command[1], command[2], "")
}
ThreadController.AddToMainBuffer("Restart.Box")
out.println("Please wait...")
Thread.sleep(Settings.GetSetting("refreshRate").toLong()*3)
} else {
out.println("Syntax: box.relog <username> <password> <optional: avatar URL>")
}
}
"box.refreshrate" -> {
if(command[1] != "") {
Box.changeRefreshRate(command[1].toLong())
out.println("Box refresh rate changed")
} else {
}
}
"box.getip" -> {
if(command[1] != "") {
out.println("Response: " + Box.getIP(command[1]))
}
else {
out.println("Syntax: box.getip <optional: messageID>")
}
}
"box.send" -> {
if(Box.SendMessage(command.joinToString(" ").replace("send", ""))) {
out.println("Message sent successfully")
} else {
out.println("Could not send your message. Are you logged in?")
}
}
"plugins.reload" -> {
ThreadController.AddToMainBuffer("Restart.Plugins")
}
"plugins.disable" -> {
if(ConfirmAction(out, _in)) {
Plugins.Disable()
out.println("Plugins disabled.")
}
}
"plugins.enable" -> {
if(ConfirmAction(out, _in)) {
Plugins.Enable()
out.println("Plugins enabled.")
}
}
"plugins.refreshrate" -> {
if(command[1] != "") {
Plugins.changeRefreshRate(command[1].toLong())
out.println("Refresh rate changed.")
} else {
out.println("Syntax: plugins.refreshrate <miliseconds>")
}
}
"plugins.unload" -> {
if(command[1] != "") {
if(ConfirmAction(out, _in)) {
out.println(Plugins.unloadPlugin(command[1]))
}
} else {
out.println("Syntax: plugins.unload <plugin name>")
}
}
"plugins.load" -> {
//TODO: Bug - the plugin needs to be correctly capitalised or it will crash the thread
if(command[1] != "") {
out.println("Warning: There's currently a bug that will unrecoverably crash the CLI module if you misspell the plugin's name or write it in the wrong CaSe.")
if(Plugins.LoadPlugin(command[1]+".kt")) {
out.println("Plugin loaded successfully")
} else {
out.println("Plugin loading failed")
}
} else {
out.println("Syntax: plugins.load <plugin name>")
}
}
"plugins.reload" -> {
if(command[1] != "") {
if(Plugins.reloadPlugin(command[1])) {
out.println("Plugin reloaded successfully")
} else {
out.println("Plugin reloading failed")
}
} else {
out.println("Syntax: plugins.reload <plugin name>")
}
}
"plugins.savesettings" -> {
Plugins.SavePluginSettings()
out.println("Saved")
}
"plugins.getsettings" -> {
out.println(Plugins.GetAllSettings())
}
"plugins.setsetting" -> {
if(command[1] != "" && command[2] != "") {
Plugins.SetSetting(command[1], command[2])
out.println(command[1] + " set to " + command[2])
} else {
out.println("Syntax: plugins.setsetting <name> <value>")
}
}
"plugins.command" -> {
if (command[1] == "" || command[2] == "") {
out.println("Wrong syntax. Syntax - plugins.command <pluginname> <command>")
} else {
var param = command.joinToString(",")
param = param.substring(param.indexOf(",")+1) //Pluginname
param = param.substring(param.indexOf(",")+1) //Command
out.println(Plugins.executeFunction(command[1], param))
}
}
else -> {
out.println("Unrecognised command")
}
}
} catch (e: Exception) {
out.println("An error occurred while executing your command")
Logger.LogMessage(999, "CLI command execution failure: " + e.toString())
}
//Special case : Break out of the while loop if the client has quit
if(!connectionActive) {
break;
}
}
}
//CLI misc functions
private fun ConfirmAction(output :PrintWriter, input :BufferedReader) :Boolean
{
output.println("Are you sure? (no)")
try {
output.printf("> ")
var userInput = input.readLine() //My major gripe with kotlin - you can't have expression within if, while etc. Sort of annoying.
if(userInput == "yes") {
return true
}
else {
output.println("Command cancelled")
return false
}
} catch(e: Exception) {
//Client has DCed
}
return false
}
private fun CLIChat(output :PrintWriter, input :BufferedReader, client :java.net.Socket)
{
//TODO: Have CLI chat be independent of input
// Very hacky CLI chat. It basically relies on timeout interruptions to receive messages and it isn't the most stable thing around.
//Initialise environment
val SessionStartTime = Settings.getCurrentTime();
Logger.LogMessage(57)
ThreadController.GetCLIBuffer() //Clear buffer
Box.toCLI = true
client.soTimeout = Settings.GetSetting("refreshRate").toInt()
//Welcome message
output.print("\u001B[2J")
output.flush()
output.println("CLI Chat 1.0. Enjoy your stay. Please note that this will only show messages written since chat was started. To see logs, please refer to your logs directory.")
output.println("Write really short messages to the char just write anything and press enter, :quit to quit, :write .> enter -> message to type longer messages without being interrupted. (this will pause receiving of messages though)")
//Print messages and allow input
var CLIActive = true
while(CLIActive) {
for(msg in ThreadController.GetCLIBuffer()) {
output.println(msg)
}
try {
var userInput = input.readLine()
when (userInput) {
":quit" -> {
CLIActive = false
client.soTimeout = 0
Box.toCLI = false
Logger.LogMessage(58, "Session lasted " + (Settings.getCurrentTime() - SessionStartTime).toString() + " seconds")
ThreadController.GetCLIBuffer()
output.print("\u001B[2J")
}
":write" -> {
output.printf(":")
client.soTimeout = 0
userInput = input.readLine()
Box.SendMessage(userInput)
client.soTimeout = Settings.GetSetting("refreshRate").toInt()
}
else -> {
Box.SendMessage(userInput)
}
}
} catch (e: Exception) {
}
}
return
}
} | bsd-2-clause | a0e63697fe548de34578ca618f12dd75 | 45.603448 | 242 | 0.426992 | 5.623209 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/view/ViewPagerProperty.kt | 1 | 648 | package com.github.kittinunf.reactiveandroid.support.v4.view
import android.support.v4.view.ViewPager
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Properties
//================================================================================
val ViewPager.rx_currentItem: MutableProperty<Int>
get() {
val getter = { currentItem }
val setter: (Int) -> Unit = { currentItem = it }
return createMainThreadMutableProperty(getter, setter)
}
| mit | c5778d43d01d168c944ecfc0b92d7ea7 | 37.117647 | 82 | 0.564815 | 5.944954 | false | false | false | false |
ujpv/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RustExpressionAnnotatorTest.kt | 1 | 3068 | package org.rust.ide.annotator
class RustExpressionAnnotatorTest : RustAnnotatorTestBase() {
override val dataPath = "org/rust/ide/annotator/fixtures/expressions"
fun testUnnecessaryParens() = checkWarnings("""
fn test() {
if <weak_warning>(true)</weak_warning> {
let _ = 1;
}
for x in <weak_warning>(0..10)</weak_warning> {
let _ = 1;
}
match <weak_warning>(x)</weak_warning> {
_ => println!("Hello world")
}
if <weak_warning>(pred)</weak_warning> {
return <weak_warning>(true)</weak_warning>;
}
while <weak_warning>(true)</weak_warning> {
let _ = 1;
}
let e = (<weak_warning descr="Redundant parentheses in expression">(4 + 3)</weak_warning>);
}
""")
fun testStructExpr() = checkWarnings("""
#[derive(Default)]
struct S {
foo: i32,
bar: i32
}
struct Empty {}
enum E {
V {
foo: i32
}
}
fn main() {
let _ = S {
foo: 92,
<error descr="No such field">baz</error>: 62,
bar: 11,
};
let _ = S {
foo: 92,
..S::default()
};
let _ = S {
foo: 92,
<error descr="Some fields are missing">}</error>;
let _ = S {
foo: 1,
<error descr="Duplicate field">foo</error>: 2,
<error descr="Some fields are missing">}</error>;
let _ = S {
foo: 1,
<error>foo</error>: 2,
..S::default()
};
let _ = Empty { };
let _ = E::V {
<error>bar</error>: 92
<error>}</error>;
}
""")
fun testStructExprQuickFix() = checkQuickFix("Add missing fields", """
struct S {
foo: i32,
bar: f64
}
fn main() {
let _ = S {
/*caret*/
};
}
""", """
struct S {
foo: i32,
bar: f64
}
fn main() {
let _ = S {
foo: /*caret*/(),
bar: (),
};
}
""")
fun testStructExprQuickFix2() = checkQuickFix("Add missing fields", """
struct S {
a: i32,
b: i32,
c: i32,
d: i32
}
fn main() {
let _ = S {
a: 92,
c: 92/*caret*/
};
}
""", """
struct S {
a: i32,
b: i32,
c: i32,
d: i32
}
fn main() {
let _ = S {
b: /*caret*/(),
d: (),
a: 92,
c: 92
};
}
""")
}
| mit | 4d2e6e0c117dd7e632c5862e5469f08c | 21.071942 | 103 | 0.347132 | 4.491947 | false | true | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/Payments.kt | 1 | 832 | package net.perfectdreams.loritta.cinnamon.pudding.tables
import net.perfectdreams.loritta.cinnamon.pudding.utils.PaymentGateway
import net.perfectdreams.loritta.cinnamon.pudding.utils.PaymentReason
import net.perfectdreams.exposedpowerutils.sql.jsonb
import org.jetbrains.exposed.dao.id.LongIdTable
object Payments : LongIdTable() {
val userId = long("user").index()
val gateway = enumeration("gateway", PaymentGateway::class)
val reason = enumeration("reason", PaymentReason::class)
val money = decimal("money", 12, 2).index()
val createdAt = long("created_at")
val paidAt = long("paid_at").nullable()
val expiresAt = long("expires_at").nullable()
val discount = double("discount").nullable()
val referenceId = uuid("reference_id").nullable()
val metadata = jsonb("metadata").nullable()
} | agpl-3.0 | 03eedbdaf7bbb98bf55226a93f64263d | 42.842105 | 70 | 0.741587 | 4.118812 | false | false | false | false |
MoonCheesez/sstannouncer | sstannouncer/app/src/main/java/sst/com/anouncements/feed/data/database/room/RoomDAL.kt | 1 | 1867 | package sst.com.anouncements.feed.data.database.room
import sst.com.anouncements.feed.model.Feed
import sst.com.anouncements.feed.data.database.FeedDAL
import java.util.*
class RoomDAL(private val database: FeedDatabase) : FeedDAL {
override fun getFeed(feedURL: String): Feed {
// Retrieve feed and entry entities
val feedEntity = database.feedDao().getFeed(feedURL)
val entryEntities = database.entryDao().getFeedEntries(feedEntity.id)
// Convert to Feed and Entry objects
val entries = List(entryEntities.size) { entryEntities[it].toEntry() }
return Feed(
feedEntity.id,
entries,
feedEntity.lastUpdated,
// The rest of the fields are not persisted
listOf(), "", ""
)
}
override fun hasFeed(feedURL: String): Boolean = database.feedDao().countFeed(feedURL) == 1
override fun updateFeed(newFeed: Feed, feedURL: String) {
val feedEntity = database.feedDao().getFeed(feedURL)
if (feedEntity.id == newFeed.id
&& feedEntity.lastUpdated.compareTo(newFeed.lastUpdated) == 0) {
// Nothing has been updated so don't do anything
return
}
// This is not very efficient, but for small number of entries, it is acceptable
overwriteFeed(newFeed, feedURL)
}
override fun overwriteFeed(newFeed: Feed, feedURL: String) {
// Do not check for any existing objects
database.feedDao().saveFeed(FeedEntity(newFeed, feedURL))
val entryEntities = List(newFeed.entries.size) {
EntryEntity(newFeed.entries[it], newFeed.id)
}
database.entryDao().insertEntries(entryEntities)
}
override fun getFeedLastUpdated(feedURL: String): Date {
return database.feedDao().getFeedLastUpdated(feedURL)
}
} | mit | 42594c3a0a8a3869796018153b79667f | 35.627451 | 95 | 0.653455 | 4.176734 | false | false | false | false |
shyiko/ktlint | ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ModifierOrderRuleTest.kt | 1 | 5646 | package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.test.format
import com.pinterest.ktlint.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ModifierOrderRuleTest {
@Test
fun testLint() {
// pretty much every line below should trip an error
assertThat(
ModifierOrderRule().lint(
"""
abstract @Deprecated open class A { // open is here for test purposes only, otherwise it's redundant
open protected val v = ""
open suspend internal fun f(v: Any): Any = ""
lateinit public var lv: String
tailrec abstract fun findFixPoint(x: Double = 1.0): Double
}
class B : A() {
override public val v = ""
suspend override fun f(v: Any): Any = ""
tailrec override fun findFixPoint(x: Double): Double
= if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
override @Annotation fun getSomething() = ""
override @Annotation suspend public @Woohoo(data = "woohoo") fun doSomething() = ""
@A
@B(v = [
"foo",
"baz",
"bar"
])
@C
suspend public fun returnsSomething() = ""
companion object {
const internal val V = ""
}
}
""".trimIndent()
)
).isEqualTo(
listOf(
LintError(1, 1, "modifier-order", "Incorrect modifier order (should be \"@Annotation... open abstract\")"),
LintError(2, 5, "modifier-order", "Incorrect modifier order (should be \"protected open\")"),
LintError(3, 5, "modifier-order", "Incorrect modifier order (should be \"internal open suspend\")"),
LintError(4, 5, "modifier-order", "Incorrect modifier order (should be \"public lateinit\")"),
LintError(5, 5, "modifier-order", "Incorrect modifier order (should be \"abstract tailrec\")"),
LintError(9, 5, "modifier-order", "Incorrect modifier order (should be \"public override\")"),
LintError(10, 5, "modifier-order", "Incorrect modifier order (should be \"override suspend\")"),
LintError(11, 5, "modifier-order", "Incorrect modifier order (should be \"override tailrec\")"),
LintError(13, 5, "modifier-order", "Incorrect modifier order (should be \"@Annotation... override\")"),
LintError(14, 5, "modifier-order", "Incorrect modifier order (should be \"@Annotation... public override suspend\")"),
LintError(15, 5, "modifier-order", "Incorrect modifier order (should be \"@Annotation... public suspend\")"),
LintError(25, 8, "modifier-order", "Incorrect modifier order (should be \"internal const\")")
)
)
}
@Test
fun testFormat() {
assertThat(
ModifierOrderRule().format(
"""
abstract @Deprecated open class A { // open is here for test purposes only, otherwise it's redundant
open protected val v = ""
open suspend internal fun f(v: Any): Any = ""
lateinit public var lv: String
tailrec abstract fun findFixPoint(x: Double = 1.0): Double
}
class B : A() {
override public val v = ""
suspend override fun f(v: Any): Any = ""
tailrec override fun findFixPoint(x: Double): Double
= if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
override @Annotation fun getSomething() = ""
suspend @Annotation override public @Woohoo(data = "woohoo") fun doSomething() = ""
@A
@B(v = [
"foo",
"baz",
"bar"
])
@C
suspend public fun returnsSomething() = ""
companion object {
const internal val V = ""
}
}
"""
)
).isEqualTo(
"""
@Deprecated open abstract class A { // open is here for test purposes only, otherwise it's redundant
protected open val v = ""
internal open suspend fun f(v: Any): Any = ""
public lateinit var lv: String
abstract tailrec fun findFixPoint(x: Double = 1.0): Double
}
class B : A() {
public override val v = ""
override suspend fun f(v: Any): Any = ""
override tailrec fun findFixPoint(x: Double): Double
= if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
@Annotation override fun getSomething() = ""
@Annotation @Woohoo(data = "woohoo") public override suspend fun doSomething() = ""
@A
@B(v = [
"foo",
"baz",
"bar"
])
@C
public suspend fun returnsSomething() = ""
companion object {
internal const val V = ""
}
}
"""
)
}
}
| mit | df8fb7d773c191f5cbaa9fde66cdda64 | 42.430769 | 134 | 0.487956 | 5.175069 | false | true | false | false |
vanniktech/Emoji | generator/template/Category.kt | 1 | 1170 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.<%= package %>.category
import com.vanniktech.emoji.EmojiCategory
import com.vanniktech.emoji.<%= package %>.<%= name %>
internal class <%= category %>Category : EmojiCategory {
override val categoryNames: Map<String, String>
get() = mapOf(<% categoryNames.forEach(function(category) { %>
"<%= category.key %>" to "<%= category.value %>",<% }); %>
)
override val emojis = ALL_EMOJIS
private companion object {
val ALL_EMOJIS: List<<%= name %>> = <%= chunks %>
}
}
| apache-2.0 | 57f854ab1a526014ac2d97d18b09dc2a | 34.393939 | 78 | 0.695205 | 4.013746 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/User.kt | 1 | 1251 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param id
* @param fullName
* @param email
* @param name
*/
data class User(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("id") val id: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("fullName") val fullName: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("email") val email: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("name") val name: kotlin.String? = null
) {
}
| mit | c71718c3f496a4f050a8bf9e844c15f9 | 28.093023 | 75 | 0.730616 | 3.996805 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/module_tests/AbstractPacketProducer.kt | 1 | 3388 | /*
* Copyright @ 2018 - Present, 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.module_tests
import io.pkts.Pcap
import io.pkts.packet.Packet
import io.pkts.packet.UDPPacket
import io.pkts.protocol.Protocol
import org.jitsi.rtp.UnparsedPacket
import java.util.concurrent.TimeUnit
abstract class AbstractPacketProducer : PacketProducer {
private val handlers = mutableListOf<PacketReceiver>()
override fun subscribe(handler: PacketReceiver) {
handlers.add(handler)
}
protected fun onPacket(packet: org.jitsi.rtp.Packet) {
handlers.forEach { it(packet) }
}
}
/**
* Read data from a PCAP file and play it out at a rate consistent with the packet arrival times. I.e. if the PCAP
* file captured data flowing at 2mbps, this producer will play it out at 2mbps
*/
class PcapPacketProducer(
pcapFilePath: String
) : AbstractPacketProducer() {
private val pcap = Pcap.openStream(pcapFilePath)
var running: Boolean = true
companion object {
private fun translateToUnparsedPacket(pktsPacket: Packet): UnparsedPacket {
// We always allocate a buffer with capacity 1500, so the packet has room to 'grow'
val packetBuf = ByteArray(1500)
return if (pktsPacket.hasProtocol(Protocol.UDP)) {
val udpPacket = pktsPacket.getPacket(Protocol.UDP) as UDPPacket
System.arraycopy(udpPacket.payload.array, 0, packetBuf, 0, udpPacket.payload.array.size)
UnparsedPacket(packetBuf, 0, udpPacket.payload.array.size)
} else {
// When capturing on the loopback interface, the packets have a null ethernet
// frame which messes up the pkts libary's parsing, so instead use a hack to
// grab the buffer directly
System.arraycopy(pktsPacket.payload.rawArray, 32, packetBuf, 0, pktsPacket.payload.rawArray.size - 32)
UnparsedPacket(packetBuf, 0, pktsPacket.payload.rawArray.size - 32)
}
}
private fun nowMicros(): Long = System.nanoTime() / 1000
}
fun run() {
var firstPacketArrivalTime = -1L
val startTime = nowMicros()
while (running) {
pcap.loop { pkt ->
if (firstPacketArrivalTime == -1L) {
firstPacketArrivalTime = pkt.arrivalTime
}
val expectedSendTime = pkt.arrivalTime - firstPacketArrivalTime
val nowClockTime = nowMicros() - startTime
if (expectedSendTime > nowClockTime) {
TimeUnit.MICROSECONDS.sleep(expectedSendTime - nowClockTime)
}
val packet = translateToUnparsedPacket(pkt)
onPacket(packet)
true
}
running = false
}
}
}
| apache-2.0 | f82b39bf0c6f44198a37a4c5a055c466 | 37.5 | 118 | 0.650236 | 4.277778 | false | false | false | false |
dector/tlamp | desktop/src/App.kt | 1 | 3750 | import javafx.application.Application
import javafx.collections.FXCollections
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.ComboBox
import javafx.scene.layout.GridPane
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.stage.Stage
import jssc.SerialPort
import jssc.SerialPortList
import kotlin.system.exitProcess
class TLamp : Application() {
val portsList = FXCollections.observableArrayList<String>()
var currentPort: SerialPort? = null
override fun start(primaryStage: Stage?) {
val root = VBox().apply {
alignment = Pos.CENTER
spacing = 16.0
}
HBox().apply {
alignment = Pos.CENTER
spacing = 16.0
ComboBox(portsList).apply {
valueProperty().addListener { o, old, new -> if (old != new) newPortSelected(new) }
}.let { children.add(it) }
Button("Update").let { children.add(it) }
root.children.add(this)
}
val grid = GridPane().apply {
alignment = Pos.CENTER
padding = Insets(8.0, 8.0, 8.0, 8.0)
hgap = 8.0
vgap = 8.0
style = "-fx-background-color: #aeaeae"
root.children.add(this)
}
Color.values().forEach { color ->
Button(" ").apply {
style = "-fx-background-color: ${color.value}"
setOnMouseClicked { sendSetColor(color) }
val colorIndex = Color.values().indexOf(color)
val rowLength = 6
val row = colorIndex / rowLength
val column = colorIndex - row * rowLength
grid.add(this, column + 1, row + 1)
}
}
val scene = Scene(root, 400.0, 200.0)
primaryStage?.scene = scene
primaryStage?.title = "tLamp"
primaryStage?.show()
primaryStage?.setOnCloseRequest {
currentPort?.closePort()
exitProcess(0)
}
updatePortsList()
}
fun updatePortsList() {
val ports = SerialPortList.getPortNames()
portsList.setAll(*ports)
}
fun newPortSelected(name: String) {
val port = SerialPort(name)
if (! port.openPort()) {
println("Can't open port $name")
return
}
println("Port $name opened. Configuring")
port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE)
port.addEventListener {
if (it.isRXCHAR && it.eventValue > 0) {
onDataReceived(port, it.eventValue)
}
}
currentPort = port
}
fun onDataReceived(port: SerialPort, amount: Int) {
val data = port.readString(amount)
print(">> $data")
}
fun sendSetColor(color: Color) {
val port = currentPort ?: return
val data = "SET " + color.value
port.writeString(data)
println("<< $data")
}
}
enum class Color(val value: String) {
RED ("#FF0000"),
CYAN ("#00FFFF"),
BLUE ("#0000FF"),
DARK_BLUE ("#0000A0"),
PURPLE ("#800080"),
YELLOW ("#FFFF00"),
LIME ("#00FF00"),
FUCHSIA ("#FF00FF"),
OLIVE ("#808000"),
GREEN ("#008000"),
MAROON ("#800000"),
BROWN ("#A52A2A"),
ORANGE ("#FFA500"),
BLACK ("#000000"),
GREY ("#808080"),
SILVER ("#C0C0C0"),
WHITE ("#FFFFFF")
}
fun main(vararg args: String) {
Application.launch(TLamp::class.java)
} | mit | 02c75c5c0fcc54052647e3c07578e497 | 26.181159 | 118 | 0.552267 | 4.084967 | false | false | false | false |
curiosityio/AndroidBoilerplate | androidboilerplate/src/main/java/com/curiosityio/androidboilerplate/util/YouTubeUtil.kt | 1 | 604 | package com.curiosityio.androidboilerplate.util
open class YouTubeUtil {
companion object {
fun getVideoIdFromUrl(videoUrl: String): String? {
val split = videoUrl.split(".+(v=)".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (split.size == 2) {
return split[1]
}
return null
}
fun getThumbnailUrlForVideoUrl(videoUrl: String): String? {
val vidId = getVideoIdFromUrl(videoUrl) ?: return null
return "https://img.youtube.com/vi/$vidId/hqdefault.jpg"
}
}
}
| mit | d7e77f2f8faff6947b453ce75c9906e7 | 25.26087 | 104 | 0.57947 | 4.376812 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/authenticator/SimpleWebServer.kt | 1 | 2881 | package com.baulsupp.okurl.authenticator
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.Closeable
import java.io.IOException
import java.io.PrintWriter
import java.net.InetSocketAddress
import java.util.logging.Level
import java.util.logging.Logger
class SimpleWebServer(
private val port: Int = 3000,
private val codeReader: (HttpUrl) -> String?
) : Closeable, HttpHandler {
private val logger = Logger.getLogger(SimpleWebServer::class.java.name)
private var server: HttpServer = HttpServer.create(InetSocketAddress("localhost", port), 1)
private val channel = Channel<Result<String>>()
val redirectUri = "http://localhost:$port/callback"
init {
server.createContext("/", this)
server.start()
logger.log(Level.FINE, "listening at $redirectUri")
}
override fun handle(exchange: HttpExchange) {
exchange.responseHeaders.add("Content-Type", "text/html; charset=utf-8")
exchange.sendResponseHeaders(200, 0)
PrintWriter(exchange.responseBody).use { out ->
processRequest(exchange, out)
}
exchange.close()
}
fun processRequest(exchange: HttpExchange, out: PrintWriter) {
val result = runCatching {
val url = "http://localhost:$port${exchange.requestURI}".toHttpUrl()
val error = url.queryParameter("error")
if (error != null) {
throw IOException(error)
}
codeReader(url) ?: throw IllegalArgumentException("no code read")
}.onSuccess {
out.println(generateSuccessBody())
}.onFailure {
out.println(generateFailBody("$it"))
}
this.channel.offer(result) || throw IllegalStateException("unable to send to channel")
}
private fun generateSuccessBody(): String = """<html>
<body background="http://win.blogadda.com/wp-content/uploads/2015/08/inspire-win-15.jpg">
<h1>Authorization Token Received!</h1>
</body>
</html>"""
private fun generateFailBody(error: String): String = """<html>
<body background="http://adsoftheworld.com/sites/default/files/fail_moon_aotw.jpg">
<h1>Authorization Error!</h1>
<p style="font-size: 600%; font-family: Comic Sans, Comic Sans MS, cursive;">$error</p></body>
</html>"""
override fun close() {
channel.close()
server.stop(0)
}
suspend fun waitForCode(): String = channel.receive().getOrThrow()
companion object {
fun forCode(): SimpleWebServer {
return SimpleWebServer { r ->
r.queryParameter("code")
}
}
@JvmStatic
fun main(args: Array<String>) {
SimpleWebServer.forCode().use { ws ->
val s = runBlocking {
ws.waitForCode()
}
println("result = $s")
}
}
}
}
| apache-2.0 | f49a85daa54a0939c82ace5bd7eefc16 | 27.245098 | 94 | 0.694551 | 3.96832 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/buildquality/src/main/kotlin/org/gradle/gradlebuild/buildquality/classycle/ClassyclePlugin.kt | 1 | 1896 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.buildquality.classycle
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.*
import accessors.java
import accessors.reporting
internal
val classycleBaseName = "classycle"
@Suppress("unused")
// TODO move into buildquality
open class ClassyclePlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
val extension = extensions.create<ClassycleExtension>(classycleBaseName, project)
configurations.create(classycleBaseName)
dependencies.add(classycleBaseName, "classycle:classycle:1.4.2@jar")
val classycle = tasks.register("classycle")
java.sourceSets.all {
val taskName = getTaskName("classycle", null)
val sourceSetTask = tasks.register(
taskName,
Classycle::class.java,
output.classesDirs,
extension.excludePatterns,
name,
reporting.file("classycle"),
extension.reportResourcesZip
)
classycle { dependsOn(sourceSetTask) }
tasks.named("check") { dependsOn(sourceSetTask) }
tasks.named("codeQuality") { dependsOn(sourceSetTask) }
}
}
}
| apache-2.0 | 9d64b1801e99d9c638e1f4176dfa99d9 | 32.857143 | 89 | 0.677215 | 4.409302 | false | false | false | false |
vania-pooh/kotlin-algorithms | src/com/freaklius/kotlin/algorithms/sort/SortLauncher.kt | 1 | 1890 | package com.freaklius.kotlin.algorithms.sort
/**
* This class launches all specified sort algorithms and compares their performance
*/
class SortLauncher{
/**
* Launches sort algorithms
*/
fun launch() {
val arr: Array<Long> = randomNumericArray(10, 100)
for (algorithm in getAlgorithmsList()){
measureAlgorithm(arr.clone(), algorithm)
}
}
/**
* Executes and measures a single algorithm
*/
private fun measureAlgorithm(arr: Array<Long>, algorithm: SortAlgorithm){
println("--------------------------------------")
println("Algorithm name: " + algorithm.getName())
println("Initial array: " + arrayToString(arr))
val startTime : Long = System.nanoTime()
val sortedArr = algorithm.sort(arr)
val endTime : Long = System.nanoTime()
println("Sorted array: " + arrayToString(sortedArr))
println("Is array sorted in ascending order: " + isSortedAsc(sortedArr))
val avgTimePerElement : Double = ((endTime - startTime).toDouble() / arr.size.toDouble())
val runTime : Double = (endTime - startTime).toDouble()
println("Average time per element, ns: " + avgTimePerElement)
println("Total Array run time, ns: " + runTime)
}
/**
* Returns a list of algorithms to be tested
*/
private fun getAlgorithmsList() : Array<SortAlgorithm>{
return arrayOf(
BubbleSort(),
SelectionSort(),
InsertionSort(),
CombSort(),
MergeSort(),
HeapSort(),
QuickSort(),
CountingSort(),
RadixSort(),
BucketSort(),
BogoSort()
)
}
}
/**
* Entry point function
*/
fun main(args: Array<String>) {
SortLauncher().launch()
}
| mit | 3fe97eeab3ce5bfcb098a724dc60fc62 | 27.208955 | 97 | 0.559788 | 4.772727 | false | false | false | false |
jainaman224/Algo_Ds_Notes | Counting_Sort/Counting_Sort.kt | 1 | 1697 | // Kotlin Code for Counting Sort
public class Counting_Sort {
// Function that sort the given input
fun sort(int:input[]):void
{
int n = input.length;
int output[] = new int[n];
int max = input[0];
int min = input[0];
for(i in 1 until n)
{
if(input[i] > max)
{
max = input[i];
}
else if(input[i] < min)
{
min = input[i];
}
}
// Size of count array
int k = max - min + 1;
int count_array[] = new int[k];
for(i in 0 until n)
{
count_array[input[i] - min]++;
}
for(i in 1 until k)
{
count_array[i] += count_array[i - 1];
}
for(i in 0 until n)
{
output[count_array[input[i] - min] - 1] = input[i];
count_array[input[i] - min]--;
}
// Copy the output array to input, so that input now contains sorted values
for(i in 0 until n)
{
input[i] = output[i];
}
}
// Main Function
fun main()
{
var read = Scanner(System.`in`)
println("Enter the size of Array:")
val arrSize = read.nextLine().toInt()
var input = IntArray(arrSize)
println("Enter elements")
for(i in 0 until arrSize)
{
input[i] = read.nextLine().toInt()
}
sort(input);
for(i in 0 until arrSize)
{
println(input[i]);
}
}
}
/*
Input
2 1 4 1 3 5 7 5 4
Output
1 1 2 3 4 4 5 5 7
*/
| gpl-3.0 | 06e0c7863eca3c79c82d2534907a99ba | 20.75641 | 83 | 0.424867 | 3.721491 | false | false | false | false |
xfournet/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleNonCodeMembersContributor.kt | 1 | 9669 | /*
* 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 org.jetbrains.plugins.gradle.service.resolve
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Ref
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiTreeUtil
import groovy.lang.Closure
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROJECT
import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor.Companion.getDocumentation
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleExtensionsData
import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_STRATEGY_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getDelegatesToInfo
/**
* @author Vladislav.Soroka
*
* @since 11/25/2016
*/
class GradleNonCodeMembersContributor : NonCodeMembersContributor() {
override fun processDynamicElements(qualifierType: PsiType,
aClass: PsiClass?,
processor: PsiScopeProcessor,
place: PsiElement,
state: ResolveState) {
if (aClass == null) return
val containingFile = place.containingFile
if (!containingFile.isGradleScript() || containingFile?.originalFile?.virtualFile == aClass.containingFile?.originalFile?.virtualFile) return
processDeclarations(aClass, processor, state, place)
if (qualifierType.equalsToText(GRADLE_API_PROJECT)) {
val propCandidate = place.references.singleOrNull()?.canonicalText ?: return
val extensionsData: GradleExtensionsData?
val methodCall = place.children.singleOrNull()
if (methodCall is GrMethodCallExpression) {
val projectPath = methodCall.argumentList.expressionArguments.singleOrNull()?.reference?.canonicalText ?: return
if (projectPath == ":") {
val file = containingFile?.originalFile?.virtualFile ?: return
val module = ProjectFileIndex.SERVICE.getInstance(place.project).getModuleForFile(file)
val rootProjectPath = ExternalSystemApiUtil.getExternalRootProjectPath(module)
extensionsData = GradleExtensionsSettings.getInstance(place.project).getExtensionsFor(rootProjectPath, rootProjectPath) ?: return
}
else {
val module = ModuleManager.getInstance(place.project).findModuleByName(projectPath.trimStart(':')) ?: return
extensionsData = GradleExtensionsSettings.getInstance(place.project).getExtensionsFor(module) ?: return
}
}
else if (methodCall is GrReferenceExpression) {
if (place.children[0].text == "rootProject") {
val file = containingFile?.originalFile?.virtualFile ?: return
val module = ProjectFileIndex.SERVICE.getInstance(place.project).getModuleForFile(file)
val rootProjectPath = ExternalSystemApiUtil.getExternalRootProjectPath(module)
extensionsData = GradleExtensionsSettings.getInstance(place.project).getExtensionsFor(rootProjectPath, rootProjectPath) ?: return
}
else return
}
else return
val processVariable: (GradleExtensionsSettings.TypeAware) -> Boolean = {
val docRef = Ref.create<String>()
val variable = object : GrLightVariable(place.manager, propCandidate, it.typeFqn, place) {
override fun getNavigationElement(): PsiElement {
val navigationElement = super.getNavigationElement()
navigationElement.putUserData(NonCodeMembersHolder.DOCUMENTATION, docRef.get())
return navigationElement
}
}
val doc = getDocumentation(it, variable)
docRef.set(doc)
place.putUserData(NonCodeMembersHolder.DOCUMENTATION, doc)
processor.execute(variable, state)
}
extensionsData.tasks.firstOrNull { it.name == propCandidate }?.let(processVariable)
extensionsData.findProperty(propCandidate)?.let(processVariable)
}
else {
val propCandidate = place.references.singleOrNull()?.canonicalText ?: return
val domainObjectType = (qualifierType.superTypes.firstOrNull { it is PsiClassType } as? PsiClassType)?.parameters?.singleOrNull() ?: return
if (!InheritanceUtil.isInheritor(qualifierType, GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER)) return
val classHint = processor.getHint(com.intellij.psi.scope.ElementClassHint.KEY)
val shouldProcessMethods = ResolveUtil.shouldProcessMethods(classHint)
val shouldProcessProperties = ResolveUtil.shouldProcessProperties(classHint)
if (GradleResolverUtil.canBeMethodOf(propCandidate, aClass)) return
val domainObjectFqn = TypesUtil.getQualifiedName(domainObjectType) ?: return
val javaPsiFacade = JavaPsiFacade.getInstance(place.project)
val domainObjectPsiClass = javaPsiFacade.findClass(domainObjectFqn, place.resolveScope) ?: return
if (GradleResolverUtil.canBeMethodOf(propCandidate, domainObjectPsiClass)) return
if (GradleResolverUtil.canBeMethodOf("get" + propCandidate.capitalize(), domainObjectPsiClass)) return
if (GradleResolverUtil.canBeMethodOf("set" + propCandidate.capitalize(), domainObjectPsiClass)) return
val closure = PsiTreeUtil.getParentOfType(place, GrClosableBlock::class.java)
val typeToDelegate = closure?.let { getDelegatesToInfo(it)?.typeToDelegate }
if (typeToDelegate != null) {
val fqNameToDelegate = TypesUtil.getQualifiedName(typeToDelegate) ?: return
val classToDelegate = javaPsiFacade.findClass(fqNameToDelegate, place.resolveScope) ?: return
if (classToDelegate !== aClass) {
val parent = place.parent
if (parent is GrMethodCall) {
if (canBeMethodOf(propCandidate, parent, typeToDelegate)) return
}
}
}
if (!shouldProcessMethods && shouldProcessProperties && place is GrReferenceExpression && place.parent !is GrApplicationStatement) {
val variable = object : GrLightField(propCandidate, domainObjectFqn, place) {
override fun getNavigationElement(): PsiElement {
val navigationElement = super.getNavigationElement()
return navigationElement
}
}
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(variable, state)) return
}
if (shouldProcessMethods && place is GrReferenceExpression) {
val call = PsiTreeUtil.getParentOfType(place, GrMethodCall::class.java) ?: return
val args = call.argumentList
var argsCount = GradleResolverUtil.getGrMethodArumentsCount(args)
argsCount += call.closureArguments.size
argsCount++ // Configuration name is delivered as an argument.
// at runtime, see org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod
val wrappedBase = GrLightMethodBuilder(place.manager, propCandidate).apply {
returnType = domainObjectType
containingClass = aClass
val closureParam = addAndGetParameter("configuration", GROOVY_LANG_CLOSURE, true)
closureParam.putUserData(DELEGATES_TO_KEY, domainObjectFqn)
closureParam.putUserData(DELEGATES_TO_STRATEGY_KEY, Closure.DELEGATE_FIRST)
val method = aClass.findMethodsByName("create", true).firstOrNull { it.parameterList.parametersCount == argsCount }
if (method != null) navigationElement = method
}
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(wrappedBase, state)) return
}
}
}
}
| apache-2.0 | 7a967b3445624f5c99a33c30849e0ba8 | 54.251429 | 145 | 0.743407 | 5.017644 | false | false | false | false |
sephiroth74/Material-BottomNavigation | bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/FixedLayout.kt | 1 | 5141 | package it.sephiroth.android.library.bottomnavigation
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.util.Log.INFO
import android.view.MotionEvent
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import it.sephiroth.android.library.bottomnavigation.MiscUtils.log
import it.sephiroth.android.library.bottonnavigation.R
/**
* Created by crugnola on 4/4/16.
* MaterialBottomNavigation
*
* The MIT License
*/
class FixedLayout(context: Context) : ItemsLayoutContainer(context) {
private val maxActiveItemWidth: Int
private val minActiveItemWidth: Int
private var totalChildrenSize: Int = 0
private var hasFrame: Boolean = false
private var selectedIndex: Int = 0
private var itemFinalWidth: Int = 0
private var menu: MenuParser.Menu? = null
init {
val res = resources
maxActiveItemWidth = res.getDimensionPixelSize(R.dimen.bbn_fixed_maxActiveItemWidth)
minActiveItemWidth = res.getDimensionPixelSize(R.dimen.bbn_fixed_minActiveItemWidth)
}
override fun removeAll() {
removeAllViews()
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
if (!hasFrame || childCount == 0) {
return
}
if (totalChildrenSize == 0) {
totalChildrenSize = itemFinalWidth * (childCount - 1) + itemFinalWidth
}
val width = r - l
var left = (width - totalChildrenSize) / 2
for (i in 0 until childCount) {
val child = getChildAt(i)
val params = child.layoutParams
setChildFrame(child, left, 0, params.width, params.height)
left += child.width
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
hasFrame = true
if (null != menu) {
populateInternal(menu!!)
menu = null
}
}
private fun setChildFrame(child: View, left: Int, top: Int, width: Int, height: Int) {
child.layout(left, top, left + width, top + height)
}
override fun setSelectedIndex(index: Int, animate: Boolean) {
MiscUtils.log(Log.INFO, "setSelectedIndex: $index")
if (selectedIndex == index) {
return
}
val oldSelectedIndex = this.selectedIndex
this.selectedIndex = index
if (!hasFrame || childCount == 0) {
return
}
val current = getChildAt(oldSelectedIndex) as BottomNavigationFixedItemView
val child = getChildAt(index) as BottomNavigationFixedItemView
current.setExpanded(false, 0, animate)
child.setExpanded(true, 0, animate)
}
override fun setItemEnabled(index: Int, enabled: Boolean) {
log(INFO, "setItemEnabled(%d, %b)", index, enabled)
val child = getChildAt(index) as BottomNavigationItemViewAbstract
child.isEnabled = enabled
child.postInvalidate()
requestLayout()
}
override fun getSelectedIndex(): Int {
return selectedIndex
}
override fun populate(menu: MenuParser.Menu) {
log(Log.INFO, "populate: $menu")
if (hasFrame) {
populateInternal(menu)
} else {
this.menu = menu
}
}
@SuppressLint("ClickableViewAccessibility")
private fun populateInternal(menu: MenuParser.Menu) {
log(Log.DEBUG, "populateInternal")
val parent = parent as BottomNavigation
val screenWidth = parent.width
var proposedWidth = Math.min(Math.max(screenWidth / menu.itemsCount, minActiveItemWidth), maxActiveItemWidth)
if (proposedWidth * menu.itemsCount > screenWidth) {
proposedWidth = screenWidth / menu.itemsCount
}
this.itemFinalWidth = proposedWidth
for (i in 0 until menu.itemsCount) {
val item = menu.getItemAt(i)
val params = LinearLayout.LayoutParams(proposedWidth, height)
val view = BottomNavigationFixedItemView(parent, i == selectedIndex, menu)
view.item = item
view.layoutParams = params
view.isClickable = true
view.setTypeface(parent.typeface)
view.setOnTouchListener { v, event ->
val action = event.actionMasked
if (action == MotionEvent.ACTION_DOWN) {
itemClickListener?.onItemDown(this@FixedLayout, v, true, event.x, event.y)
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
itemClickListener?.onItemDown(this@FixedLayout, v, false, event.x, event.y)
}
false
}
view.setOnClickListener { v ->
itemClickListener?.onItemClick(this@FixedLayout, v, i, true)
}
view.setOnLongClickListener {
Toast.makeText(context, item.title, Toast.LENGTH_SHORT).show()
true
}
addView(view)
}
}
}
| mit | 51eaab0cc57ca37d232fa537c1ab9c68 | 31.333333 | 117 | 0.621863 | 4.549558 | false | false | false | false |
mmartin101/GhibliAPIAndroid | app/src/mock/java/com/mmartin/ghibliapi/data/PeopleFakeRemoteDataSource.kt | 1 | 1785 | package com.mmartin.ghibliapi.data
import javax.inject.Inject
import com.mmartin.ghibliapi.App
import com.mmartin.ghibliapi.data.model.Film
import com.mmartin.ghibliapi.data.model.Person
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import io.reactivex.Single
import okio.Buffer
import java.io.IOException
class PeopleFakeRemoteDataSource @Inject constructor(val app: App) : DataSource<Person>() {
private var moshi = Moshi.Builder().build()
private var personList = listOf<Person>()
override val allItems: Single<List<Person>>
get() {
return Single.create<List<Person>> { sub ->
if (personList.isEmpty()) {
try {
val inputStream = app.assets.open("json/people.json")
val type = Types.newParameterizedType(List::class.java, Film::class.java)
val jsonAdapter = moshi.adapter<List<Person>>(type)
jsonAdapter.fromJson(Buffer().readFrom(inputStream))?.let {
personList = it
sub.onSuccess(it)
}
sub.onSuccess(personList)
} catch (e: IOException) {
sub.onError(e)
}
} else {
Single.create<List<Person>> { emitter ->
emitter.onSuccess(personList)
}
}
}
}
override fun getItem(id: String): Single<Person> {
return Single.create { sub ->
personList.find { it.id == id }?.let { sub.onSuccess(it) }
?: sub.onError(NoSuchElementException("No film with that id..."))
}
}
} | mit | 208e934e73c347a4c17b9f13faed0860 | 37 | 97 | 0.542297 | 4.785523 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/feature/blocking/BlockingController.kt | 3 | 3448 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.blocking
import android.view.View
import com.bluelinelabs.conductor.RouterTransaction
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.moez.QKSMS.common.QkChangeHandler
import com.moez.QKSMS.common.base.QkController
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.animateLayoutChanges
import com.moez.QKSMS.feature.blocking.manager.BlockingManagerController
import com.moez.QKSMS.feature.blocking.messages.BlockedMessagesController
import com.moez.QKSMS.feature.blocking.numbers.BlockedNumbersController
import com.moez.QKSMS.injection.appComponent
import kotlinx.android.synthetic.main.blocking_controller.*
import kotlinx.android.synthetic.main.settings_switch_widget.view.*
import javax.inject.Inject
class BlockingController : QkController<BlockingView, BlockingState, BlockingPresenter>(), BlockingView {
override val blockingManagerIntent by lazy { blockingManager.clicks() }
override val blockedNumbersIntent by lazy { blockedNumbers.clicks() }
override val blockedMessagesIntent by lazy { blockedMessages.clicks() }
override val dropClickedIntent by lazy { drop.clicks() }
@Inject lateinit var colors: Colors
@Inject override lateinit var presenter: BlockingPresenter
init {
appComponent.inject(this)
retainViewMode = RetainViewMode.RETAIN_DETACH
layoutRes = R.layout.blocking_controller
}
override fun onViewCreated() {
super.onViewCreated()
parent.postDelayed({ parent?.animateLayoutChanges = true }, 100)
}
override fun onAttach(view: View) {
super.onAttach(view)
presenter.bindIntents(this)
setTitle(R.string.blocking_title)
showBackButton(true)
}
override fun render(state: BlockingState) {
blockingManager.summary = state.blockingManager
drop.checkbox.isChecked = state.dropEnabled
blockedMessages.isEnabled = !state.dropEnabled
}
override fun openBlockedNumbers() {
router.pushController(RouterTransaction.with(BlockedNumbersController())
.pushChangeHandler(QkChangeHandler())
.popChangeHandler(QkChangeHandler()))
}
override fun openBlockedMessages() {
router.pushController(RouterTransaction.with(BlockedMessagesController())
.pushChangeHandler(QkChangeHandler())
.popChangeHandler(QkChangeHandler()))
}
override fun openBlockingManager() {
router.pushController(RouterTransaction.with(BlockingManagerController())
.pushChangeHandler(QkChangeHandler())
.popChangeHandler(QkChangeHandler()))
}
}
| gpl-3.0 | f2a50517153dbd8c42eaba42a407cd5c | 37.741573 | 105 | 0.739849 | 4.6469 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/specs/physics/JointSpec.kt | 1 | 5061 | package com.binarymonks.jj.core.specs.physics
import com.badlogic.gdx.math.Matrix3
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.physics.box2d.JointDef
import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef
import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef
import com.badlogic.gdx.physics.box2d.joints.WeldJointDef
import com.binarymonks.jj.core.extensions.copy
import com.binarymonks.jj.core.pools.vec2
/**
* Like a [com.badlogic.gdx.physics.box2d.JointDef] but with names of Scenes in a scene rather than bodies.
*
* @param nameA instance name of Body A. Leave null to use scene Body.
* @param nameB instance name of Body B.
*/
abstract class JointSpec(
val nameA: String?,
val nameB: String
) {
var collideConnected: Boolean = false
abstract fun toJointDef(bodyA: Body, bodyB: Body, transform: Matrix3): JointDef
}
class RevoluteJointSpec(
nameA: String?,
nameB: String
) : JointSpec(nameA, nameB) {
constructor(nameA: String?,
nameB: String,
anchor: Vector2) : this(nameA, nameB) {
this.anchor = anchor
}
constructor(nameA: String?,
nameB: String,
localAnchorA: Vector2,
localAnchorB: Vector2
) : this(nameA, nameB) {
this.localAnchorB = localAnchorB
this.localAnchorA = localAnchorA
}
var anchor: Vector2? = null
private set
var localAnchorA: Vector2? = null
private set
var localAnchorB: Vector2? = null
private set
var enableLimit = false
var lowerAngle = 0f
var upperAngle = 0f
var enableMotor = false
var motorSpeed = 0f
var maxMotorTorque = 0f
override fun toJointDef(bodyA: Body, bodyB: Body, transform: Matrix3): JointDef {
val revJoint = RevoluteJointDef()
if (anchor != null) {
revJoint.initialize(bodyA, bodyB, anchor!!.copy().mul(transform))
} else {
revJoint.bodyA = bodyA
revJoint.bodyB = bodyB
revJoint.localAnchorA.set(localAnchorA!!.copy())
revJoint.localAnchorB.set(localAnchorB!!.copy())
}
revJoint.enableLimit = enableLimit
revJoint.lowerAngle = lowerAngle
revJoint.upperAngle = upperAngle
revJoint.enableMotor = enableMotor
revJoint.motorSpeed = motorSpeed
revJoint.maxMotorTorque = maxMotorTorque
return revJoint
}
}
class WeldJointSpec(
nameA: String?,
nameB: String,
val anchor: Vector2
) : JointSpec(nameA, nameB) {
var frequencyHz = 0f
var dampingRatio = 0f
override fun toJointDef(bodyA: Body, bodyB: Body, transform: Matrix3): JointDef {
val weldJoint = WeldJointDef()
weldJoint.initialize(bodyA, bodyB, anchor.copy().mul(transform))
weldJoint.frequencyHz = frequencyHz
weldJoint.dampingRatio = dampingRatio
return weldJoint
}
}
class PrismaticJointSpec(
nameA: String?,
nameB: String
) : JointSpec(nameA, nameB) {
constructor(
nameA: String?,
nameB: String,
localAnchorA: Vector2,
localAnchorB: Vector2,
localAxisA: Vector2
) : this(nameA, nameB) {
this.localAnchorA = localAnchorA
this.localAnchorB = localAnchorB
this.localAxisA = localAxisA
}
/** The local anchor point relative to body1's origin. */
var localAnchorA: Vector2? = vec2()
/** The local anchor point relative to body2's origin. */
var localAnchorB: Vector2? = vec2()
/** The local translation axis in body1. */
var localAxisA: Vector2? = vec2(1f, 0f)
/** The constrained angle between the bodies: body2_angle - body1_angle. */
var referenceAngle = 0f
/** Enable/disable the joint limit. */
var enableLimit = false
/** The lower translation limit, usually in meters. */
var lowerTranslation = 0f
/** The upper translation limit, usually in meters. */
var upperTranslation = 0f
/** Enable/disable the joint motor. */
var enableMotor = false
/** The maximum motor torque, usually in N-m. */
var maxMotorForce = 0f
/** The desired motor speed in radians per second. */
var motorSpeed = 0f
override fun toJointDef(bodyA: Body, bodyB: Body, transform: Matrix3): JointDef {
val prisJoint = PrismaticJointDef()
prisJoint.bodyA = bodyA
prisJoint.bodyB = bodyB
prisJoint.localAnchorA.set(localAnchorA)
prisJoint.localAnchorB.set(localAnchorB)
prisJoint.localAxisA.set(localAxisA)
prisJoint.referenceAngle = referenceAngle
prisJoint.enableLimit = enableLimit
prisJoint.lowerTranslation = lowerTranslation
prisJoint.upperTranslation = upperTranslation
prisJoint.enableMotor = enableMotor
prisJoint.maxMotorForce = maxMotorForce
prisJoint.motorSpeed = motorSpeed
return prisJoint
}
}
| apache-2.0 | 99143252dacfacf7fa34fb3cad9a5cdf | 30.04908 | 107 | 0.654219 | 3.776866 | false | false | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/data/templates/unofficial/kiwiInput.kt | 2 | 3544 | package com.github.czyzby.setup.data.templates.unofficial
import com.github.czyzby.setup.data.libs.unofficial.Kiwi
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.data.templates.official.ClassicTemplate
import com.github.czyzby.setup.views.ProjectTemplate
/**
* Classic project template using Kiwi utilities and listening to user input.
* @author MJ
*/
@ProjectTemplate
class KiwiInputTemplate : ClassicTemplate(){
override val id = "kiwiInputTemplate"
private lateinit var mainClass: String
override val width: String
get() = mainClass + ".WIDTH"
override val height: String
get() = mainClass + ".HEIGHT"
override val description: String
get() = "Project template included simple launchers and an `InputAwareApplicationListener` extension (from [Kiwi](https://github.com/czyzby/gdx-lml/tree/master/kiwi) library) that draws BadLogic logo and changes its color after the application is clicked/touched."
override fun apply(project: Project) {
mainClass = project.basic.mainClass
super.apply(project)
// Adding gdx-kiwi dependency:
Kiwi().initiate(project)
}
override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage};
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.github.czyzby.kiwi.util.gdx.InputAwareApplicationListener;
import com.github.czyzby.kiwi.util.gdx.asset.Disposables;
import com.github.czyzby.kiwi.util.gdx.collection.immutable.ImmutableArray;
import com.github.czyzby.kiwi.util.gdx.scene2d.Actors;
import com.github.czyzby.kiwi.util.gdx.viewport.LetterboxingViewport;
import com.github.czyzby.kiwi.util.gdx.viewport.Viewports;
/** {@link com.badlogic.gdx.ApplicationListener} implementation shared by all platforms. */
public class ${project.basic.mainClass} extends InputAwareApplicationListener {
/** Default application size. */
public static final int WIDTH = 640, HEIGHT = 480;
// Static Kiwi utility - creates an immutable array of colors:
private final Array<Color> colors = ImmutableArray.of(Color.WHITE, Color.RED, Color.GREEN,
Color.BLUE, Color.ORANGE, Color.PURPLE, Color.PINK, Color.SKY, Color.SCARLET);
private Stage stage;
private Texture texture;
private Image image;
@Override
public void initiate() {
stage = new Stage(new LetterboxingViewport());
texture = new Texture("badlogic.png");
image = new Image(texture);
stage.addActor(image);
Actors.centerActor(image);
}
@Override
public void resize(int width, int height) {
Viewports.update(stage);
Actors.centerActor(image);
}
@Override
public void render(float deltaTime) {
// InputAwareApplicationListener automatically clears the screen with black color.
stage.act(deltaTime);
stage.draw();
}
@Override
public void dispose() {
// Null-safe disposing utility method:
Disposables.disposeOf(stage, texture);
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// Changing current logo color when the screen is clicked/touched:
image.setColor(colors.random());
return true;
}
}"""
}
| unlicense | 935a0a1f5d21e44de3ee30bfdadbbdf6 | 37.107527 | 272 | 0.722912 | 4.154748 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/main/kotlin/glimpse/cameras/OrthographicCameraProjectionBuilder.kt | 1 | 1092 | package glimpse.cameras
/**
* Builder of an [OrthographicCameraProjection].
*/
class OrthographicCameraProjectionBuilder {
private var height: () -> Float = { 2f }
private var aspect: () -> Float = { 1f }
private var near: Float = 1f
private var far: Float = 100f
/**
* Sets camera projected region height lambda.
*/
fun height(height: () -> Float) {
this.height = height
}
/**
* Sets camera aspect ratio lambda.
*/
fun aspect(aspect: () -> Float) {
this.aspect = aspect
}
/**
* Sets camera near and far clipping planes.
*/
fun distanceRange(range: Pair<Float, Float>) {
near = range.first
far = range.second
}
internal fun build(): OrthographicCameraProjection = OrthographicCameraProjection(height, aspect, near, far)
}
/**
* Builds orthographic camera projecion initialized with an [init] function.
*/
fun CameraBuilder.orthographic(init: OrthographicCameraProjectionBuilder.() -> Unit) {
val cameraProjectionBuilder = OrthographicCameraProjectionBuilder()
cameraProjectionBuilder.init()
cameraProjection = cameraProjectionBuilder.build()
}
| apache-2.0 | 75ad5d1675fadc11931e7be89d13b4d3 | 23.266667 | 109 | 0.712454 | 3.84507 | false | false | false | false |
carlphilipp/stock-tracker-android | src/fr/cph/stock/android/domain/ShareValue.kt | 1 | 3056 | /**
* 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.domain
import android.os.Parcel
import android.os.Parcelable
import fr.cph.stock.android.util.UserContext
import kotlin.properties.Delegates
class ShareValue constructor() : Parcelable {
lateinit var date: String
lateinit var account: String
private var portfolioValue: Double by Delegates.notNull()
private var shareQuantity: Double by Delegates.notNull()
private var shareValue: Double by Delegates.notNull()
private var monthlyYield: Double by Delegates.notNull()
private var up: Boolean = false
var commentary: String? = null
constructor(source: Parcel) : this() {
readFromParcel(source)
}
fun getShareValue(): String {
return UserContext.FORMAT_LOCAL_ONE.format(shareValue)
}
val isUp: Boolean
get() = shareValue > 100
fun getPortfolioValue(): String {
return UserContext.FORMAT_CURRENCY_ONE.format(portfolioValue)
}
fun getShareQuantity(): String {
return UserContext.FORMAT_LOCAL_ONE.format(shareQuantity)
}
fun getMonthlyYield(): String {
return UserContext.FORMAT_CURRENCY_ONE.format(monthlyYield)
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(date)
dest.writeString(account)
dest.writeDouble(portfolioValue)
dest.writeDouble(shareQuantity)
dest.writeDouble(shareValue)
dest.writeDouble(monthlyYield)
dest.writeString(commentary)
dest.writeByte((if (up) 1 else 0).toByte()) // myBoolean = in.readByte() == 1;
}
private fun readFromParcel(source: Parcel) {
date = source.readString()
account = source.readString()
portfolioValue = source.readDouble()
shareQuantity = source.readDouble()
shareValue = source.readDouble()
monthlyYield = source.readDouble()
commentary = source.readString()
up = source.readByte().toInt() == 1
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<ShareValue> = object : Parcelable.Creator<ShareValue> {
override fun createFromParcel(source: Parcel): ShareValue {
return ShareValue(source)
}
override fun newArray(size: Int): Array<ShareValue?> {
return arrayOfNulls(size)
}
}
}
}
| apache-2.0 | 139e70429730c7bc2a187e04cf9b8870 | 29.868687 | 95 | 0.671466 | 4.500736 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/visiblequests/TeamModeQuestFilter.kt | 1 | 2583 | package de.westnordost.streetcomplete.data.visiblequests
import android.content.SharedPreferences
import androidx.core.content.edit
import de.westnordost.streetcomplete.Prefs
import de.westnordost.streetcomplete.data.osm.created_elements.CreatedElementsSource
import de.westnordost.streetcomplete.data.osm.osmquests.OsmQuest
import de.westnordost.streetcomplete.data.osmnotes.notequests.OsmNoteQuest
import de.westnordost.streetcomplete.data.quest.Quest
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
/** Controller for filtering all quests that are hidden because they are shown to other users in
* team mode. Takes care of persisting team mode settings and notifying listeners about changes */
@Singleton class TeamModeQuestFilter @Inject internal constructor(
private val createdElementsSource: CreatedElementsSource,
private val prefs: SharedPreferences
) {
/* Must be a singleton because there is a listener that should respond to a change in the
* shared preferences */
private val teamSize: Int get() = prefs.getInt(Prefs.TEAM_MODE_TEAM_SIZE, -1)
val indexInTeam: Int get() = prefs.getInt(Prefs.TEAM_MODE_INDEX_IN_TEAM, -1)
val isEnabled: Boolean get() = teamSize > 0
interface TeamModeChangeListener {
fun onTeamModeChanged(enabled: Boolean)
}
private val listeners: MutableList<TeamModeChangeListener> = CopyOnWriteArrayList()
fun isVisible(quest: Quest): Boolean =
!isEnabled ||
quest.stableId < 0 ||
quest is OsmQuest && createdElementsSource.contains(quest.elementType, quest.elementId) ||
quest.stableId % teamSize == indexInTeam.toLong()
private val Quest.stableId: Long get() = when(this) {
is OsmQuest -> elementId
is OsmNoteQuest -> id
else -> 0
}
fun enableTeamMode(teamSize: Int, indexInTeam: Int) {
prefs.edit {
putInt(Prefs.TEAM_MODE_TEAM_SIZE, teamSize)
putInt(Prefs.TEAM_MODE_INDEX_IN_TEAM, indexInTeam)
}
listeners.forEach { it.onTeamModeChanged(true) }
}
fun disableTeamMode() {
prefs.edit().putInt(Prefs.TEAM_MODE_TEAM_SIZE, -1).apply()
listeners.forEach { it.onTeamModeChanged(false) }
}
/* ------------------------------------ Listeners ------------------------------------------- */
fun addListener(listener: TeamModeChangeListener) {
listeners.add(listener)
}
fun removeListener(listener: TeamModeChangeListener) {
listeners.remove(listener)
}
}
| gpl-3.0 | c89f6195a9dd3f25b504cfdb4b81153a | 37.552239 | 100 | 0.701123 | 4.492174 | false | false | false | false |
IntershopCommunicationsAG/scmversion-gradle-plugin | src/main/kotlin/com/intershop/gradle/scm/services/file/FileLocalService.kt | 1 | 2189 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.scm.services.file
import com.intershop.gradle.scm.services.ScmLocalService
import com.intershop.gradle.scm.utils.PrefixConfig
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
/**
* This is the container of all information from an existing
* working copy without any access to the remote location of the project.
*/
open class FileLocalService(projectDir: File,
prefixes: PrefixConfig) : ScmLocalService(projectDir, prefixes) {
companion object {
@JvmStatic
protected val log: Logger = LoggerFactory.getLogger(this::class.java.name)
}
init {
log.warn("This project is not included in a SCM!")
}
/**
* It returns the remote url, calculated from the properties of the working copy (read only).
* For this provider it is only the file path.
*
* @return remote url
*/
override val remoteUrl: String
get() = projectDir.toURI().toURL().toString()
/**
* The revision id from the working copy (read only).
* For this provider it is always 'unknown'.
*
* @return revision id
*/
override val revID: String
get() = "unknown"
/**
* The base (stabilization) branch name of the current working copy.
*
* @property branchName
*/
override val branchName: String
get() = "trunk"
/**
* This is true, if the local working copy changed.
*
* @property changed
*/
override val changed: Boolean
get() = true
}
| apache-2.0 | db8e4e233371278fce5e3ad905080789 | 28.581081 | 97 | 0.667885 | 4.309055 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/catalog/CatalogBuilderBase.kt | 1 | 1062 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("UNCHECKED_CAST")
package org.lanternpowered.server.catalog
import org.lanternpowered.api.key.NamespacedKey
import org.spongepowered.api.CatalogType
import org.spongepowered.api.util.CatalogBuilder
import org.spongepowered.api.util.ResettableBuilder
abstract class CatalogBuilderBase<C : CatalogType, B : ResettableBuilder<C, B>> : CatalogBuilder<C, B> {
protected var key: NamespacedKey? = null
override fun key(key: NamespacedKey) = apply {
check(key.namespace.isNotBlank()) { "The key namespace may not be blank." }
check(key.value.isNotBlank()) { "The key value may not be blank." }
this.key = key
} as B
override fun reset() = apply {
this.key = null
} as B
}
| mit | 2cfa89e3cfe9184a96e1a2d99c1056dd | 31.181818 | 104 | 0.707156 | 3.847826 | false | false | false | false |
mediathekview/MediathekView | src/main/java/mediathek/tool/swing/MultilineLabel.kt | 1 | 1520 | package mediathek.tool.swing
import java.awt.Dimension
import java.awt.Rectangle
import javax.swing.*
import javax.swing.plaf.UIResource
import javax.swing.text.DefaultCaret
class MultilineLabel : JTextArea() {
private fun initComponents() {
adjustUI()
}
override fun updateUI() {
super.updateUI()
adjustUI()
}
/**
* Adjusts UI to make sure it looks like a label instead of a text area.
*/
private fun adjustUI() {
lineWrap = true
wrapStyleWord = true
isEditable = false
isRequestFocusEnabled = false
isFocusable = false
setComponentTransparent(this)
caret = object : DefaultCaret() {
override fun adjustVisibility(nloc: Rectangle) {}
}
LookAndFeel.installBorder(this, "Label.border")
val fg = foreground
if (fg == null || fg is UIResource) {
foreground = UIManager.getColor("Label.foreground")
}
val f = font
if (f == null || f is UIResource) {
font = UIManager.getFont("Label.font")
}
background = null
}
override fun getMinimumSize(): Dimension {
return preferredSize
}
private fun setComponentTransparent(component: JComponent) {
component.isOpaque = false
component.putClientProperty("Nimbus.Overrides.InheritDefaults", false)
component.putClientProperty("Nimbus.Overrides", UIDefaults())
}
init {
initComponents()
}
} | gpl-3.0 | 5bb53180dd3f3e5e3a1052bb96be1d93 | 25.684211 | 78 | 0.619079 | 4.85623 | false | false | false | false |
devmil/PaperLaunch | app/src/main/java/de/devmil/paperlaunch/view/utils/IntentSelector.kt | 1 | 16935 | /*
* Copyright 2015 Devmil Solutions
*
* 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 de.devmil.paperlaunch.view.utils
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.content.pm.ResolveInfo
import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import de.devmil.paperlaunch.R
import java.lang.ref.WeakReference
import java.util.*
class IntentSelector : Activity() {
private var llWait: LinearLayout? = null
private var lvActivities: ExpandableListView? = null
private var chkShowAllActivities: CheckBox? = null
private var lvShortcuts: ExpandableListView? = null
private var txtShortcuts: TextView? = null
private var toolbar: Toolbar? = null
class SearchTask
constructor(intentSelector : IntentSelector) : AsyncTask<Unit, Int, Unit>() {
private val entries = mutableListOf<IntentApplicationEntry>()
var isAnotherSearchRunning: Boolean = false
var isObsolete: Boolean = false
override fun doInBackground(vararg params: Unit?) {
//this approach can kill the PackageManager if there are too many apps installed
// List<ResolveInfo> shortcutResolved = getPackageManager().queryIntentActivities(shortcutIntent, PackageManager.GET_ACTIVITIES | PackageManager.GET_INTENT_FILTERS);
// List<ResolveInfo> mainResolved = getPackageManager().queryIntentActivities(mainIntent, PackageManager.GET_ACTIVITIES | PackageManager.GET_INTENT_FILTERS);
// List<ResolveInfo> launcherResolved = getPackageManager().queryIntentActivities(launcherIntent, PackageManager.GET_ACTIVITIES | PackageManager.GET_INTENT_FILTERS);
intentSelectorRef.get()?.let {
val pm = it.packageManager
val shortcutResolved = ArrayList<ResolveInfo>()
val mainResolved = ArrayList<ResolveInfo>()
val launcherResolved = ArrayList<ResolveInfo>()
val appInfos = pm.getInstalledApplications(PackageManager.GET_META_DATA)
val showAll = it.chkShowAllActivities!!.isChecked
for (appInfo in appInfos) {
if(isCancelled || isObsolete) {
return
}
val shortcutIntent = Intent(Intent.ACTION_CREATE_SHORTCUT)
shortcutIntent.`package` = appInfo.packageName
val appShortcutResolved = pm.queryIntentActivities(shortcutIntent, PackageManager.GET_META_DATA)
shortcutResolved.addAll(appShortcutResolved)
var addMainActivities = true
if (showAll) {
try {
val pi = pm.getPackageInfo(appInfo.packageName, PackageManager.GET_ACTIVITIES or PackageManager.GET_INTENT_FILTERS)
for (ai in pi.activities) {
val ri = ResolveInfo()
ri.activityInfo = ai
mainResolved.add(ri)
}
addMainActivities = false
} catch (e: Exception) {
}
}
if (addMainActivities) {
val mainIntent = Intent(Intent.ACTION_MAIN)
mainIntent.`package` = appInfo.packageName
val appMainResolved = pm.queryIntentActivities(mainIntent, PackageManager.GET_META_DATA)
mainResolved.addAll(appMainResolved)
}
val launcherIntent = Intent(Intent.ACTION_MAIN)
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER)
launcherIntent.`package` = appInfo.packageName
val appLauncherResolved = pm.queryIntentActivities(launcherIntent, PackageManager.GET_META_DATA)
launcherResolved.addAll(appLauncherResolved)
}
for (ri in shortcutResolved) {
if(isCancelled || isObsolete) {
return
}
addResolveInfo(ri, IntentApplicationEntry.IntentType.Shortcut, false, entries)
}
for (ri in mainResolved) {
if(isCancelled || isObsolete) {
return
}
addResolveInfo(ri, IntentApplicationEntry.IntentType.Main, showAll, entries)
}
for (ri in launcherResolved) {
if(isCancelled || isObsolete) {
return
}
addResolveInfo(ri, IntentApplicationEntry.IntentType.Launcher, false, entries)
}
//sort
val comparator = Comparator<IntentApplicationEntry> { object1, object2 -> object1.compareTo(object2) }
entries.sortWith(comparator)
entries.forEach { if(!isCancelled && !isObsolete) it.sort() }
}
}
override fun onPreExecute() {
super.onPreExecute()
val localIntentSelector = intentSelectorRef.get()
localIntentSelector?.runOnUiThread { localIntentSelector.llWait!!.visibility = View.VISIBLE }
}
override fun onPostExecute(result: Unit?) {
super.onPostExecute(result)
val localIntentSelector = intentSelectorRef.get()
localIntentSelector?.runOnUiThread {
if(!isCancelled && !isObsolete) {
localIntentSelector.adapterActivities = IntentSelectorAdapter(localIntentSelector, entries, IntentApplicationEntry.IntentType.Main)
localIntentSelector.adapterShortcuts = IntentSelectorAdapter(localIntentSelector, entries, IntentApplicationEntry.IntentType.Shortcut)
localIntentSelector.lvActivities!!.setAdapter(localIntentSelector.adapterActivities)
localIntentSelector.lvShortcuts!!.setAdapter(localIntentSelector.adapterShortcuts)
}
if(!isAnotherSearchRunning) {
localIntentSelector.llWait!!.visibility = View.GONE
}
}
}
override fun onCancelled() {
super.onCancelled()
val localIntentSelector = intentSelectorRef.get()
localIntentSelector?.runOnUiThread {
if(!isAnotherSearchRunning) {
localIntentSelector.llWait!!.visibility = View.GONE
}
}
}
private fun addResolveInfo(ri: ResolveInfo, intentType: IntentApplicationEntry.IntentType, addAll: Boolean, entries : MutableList<IntentApplicationEntry>) {
intentSelectorRef.get()?.let {
try {
if (!addAll && !ri.activityInfo.exported)
return
var newEntry = IntentApplicationEntry(it, ri.activityInfo.packageName)
if (!entries.contains(newEntry)) {
entries.add(newEntry)
} else {
newEntry = entries[entries.indexOf(newEntry)]
}
newEntry.addResolveInfo(ri, intentType)
} catch (e: NameNotFoundException) {
Log.e(TAG, "Error while adding a package", e)
}
}
}
private var intentSelectorRef: WeakReference<IntentSelector> = WeakReference(intentSelector)
}
private var mSearchTask : SearchTask? = null
internal var adapterActivities: IntentSelectorAdapter? = null
internal var adapterShortcuts: IntentSelectorAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(mSearchTask != null) {
mSearchTask!!.cancel(true)
mSearchTask = null
}
var shortcutText = ""
if (intent.hasExtra(EXTRA_SHORTCUT_TEXT))
shortcutText = intent.getStringExtra(EXTRA_SHORTCUT_TEXT)
var shortcutLabel = "Shortcuts"
if (intent.hasExtra(EXTRA_STRING_SHORTCUTS))
shortcutLabel = intent.getStringExtra(EXTRA_STRING_SHORTCUTS)
var activitiesLabel = "Shortcuts"
if (intent.hasExtra(EXTRA_STRING_ACTIVITIES))
activitiesLabel = intent.getStringExtra(EXTRA_STRING_ACTIVITIES)
setContentView(R.layout.common__intentselectorview)
llWait = findViewById(R.id.common__intentSelector_llWait)
// progressWait = (ProgressBar)findViewById(R.id.intentSelector_progressWait);
lvActivities = findViewById(R.id.common__intentSelector_lvActivities)
chkShowAllActivities = findViewById(R.id.common__intentSelector_chkShowAllActivities)
lvShortcuts = findViewById(R.id.common__intentSelector_lvShortcuts)
txtShortcuts = findViewById(R.id.common__intentSelector_txtShortcuts)
toolbar = findViewById(R.id.common__intentSelector_toolbar)
setActionBar(toolbar)
txtShortcuts!!.text = shortcutText
lvActivities!!.setOnChildClickListener { _, _, groupPosition, childPosition, _ ->
val resultIntent = Intent(Intent.ACTION_MAIN)
val entry = adapterActivities!!.getChild(groupPosition, childPosition) as IntentApplicationEntry.IntentItem
resultIntent.setClassName(entry.packageName, entry.activityName)
setResultIntent(resultIntent)
true
}
chkShowAllActivities!!.setOnCheckedChangeListener { _, _ -> startSearch() }
lvShortcuts!!.setOnChildClickListener { _, _, groupPosition, childPosition, _ ->
val shortcutIntent = Intent(Intent.ACTION_CREATE_SHORTCUT)
val entry = adapterShortcuts!!.getChild(groupPosition, childPosition) as IntentApplicationEntry.IntentItem
shortcutIntent.setClassName(entry.packageName, entry.activityName)
startActivityForResult(shortcutIntent, CREATE_SHORTCUT_REQUEST)
false
}
val tabs = this.findViewById<TabHost>(android.R.id.tabhost)
tabs.setup()
val tspecActivities = tabs.newTabSpec(activitiesLabel)
tspecActivities.setIndicator(activitiesLabel)
tspecActivities.setContent(R.id.common__intentSelector_tabActivities)
tabs.addTab(tspecActivities)
val tspecShortcuts = tabs.newTabSpec(shortcutLabel)
tspecShortcuts.setIndicator(shortcutLabel)
if (shortcutText == "") {
tspecShortcuts.setContent(R.id.common__intentSelector_tabShortcuts)
txtShortcuts!!.visibility = View.GONE
} else {
tspecShortcuts.setContent(R.id.common__intentSelector_tabTextShortcuts)
lvShortcuts!!.visibility = View.GONE
}
tabs.addTab(tspecShortcuts)
llWait!!.visibility = View.VISIBLE
startSearch()
}
private fun startSearch() {
if (mSearchTask != null) {
mSearchTask!!.isAnotherSearchRunning = true
mSearchTask!!.isObsolete = true
mSearchTask!!.cancel(true)
mSearchTask = null
}
mSearchTask = SearchTask(this)
mSearchTask!!.execute()
}
private fun setResultIntent(intent: Intent) {
setResult(Activity.RESULT_OK, intent)
[email protected]()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(data == null) {
return
}
if (requestCode == CREATE_SHORTCUT_REQUEST && resultCode == Activity.RESULT_OK) {
setResultIntent(data)
}
super.onActivityResult(requestCode, resultCode, data)
}
internal class IntentSelectorAdapter(private val context: Context, entriesList: List<IntentApplicationEntry>, private val intentType: IntentApplicationEntry.IntentType) : BaseExpandableListAdapter() {
private val entries: MutableList<IntentApplicationEntry>
init {
this.entries = entriesList
.filter { getSubList(it).isNotEmpty() }
.toMutableList()
}
fun getSubList(entry: IntentApplicationEntry): List<IntentApplicationEntry.IntentItem> {
return IntentSelector.getSubList(entry, intentType)
}
override fun getChild(groupPosition: Int, childPosition: Int): Any {
return getSubList(entries[groupPosition])[childPosition]
}
override fun getChildId(groupPosition: Int, childPosition: Int): Long {
return (groupPosition * 1000 + childPosition).toLong()
}
override fun getChildView(groupPosition: Int, childPosition: Int,
isLastChild: Boolean, convertView: View?, parent: ViewGroup): View {
var effectiveConvertView = convertView
if (effectiveConvertView == null) {
effectiveConvertView = LayoutInflater.from(context).inflate(R.layout.common__intentselectoritem, parent, false)
}
val txt = effectiveConvertView!!.findViewById<TextView>(R.id.common__intentselectoritem_text)
val txtActivityName = effectiveConvertView.findViewById<TextView>(R.id.common__intentselectoritem_activityName)
txt.text = getSubList(entries[groupPosition])[childPosition].displayName
txtActivityName.text = getSubList(entries[groupPosition])[childPosition].activityName
return effectiveConvertView
}
override fun getChildrenCount(groupPosition: Int): Int {
return getSubList(entries[groupPosition]).size
}
override fun getGroup(groupPosition: Int): Any {
return entries[groupPosition]
}
override fun getGroupCount(): Int {
return entries.size
}
override fun getGroupId(groupPosition: Int): Long {
return (groupPosition * 1000).toLong()
}
override fun getGroupView(groupPosition: Int, isExpanded: Boolean,
convertView: View?, parent: ViewGroup): View {
var effectiveConvertView = convertView
if (effectiveConvertView == null) {
effectiveConvertView = LayoutInflater.from(context).inflate(R.layout.common__intentselectorgroup, parent, false)
}
val img = effectiveConvertView!!.findViewById<ImageView>(R.id.common__intentselectorgroup_img)
val txt = effectiveConvertView.findViewById<TextView>(R.id.common__intentselectorgroup_text)
txt.text = entries[groupPosition].name
val appIcon = entries[groupPosition].getAppIcon()
if (appIcon != null) {
img.setImageDrawable(entries[groupPosition].getAppIcon())
img.visibility = View.VISIBLE
} else {
img.visibility = View.INVISIBLE
}
return effectiveConvertView
}
override fun hasStableIds(): Boolean {
return false
}
override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
return true
}
}
companion object {
private val TAG = IntentSelector::class.java.simpleName
private val CREATE_SHORTCUT_REQUEST = 1
var EXTRA_SHORTCUT_TEXT = "de.devmil.common.extras.SHORTCUT_TEXT"
var EXTRA_STRING_SHORTCUTS = "de.devmil.common.extras.STRING_SHORTCUTS"
var EXTRA_STRING_ACTIVITIES = "de.devmil.common.extras.STRING_ACTIVITIES"
private fun getSubList(entry: IntentApplicationEntry, intentType: IntentApplicationEntry.IntentType): List<IntentApplicationEntry.IntentItem> {
when (intentType) {
IntentApplicationEntry.IntentType.Main, IntentApplicationEntry.IntentType.Launcher -> return entry.getMainActivityIntentItems()
IntentApplicationEntry.IntentType.Shortcut -> return entry.getShortcutIntentItems()
}
}
}
}
| apache-2.0 | 43df247b66fe75087ef0488531424ebb | 42.201531 | 204 | 0.62917 | 5.297154 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Interactors/Helpers/AESCryptHelper.kt | 1 | 1317 | package com.polito.sismic.Interactors.Helpers
import android.util.Base64
import java.nio.charset.Charset
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
/**
* Created by Matteo on 14/10/2017.
*/
class AESCryptHelper {
companion object {
private val ALGORITHM = "AES/CBC/PKCS5Padding"
private val KEY = "seismicsverifies"
fun encrypt(value: String): String {
val key = generateKey()
val cipher = Cipher.getInstance(ALGORITHM)
cipher.init(Cipher.ENCRYPT_MODE, key)
val encryptedByteValue = cipher.doFinal(value.toByteArray(charset("utf-8")))
return Base64.encodeToString(encryptedByteValue, Base64.DEFAULT)
}
fun decrypt(value: String): String {
val key = generateKey()
val cipher = Cipher.getInstance(ALGORITHM)
cipher.init(Cipher.DECRYPT_MODE, key)
val decryptedValue64 = Base64.decode(value, Base64.DEFAULT)
val decryptedByteValue = cipher.doFinal(decryptedValue64)
return String(decryptedByteValue, Charset.defaultCharset()) //utf-8
}
private fun generateKey(): SecretKeySpec {
return SecretKeySpec(AESCryptHelper.KEY.toByteArray(), AESCryptHelper.ALGORITHM)
}
}
} | mit | 8c1fbd881aa3dabf1f076c9ca4671e27 | 29.651163 | 92 | 0.657555 | 4.360927 | false | false | false | false |
clappr/clappr-android | clappr/src/test/kotlin/io/clappr/player/playback/ExoPlayerTestUtil.kt | 1 | 1922 | package io.clappr.player.playback
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.Format
import com.google.android.exoplayer2.source.TrackGroup
import com.google.android.exoplayer2.source.TrackGroupArray
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.trackselection.MappingTrackSelector
import io.mockk.every
import io.mockk.mockk
fun buildAvailableTracks(vararg renderers: Pair<Int, List<String?>>): MappingTrackSelector {
val rendererMap = renderers.toMap()
val trackSelector = mockk<DefaultTrackSelector>(relaxUnitFun = true)
val mappedTrackInfo = mockk<MappingTrackSelector.MappedTrackInfo>()
every { trackSelector.currentMappedTrackInfo } returns mappedTrackInfo
every { mappedTrackInfo.rendererCount } returns rendererMap.size
rendererMap.keys.forEachIndexed { index, rendererType ->
val languages = rendererMap[rendererType].orEmpty()
val formats = languages.map { createFormat(rendererType, it) }
val trackGroups = formats.map { TrackGroup(it) }.toTypedArray()
val trackGroupArray = TrackGroupArray(*trackGroups)
every { mappedTrackInfo.getRendererType(index) } returns rendererType
every { mappedTrackInfo.getTrackGroups(index) } returns trackGroupArray
}
return trackSelector
}
private fun createFormat(renderType: Int, language: String?) = when (renderType) {
C.TRACK_TYPE_AUDIO -> createAudioFormat(language)
C.TRACK_TYPE_TEXT -> createTextFormat(language)
else -> createSampleFormat()
}
private fun createAudioFormat(language: String?) =
Format.createAudioSampleFormat(null, null, null, 0, 0, 0, 0, null, null, 0, language)
private fun createTextFormat(language: String?) =
Format.createTextSampleFormat(null, null, 0, language)
private fun createSampleFormat() =
Format.createSampleFormat(null, null, 0) | bsd-3-clause | 53862c63ec905aadf530eb6cc1a2ada9 | 40.804348 | 92 | 0.771592 | 4.449074 | false | false | false | false |
myTargetSDK/mytarget-android | myTargetDemo/app/src/main/java/com/my/targetDemoApp/activities/InstreamActivity.kt | 1 | 11408 | package com.my.targetDemoApp.activities
import android.net.Uri
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.DefaultTimeBar
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.google.android.material.snackbar.Snackbar
import com.my.target.instreamads.InstreamAd
import com.my.target.instreamads.InstreamAdPlayer
import com.my.targetDemoApp.AdvertisingType
import com.my.targetDemoApp.R
import com.my.targetDemoApp.addParsedString
import com.my.targetDemoApp.databinding.ActivityNormalInstreamBinding
import com.my.targetDemoApp.player.DefaultPlayerEventListener
class InstreamActivity : AppCompatActivity(), DefaultPlayerEventListener,
InstreamAd.InstreamAdListener {
companion object {
const val KEY_SLOT = "slotId"
const val KEY_PARAMS = "params"
const val TAG = "InstreamActivity"
}
private var loaded: Boolean = false
private var slotId: Int = AdvertisingType.INSTREAM.defaultSlot
private var params: String? = null
private var currentAd: String? = null
private var prerollPlayed = false
private var postRollPlayed = false
private var currentMidPoint: Float? = null
private var instreamAdBanner: InstreamAd.InstreamAdBanner? = null
private var bigPlayer: InstreamAdPlayer? = null
private var rootPadding: Int = 0
private lateinit var viewBinding: ActivityNormalInstreamBinding
private lateinit var instreamAd: InstreamAd
private lateinit var exoPlayer: SimpleExoPlayer
private lateinit var mediaSource: MediaSource
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityNormalInstreamBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
slotId = intent.getIntExtra(KEY_SLOT, AdvertisingType.INSTREAM.defaultSlot)
params = intent.getStringExtra(KEY_PARAMS)
initPlayer()
initAd()
rootPadding = viewBinding.rootContentLayout.paddingLeft
}
private fun initAd() {
instreamAd = InstreamAd(slotId, this)
instreamAd.customParams.addParsedString(params)
instreamAd.useDefaultPlayer()
bigPlayer = instreamAd.player
instreamAd.listener = this
}
private fun initPlayer() {
exoPlayer = SimpleExoPlayer.Builder(this)
.build()
mediaSource = ProgressiveMediaSource.Factory(
DefaultDataSourceFactory(this, Util.getUserAgent(this, "myTarget"))
)
.createMediaSource(
MediaItem.fromUri(Uri.parse("https://r.mradx.net/img/ED/518795.mp4"))
)
exoPlayer.addListener(this)
exoPlayer.playWhenReady = false
viewBinding.exoplayerView.player = exoPlayer
viewBinding.exoplayerView.keepScreenOn = true
exoPlayer.setMediaSource(mediaSource)
exoPlayer.prepare()
viewBinding.exoplayerView.requestFocus()
viewBinding.btnLoad.setOnClickListener {
instreamAd.load()
setStatus(process = "Ad loading")
}
viewBinding.btnPause.setOnClickListener { instreamAd.pause() }
viewBinding.btnResume.setOnClickListener { instreamAd.resume() }
viewBinding.btnStop.setOnClickListener { instreamAd.stop() }
viewBinding.btnSkipBanner.setOnClickListener {
instreamAd.skipBanner()
}
viewBinding.btnSkip.setOnClickListener {
instreamAd.skip()
}
viewBinding.btnCta.setOnClickListener { instreamAd.handleClick() }
}
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playbackState == Player.STATE_READY && playWhenReady) {
startPreroll()
} else if (playbackState == Player.STATE_ENDED) {
startPostRoll()
}
}
override fun onPause() {
super.onPause()
if (currentAd != null) {
instreamAd.pause()
} else {
exoPlayer.playWhenReady = false
}
}
override fun onResume() {
super.onResume()
if (currentAd != null) {
instreamAd.resume()
}
}
override fun onLoad(ad: InstreamAd) {
setStatus(status = "Ad is loaded")
processLoadedAd(ad)
}
override fun onNoAd(reason: String, ad: InstreamAd) {
setStatus(status = "No ad")
}
override fun onError(reason: String, ad: InstreamAd) {
setStatus(status = "Error $reason")
}
override fun onBannerStart(ad: InstreamAd, banner: InstreamAd.InstreamAdBanner) {
viewBinding.exoplayerView.hideController()
viewBinding.exoplayerView.useController = false
var status = "Banner started: $currentAd"
if (currentAd == "midroll") {
status += " на $currentMidPoint"
}
setStatus("Banner playing", status)
processBanner(banner)
}
override fun onBannerResume(p0: InstreamAd, p1: InstreamAd.InstreamAdBanner) {
Log.d(TAG, "onBannerResume")
}
override fun onBannerPause(p0: InstreamAd, p1: InstreamAd.InstreamAdBanner) {
Log.d(TAG, "onBannerPause")
}
override fun onBannerComplete(ad: InstreamAd, banner: InstreamAd.InstreamAdBanner) {
viewBinding.exoplayerView.useController = true
viewBinding.exoplayerView.isEnabled = true
setStatus(status = "Banner finished")
processBanner()
showSkipButton(false)
}
override fun onBannerTimeLeftChange(timeLeft: Float, duration: Float, ad: InstreamAd) {
instreamAdBanner?.let {
val position: Float = it.duration - timeLeft
viewBinding.tvPositionContent.text = position.toString()
if (it.allowClose && (position >= it.allowCloseDelay)) {
showSkipButton(true)
}
}
}
override fun onComplete(section: String, ad: InstreamAd) {
setStatus(status = "Ad section finished")
viewBinding.videoFrame.removeView(instreamAd.player?.view)
currentAd = null
exoPlayer.playWhenReady = true
}
override fun onBannerShouldClose()
{
}
private fun startPreroll() {
if (prerollPlayed || !loaded) {
return
}
prerollPlayed = true
currentAd = "preroll"
exoPlayer.playWhenReady = false
if (addAdPlayer()) {
instreamAd.startPreroll()
setStatus(status = "Starting preroll")
}
}
private fun startPostRoll() {
if (postRollPlayed || !loaded) {
return
}
postRollPlayed = true
currentAd = "postroll"
exoPlayer.playWhenReady = false
if (addAdPlayer()) {
instreamAd.startPostroll()
setStatus(status = "Starting postroll")
}
}
private fun startMidroll(midPoint: Float) {
if (!loaded) {
return
}
if (!instreamAd.midPoints.any { it == midPoint }) {
return
}
currentAd = "midroll"
exoPlayer.playWhenReady = false
if (addAdPlayer()) {
instreamAd.startMidroll(midPoint)
setStatus(status = "Starting midroll at $midPoint")
currentMidPoint = midPoint
}
}
private fun addAdPlayer(): Boolean {
if (instreamAd.player?.view?.parent != null) {
Snackbar.make(
viewBinding.rootContentLayout, "Player already created",
Snackbar.LENGTH_SHORT
)
.show()
return false
}
viewBinding.videoFrame.addView(
instreamAd.player?.view, 1,
ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
)
return true
}
private fun processLoadedAd(ad: InstreamAd) {
loaded = true
viewBinding.tvFullscreenContent.text = boolTextValue(ad.isFullscreen)
viewBinding.tvLoadingTimeoutContent.text = ad.loadingTimeout.toString()
viewBinding.tvQualityContent.text = ad.videoQuality.toString()
instreamAd.midPoints
ad.configureMidpoints((exoPlayer.duration.toFloat() / 1000))
processMidPoints()
}
private fun processBanner(banner: InstreamAd.InstreamAdBanner? = null) {
instreamAdBanner = banner
viewBinding.tvDurationContent.text = banner?.duration?.toString() ?: getString(R.string.n_a)
viewBinding.tvDimensionsContent.text =
banner?.let { "${banner.videoWidth}x${banner.videoHeight}" } ?: getString(
R.string.n_a
)
viewBinding.tvCloseDelayContent.text =
banner?.allowCloseDelay?.toString() ?: getString(R.string.n_a)
viewBinding.tvAllowcloseContent.text = boolTextValue(banner?.allowClose)
viewBinding.tvHaspauseContent.text = boolTextValue(banner?.allowPause)
viewBinding.tvPositionContent.text = getString(R.string.n_a)
viewBinding.btnPause.isEnabled = banner?.allowPause ?: true
viewBinding.btnResume.isEnabled = banner?.allowPause ?: true
showCtaButton(banner?.ctaText)
}
private fun showCtaButton(ctaText: String?) {
if (ctaText == null) {
viewBinding.btnCta.visibility = View.GONE
} else {
viewBinding.btnCta.visibility = View.VISIBLE
}
viewBinding.btnCta.text = ctaText
}
private fun showSkipButton(b: Boolean) {
if (b) {
viewBinding.btnSkipBanner.visibility = View.VISIBLE
viewBinding.btnSkip.visibility = View.VISIBLE
} else {
viewBinding.btnSkipBanner.visibility = View.GONE
viewBinding.btnSkip.visibility = View.GONE
}
}
private fun processMidPoints() {
val adGroupTimesMs = instreamAd.midPoints.map { (it * 1000).toLong() }
.toLongArray()
viewBinding.root.findViewById<DefaultTimeBar>(R.id.exo_progress)
.setAdGroupTimesMs(
adGroupTimesMs, BooleanArray(adGroupTimesMs.size) { true },
adGroupTimesMs.size
)
for (midPoint in adGroupTimesMs) {
exoPlayer.createMessage { _, _ -> startMidroll((midPoint / 1000).toFloat()) }
.setPosition(midPoint)
.setLooper(Looper.getMainLooper())
.send()
}
}
private fun boolTextValue(bool: Boolean?): String {
return when (bool) {
true -> "☑"
false -> "☐"
else -> getString(R.string.n_a)
}
}
private fun setStatus(process: String = "", status: String = "") {
viewBinding.tvProcessContent.text = process
viewBinding.tvStatusContent.text = status
}
} | lgpl-3.0 | 4c69a5a60af604f5368e7a23b6ba18a2 | 32.9375 | 100 | 0.645325 | 4.506719 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-android | superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/ui/managed/AdViewJavaScriptBridge.kt | 1 | 1064 | package tv.superawesome.sdk.publisher.common.ui.managed
import android.webkit.JavascriptInterface
class AdViewJavaScriptBridge(private val listener: Listener) {
@JavascriptInterface
fun adLoaded() = listener.adLoaded()
@JavascriptInterface
fun adEmpty() = listener.adEmpty()
@JavascriptInterface
fun adFailedToLoad() = listener.adFailedToLoad()
@JavascriptInterface
fun adAlreadyLoaded() = listener.adAlreadyLoaded()
@JavascriptInterface
fun adShown() = listener.adShown()
@JavascriptInterface
fun adFailedToShow() = listener.adFailedToShow()
@JavascriptInterface
fun adClicked() = listener.adClicked()
@JavascriptInterface
fun adEnded() = listener.adEnded()
@JavascriptInterface
fun adClosed() = listener.adClosed()
interface Listener {
fun adLoaded()
fun adEmpty()
fun adFailedToLoad()
fun adAlreadyLoaded()
fun adShown()
fun adFailedToShow()
fun adClicked()
fun adEnded()
fun adClosed()
}
} | lgpl-3.0 | 258ebdb70b19f4dd6d922959be2658fc | 19.480769 | 62 | 0.676692 | 4.81448 | false | false | false | false |
ahmedeltaher/MVP-Sample | app/src/main/java/com/task/data/remote/RemoteRepository.kt | 1 | 1924 | package com.task.data.remote
import com.task.App
import com.task.data.remote.service.NewsService
import com.task.utils.Constants
import com.task.utils.Constants.INSTANCE.ERROR_UNDEFINED
import com.task.utils.Network.Utils.isConnected
import retrofit2.Call
import java.io.IOException
import javax.inject.Inject
/**
* Created by AhmedEltaher on 5/12/2016
*/
class RemoteRepository @Inject
constructor(private val serviceGenerator: ServiceGenerator) : RemoteSource {
override suspend fun requestNews(): ServiceResponse? {
return if (!isConnected(App.context)) {
ServiceResponse(ServiceError(code = -1, description = ServiceError.NETWORK_ERROR))
} else {
val newsService = serviceGenerator.createService(NewsService::class.java, Constants.BASE_URL)
processCall(newsService.fetchNews(), false)
}
}
private fun processCall(call: Call<*>, isVoid: Boolean): ServiceResponse {
if (!isConnected(App.context)) {
return ServiceResponse(ServiceError())
}
try {
val response = call.execute()
?: return ServiceResponse(ServiceError(ServiceError.NETWORK_ERROR, ERROR_UNDEFINED))
val responseCode = response.code()
/**
* isVoid is for APIs which reply only with code without any body, such as some Apis
* reply with 200 or 401....
*/
return if (response.isSuccessful) {
val apiResponse: Any? = if (isVoid) null else response.body()
ServiceResponse(responseCode, apiResponse)
} else {
val serviceError = ServiceError(response.message(), responseCode)
ServiceResponse(serviceError)
}
} catch (e: IOException) {
return ServiceResponse(ServiceError(ServiceError.NETWORK_ERROR, ERROR_UNDEFINED))
}
}
}
| apache-2.0 | 46a80ead31c2fe9e87f3114552e84220 | 35.301887 | 105 | 0.647609 | 4.704156 | false | false | false | false |
NextFaze/dev-fun | test/src/testData/kotlin/tested/kapt_and_compile/simple_jvm_static_functions_in_objects/SimpleJvmStaticFunctionsInObjects.kt | 1 | 1901 | @file:Suppress("unused", "PackageName")
package tested.kapt_and_compile.simple_jvm_static_functions_in_objects
import com.nextfaze.devfun.function.DeveloperFunction
annotation class SimpleJvmStaticFunctionsInObjects
object SimpleObject {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
internal object InternalSimpleObject {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
private object PrivateSimpleObject {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
| apache-2.0 | d1d8e6340ff430f47ec348bc4f202887 | 20.602273 | 70 | 0.709627 | 4.92487 | false | false | false | false |
free5ty1e/primestationone-control-android | app/src/main/java/com/chrisprime/primestationonecontrol/views/DiscoveryEmptyView.kt | 1 | 1941 | package com.chrisprime.primestationonecontrol.views
import android.content.Context
import android.support.annotation.StringRes
import android.util.AttributeSet
import android.view.View
import android.widget.ScrollView
import com.chrisprime.primestationonecontrol.R
import kotlinx.android.synthetic.main.view_discovery_empty.view.*
class DiscoveryEmptyView : ScrollView {
constructor(context: Context) : super(context) {
if (!isInEditMode) {
init(null)
}
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
if (!isInEditMode) {
init(attrs)
}
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
if (!isInEditMode) {
init(attrs)
}
}
private fun init(attrs: AttributeSet?) {
View.inflate(context, R.layout.view_discovery_empty, this)
isFillViewport = true
}
fun setOnButtonClick(action0: () -> Unit) {
view_discovery_empty_button.setOnClickListener { v -> action0.invoke() }
}
fun setStrings(@StringRes titleStrId: Int, @StringRes bodyStrId: Int, @StringRes buttonStrId: Int) {
if (titleStrId > -1) {
view_discovery_empty_logo.visibility = View.GONE
view_discovery_empty_title_textview.visibility = View.VISIBLE
view_discovery_empty_title_textview.setText(titleStrId)
} else {
view_discovery_empty_logo.visibility = View.VISIBLE
view_discovery_empty_title_textview.visibility = View.INVISIBLE
}
view_discovery_empty_body_textview.setText(bodyStrId)
if (buttonStrId > -1) {
view_discovery_empty_button.visibility = View.VISIBLE
view_discovery_empty_button.setText(buttonStrId)
} else {
view_discovery_empty_button.visibility = View.GONE
}
}
}
| mit | 977c4ac0b7ff72693ccacbe9f19617c2 | 33.052632 | 113 | 0.659454 | 4.303769 | false | false | false | false |
dafi/photoshelf | imageviewer/src/main/java/com/ternaryop/photoshelf/imageviewer/activity/ImageViewerActivity.kt | 1 | 8869 | package com.ternaryop.photoshelf.imageviewer.activity
import android.annotation.SuppressLint
import android.app.ActivityOptions
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.ternaryop.compat.content.getActivityInfoCompat
import com.ternaryop.compat.os.getSerializableCompat
import com.ternaryop.photoshelf.activity.AbsPhotoShelfActivity
import com.ternaryop.photoshelf.activity.ImageViewerData
import com.ternaryop.photoshelf.imageviewer.R
import com.ternaryop.photoshelf.imageviewer.service.WallpaperService
import com.ternaryop.photoshelf.imageviewer.util.ImageViewerUtil
import com.ternaryop.photoshelf.util.menu.enableAll
import com.ternaryop.utils.dialog.showErrorDialog
import com.ternaryop.utils.intent.ShareChooserParams
import com.ternaryop.utils.text.fromHtml
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.net.URI
import java.net.URISyntaxException
import java.net.URL
import java.util.Locale
const val DIMENSIONS_POST_DELAY_MILLIS = 3000L
const val FILE_PROVIDER_SHARE_AUTHORITY = "com.ternaryop.photoshelf.imagepicker.viewer.fileProviderShareAuthority"
private const val SUBDIRECTORY_PICTURES = "TernaryOpPhotoShelf"
@SuppressLint("SetJavaScriptEnabled")
class ImageViewerActivity : AbsPhotoShelfActivity() {
private var webViewLoaded: Boolean = false
private var imageHostUrl: String? = null
private lateinit var detailsText: TextView
override val contentViewLayoutId: Int = R.layout.activity_webview
// no frame inside the layout so no need for contentFrameId
override val contentFrameId: Int = 0
private lateinit var imageViewerData: ImageViewerData
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = ""
val progressBar = findViewById<View>(R.id.webview_progressbar) as ProgressBar
detailsText = findViewById<View>(R.id.details_text) as TextView
imageViewerData = intent.extras?.getSerializableCompat(EXTRA_IMAGE_VIEWER_DATA, ImageViewerData::class.java)
?: return
val data = "<body><img src=\"${imageViewerData.imageUrl}\"/></body>"
prepareWebView(progressBar).loadDataWithBaseURL(null, data, "text/html", "UTF-8", null)
try {
imageHostUrl = URI(imageViewerData.imageUrl).host
} catch (ignored: URISyntaxException) {
}
drawerToolbar.overflowIcon = ContextCompat.getDrawable(this, R.drawable.ic_imageviewer_overflow)
}
override fun createFragment(): Fragment? = null
private fun prepareWebView(progressBar: ProgressBar): WebView {
val webView = findViewById<View>(R.id.webview_view) as WebView
webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(this, "dimRetriever")
webViewLoaded = false
webView.setInitialScale(1)
webView.settings.loadWithOverviewMode = true
webView.settings.useWideViewPort = true
webView.settings.builtInZoomControls = true
webView.settings.setSupportZoom(true)
webView.settings.displayZoomControls = false
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
progressBar.progress = newProgress
}
}
webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
progressBar.progress = 0
progressBar.visibility = View.VISIBLE
}
override fun onPageFinished(view: WebView, url: String) {
webViewLoaded = true
progressBar.visibility = View.GONE
@Suppress("MaxLineLength")
view.loadUrl("javascript:var img = document.querySelector('img');dimRetriever.setDimensions(img.width, img.height)")
invalidateOptionsMenu()
}
}
return webView
}
@JavascriptInterface
@Suppress("unused")
fun setDimensions(w: Int, h: Int) {
runOnUiThread {
detailsText.visibility = View.VISIBLE
detailsText.text = String.format(Locale.US, "%s (%1dx%2d)", imageHostUrl, w, h)
Handler(Looper.getMainLooper())
.postDelayed({ detailsText.visibility = View.GONE }, DIMENSIONS_POST_DELAY_MILLIS)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.image_viewer, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.enableAll(webViewLoaded)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_image_viewer_wallpaper -> {
WallpaperService.startChange(this, imageViewerData.imageUrl)
return true
}
R.id.action_image_viewer_share -> {
startShareImage()
return true
}
R.id.action_image_viewer_download -> {
startDownload()
return true
}
R.id.action_image_viewer_copy_url -> {
ImageViewerUtil.copyToClipboard(
this, imageViewerData.imageUrl,
getString(R.string.image_url_description), R.string.url_copied_to_clipboard_title
)
return true
}
R.id.action_image_viewer_details -> {
toggleDetails()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun startDownload() {
val fileName = ImageViewerUtil.buildFileName(imageViewerData.imageUrl, imageViewerData.tag)
launch {
try {
val relativePath = File(SUBDIRECTORY_PICTURES, fileName)
ImageViewerUtil.download(this@ImageViewerActivity, imageViewerData.imageUrl, relativePath)
} catch (t: Throwable) {
t.showErrorDialog(this@ImageViewerActivity)
}
}
}
private fun startShareImage() {
try {
val destFile = ImageViewerUtil.buildSharePath(this, imageViewerData.imageUrl, "images")
val shareChooserParams = ShareChooserParams(
FileProvider.getUriForFile(this, getFileProvider(), destFile),
getString(R.string.share_image_title),
imageViewerData.title?.fromHtml()?.toString() ?: ""
)
launch(Dispatchers.IO) {
ImageViewerUtil.shareImage(this@ImageViewerActivity, URL(imageViewerData.imageUrl), shareChooserParams)
}
} catch (t: Throwable) {
t.showErrorDialog(this)
}
}
private fun toggleDetails() {
detailsText.visibility = if (detailsText.visibility == View.GONE) View.VISIBLE else View.GONE
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right)
}
private fun getFileProvider(): String {
val componentName = ComponentName(this, javaClass)
val data = packageManager.getActivityInfoCompat(componentName, PackageManager.GET_META_DATA.toLong()).metaData
return checkNotNull(data.getString(FILE_PROVIDER_SHARE_AUTHORITY)) {
"Unable to find $FILE_PROVIDER_SHARE_AUTHORITY"
}
}
companion object {
const val EXTRA_IMAGE_VIEWER_DATA = "com.ternaryop.photoshelf.extra.IMAGE_VIEWER_DATA"
fun startImageViewer(context: Context, imageViewerData: ImageViewerData) {
val intent = Intent(context, ImageViewerActivity::class.java)
val bundle = Bundle()
bundle.putSerializable(EXTRA_IMAGE_VIEWER_DATA, imageViewerData)
intent.putExtras(bundle)
val animBundle = ActivityOptions.makeCustomAnimation(
context,
R.anim.slide_in_left,
R.anim.slide_out_left
).toBundle()
context.startActivity(intent, animBundle)
}
}
}
| mit | 067ef934b559f0740788e028049e54bb | 37.393939 | 132 | 0.672793 | 4.794054 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/actions/WidgetActions.kt | 1 | 6172 | @file:Suppress("unused", "DEPRECATION", "UNUSED_PARAMETER")
package org.droidmate.exploration.actions
import org.droidmate.deviceInterface.exploration.*
import org.droidmate.explorationModel.ExplorationTrace.Companion.widgetTargets
import org.droidmate.explorationModel.firstCenter
import org.droidmate.explorationModel.firstOrEmpty
import org.droidmate.explorationModel.interaction.Widget
/**
* These are the new interface functions to interact with any widget.
* The implementation of the actions itself is going to be refactored in the new version and all
* old ExplorationActions are going to be removed.
* Instead we are going to have :
* ExplorationContext and Widgets Actions (via extension function)
* + a LaunchApp action + ActionQue to handle a set of actions which is executed on the device before fetching a new state
*/
/**
* issue a click to [this.visibleAreas.firstCenter()] if it exists and to the boundaries center otherwise.
* The widget has to be clickable and enabled. If it is not definedAsVisible this method will throw an exception
* (you should use [navigateTo] instead).
*/
@JvmOverloads
fun Widget.click(delay: Long = 0, isVisible: Boolean = false, ignoreClickable: Boolean = false): ExplorationAction {
if (!(definedAsVisible || isVisible) || !enabled || !(clickable||selected.isEnabled()||ignoreClickable))
throw RuntimeException("ERROR: tried to click non-actionable Widget $this")
widgetTargets.add(this)
return clickCoordinate().let { (x, y) -> Click(x, y, true, delay) }
}
fun Widget.clickEvent(delay: Long = 0, ignoreClickable: Boolean = false): ExplorationAction {
if (!enabled || !(clickable||selected.isEnabled()||ignoreClickable))
throw RuntimeException("ERROR: tried to click non-actionable Widget $this")
widgetTargets.add(this)
return if(!clickable) clickCoordinate().let { (x, y) -> Click(x, y, true, delay) }
else clickCoordinate().let { (x, y) -> ClickEvent(this.idHash, x, y,true, delay) }
}
@JvmOverloads
fun Widget.tick(delay: Long = 0, ignoreVisibility: Boolean = false): ExplorationAction {
if (!(definedAsVisible || ignoreVisibility) || !enabled)
throw RuntimeException("ERROR: tried to tick non-actionable (checkbox) Widget $this")
widgetTargets.add(this)
return clickCoordinate().let { (x, y) -> Tick(idHash,x, y, true, delay) }
}
@JvmOverloads
fun Widget.longClick(delay: Long = 0, isVisible: Boolean = false): ExplorationAction {
if (!(definedAsVisible || isVisible) || !enabled || !longClickable)
throw RuntimeException("ERROR: tried to long-click non-actionable Widget $this")
widgetTargets.add(this)
return clickCoordinate().let { (x, y) -> LongClick(x, y, true, delay) }
}
@JvmOverloads
fun Widget.longClickEvent(delay: Long = 0, ignoreVisibility: Boolean = false): ExplorationAction {
if (!(definedAsVisible || ignoreVisibility) || !enabled || !longClickable)
throw RuntimeException("ERROR: tried to long-click non-actionable Widget $this")
widgetTargets.add(this)
return clickCoordinate().let { (x, y) -> LongClickEvent(this.idHash, x, y, true, delay) }
}
@JvmOverloads
fun Widget.setText(newContent: String, ignoreVisibility: Boolean = false,
enableValidation: Boolean = true, delay: Long =0, sendEnter: Boolean = true,
closeKeyboard: Boolean = false): ExplorationAction {
if (enableValidation && (!(definedAsVisible || ignoreVisibility) || !enabled || !isInputField))
throw RuntimeException("ERROR: tried to enter text on non-actionable Widget $this")
widgetTargets.add(this)
return TextInsert(this.idHash, newContent, true, delay, sendEnter, closeKeyboard)
}
fun Widget.dragTo(x: Int, y: Int, stepSize: Int): ExplorationAction = TODO()
//FIXME the center points may be overlayed by other elements, swiping the corners would be safer
fun Widget.swipeUp(stepSize: Int = this.visibleAreas.firstOrEmpty().height / 2): ExplorationAction = Swipe(Pair(this.visibleBounds.center.first, this.visibleBounds.topY + this.visibleBounds.height), Pair(this.visibleBounds.center.first, this.visibleBounds.topY), stepSize, true)
fun Widget.swipeDown(stepSize: Int = this.visibleAreas.firstOrEmpty().height / 2): ExplorationAction = Swipe(Pair(this.visibleBounds.center.first, this.visibleBounds.topY), Pair(this.visibleBounds.center.first, this.visibleBounds.topY + this.visibleBounds.height), stepSize, true)
fun Widget.swipeLeft(stepSize: Int = this.visibleAreas.firstOrEmpty().width / 2): ExplorationAction = Swipe(Pair(this.visibleBounds.leftX + this.visibleBounds.width, this.visibleBounds.center.second), Pair(this.visibleBounds.leftX, this.visibleBounds.center.second), stepSize, true)
fun Widget.swipeRight(stepSize: Int = this.visibleAreas.firstOrEmpty().width / 2): ExplorationAction = Swipe(Pair(this.visibleBounds.leftX, this.visibleBounds.center.second), Pair(this.visibleBounds.leftX + this.visibleBounds.width, this.visibleBounds.center.second), stepSize, true)
/**
* Used by RobustDevice which does not currently create [Widget] objects.
* This function should not be used anywhere else.
*/
fun UiElementPropertiesI.click(): ExplorationAction = (visibleAreas.firstCenter()
?: visibleBounds.center).let{ (x,y) -> Click(x,y) }
fun Widget.clickCoordinate(): Pair<Int, Int> = visibleAreas.firstCenter() ?: visibleBounds.center
/**
* computing all widget actions may affecte the list of widgetTargets,
* it is the callers responsibility to restore the correct state for ExplorationTrace.widgets
*/
fun Widget.availableActions(delay: Long, useCoordinateClicks:Boolean): List<ExplorationAction> {
val actionList: MutableList<ExplorationAction> = mutableListOf()
if (this.longClickable){
if(useCoordinateClicks) actionList.add(this.longClick(delay))
else actionList.add(this.longClickEvent(delay))
}
if (this.clickable||this.selected.isEnabled()){
if(useCoordinateClicks) actionList.add(this.click(delay))
else actionList.add(this.clickEvent(delay))
}
if (this.checked != null)
actionList.add(this.tick(delay))
if (this.scrollable) {
actionList.add(this.swipeUp())
actionList.add(this.swipeDown())
actionList.add(this.swipeRight())
actionList.add(this.swipeLeft())
}
return actionList
} | gpl-3.0 | 8d46f8c66bf746dcd433a0da103b8076 | 50.87395 | 283 | 0.759559 | 3.840697 | false | false | false | false |
tasks/tasks | app/src/release/java/org/tasks/BuildSetup.kt | 1 | 924 | package org.tasks
import android.annotation.SuppressLint
import android.util.Log
import timber.log.Timber
import javax.inject.Inject
class BuildSetup @Inject constructor() {
fun setup() = Timber.plant(ErrorReportingTree())
private class ErrorReportingTree : Timber.Tree() {
@SuppressLint("LogNotTimber")
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority < Log.WARN) {
return
}
if (priority == Log.ERROR) {
if (t == null) {
Log.e(tag, message)
} else {
Log.e(tag, message, t)
}
} else if (priority == Log.WARN) {
if (t == null) {
Log.w(tag, message)
} else {
Log.w(tag, message, t)
}
}
}
}
} | gpl-3.0 | ea8ba7461cff6dc0845fbc2e944f5a9a | 27.90625 | 87 | 0.482684 | 4.4 | false | false | false | false |
cout970/Magneticraft | ignore/test/tileentity/multiblock/TileGrinder.kt | 2 | 15275 | package tileentity.multiblock
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.api.heat.IHeatNodeHandler
import com.cout970.magneticraft.api.internal.energy.ElectricNode
import com.cout970.magneticraft.api.internal.heat.HeatConnection
import com.cout970.magneticraft.api.internal.heat.HeatContainer
import com.cout970.magneticraft.api.internal.registries.machines.grinder.GrinderRecipeManager
import com.cout970.magneticraft.api.registries.machines.grinder.IGrinderRecipe
import com.cout970.magneticraft.block.PROPERTY_ACTIVE
import com.cout970.magneticraft.block.PROPERTY_DIRECTION
import com.cout970.magneticraft.config.Config
import com.cout970.magneticraft.misc.ElectricConstants
import com.cout970.magneticraft.misc.block.isIn
import com.cout970.magneticraft.misc.crafting.CraftingProcess
import com.cout970.magneticraft.misc.damage.DamageSources
import com.cout970.magneticraft.misc.gui.ValueAverage
import com.cout970.magneticraft.misc.inventory.ItemInputHelper
import com.cout970.magneticraft.misc.inventory.ItemOutputHelper
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.inventory.set
import com.cout970.magneticraft.misc.tileentity.ITileTrait
import com.cout970.magneticraft.misc.tileentity.TraitElectricity
import com.cout970.magneticraft.misc.tileentity.TraitHeat
import com.cout970.magneticraft.multiblock.IMultiblockCenter
import com.cout970.magneticraft.multiblock.Multiblock
import com.cout970.magneticraft.multiblock.impl.MultiblockGrinder
import com.cout970.magneticraft.registry.HEAT_NODE_HANDLER
import com.cout970.magneticraft.registry.ITEM_HANDLER
import com.cout970.magneticraft.registry.fromTile
import com.cout970.magneticraft.tileentity.TileBase
import com.cout970.magneticraft.util.*
import com.cout970.magneticraft.util.vector.*
import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.EntityLiving
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.AxisAlignedBB
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.items.IItemHandler
import net.minecraftforge.items.ItemStackHandler
import java.util.*
/**
* Created by cout970 on 19/08/2016.
*/
@TileRegister("grinder")
class TileGrinder : TileBase(), IMultiblockCenter {
override var multiblock: Multiblock? get() = MultiblockGrinder
set(value) {/* ignored */}
override var centerPos: BlockPos? get() = BlockPos.ORIGIN
set(value) {/* ignored */}
val heatNode = HeatContainer(
worldGetter = { this.world },
posGetter = { this.getPos() },
dissipation = 0.025,
specificHeat = IRON_HEAT_CAPACITY * 20, /*PLACEHOLDER*/
maxHeat = (IRON_HEAT_CAPACITY * 20.0) * Config.defaultMachineMaxTemp,
conductivity = DEFAULT_CONDUCTIVITY
)
val traitHeat: TraitHeat = TraitHeat(this, listOf(heatNode), this::updateHeatConnections)
val node = ElectricNode({ worldObj }, { pos + direction.rotatePoint(BlockPos.ORIGIN, ENERGY_INPUT) })
val traitElectricity = TraitElectricity(this, listOf(node))
override val traits: List<ITileTrait> = listOf(traitHeat, traitElectricity)
override var multiblockFacing: EnumFacing? = null
val safeHeat: Long = ((IRON_HEAT_CAPACITY * 20 * Config.defaultMachineSafeTemp)).toLong()
val efficiency = 0.9
var overTemp = false
val grinderDamage = 8f
val in_inv_size = 4
val inventory = ItemStackHandler(in_inv_size)
val craftingProcess: CraftingProcess
val production = ValueAverage()
private var recipeCache: IGrinderRecipe? = null
private var inputCache: ItemStack? = null
init {
craftingProcess = CraftingProcess({
//craft
val outputHelper = ItemOutputHelper(world, posTransform(ITEM_OUTPUT),
direction.rotatePoint(BlockPos(0, 0, 0), ITEM_OUTPUT_OFF).toVec3d())
val recipe = getRecipe()!!
var result = recipe.primaryOutput
val secondary = if (recipe.probability > 0 && Random().nextFloat() <= recipe.probability) recipe.secondaryOutput else null
result = outputHelper.ejectItems(result, false)
if (secondary != null) outputHelper.ejectItems(secondary,
false) //This will lose secondaries if there's no space for them after adding the result
if (result == null) {
consumeInput()
return@CraftingProcess
}
}, {
//can craft
node.voltage > ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE
&& checkOutputValid()
&& overTemp == false
}, {
// use energy
val interp = interpolate(node.voltage, ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE,
ElectricConstants.TIER_1_MAX_VOLTAGE)
val applied = node.applyPower(-Config.grinderConsumption * interp * 6, false)
if (heatNode.applyHeat(applied * (1 - efficiency) * ENERGY_TO_HEAT,
false) > 0) { //If there's any heat leftover after we tried to push heat, the machine has overheated
overTemp = true
}
production += applied
}, {
getRecipe()?.duration ?: 120f
})
}
override fun shouldRefresh(world: World, pos: BlockPos, oldState: IBlockState, newState: IBlockState): Boolean {
return oldState.block !== newState.block
}
fun posTransform(worldPos: BlockPos): BlockPos = direction.rotatePoint(BlockPos.ORIGIN, worldPos) + pos
fun getRecipe(input: ItemStack): IGrinderRecipe? {
if (input === inputCache) return recipeCache
val recipe = GrinderRecipeManager.findRecipe(input)
if (recipe != null) {
recipeCache = recipe
inputCache = input
}
return recipe
}
fun getRecipe(): IGrinderRecipe? = if (inventory[0] != null) getRecipe(inventory[0]!!) else null
override fun update() {
if (worldObj.isServer && active) {
val inputHelper = ItemInputHelper(world, direction.rotateBox(BlockPos.ORIGIN.toVec3d(),
(AxisAlignedBB(-1.0, 2.0, 0.0, 2.0, 4.0, 3.0))) + pos.toVec3d(), inventory)
if (shouldTick(20)) {
inputHelper.suckItems()
sendUpdateToNearPlayers()
}
if (shouldTick(10)) {
if (node.voltage > ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE) {
val entities = world.getEntitiesWithinAABB(EntityLiving::class.java,
direction.rotateBox(BlockPos.ORIGIN.toVec3d(), INTERNAL_AABB) + pos.toVec3d())
if (!entities.isEmpty()) {
val interp = interpolate(node.voltage, ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE,
ElectricConstants.TIER_1_MAX_VOLTAGE)
entities.forEach {
it.attackEntityFrom(DamageSources.damageSourceGrinder, (grinderDamage * interp).toFloat())
craftingProcess.useEnergy
}
sendUpdateToNearPlayers()
}
}
}
craftingProcess.tick(worldObj, 1.0f)
production.tick()
if (heatNode.heat < safeHeat) overTemp = false
}
super.update()
}
override fun onActivate() {
getBlockState()
sendUpdateToNearPlayers()
}
override fun onDeactivate() {
}
val direction: EnumFacing get() = if (PROPERTY_DIRECTION.isIn(getBlockState()))
getBlockState()[PROPERTY_DIRECTION] else EnumFacing.NORTH
val active: Boolean get() = if (PROPERTY_ACTIVE.isIn(getBlockState()))
getBlockState()[PROPERTY_ACTIVE] else false
override fun save(): NBTTagCompound {
val nbt = newNbt {
if (multiblockFacing != null){
add("direction", multiblockFacing!!)
}
add("inv", inventory.serializeNBT())
add("crafting", craftingProcess.serializeNBT())
}
return super.save().also { it.merge(nbt) }
}
override fun load(nbt: NBTTagCompound) = nbt.run {
if (hasKey("direction")) multiblockFacing = getEnumFacing("direction")
if (hasKey("inv")) inventory.deserializeNBT(getCompoundTag("inv"))
if (hasKey("crafting")) craftingProcess.deserializeNBT(getCompoundTag("crafting"))
super.load(nbt)
}
override fun getRenderBoundingBox(): AxisAlignedBB = (pos - BlockPos(1, 2, 0)) toAABBWith (pos + BlockPos(2, 4, 3))
companion object {
val ENERGY_INPUT = BlockPos(0, 1, 1)
val ITEM_INPUT = BlockPos(0, 3, 1)
val ITEM_OUTPUT = BlockPos(0, 1, 2)
val ITEM_OUTPUT_OFF = BlockPos(0, 0, 1)
val HEAT_OUTPUT = BlockPos(0, 1, 1)
val POTENTIAL_CONNECTIONS = setOf(
BlockPos(-1, 1, 1)) //Optimistation to stop multiblocks checking inside themselves for heat connections
val INTERNAL_AABB = AxisAlignedBB(-1.0, 2.0, 0.0, 2.0, 3.5, 3.0)
}
override fun onBreak() {
super.onBreak()
if (worldObj.isServer) {
(0 until inventory.slots)
.mapNotNull { inventory[it] }
.forEach { dropItem(it, pos) }
}
}
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?, relPos: BlockPos): Boolean {
if(capability == HEAT_NODE_HANDLER){
if(facing == null ||
direction.rotatePoint(BlockPos.ORIGIN, ENERGY_INPUT) == relPos && facing == direction.rotateY() ||
direction.rotatePoint(BlockPos.ORIGIN, HEAT_OUTPUT) == relPos && facing == direction.rotateYCCW()){
return true
}
}
if (capability == ITEM_HANDLER) {
if (facing == null)
return true
if (direction.rotatePoint(BlockPos.ORIGIN, ITEM_INPUT) == relPos && facing == EnumFacing.UP)
return true
if (direction.rotatePoint(BlockPos.ORIGIN, ITEM_OUTPUT) == relPos && facing == direction.rotateY())
return true
}
return false
}
@Suppress("UNCHECKED_CAST")
override fun <T> getCapability(capability: Capability<T>, facing: EnumFacing?, relPos: BlockPos): T? {
if(capability == HEAT_NODE_HANDLER){
if(facing == null ||
direction.rotatePoint(BlockPos.ORIGIN, ENERGY_INPUT) == relPos && facing == direction.rotateY() ||
direction.rotatePoint(BlockPos.ORIGIN, HEAT_OUTPUT) == relPos && facing == direction.rotateYCCW()){
return traitHeat as T
}
}
if (capability == ITEM_HANDLER) {
if (facing == null)
return inventory as T
if (direction.rotatePoint(BlockPos.ORIGIN, ITEM_INPUT) == relPos && facing == EnumFacing.UP)
return InInventory(inventory, in_inv_size) as T
if (direction.rotatePoint(BlockPos.ORIGIN, ITEM_INPUT) == relPos && facing == EnumFacing.UP)
return OutInventory() as T
}
return null
}
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean {
if (capability == ITEM_HANDLER) return true
if (capability == HEAT_NODE_HANDLER) return true
return super.hasCapability(capability, facing)
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getCapability(capability: Capability<T>, facing: EnumFacing?): T? {
if (capability == ITEM_HANDLER) {
if (facing == null)
return inventory as T
if (facing == EnumFacing.UP)
return InInventory(inventory, in_inv_size) as T
}
if (capability == HEAT_NODE_HANDLER) return traitHeat as T
return super.getCapability(capability, facing)
}
override fun shouldRenderInPass(pass: Int): Boolean {
return if (active) super.shouldRenderInPass(pass) else pass == 1
}
//If the last crafting action empties the active slot,
// take the last filled slot, and place it in the last empty slot below it in the queue.
// Repeat until the queue is sorted
fun consumeInput() {
val recipe = getRecipe() ?: return
inventory[0]!!.stackSize -= recipe.input.stackSize
if (inventory[0]!!.stackSize == 0) inventory.setStackInSlot(0, null)
else return
for (i in (1 until in_inv_size).reversed()) {
if (inventory[i] == null) continue
for (j in (0 until i).reversed()) {
if (inventory[j] != null) continue
inventory[j] = inventory[i]
inventory.setStackInSlot(i, null)
}
}
}
fun checkOutputValid(): Boolean {
val outputHelper = ItemOutputHelper(world, posTransform(ITEM_OUTPUT),
direction.rotatePoint(BlockPos(0, 0, 0), ITEM_OUTPUT_OFF).toVec3d())
val recipe = getRecipe() ?: return false
if (inventory[0]!!.stackSize < recipe.input.stackSize) return false
if (outputHelper.ejectItems(recipe.primaryOutput, true) != null) return false
if (outputHelper.ejectItems(recipe.secondaryOutput, true) != null) return false
//Technically means that secondary output will be wasted if the output inventory only has room for the primary under certain circumstances
return true
}
fun updateHeatConnections(traitHeat: TraitHeat) {
traitHeat.apply {
for (j in POTENTIAL_CONNECTIONS) {
val relPos = posTransform(j)
val tileOther = world.getTileEntity(relPos) ?: continue
val handler = (HEAT_NODE_HANDLER!!.fromTile(tileOther) ?: continue) as? IHeatNodeHandler ?: continue
for (otherNode in handler.nodes.filter { it is IHeatNode }.map { it as IHeatNode }) {
connections.add(HeatConnection(heatNode, otherNode))
handler.addConnection(HeatConnection(otherNode, heatNode))
}
}
}
}
//TODO add an utility class for this
class InInventory(val inv: IItemHandler, private val in_size: Int) : IItemHandler by inv {
override fun getSlots(): Int {
return in_size
}
override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack? {
return null
}
}
class OutInventory : IItemHandler {
override fun getSlots(): Int {
return 0
}
override fun getStackInSlot(slot: Int): ItemStack? {
return null
}
override fun insertItem(slot: Int, stack: ItemStack?, simulate: Boolean): ItemStack? {
return stack
}
override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack? {
return null
}
}
} | gpl-2.0 | c5b56e701b166b163854e7927a6b723f | 41.198895 | 146 | 0.637447 | 4.403286 | false | false | false | false |
alpha-cross/ararat | library/src/main/java/org/akop/ararat/io/UClickJsonFormatter.kt | 2 | 8327 | // Copyright (c) Akop Karapetyan
//
// 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 org.akop.ararat.io
import android.util.JsonReader
import android.util.JsonWriter
import org.akop.ararat.core.Crossword
import org.akop.ararat.core.Pos
import org.akop.ararat.core.buildWord
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.charset.Charset
class UClickJsonFormatter : CrosswordFormatter {
private var encoding = DEFAULT_ENCODING
override fun setEncoding(encoding: String) {
this.encoding = encoding
}
@Throws(IOException::class)
override fun read(builder: Crossword.Builder, inputStream: InputStream) {
val reader = JsonReader(inputStream.bufferedReader(Charset.forName(encoding)))
var layout: Map<Int, Pos>? = null
var solution: Map<Pos, String>? = null
var acrossClues: Map<Int, String>? = null
var downClues: Map<Int, String>? = null
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (name) {
"Author" -> builder.author = reader.nextString()
"Title" -> builder.title = reader.nextString()
"Copyright" -> builder.copyright = reader.nextString()
"Layout" -> layout = readLayout(reader)
"Solution" -> solution = readSolution(reader)
"AcrossClue" -> acrossClues = readClues(reader)
"DownClue" -> downClues = readClues(reader)
"Width" -> builder.width = reader.nextInt()
"Height" -> builder.height = reader.nextInt()
// "Date" -> user = readUser(reader)
// "Editor" -> user = readUser(reader)
else -> reader.skipValue()
}
}
reader.endObject()
if (builder.width == 0 || builder.height == 0) {
throw FormatException("Width (${builder.width}) or height(${builder.height}) not set")
}
if (layout == null) throw FormatException("Missing layout")
if (solution == null) throw FormatException("Missing solution")
if (acrossClues == null) throw FormatException("Missing clues for Across")
if (downClues == null) throw FormatException("Missing clues for Down")
acrossClues.forEach { (n, hint) ->
val start = layout[n] ?: throw FormatException("No start position for $n Across")
builder.words += buildWord {
this.number = n
this.direction = Crossword.Word.DIR_ACROSS
this.hint = hint
this.startRow = start.r
this.startColumn = start.c
for (i in start.c until builder.width) {
val sol = solution[Pos(start.r, i)]!!
if (sol == " ") break
this.cells += Crossword.Cell(sol, 0)
}
}
}
downClues.forEach { (n, hint) ->
val start = layout[n] ?: throw FormatException("No start position for number $n Down")
builder.words += buildWord {
this.number = n
this.direction = Crossword.Word.DIR_DOWN
this.hint = hint
this.startRow = start.r
this.startColumn = start.c
for (i in start.r until builder.height) {
val sol = solution[Pos(i, start.c)]!!
if (sol == " ") break
this.cells += Crossword.Cell(sol, 0)
}
}
}
}
private fun readLayout(reader: JsonReader): Map<Int, Pos> {
val map = HashMap<Int, Pos>()
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when {
name.matches("Line\\d+".toRegex()) -> {
val row = name.substring(4).toInt() - 1
val numbers = reader.nextString().chunked(2) { it.toString().toInt() }
numbers.forEachIndexed { i, n -> map[n] = Pos(row, i) }
}
else -> reader.skipValue()
}
}
reader.endObject()
return map
}
private fun readSolution(reader: JsonReader): Map<Pos, String> {
val map = HashMap<Pos, String>()
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when {
name.matches("Line\\d+".toRegex()) -> {
val row = name.substring(4).toInt() - 1
val letters = reader.nextString().chunked(1)
letters.forEachIndexed { i, s -> map[Pos(row, i)] = s }
}
else -> reader.skipValue()
}
}
reader.endObject()
return map
}
private fun readClues(reader: JsonReader): Map<Int, String> {
val map = HashMap<Int, String>()
reader.nextString().split("\n".toRegex()).forEach {
val pair = it.split("\\|".toRegex(), limit = 2)
if (pair.size == 2) map[pair[0].toInt()] = pair[1]
}
return map
}
@Throws(IOException::class)
override fun write(crossword: Crossword, outputStream: OutputStream) {
val writer = JsonWriter(outputStream.writer(Charset.forName(encoding)))
writer.beginObject()
writer.name("Width").value(crossword.width.toString())
writer.name("Height").value(crossword.height.toString())
writer.name("Author").value(crossword.author)
writer.name("Title").value(crossword.title)
writer.name("Copyright").value(crossword.copyright)
writer.name("AcrossClue").value(crossword.wordsAcross
.joinToString("\n") { "${"%02d".format(it.number)}|${it.hint}" })
writer.name("DownClue").value(crossword.wordsDown
.joinToString("\n", postfix = "\nend\n") { "${"%02d".format(it.number)}|${it.hint}" })
val layoutMap = Array(crossword.height, { IntArray(crossword.width) })
writer.name("Solution").beginObject()
val allAnswers = buildString {
crossword.cellMap.forEachIndexed { i, row ->
row.forEachIndexed { j, col -> if (col?.chars == null) layoutMap[i][j] = -1 }
writer.name("Line${i + 1}").value(row.joinToString("") { it?.chars ?: " " })
append(row.joinToString("") { it?.chars ?: "-" })
}
}
writer.endObject()
writer.name("Layout").beginObject()
crossword.wordsAcross.forEach { layoutMap[it.startRow][it.startColumn] = it.number }
crossword.wordsDown.forEach { layoutMap[it.startRow][it.startColumn] = it.number }
layoutMap.forEachIndexed { i, row ->
writer.name("Line${i + 1}").value(row.joinToString("") { "%02d".format(it) })
}
writer.endObject()
writer.name("AllAnswer").value(allAnswers)
writer.endObject()
writer.flush()
}
override fun canRead(): Boolean {
return true
}
override fun canWrite(): Boolean {
return true
}
companion object {
private const val DEFAULT_ENCODING = "UTF-8"
}
}
| mit | a141f8f4f0ed8dbee4f9966976e079ed | 37.550926 | 102 | 0.577759 | 4.417507 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-elastic/src/main/java/net/nemerosa/ontrack/extension/elastic/metrics/ECSEntry.kt | 1 | 1339 | package net.nemerosa.ontrack.extension.elastic.metrics
import com.fasterxml.jackson.annotation.JsonProperty
import org.apache.commons.codec.digest.DigestUtils
import java.time.LocalDateTime
/**
* See https://www.elastic.co/guide/en/ecs/current/index.html
*/
data class ECSEntry(
@JsonProperty("@timestamp")
val timestamp: LocalDateTime,
val event: ECSEvent,
val labels: Map<String, String>? = null,
val tags: List<String>? = null,
/**
* Specific entries for Ontrack (non-ECS)
*/
@JsonProperty("Ontrack")
val ontrack: Map<String, Any?>? = null,
) {
/**
* Computing a unique ID for this entry
*/
fun computeId(): String {
val prefix: String = DigestUtils.md5Hex(event.category)
val base = "$event-${labels?.toSortedMap()}-${tags?.sorted()}-$timestamp"
val hashedBase = DigestUtils.sha1Hex(base)
return "$prefix-$hashedBase"
}
}
data class ECSEvent(
val kind: ECSEventKind = ECSEventKind.metric,
val category: String,
val type: String? = null,
val outcome: ECSEventOutcome? = null,
val action: String? = null,
val dataset: String? = null,
val duration: Long? = null,
val module: String? = null,
)
enum class ECSEventKind {
metric,
}
enum class ECSEventOutcome {
failure,
success,
unknown,
}
| mit | 9d99a70f1a9fe4f0cdd99fa3b572e2d0 | 24.75 | 81 | 0.657207 | 3.678571 | false | false | false | false |
nickbutcher/plaid | core/src/test/java/io/plaidapp/core/dribbble/data/TestData.kt | 1 | 1607 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.dribbble.data
import io.plaidapp.core.dribbble.data.api.model.Images
import io.plaidapp.core.dribbble.data.api.model.Shot
import io.plaidapp.core.dribbble.data.api.model.User
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody
/**
* Dribbble test data
*/
val player = User(
id = 1L,
name = "Nick Butcher",
username = "nickbutcher",
avatarUrl = "www.prettyplaid.nb"
)
val shots = listOf(
Shot(
id = 1L,
title = "Foo",
page = 0,
description = "",
images = Images(),
user = player
),
Shot(
id = 2L,
title = "Bar",
page = 0,
description = "",
images = Images(),
user = player
),
Shot(
id = 3L,
title = "Baz",
page = 0,
description = "",
images = Images(),
user = player
)
)
val errorResponseBody = "Error".toResponseBody("".toMediaTypeOrNull())
| apache-2.0 | d2af48e0159dca4b9608365e764c2f7c | 24.507937 | 75 | 0.637834 | 3.967901 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/views/FastScrollRecyclerView.kt | 1 | 1802 | package org.equeim.tremotesf.ui.views
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import androidx.annotation.AttrRes
import androidx.core.content.withStyledAttributes
import androidx.core.view.marginBottom
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.l4digital.fastscroll.FastScroller
class FastScrollRecyclerView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
@AttrRes defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
@SuppressLint("ResourceType")
val fastScroller = FastScroller(context).apply {
context.withStyledAttributes(
attrs = intArrayOf(
androidx.appcompat.R.attr.colorControlActivated,
androidx.appcompat.R.attr.colorControlNormal
)
) {
setBubbleColor(getColor(0, 0))
setHandleColor(getColor(1, 0))
}
}
private val fastScrollerMarginBottom = context.resources.getDimensionPixelSize(com.l4digital.fastscroll.R.dimen.fastscroll_scrollbar_margin_bottom)
override fun onAttachedToWindow() {
super.onAttachedToWindow()
fastScroller.attachRecyclerView(this)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
if (fastScroller.marginBottom != (fastScrollerMarginBottom + paddingBottom)) {
fastScroller.updateLayoutParams<MarginLayoutParams> {
bottomMargin = (fastScrollerMarginBottom + paddingBottom)
}
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
fastScroller.detachRecyclerView()
}
} | gpl-3.0 | 96dc9f8cc53a6702d09033c83e45daa4 | 34.352941 | 151 | 0.705882 | 4.964187 | false | false | false | false |
candalo/rss-reader | app/src/main/java/com/github/rssreader/features/feed/domain/models/FeedItem.kt | 1 | 305 | package com.github.rssreader.features.feed.domain.models
data class FeedItem(
val title: String = "",
val link: String = "",
val description: String = "",
val authorEmail: String = "",
val categories: List<String> = ArrayList(),
val pubDate: String = ""
) | mit | 45c1ee762da5c1e3a9683d17fa75cc8d | 26.818182 | 56 | 0.593443 | 4.485294 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/animation/ImageAnimationView.kt | 1 | 3409 | package com.soywiz.korge.view.animation
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
import com.soywiz.klock.*
import com.soywiz.kmem.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.format.*
inline fun Container.imageAnimationView(animation: ImageAnimation? = null, direction: ImageAnimation.Direction? = null, block: @ViewDslMarker ImageAnimationView.() -> Unit = {})
= ImageAnimationView(animation, direction).addTo(this, block)
open class ImageAnimationView(animation: ImageAnimation? = null, direction: ImageAnimation.Direction? = null) : Container() {
private var nframes: Int = 1
var animation: ImageAnimation? = animation
set(value) {
if (field !== value) {
field = value
didSetAnimation()
}
}
var direction: ImageAnimation.Direction? = direction
private val computedDirection: ImageAnimation.Direction get() = direction ?: animation?.direction ?: ImageAnimation.Direction.FORWARD
private val layers = fastArrayListOf<Image>()
private var nextFrameIn = 0.milliseconds
private var nextFrameIndex = 0
private var dir = +1
var smoothing: Boolean = true
set(value) {
if (field != value) {
field = value
layers.fastForEach { it.smoothing = value }
}
}
private fun setFrame(frameIndex: Int) {
val frame = animation?.frames?.getCyclicOrNull(frameIndex)
if (frame != null) {
frame.layerData.fastForEach {
val image = layers[it.layer.index]
image.bitmap = it.slice
image.smoothing = smoothing
image.xy(it.targetX, it.targetY)
}
nextFrameIn = frame.duration
dir = when (computedDirection) {
ImageAnimation.Direction.FORWARD -> +1
ImageAnimation.Direction.REVERSE -> -1
ImageAnimation.Direction.PING_PONG -> if (frame.index + dir !in 0 until nframes) -dir else dir
}
nextFrameIndex = (frame.index + dir) umod nframes
} else {
layers.fastForEach { it.bitmap = Bitmaps.transparent }
}
}
private fun setFirstFrame() {
if (computedDirection == ImageAnimation.Direction.REVERSE) {
setFrame(nframes - 1)
} else {
setFrame(0)
}
}
private fun didSetAnimation() {
nframes = animation?.frames?.size ?: 1
layers.clear()
removeChildren()
dir = +1
val animation = this.animation
if (animation != null) {
for (layer in animation.layers) {
val image = Image(Bitmaps.transparent)
layers.add(image)
addChild(image)
}
}
setFirstFrame()
}
private var running = true
fun play() { running = true }
fun stop() { running = false }
fun rewind() { setFirstFrame() }
init {
didSetAnimation()
addUpdater {
//println("running=$running, nextFrameIn=$nextFrameIn, nextFrameIndex=$nextFrameIndex")
if (running) {
nextFrameIn -= it
if (nextFrameIn <= 0.0.milliseconds) {
setFrame(nextFrameIndex)
}
}
}
}
}
| apache-2.0 | fe6d6bfa5a13abbd095909b01e809eb7 | 32.097087 | 177 | 0.579055 | 4.59434 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/PostTableConnection.kt | 1 | 3346 | package com.emogoth.android.phone.mimi.db
import com.emogoth.android.phone.mimi.db.MimiDatabase.Companion.getInstance
import com.emogoth.android.phone.mimi.db.models.Post
import com.mimireader.chanlib.models.ChanPost
import com.mimireader.chanlib.models.ChanThread
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.functions.Function
object PostTableConnection {
val LOG_TAG = PostTableConnection::class.java.simpleName
@JvmStatic
fun fetchThread(threadId: Long): Single<List<Post>> {
return getInstance()?.posts()?.getThread(threadId)?.firstOrError()
?: Single.just(emptyList())
}
@JvmStatic
fun watchThread(threadId: Long): Flowable<List<Post>> {
return getInstance()?.posts()?.getThread(threadId) ?: Flowable.just(emptyList())
}
@JvmStatic
fun mapDbPostsToChanThread(boardName: String, threadId: Long): Function<List<Post>, ChanThread> {
return Function { Posts: List<Post> -> convertDbPostsToChanThread(boardName, threadId, Posts) }
}
fun convertDbPostsToChanThread(boardName: String, threadId: Long, posts: List<Post>): ChanThread {
if (posts.isEmpty()) {
return ChanThread.empty()
}
val p: ArrayList<ChanPost> = ArrayList(posts.size)
for (dbPost in posts) {
p.add(dbPost.toPost())
}
return ChanThread(boardName, threadId, p)
}
@JvmStatic
fun putThread(thread: ChanThread): Boolean {
getInstance()?.posts()?.deleteThread(thread.threadId) ?: return false
getInstance()?.posts()?.insert(convertToPosts(thread)) ?: return false
return true
}
private fun convertToPosts(thread: ChanThread?): List<Post> {
if (thread == null || thread.posts == null || thread.posts.size == 0) {
return emptyList()
}
val posts: MutableList<Post> = ArrayList(thread.posts.size)
for (i in thread.posts.indices) {
posts.add(Post(thread.boardName, thread.threadId, thread.posts[i]))
}
return posts
}
@JvmStatic
fun removeThreads(threads: List<Long>): Single<Boolean> {
return Single.defer {
getInstance()?.posts()?.deleteThreads(threads) ?: Single.just(false)
Single.just(true)
}
}
@JvmStatic
fun removeThread(thread: Long): Single<Boolean> {
return Single.defer {
getInstance()?.posts()?.deleteThread(thread) ?: Single.just(false)
Single.just(true)
}
}
@JvmStatic
fun fetchThreadIds(): Single<List<Long>> {
return getInstance()?.posts()?.getFirstPosts()?.firstOrError()
?.flatMap { posts: List<Post> ->
if (posts.isEmpty()) {
return@flatMap Single.just(emptyList<Long>())
}
val values: ArrayList<Long> = ArrayList(posts.size)
for (p in posts) {
values.add(p.toPost().no)
}
Single.just(values)
} ?: Single.just(emptyList())
}
@JvmStatic
fun removeAllThreads(): Single<Boolean> {
return Single.defer {
getInstance()?.posts()?.clear() ?: Single.just(false)
Single.just(true)
}
}
} | apache-2.0 | fc8c013c2ff1efb9d09ef327ee264249 | 33.505155 | 103 | 0.604901 | 4.431788 | false | false | false | false |
soywiz/korge | korge-swf/src/commonMain/kotlin/com/soywiz/korfl/AMF3.kt | 1 | 2313 | package com.soywiz.korfl
import com.soywiz.klock.*
import com.soywiz.korio.serialization.xml.*
import com.soywiz.korio.stream.*
import kotlin.collections.List
import kotlin.collections.Map
import kotlin.collections.arrayListOf
import kotlin.collections.map
import kotlin.collections.set
// http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/amf/pdf/amf-file-format-spec.pdf
object AMF3 {
fun read(s: SyncStream): Any? {
val out = Reader(s).read()
return out
}
class Reader(val i: SyncStream) {
fun readObject(): Map<String, Any?> {
var len = readInt()
val dyn = ((len ushr 3) and 0x01) == 1
len = len ushr 4
i.readU8()
val h = linkedMapOf<String, Any?>()
if (dyn) {
while (true) {
val s = readString()
if (s == "") break
h[s] = read()
}
} else {
val keys = (0 until len).map { readString() }
for (n in 0 until len) h[keys[n]] = read()
}
return h
}
fun readMap(len: Int): Map<Any?, Any?> {
val h = linkedMapOf<Any?, Any?>()
i.readU8()
for (i in 0 until len) h[read()] = read()
return h
}
fun readArray(n: Int): List<Any?> {
val a = arrayListOf<Any?>()
read()
for (i in 0 until n) a.add(read())
return a
}
fun readBytes(size: Int): ByteArray = i.readBytes(size)
fun readInt(preShift: Int = 0): Int {
var ret = 0
var c = i.readU8()
if (c > 0xbf) ret = 0x380
var n = 0
while (++n < 4 && c > 0x7f) {
ret = ret or (c and 0x7f)
ret = ret shl 7
c = i.readU8()
}
if (n > 3) ret = ret shl 1
ret = ret or c
return ret ushr preShift
}
fun readString(): String = i.readString(readInt(1))
fun readWithCode(id: Int): Any? = when (id) {
0x00 -> Undefined
0x01 -> null
0x02 -> false
0x03 -> true
0x04 -> readInt()
0x05 -> i.readF64BE()
0x06 -> readString()
0x07 -> throw Error("XMLDocument unsupported")
0x08 -> run { i.readU8(); DateTime(i.readF64BE().toLong()) }
0x09 -> readArray(readInt(1))
0x0a -> readObject()
0x0b -> Xml(readString())
0x0c -> readBytes(readInt(1))
0x0d, 0x0e, 0x0f -> readArray(readInt(1))
0x10 -> run { val len = readInt(1); readString(); readArray(len) }
0x11 -> readMap(readInt(1))
else -> throw Error("Unknown AMF " + id)
}
fun read() = readWithCode(i.readU8())
}
}
| apache-2.0 | 116fcf4a922a8ec4847119cc679959dc | 23.09375 | 104 | 0.605275 | 2.740521 | false | false | false | false |
Le-Chiffre/Yttrium | Server/src/com/rimmer/yttrium/server/binary/BinaryConnection.kt | 2 | 4167 | package com.rimmer.yttrium.server.binary
import com.rimmer.metrics.Metrics
import com.rimmer.yttrium.Context
import com.rimmer.yttrium.Task
import com.rimmer.yttrium.logMessage
import com.rimmer.yttrium.logWarning
import com.rimmer.yttrium.server.ServerContext
import java.io.IOException
import java.util.*
/**
* Represents a persistent connection to a client with a binary api.
* Automatically handles reconnects and queuing requests while doing so.
* Note that reconnecting is currently based on new requests coming in -
* adding a single request without anything more will not handle reconnecting.
*/
class BinaryConnection(
val context: ServerContext,
val host: String,
val port: Int,
val connectTimeout: Int = 60 * 1000,
val requestTimeout: Int = 120 * 1000,
val reconnectInterval: Int = 4 * 1000,
val maxRetries: Int = 2,
val name: String = "server",
val useNative: Boolean = true,
val metrics: Metrics? = null
) {
private val metricName = "Connection:$name"
inner class Command<T>(val context: Context, val added: Long, private val f: (BinaryClient) -> Task<T>, val task: Task<T>, val metricCall: Any?, val metricId: Int) {
private var retries: Int = 0
operator fun invoke(client: BinaryClient) {
f(client).handler = { r, e ->
if(e == null) {
metrics?.endEvent(metricCall, metricId)
task.finish(r!!)
} else if(e is IOException && retries < maxRetries) {
logWarning("${name.capitalize()} request failed due to network, trying again...")
retries++
add(this)
} else {
metrics?.endEvent(metricCall, metricId)
task.fail(e)
}
}
}
}
fun <T> add(context: Context, f: (BinaryClient) -> Task<T>): Task<T> {
val metric = metrics?.startEvent(context.listenerData, metricName, "request")
val task = Task<T>()
add(Command(context, System.currentTimeMillis(), f, task, context.listenerData, metric ?: 0))
return task
}
private fun <T> add(command: Command<T>) {
val client = ensureClient(command.context)
val handler = client.handler
if(handler === null) {
client.queue.offer(command)
} else {
command(handler)
}
}
private class Client {
var handler: BinaryClient? = null
var lastConnect = 0L
val queue = ArrayDeque<Command<*>>()
}
private val clients = context.handlerGroup.associate { it to Client() }
private fun ensureClient(context: Context): Client {
val client = clients[context.eventLoop] ?:
throw IllegalArgumentException("Invalid context event loop - the event loop must be in the server's handlerGroup.")
val handler = client.handler
if(handler === null || !handler.connected || (handler.pendingRequests > 0 && handler.responseTimer > connectTimeout)) {
handler?.close()
client.handler = null
val time = System.currentTimeMillis()
if(time - client.lastConnect < reconnectInterval) return client
client.lastConnect = time
val i = client.queue.iterator()
while(i.hasNext()) {
val it = i.next()
if(time - it.added > requestTimeout) {
it.task.fail(IOException("Request timed out."))
i.remove()
}
}
connectBinary(context.eventLoop, host, port, useNative = useNative) { c, e ->
client.handler = c
if(e == null) {
logMessage("Connected to $name.")
val queue = client.queue
while(queue.isNotEmpty()) {
queue.poll()(c!!)
}
} else {
logWarning("Failed to connect to $name: $e. Retrying in at least $reconnectInterval ms.")
}
}
}
return client
}
} | mit | 1e375eb237b5f5308876b5818a6a980e | 34.931034 | 169 | 0.574994 | 4.584158 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-Samples/src/main/kotlin/js/katydid/samples/digitalclock/DigitalClockView.kt | 1 | 2133 | //
// (C) Copyright 2019 Martin E. Nordberg III
// Apache 2.0 License
//
package js.katydid.samples.digitalclock
import o.katydid.css.colors.red
import o.katydid.css.styles.builders.color
import o.katydid.css.styles.style
import o.katydid.vdom.builders.KatydidFlowContentBuilder
//---------------------------------------------------------------------------------------------------------------------
/**
* Constructs the Katydid virtual DOM tree for given input [applicationState].
* @return the root of the application's virtual DOM tree for given application state.
*/
fun viewDigitalClock(applicationState: DigitalClockAppState): KatydidFlowContentBuilder<DigitalClockMsg>.() -> Unit =
{
// This top level element replaces the "#app" div in digitalclock.html.
main("#digital-clock-app") {
val timePieces = applicationState.time.toTimeString().split(" ", limit=2)
val time = timePieces[0]
val timeZone = timePieces[1]
h1 {
text(timeZone)
}
div ( "#display" ) {
style {
color(red)
}
div("#h1.clock.digit") {
text(time.substring(0..0))
}
div("#h2.clock.digit") {
text(time.substring(1..1))
}
div("#m0.clock.separator") {
text(":")
}
div("#m1.clock.digit") {
text(time.substring(3..3))
}
div("#m2.clock.digit") {
text(time.substring(4..4))
}
div("#s0.clock.separator") {
text(":")
}
div("#s1.clock.digit") {
text(time.substring(6..6))
}
div("#s2.clock.digit") {
text(time.substring(7..7))
}
}
}
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | d193b9f826f832282f1bdb29032e3a2c | 29.042254 | 119 | 0.42616 | 5.03066 | false | false | false | false |
cashapp/sqldelight | sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/inspections/SchemaNeedsMigrationInspection.kt | 1 | 6799 | package app.cash.sqldelight.intellij.inspections
import app.cash.sqldelight.core.SqlDelightProjectService
import app.cash.sqldelight.core.lang.MigrationFile
import app.cash.sqldelight.core.lang.psi.parameterValue
import app.cash.sqldelight.core.lang.util.migrationFiles
import app.cash.sqldelight.intellij.refactoring.SqlDelightSignatureBuilder
import app.cash.sqldelight.intellij.refactoring.SqlDelightSuggestedRefactoringExecution
import app.cash.sqldelight.intellij.refactoring.SqlDelightSuggestedRefactoringExecution.SuggestedMigrationData
import com.alecstrong.sql.psi.core.psi.SqlCreateTableStmt
import com.alecstrong.sql.psi.core.psi.SqlVisitor
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature
internal class SchemaNeedsMigrationInspection : LocalInspectionTool() {
private val refactoringExecutor = SqlDelightSuggestedRefactoringExecution()
private val signatureBuilder = SqlDelightSignatureBuilder()
override fun buildVisitor(
holder: ProblemsHolder,
isOnTheFly: Boolean,
) = ensureReady(holder.file) {
object : SqlVisitor() {
override fun visitCreateTableStmt(createTable: SqlCreateTableStmt) = ignoreInvalidElements {
val dbFile = sqlDelightFile.findDbFile() ?: return
val topMigrationFile = fileIndex.sourceFolders(sqlDelightFile).asSequence()
.flatMap { it.migrationFiles() }
.maxByOrNull { it.version }
val tables = (topMigrationFile ?: dbFile).tables(true)
val tableWithSameName = tables.find { it.tableName.name == createTable.tableName.name }
val signature = signatureBuilder.signature(createTable) ?: return
if (tableWithSameName == null) {
/*
* TODO: Reenable this once it performs faster. Evaluating oldQuery.query is expensive.
val tableWithDifferentName = tables.find { oldQuery ->
val oldColumns = oldQuery.query.columns
oldColumns.size == signature.parameters.size &&
oldColumns.map { it.parameterValue() }.containsAll(signature.parameters)
}
if (tableWithDifferentName != null) {
holder.registerProblem(
createTable.tableName, "Table needs to be renamed in a migration", GENERIC_ERROR,
AlterTableNameMigrationQuickFix(
createTable, tableWithDifferentName.tableName.name, topMigrationFile
)
)
return
}*/
holder.registerProblem(
createTable.tableName,
"Table needs to be added in a migration",
GENERIC_ERROR,
CreateTableMigrationQuickFix(createTable, topMigrationFile),
)
return
}
val oldSignature = Signature.create(
name = tableWithSameName.tableName.name,
type = null,
parameters = tableWithSameName.query.columns.mapNotNull { it.parameterValue() },
additionalData = null,
) ?: return
if (oldSignature != signature) {
holder.registerProblem(
createTable.tableName,
"Table needs to be altered in a migration",
GENERIC_ERROR,
AlterTableMigrationQuickFix(createTable, oldSignature, signature),
)
}
}
}
}
inner class AlterTableNameMigrationQuickFix(
createTableStmt: SqlCreateTableStmt,
private val oldName: String,
private val newestMigrationFile: MigrationFile?,
) : LocalQuickFixOnPsiElement(createTableStmt) {
private val createTableRef = SmartPointerManager.getInstance(createTableStmt.project)
.createSmartPsiElementPointer(createTableStmt, createTableStmt.containingFile)
override fun getFamilyName(): String = name
override fun getText(): String =
"Add migration for ${createTableRef.element?.tableName?.text.orEmpty()}"
override fun invoke(
project: Project,
file: PsiFile,
startElement: PsiElement,
endElement: PsiElement,
) {
val strategy = SqlDelightProjectService.getInstance(file.project).dialect.migrationStrategy
val changeName = strategy.tableNameChanged(
oldName = oldName,
newName = createTableRef.element?.tableName?.name ?: return,
)
refactoringExecutor.performChangeSignature(
SuggestedMigrationData(
declarationPointer = createTableRef,
newestMigrationFile = newestMigrationFile,
preparedMigration = changeName,
),
)
}
}
inner class CreateTableMigrationQuickFix(
createTableStmt: SqlCreateTableStmt,
private val newestMigrationFile: MigrationFile?,
) : LocalQuickFixOnPsiElement(createTableStmt) {
private val createTableRef = SmartPointerManager.getInstance(createTableStmt.project)
.createSmartPsiElementPointer(createTableStmt, createTableStmt.containingFile)
override fun getFamilyName(): String = name
override fun getText(): String =
"Add migration for ${createTableRef.element?.tableName?.text.orEmpty()}"
override fun invoke(
project: Project,
file: PsiFile,
startElement: PsiElement,
endElement: PsiElement,
) {
refactoringExecutor.performChangeSignature(
SuggestedMigrationData(
declarationPointer = createTableRef,
newestMigrationFile = newestMigrationFile,
preparedMigration = "${createTableRef.element?.text.orEmpty()};",
),
)
}
}
inner class AlterTableMigrationQuickFix(
createTableStmt: SqlCreateTableStmt,
private val oldSignature: Signature,
private val newSignature: Signature,
) : LocalQuickFixOnPsiElement(createTableStmt) {
private val createTableRef = SmartPointerManager.getInstance(createTableStmt.project)
.createSmartPsiElementPointer(createTableStmt, createTableStmt.containingFile)
override fun getFamilyName(): String = name
override fun getText(): String =
"Add migration for ${createTableRef.element?.tableName?.text.orEmpty()}"
override fun invoke(
project: Project,
file: PsiFile,
startElement: PsiElement,
endElement: PsiElement,
) {
val migrationData = refactoringExecutor.prepareChangeSignature(
declaration = createTableRef,
oldSignature = oldSignature,
newSignature = newSignature,
) ?: return
refactoringExecutor.performChangeSignature(migrationData)
}
}
}
| apache-2.0 | 12da25fc2d71b662fa07f6b72f944026 | 37.412429 | 110 | 0.717164 | 5.336735 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/builders/media/KatydidPictureContentRestrictions.kt | 1 | 1592 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.builders.media
//---------------------------------------------------------------------------------------------------------------------
/**
* Set of restrictions on media content.
*/
internal class KatydidPictureContentRestrictions(
itsSourceAllowed: Boolean = true
) {
private var imgAllowed = true
private var sourceAllowed = itsSourceAllowed
private var sourceElementSeen = false
////
/**
* Confirms that an `<img>` element is allowed. Also disallows a second `<img>` or any more `<source>`
* elements after this call.
* @throws IllegalStateException if `<img>` is not allowed.
*/
fun confirmImgAllowedThenDisallow() {
check(imgAllowed) { "Element type <img> not allowed here" }
sourceAllowed = false
imgAllowed = false
}
/**
* Confirms that a `<source>` element is allowed.
* @throws IllegalStateException if `<source>` is not allowed.
*/
fun confirmSourceAllowed() {
check(sourceAllowed) { "Element type <source> not allowed here" }
sourceElementSeen = true
}
/**
* Confirms that the img element can do without a src attribute.
*/
fun confirmSourceElementSeen() {
check(
sourceElementSeen) { "Img element must have src attribute or parent picture element must have <source> elements." }
}
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 28ebd37a679a68b97a593f522f56382a | 27.428571 | 127 | 0.548995 | 5.086262 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/RecyclerViewScrollHandler.kt | 1 | 2553 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import android.support.v7.widget.RecyclerView
import android.view.View
import de.vanita5.twittnuker.util.ContentScrollHandler.ContentListSupport
import de.vanita5.twittnuker.util.ContentScrollHandler.ViewCallback
class RecyclerViewScrollHandler<A>(contentListSupport: ContentListSupport<A>, viewCallback: ViewCallback?) : RecyclerView.OnScrollListener() {
internal val scrollHandler: ContentScrollHandler<A> = ContentScrollHandler(contentListSupport, viewCallback)
private var oldState = RecyclerView.SCROLL_STATE_IDLE
var touchSlop: Int
get() = scrollHandler.touchSlop
set(value) {
scrollHandler.touchSlop = value
}
var reversed: Boolean
get() = scrollHandler.reversed
set(value) {
scrollHandler.reversed = value
}
val touchListener: View.OnTouchListener
get() = scrollHandler.touchListener
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
scrollHandler.handleScrollStateChanged(newState, RecyclerView.SCROLL_STATE_IDLE)
}
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
val scrollState = recyclerView!!.scrollState
scrollHandler.handleScroll(dy, scrollState, oldState, RecyclerView.SCROLL_STATE_IDLE)
oldState = scrollState
}
class RecyclerViewCallback(private val recyclerView: RecyclerView) : ViewCallback {
override val computingLayout: Boolean
get() = recyclerView.isComputingLayout
override fun post(runnable: Runnable) {
recyclerView.post(runnable)
}
}
} | gpl-3.0 | 74f12f0a50156d695bff22aed0970f98 | 35.485714 | 142 | 0.728555 | 4.567084 | false | false | false | false |
borgesgabriel/password | src/main/kotlin/es/gabrielborg/keystroke/utility/polynomial/BigIntegerDividedDifferenceInterpolator.kt | 1 | 3820 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.gabrielborg.keystroke.utility.polynomial
import java.io.Serializable
import java.math.BigInteger
import org.apache.commons.math3.analysis.UnivariateFunction
import org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator
import org.apache.commons.math3.exception.MathIllegalArgumentException
import es.gabrielborg.keystroke.utility.Point
/**
* Modification to handle BigIntegers and adapted to Kotlin
*
* Implements the [Divided Difference Algorithm]
* (http://mathworld.wolfram.com/NewtonsDividedDifferenceInterpolationFormula.html) for interpolation of real univariate
* functions. For reference, see **Introduction to Numerical Analysis**,
* ISBN 038795452X, chapter 2.
*
* The actual code of Neville's evaluation is in PolynomialFunctionLagrangeForm,
* this class provides an easy-to-use interface to it.
*
* @since 1.2
*/
class BigIntegerDividedDifferenceInterpolator : UnivariateInterpolator, Serializable {
/**
* Compute an interpolating function for the dataset.
*
* @param polynomial the polynomial to be interpolated
* @return a function which interpolates the dataset.
*/
fun interpolate(polynomial: Array<Point>): BigIntegerPolynomialFunctionNewtonForm {
val x = DoubleArray(polynomial.size)
val y = Array(polynomial.size) { BigInteger.ZERO }
for (i in polynomial.indices) {
x[i] = polynomial[i].x.toDouble()
y[i] = polynomial[i].y
}
val c = DoubleArray(x.size - 1)
System.arraycopy(x, 0, c, 0, c.size)
val a = computeDividedDifference(x, y)
return BigIntegerPolynomialFunctionNewtonForm(a, c)
}
@Throws(MathIllegalArgumentException::class)
override fun interpolate(arg0: DoubleArray, arg1: DoubleArray): UnivariateFunction? {
return null
}
companion object {
/**
* Return a copy of the divided difference array.
*
* The divided difference array is defined recursively by
* f\[x0] = f(x0)
* f[x0,x1,...,xk] = (f[x1,...,xk] - f[x0,...,x[k-1]]) / (xk - x0)
*
* The computational complexity is O(N^2).
*
* @param x Interpolating points array.
* @param y Interpolating values array.
* @return a fresh copy of the divided difference array.
*/
fun computeDividedDifference(x: DoubleArray, y: Array<BigInteger>): Array<BigInteger> {
val dividedDifference = y.clone()
val n = x.size
val a = Array(n) { BigInteger.ZERO }
a[0] = dividedDifference[0]
for (i in 1..n - 1) {
for (j in 0..n - i - 1) {
val denominator = BigInteger.valueOf((x[j + i] - x[j]).toLong())
dividedDifference[j] = (dividedDifference[j + 1].subtract(dividedDifference[j])).divide(denominator)
}
a[i] = dividedDifference[0]
}
return a
}
}
} | gpl-3.0 | 088af887850b6e3c7e2053ceb2ba6a48 | 37.21 | 120 | 0.663351 | 4.042328 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/analytics/ModelPerformanceTracker.kt | 1 | 1897 | package com.stripe.android.identity.analytics
import com.stripe.android.camera.framework.StatTracker
import com.stripe.android.camera.framework.StatTrackerImpl
import com.stripe.android.camera.framework.TaskStats
import com.stripe.android.camera.framework.time.Duration
import com.stripe.android.identity.networking.IdentityRepository
import javax.inject.Inject
/**
* Tracker for model performance.
*/
internal class ModelPerformanceTracker @Inject constructor(
private val identityAnalyticsRequestFactory: IdentityAnalyticsRequestFactory,
private val identityRepository: IdentityRepository
) {
private val preprocessStats = mutableListOf<TaskStats>()
private val inferenceStats = mutableListOf<TaskStats>()
private fun List<TaskStats>.averageDuration() =
(
this.fold(Duration.ZERO) { accDuration, next ->
accDuration + next.duration
} / size
).inMilliseconds.toLong()
fun trackPreprocess(): StatTracker =
StatTrackerImpl { startedAt, _ ->
preprocessStats += TaskStats(
startedAt,
startedAt.elapsedSince(),
null
)
}
fun trackInference(): StatTracker =
StatTrackerImpl { startedAt, _ ->
inferenceStats += TaskStats(
startedAt,
startedAt.elapsedSince(),
null
)
}
suspend fun reportAndReset(mlModel: String) {
identityRepository.sendAnalyticsRequest(
identityAnalyticsRequestFactory.modelPerformance(
mlModel = mlModel,
preprocess = preprocessStats.averageDuration(),
inference = inferenceStats.averageDuration(),
frames = preprocessStats.size
)
)
preprocessStats.clear()
inferenceStats.clear()
}
}
| mit | c5cb298d80fb7bb9da8db59654c0b8ab | 31.706897 | 81 | 0.645229 | 5.358757 | false | false | false | false |
exponent/exponent | packages/expo-updates/android/src/main/java/expo/modules/updates/launcher/NoDatabaseLauncher.kt | 2 | 2720 | package expo.modules.updates.launcher
import android.content.Context
import android.os.AsyncTask
import android.util.Log
import expo.modules.updates.UpdatesConfiguration
import expo.modules.updates.db.entity.AssetEntity
import expo.modules.updates.db.entity.UpdateEntity
import expo.modules.updates.loader.EmbeddedLoader
import expo.modules.updates.manifest.BareUpdateManifest
import expo.modules.updates.manifest.EmbeddedManifest
import org.apache.commons.io.FileUtils
import java.io.File
class NoDatabaseLauncher @JvmOverloads constructor(
context: Context,
configuration: UpdatesConfiguration,
fatalException: Exception? = null
) : Launcher {
override var bundleAssetName: String? = null
override val launchedUpdate: UpdateEntity?
get() = null
override val launchAssetFile: String?
get() = null
override var localAssetFiles: Map<AssetEntity, String>? = null
private set
override val isUsingEmbeddedAssets: Boolean
get() = localAssetFiles == null
private fun writeErrorToLog(context: Context, fatalException: Exception) {
try {
val errorLogFile = File(context.filesDir, ERROR_LOG_FILENAME)
val exceptionString = fatalException.toString()
FileUtils.writeStringToFile(errorLogFile, exceptionString, "UTF-8", true)
} catch (e: Exception) {
Log.e(TAG, "Failed to write fatal error to log", e)
}
}
companion object {
private val TAG = NoDatabaseLauncher::class.java.simpleName
private const val ERROR_LOG_FILENAME = "expo-error.log"
fun consumeErrorLog(context: Context): String? {
return try {
val errorLogFile = File(context.filesDir, ERROR_LOG_FILENAME)
if (!errorLogFile.exists()) {
return null
}
val logContents = FileUtils.readFileToString(errorLogFile, "UTF-8")
errorLogFile.delete()
logContents
} catch (e: Exception) {
Log.e(TAG, "Failed to read error log", e)
null
}
}
}
init {
val embeddedUpdateManifest = EmbeddedManifest.get(context, configuration)
?: throw RuntimeException("Failed to launch with embedded update because the embedded manifest was null")
if (embeddedUpdateManifest is BareUpdateManifest) {
bundleAssetName = EmbeddedLoader.BARE_BUNDLE_FILENAME
localAssetFiles = null
} else {
bundleAssetName = EmbeddedLoader.BUNDLE_FILENAME
localAssetFiles = mutableMapOf<AssetEntity, String>().apply {
for (asset in embeddedUpdateManifest.assetEntityList) {
this[asset] = "asset:///" + asset.embeddedAssetFilename
}
}
}
if (fatalException != null) {
AsyncTask.execute { writeErrorToLog(context, fatalException) }
}
}
}
| bsd-3-clause | 4db79748852ae17b76997bcaabb6663e | 32.580247 | 111 | 0.715441 | 4.408428 | false | false | false | false |
AndroidX/androidx | benchmark/benchmark-common/src/main/java/androidx/benchmark/perfetto/AtraceTag.kt | 3 | 2783 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.perfetto
import android.os.Build
/**
* Enum representing set of all atrace tags used by macrobenchmark, and whether they're expected to
* be supported on the current device.
*
* Note that this API assumes API >= 21, as that's the library's min API
*
* While supported tags could be collected from the local device (e.g. in `AtraceTagTest`), the
* intent of this class is to track this information statically.
*/
@Suppress("unused") // enums always accessed via values()
internal enum class AtraceTag(
val tag: String
) {
ActivityManager("am"),
Audio("audio") {
override fun supported(api: Int, rooted: Boolean): Boolean {
return api >= 23
}
},
BinderDriver("binder_driver") {
override fun supported(api: Int, rooted: Boolean): Boolean {
return api >= 24
}
},
Camera("camera"),
Dalvik("dalvik"),
Frequency("freq"),
Graphics("gfx"),
HardwareModules("hal"),
Idle("idle"),
Input("input"),
MemReclaim("memreclaim") {
override fun supported(api: Int, rooted: Boolean): Boolean {
return rooted || api >= 24
}
},
Resources("res"),
Scheduling("sched"),
Synchronization("sync") {
override fun supported(api: Int, rooted: Boolean): Boolean {
return rooted || api >= 28
}
},
View("view"),
WebView("webview"),
WindowManager("wm");
/**
* Return true if the tag is available on the specified api level, with specified shell
* session root status.
*/
open fun supported(api: Int, rooted: Boolean): Boolean {
return true
}
companion object {
fun supported(
api: Int = Build.VERSION.SDK_INT,
rooted: Boolean
): Set<AtraceTag> {
return values()
.filter { it.supported(api = api, rooted = rooted) }
.toSet()
}
fun unsupported(
api: Int = Build.VERSION.SDK_INT,
rooted: Boolean
): Set<AtraceTag> {
return values().toSet() - supported(api, rooted)
}
}
} | apache-2.0 | a82432a4df028bc208036684c43a273e | 28.935484 | 99 | 0.615523 | 4.334891 | false | false | false | false |
AndroidX/androidx | wear/benchmark/integration-tests/macrobenchmark-target/src/main/java/androidx/wear/benchmark/integration/macrobenchmark/target/ScrollActivity.kt | 3 | 2258 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.benchmark.integration.macrobenchmark.target
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class ScrollActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scroll)
val recycler = findViewById<RecyclerView>(R.id.recycler)
val itemCount = 5000
val adapter = EntryAdapter(entries(itemCount))
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = adapter
}
private fun entries(size: Int) = List(size) {
Entry("Item $it")
}
}
data class Entry(val contents: String)
class EntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val content: TextView = itemView.findViewById(R.id.content)
}
class EntryAdapter(private val entries: List<Entry>) : RecyclerView.Adapter<EntryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntryViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.recycler_row, parent, false)
return EntryViewHolder(itemView)
}
override fun onBindViewHolder(holder: EntryViewHolder, position: Int) {
val entry = entries[position]
holder.content.text = entry.contents
}
override fun getItemCount(): Int = entries.size
}
| apache-2.0 | 873c4fa0205cfa2779ef768647ce8b81 | 34.84127 | 96 | 0.738707 | 4.534137 | false | false | false | false |
AndroidX/androidx | camera/integration-tests/avsynctestapp/src/main/java/androidx/camera/integration/avsync/ui/widget/Button.kt | 3 | 2820 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.avsync.ui.widget
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.FloatingActionButtonDefaults
import androidx.compose.material.FloatingActionButtonElevation
import androidx.compose.material.MaterialTheme
import androidx.compose.material.contentColorFor
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.material.ripple.RippleAlpha
import androidx.compose.material.ripple.RippleTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
@Composable
fun AdvancedFloatingActionButton(
modifier: Modifier = Modifier,
enabled: Boolean = true,
onClick: () -> Unit,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape = MaterialTheme.shapes.small.copy(CornerSize(percent = 50)),
backgroundColor: Color = MaterialTheme.colors.secondary,
contentColor: Color = contentColorFor(backgroundColor),
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
content: @Composable () -> Unit
) {
val rippleTheme = if (enabled) LocalRippleTheme.current else DisabledRippleTheme
CompositionLocalProvider(LocalRippleTheme provides rippleTheme) {
FloatingActionButton(
onClick = if (enabled) onClick else { {} },
modifier = modifier,
interactionSource = interactionSource,
shape = shape,
backgroundColor = if (enabled) backgroundColor else Color.Gray,
contentColor = contentColor,
elevation = elevation,
content = content
)
}
}
private object DisabledRippleTheme : RippleTheme {
@Composable
override fun defaultColor(): Color = Color.Transparent
@Composable
override fun rippleAlpha(): RippleAlpha = RippleAlpha(0f, 0f, 0f, 0f)
} | apache-2.0 | 3cce318a237655bf387d5abdae95887a | 38.732394 | 90 | 0.763475 | 5.008881 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/annotator/fixes/ChangeFunctionSignatureFixTest.kt | 2 | 16337 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import org.rust.ide.annotator.RsAnnotatorTestBase
import org.rust.ide.annotator.RsErrorAnnotator
class ChangeFunctionSignatureFixTest : RsAnnotatorTestBase(RsErrorAnnotator::class) {
fun `test no parameters add one parameter`() = checkFixByText("Add `i32` as `1st` parameter to function `foo`", """
fn foo() {}
fn main() {
foo<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>1/*caret*/</error>)</error>;
}
""", """
fn foo(i: i32) {}
fn main() {
foo(1);
}
""", preview = null)
fun `test no parameters add multiple parameters`() = checkFixByText("<html>Change signature to foo(<b>i32</b>, <b>bool</b>)</html>", """
fn foo() {}
fn main() {
foo<error descr="This function takes 0 parameters but 2 parameters were supplied [E0061]">(<error>1/*caret*/</error>, <error>false</error>)</error>;
}
""", """
fn foo(i: i32, x: bool) {}
fn main() {
foo(1, false);
}
""", preview = null)
fun `test add additional parameter same type forward`() = checkFixByText("Add `i32` as `1st` parameter to function `foo`", """
fn foo(a: i32) {}
fn main() {
foo<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(0, <error>1/*caret*/</error>)</error>;
foo(5);
}
""", """
fn foo(i: i32, a: i32) {}
fn main() {
foo(0, 1);
foo(, 5);
}
""", preview = null)
fun `test add additional parameter same type backward`() = checkFixByText("Add `i32` as `2nd` parameter to function `foo`", """
fn foo(a: i32) {}
fn main() {
foo<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(0, <error>1/*caret*/</error>)</error>;
foo(5,);
}
""", """
fn foo(a: i32, i: i32) {}
fn main() {
foo(0, 1);
foo(5, );
}
""", preview = null)
fun `test add additional parameter different type`() = checkFixByText("Add `bool` as `2nd` parameter to function `foo`", """
fn foo(a: i32) {}
fn main() {
foo<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(0, <error>false/*caret*/</error>)</error>;
foo(5);
}
""", """
fn foo(a: i32, x: bool) {}
fn main() {
foo(0, false);
foo(5, );
}
""", preview = null)
fun `test add multiple additional parameters forward`() = checkFixByText("<html>Change signature to foo(i32, <b>bool</b>, i32, <b>i32</b>)</html>", """
fn foo(a: i32, b: i32) {}
fn main() {
foo<error descr="This function takes 2 parameters but 4 parameters were supplied [E0061]">(0, false, <error>3/*caret*/</error>, <error>4</error>)</error>;
foo(0, 1);
}
""", """
fn foo(a: i32, b0: bool, b: i32, i: i32) {}
fn main() {
foo(0, false, 3, 4);
foo(0, , 1, );
}
""", preview = null)
fun `test add multiple additional parameters backward`() = checkFixByText("<html>Change signature to foo(<b>i32</b>, <b>bool</b>, i32, i32)</html>", """
fn foo(a: i32, b: i32) {}
fn main() {
foo<error descr="This function takes 2 parameters but 4 parameters were supplied [E0061]">(0, false, <error>3/*caret*/</error>, <error>4</error>)</error>;
foo(0, 1);
}
""", """
fn foo(i: i32, b0: bool, a: i32, b: i32) {}
fn main() {
foo(0, false, 3, 4);
foo(, , 0, 1);
}
""", preview = null)
fun `test change signature total type mismatch`() = checkFixByText("<html>Change signature to foo(<b>bool</b>, <b>bool</b>, <b>bool</b>)</html>", """
fn foo(a: i32, b: i32) {}
fn main() {
foo<error>(true, true, <error>true/*caret*/</error>)</error>;
}
""", """
fn foo(a: bool, b: bool, x: bool) {}
fn main() {
foo(true, true, true);
}
""", preview = null)
fun `test do not offer add parameter fix if argument count would not match 1`() = checkFixIsUnavailable("<html>Change signature to foo(<b>bool</b>, <b>bool</b>, <b>bool</b>, i32, i32)</html>", """
fn foo(a: i32, b: i32) {}
fn main() {
foo<error>(true, false, <error>true/*caret*/</error>)</error>;
}
""")
fun `test do not offer add parameter fix if argument count would not match 2`() = checkFixIsUnavailable("<html>Change signature to foo(i32, i32, <b>bool</b>, <b>bool</b>, <b>bool</b>)</html>", """
fn foo(a: i32, b: i32) {}
fn main() {
foo<error>(true, false, <error>true/*caret*/</error>)</error>;
}
""")
fun `test add parameter to method`() = checkFixByText("Add `i32` as `1st` parameter to method `foo`", """
struct S;
impl S {
fn foo(&self) {}
}
fn bar(s: S) {
s.foo<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>0/*caret*/</error>)</error>;
}
""", """
struct S;
impl S {
fn foo(&self, i: i32) {}
}
fn bar(s: S) {
s.foo(0);
}
""", preview = null)
fun `test add unknown type`() = checkFixByText("Add `_` as `1st` parameter to function `foo`", """
fn foo() {}
fn main() {
foo<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>Unknown/*caret*/</error>)</error>;
}
""", """
fn foo(x: _) {}
fn main() {
foo(Unknown);
}
""", preview = null)
fun `test add aliased type`() = checkFixByText("Add `Foo` as `1st` parameter to function `foo`", """
fn foo() {}
type Foo = u32;
fn bar(f: Foo) {
foo<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>f/*caret*/</error>)</error>;
}
""", """
fn foo(f: Foo) {}
type Foo = u32;
fn bar(f: Foo) {
foo(f);
}
""", preview = null)
fun `test add type with default type argument`() = checkFixByText("Add `Foo` as `1st` parameter to function `foo`", """
fn foo() {}
struct Foo<T = u32>(T);
fn bar(f: Foo) {
foo<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>f/*caret*/</error>)</error>;
}
""", """
fn foo(f: Foo) {}
struct Foo<T = u32>(T);
fn bar(f: Foo) {
foo(f);
}
""", preview = null)
fun `test import added argument type`() = checkFixByText("Add `S` as `1st` parameter to function `bar`", """
mod foo {
pub fn bar() {}
}
pub struct S;
fn main() {
let s = S;
foo::bar<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>s/*caret*/</error>)</error>;
}
""", """
mod foo {
use crate::S;
pub fn bar(s: S) {}
}
pub struct S;
fn main() {
let s = S;
foo::bar(s);
}
""", preview = null)
fun `test import changed argument type`() = checkFixByText("Change type of parameter `a` of function `bar` to `S`", """
mod foo {
pub fn bar(a: u32) {}
}
pub struct S;
fn main() {
let s = S;
foo::bar<error>(s/*caret*/)</error>;
}
""", """
mod foo {
use crate::S;
pub fn bar(a: S) {}
}
pub struct S;
fn main() {
let s = S;
foo::bar(s);
}
""", preview = null)
fun `test do not offer on tuple struct constructors`() = checkFixIsUnavailable("Add", """
struct S(u32);
fn main() {
let s = S<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(0, <error>1/*caret*/</error>)</error>;
}
""")
fun `test suggest parameter name`() = checkFixByText("Add `i32` as `1st` parameter to function `foo`", """
fn foo() {}
fn main() {
let x = 5;
foo<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(<error>x/*caret*/</error>)</error>;
}
""", """
fn foo(x: i32) {}
fn main() {
let x = 5;
foo(x);
}
""", preview = null)
fun `test skip existing parameter name`() = checkFixByText("Add `i32` as `2nd` parameter to function `foo`", """
fn foo(i: i32) {}
fn main() {
foo<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(1/*caret*/, <error>2</error>)</error>;
}
""", """
fn foo(i: i32, i0: i32) {}
fn main() {
foo(1, 2);
}
""", preview = null)
fun `test unavailable on correct method UFCS`() = checkFixIsUnavailable("Change", """
struct S {}
impl S {
fn foo(&self, a: u32) {}
}
fn bar(s: S) {
S::foo(1/*caret*/, 1);
}
""")
fun `test unavailable with disabled parameter 1`() = checkFixIsUnavailable("Change", """
fn foo(a: u32, #[cfg(foo)] b: u32, c: u32) {}
fn bar() {
foo(1, true/*caret*/);
}
""")
fun `test unavailable with disabled parameter 2`() = checkFixIsUnavailable("Add `i32`", """
fn foo(i: i32, #[cfg(foo)] b: u32) {}
fn main() {
foo<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(1/*caret*/, <error>2</error>)</error>;
}
""")
fun `test change type simple binding`() = checkFixByText("Change type of parameter `a` of function `foo` to `bool`", """
fn foo(a: u32) {}
fn bar() {
foo<error>(true/*caret*/)</error>;
}
""", """
fn foo(a: bool) {}
fn bar() {
foo(true);
}
""", preview = null)
fun `test change type complex binding`() = checkFixByText("Change type of `1st` parameter of function `foo` to `bool`", """
fn foo((a, b): (u32, u32)) {}
fn bar() {
foo<error>(true/*caret*/)</error>;
}
""", """
fn foo((a, b): bool) {}
fn bar() {
foo(true);
}
""", preview = null)
fun `test change multiple parameter types`() = checkFixByText("<html>Change signature to foo(<b>bool</b>, <b>&str</b>)</html>", """
fn foo(a: u32, b: u32) {}
fn bar() {
foo<error>(true/*caret*/, "foo")</error>;
}
""", """
fn foo(a: bool, b: &str) {}
fn bar() {
foo(true/*caret*/, "foo");
}
""", preview = null)
fun `test change type parameter in the middle`() = checkFixByText("Change type of `2nd` parameter of function `foo` to `bool`", """
fn foo(x: u32, (a, b): (u32, u32), c: u32) {}
fn bar() {
foo<error>(0, true/*caret*/, 1)</error>;
}
""", """
fn foo(x: u32, (a, b): bool, c: u32) {}
fn bar() {
foo(0, true, 1);
}
""", preview = null)
fun `test remove parameter simple binding`() = checkFixByText("Remove parameter `b` from function `foo`", """
fn foo(a: u32, b: u32) {}
fn bar() {
foo<error>(0/*caret*/<error>)</error></error>;
}
""", """
fn foo(a: u32) {}
fn bar() {
foo(0);
}
""", preview = null)
fun `test remove parameter complex binding`() = checkFixByText("Remove `2nd` parameter from function `foo`", """
fn foo(x: u32, (a, b): (u32, u32)) {}
fn bar() {
foo<error>(0/*caret*/<error>)</error></error>;
}
""", """
fn foo(x: u32) {}
fn bar() {
foo(0);
}
""", preview = null)
fun `test remove multiple parameters`() = checkFixByText("<html>Change signature to foo()</html>", """
fn foo(a: u32, b: u32) {}
fn bar() {
foo<error>(/*caret*/<error>)</error></error>;
}
""", """
fn foo() {}
fn bar() {
foo();
}
""", preview = null)
fun `test change type and remove parameters`() = checkFixByText("<html>Change signature to foo(<b>bool</b>)</html>", """
fn foo(a: u32, b: u32, c: u32) {}
fn bar() {
foo<error>(true/*caret*/<error>)</error></error>;
}
""", """
fn foo(a: bool) {}
fn bar() {
foo(true);
}
""", preview = null)
fun `test remove parameters change usage`() = checkFixByText("<html>Change signature to foo()</html>", """
fn foo(a: u32, b: u32) {}
fn bar() {
foo<error>(/*caret*/<error>)</error></error>;
foo(1, 2);
}
""", """
fn foo() {}
fn bar() {
foo();
foo();
}
""", preview = null)
fun `test change method type`() = checkFixByText("Change type of parameter `a` of method `foo` to `&str`", """
struct S {}
impl S {
fn foo(&self, a: u32) {}
}
fn bar(s: S) {
s.foo<error>(""/*caret*/)</error>;
}
""", """
struct S {}
impl S {
fn foo(&self, a: &str) {}
}
fn bar(s: S) {
s.foo("");
}
""", preview = null)
fun `test change method parameter type UFCS`() = checkFixByText("Change type of parameter `a` of method `foo` to `&str`", """
struct S {}
impl S {
fn foo(&self, a: u32) {}
}
fn bar(s: S) {
S::foo<error>(&s, ""/*caret*/)</error>;
}
""", """
struct S {}
impl S {
fn foo(&self, a: &str) {}
}
fn bar(s: S) {
S::foo(&s, "");
}
""", preview = null)
fun `test remove method parameter type UFCS`() = checkFixByText("Remove parameter `a` from method `foo`", """
struct S {}
impl S {
fn foo(&self, a: u32) {}
}
fn bar(s: S) {
S::foo<error>(&s/*caret*/<error>)</error></error>;
}
""", """
struct S {}
impl S {
fn foo(&self) {}
}
fn bar(s: S) {
S::foo(&s);
}
""", preview = null)
fun `test add method parameter UFCS`() = checkFixByText("Add `bool` as `1st` parameter to method `foo`", """
struct S {}
impl S {
fn foo(&self, a: i32) {}
}
fn bar(s: S) {
S::foo<error>(&s/*caret*/, true, <error>1</error>)</error>;
}
""", """
struct S {}
impl S {
fn foo(&self, x: bool, a: i32) {}
}
fn bar(s: S) {
S::foo(&s, true, 1);
}
""", preview = null)
fun `test add multiple additional parameters forward with normalizable associated types`() = checkFixByText("<html>Change signature to foo(i32, <b>bool</b>, i32, <b>i32</b>)</html>", """
struct Struct;
trait Trait { type Item; }
impl Trait for Struct { type Item = i32; }
fn foo(a: <Struct as Trait>::Item, b: <Struct as Trait>::Item) {}
fn main() {
foo<error descr="This function takes 2 parameters but 4 parameters were supplied [E0061]">(0, false, <error>3/*caret*/</error>, <error>4</error>)</error>;
foo(0, 1);
}
""", """
struct Struct;
trait Trait { type Item; }
impl Trait for Struct { type Item = i32; }
fn foo(a: <Struct as Trait>::Item, b0: bool, b: <Struct as Trait>::Item, i: i32) {}
fn main() {
foo(0, false, 3, 4);
foo(0, , 1, );
}
""", preview = null)
}
| mit | 5d8c83751050b29774f1b5f3bc11fe40 | 28.757741 | 200 | 0.476158 | 3.763419 | false | true | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/TavernFragment.kt | 1 | 4206 | package com.habitrpg.android.habitica.ui.fragments.social
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.viewmodels.GroupViewModel
import com.habitrpg.android.habitica.ui.viewmodels.GroupViewType
import javax.inject.Inject
class TavernFragment : BaseMainFragment<FragmentViewpagerBinding>() {
@Inject
lateinit var socialRepository: SocialRepository
override var binding: FragmentViewpagerBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding {
return FragmentViewpagerBinding.inflate(inflater, container, false)
}
internal val viewModel: GroupViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.usesTabLayout = true
this.hidesToolbar = true
this.tutorialStepIdentifier = "tavern"
this.tutorialText = getString(R.string.tutorial_tavern)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.groupViewType = GroupViewType.GUILD
viewModel.setGroupID(Group.TAVERN_ID)
setViewPagerAdapter()
binding?.viewPager?.currentItem = 0
}
override fun onDestroy() {
socialRepository.close()
super.onDestroy()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_tavern, menu)
super.onCreateOptionsMenu(menu, inflater)
}
@Suppress("ReturnCount")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_guild_refresh -> {
viewModel.retrieveGroup { }
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun setViewPagerAdapter() {
val fragmentManager = childFragmentManager
binding?.viewPager?.adapter = object : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> {
TavernDetailFragment()
}
1 -> {
ChatFragment(viewModel)
}
else -> Fragment()
}
}
override fun getItemCount(): Int {
return if (viewModel.getGroupData().value?.quest?.active == true) {
3
} else 2
}
}
tabLayout?.let {
binding?.viewPager?.let { it1 ->
TabLayoutMediator(it, it1) { tab, position ->
tab.text = when (position) {
0 -> context?.getString(R.string.inn)
1 -> context?.getString(R.string.chat)
2 -> context?.getString(R.string.world_quest)
else -> ""
}
}.attach()
}
}
}
}
| gpl-3.0 | 3d81de7fcbeb54fe16c7c3c24db75cdb | 33.344538 | 107 | 0.62292 | 5.192593 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/navigation/JarNavigationUtils.kt | 1 | 764 | package org.jetbrains.kotlin.ui.editors.navigation
import com.intellij.openapi.vfs.VirtualFile
import org.eclipse.core.resources.IFile
import org.eclipse.core.resources.ResourcesPlugin
import org.eclipse.core.runtime.Path
import java.io.File
private val ARCHIVE_EXTENSION = "jar"
fun getAcrhivedFileFromPath(url: String) =
ResourcesPlugin.getWorkspace().getRoot().getFile(pathFromUrlInArchive(url))
fun pathFromUrlInArchive(url: String) =
Path(url.replace("!",""))
fun getFqNameInsideArchive(globalPath: String) =
globalPath.substringAfterLast(ARCHIVE_EXTENSION)
.substringAfter('!')
.substringAfter(File.separatorChar)
.replace(File.separatorChar, '/')
fun isArchived(file :IFile) =
file.getFullPath().toOSString().contains(ARCHIVE_EXTENSION)
| apache-2.0 | 3a40e2613ba1af818b8fa970e477f2eb | 29.56 | 76 | 0.793194 | 3.708738 | false | false | false | false |
google/android-auto-companion-android | trustagent/src/com/google/android/libraries/car/trustagent/blemessagestream/version2/PacketPayloadStream.kt | 1 | 5248 | // Copyright 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent.blemessagestream.version2
import com.google.android.companionprotos.DeviceMessageProto.Message
import com.google.android.companionprotos.PacketProto.Packet
import com.google.android.libraries.car.trustagent.util.loge
import com.google.android.libraries.car.trustagent.util.logw
import com.google.android.libraries.car.trustagent.util.toHexString
import java.io.ByteArrayOutputStream
import java.io.IOException
/**
* Manages incoming [Packet]s by grouping them by [Packet.getMessageId] and notifying registered
* listener when a complete message has been received.
*/
class PacketPayloadStream {
/** A map of message IDs to data that are waiting to be formed into complete messages. */
private val pendingData = mutableMapOf<Int, PendingMessage>()
var listener: OnMessageCompletedListener? = null
/**
* Writes the given [packet] into message-id-based stream.
*
* If the write cannot be completed, an [IOException] will be thrown.
*
* An [IllegalStateException] can also be thrown if there is inconsistency with the packet that is
* being written (e.g. if the given `packet` is written out-of-order with the last write of a
* `packet` with the same message id). When this happens, the stream should not be reused.
*/
fun write(packet: Packet) {
val messageId = packet.messageId
var pendingMessage =
pendingData.get(messageId)?.apply {
if (!shouldProcessPacket(packet, currentPendingMessage = this)) {
return@write
}
write(packet)
}
if (pendingMessage == null) {
// The first message must start at 1, but handle receiving the last packet as this could
// represent a duplicate packet. All other cases will trigger an exception when the packet
// is parsed into a BleDeviceMessage.
if (packet.packetNumber != 1 && packet.packetNumber == packet.totalPackets) {
logw(TAG, "Received a first message that is not the start of a packet. Ignoring.")
return
}
pendingMessage = packet.toPendingMessage()
pendingData[messageId] = pendingMessage
}
if (packet.packetNumber != packet.totalPackets) {
return
}
val bleDeviceMessage =
try {
Message.parseFrom(pendingMessage.messageStream.toByteArray())
} catch (e: IOException) {
loge(TAG, "Could not parse BlePackets with message id $messageId as BleDeviceMessage.")
throw e
}
pendingData.remove(messageId)
listener?.onMessageCompleted(bleDeviceMessage)
}
/**
* Validates the given [packet]'s metadata and returns `true` if the [packet] is valid for being
* written into the message stream.
*/
private fun shouldProcessPacket(packet: Packet, currentPendingMessage: PendingMessage): Boolean {
if (currentPendingMessage.lastPacketNumber + 1 == packet.packetNumber) {
return true
}
// A duplicate packet can just be ignored, while an out-of-order packet represents that the
// stream should be closed.
if (currentPendingMessage.lastPacketNumber == packet.packetNumber) {
logw(
TAG,
"Received a duplicate packet (${packet.packetNumber}) for message ${packet.messageId}. " +
"Ignoring."
)
return false
}
throw IllegalStateException(
"Received out-of-order packet ${packet.packetNumber}. " +
"Expecting ${currentPendingMessage.lastPacketNumber + 1}"
)
}
private fun Packet.toPendingMessage(): PendingMessage {
val payloadBytes = payload.toByteArray()
val messageStream = ByteArrayOutputStream(payloadBytes.size).apply { write(payloadBytes) }
return PendingMessage(messageStream, lastPacketNumber = packetNumber)
}
/** Invoked when [BlePacket]s through [write] can be combined into a [BleDeviceMessage]. */
interface OnMessageCompletedListener {
fun onMessageCompleted(deviceMessage: Message)
}
companion object {
private const val TAG = "PacketPayloadStream"
}
}
private data class PendingMessage(
var messageStream: ByteArrayOutputStream,
var lastPacketNumber: Int
) {
/**
* Writes the `payload` and `packetNumber` from the given [packet] to this `PendingMessage`.
*
* The `payload` is appended to the end of `messageStream`. If this write encounters an error,
* then an [IOException] is thrown.
*/
fun write(packet: Packet) {
messageStream.write(packet.payload.toByteArray())
lastPacketNumber = packet.packetNumber
}
/** Returns a hex representation of [messageStream]. */
fun messageStreamToHex(): String = messageStream.toByteArray().toHexString()
}
| apache-2.0 | 6bd9cf99614a3c842423e4927e1ae295 | 35.444444 | 100 | 0.715701 | 4.398994 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/ColorPrototype.kt | 1 | 1546 | package me.proxer.app.ui.view.bbcode.prototype
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import androidx.core.text.parseAsHtml
import androidx.core.text.set
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.ui.view.bbcode.BBUtils
import me.proxer.app.ui.view.bbcode.prototype.BBPrototype.Companion.REGEX_OPTIONS
/**
* @author Ruben Gees
*/
object ColorPrototype : TextMutatorPrototype {
private const val COLOR_ARGUMENT = "color"
private val attributeRegex = Regex("color *= *(.+?)( |$)", REGEX_OPTIONS)
override val startRegex = Regex(" *color *= *\"?.*?\"?( .*?)?", REGEX_OPTIONS)
override val endRegex = Regex("/ *color *", REGEX_OPTIONS)
@Suppress("UnnecessaryLet")
override fun construct(code: String, parent: BBTree): BBTree {
val value = BBUtils.cutAttribute(code, attributeRegex) ?: ""
val color = "<font color='$value'>dummy</font>".parseAsHtml()
.let { it.getSpans(0, it.length, ForegroundColorSpan::class.java) }
.firstOrNull()?.foregroundColor
return BBTree(this, parent, args = BBArgs(custom = *arrayOf(COLOR_ARGUMENT to color)))
}
override fun mutate(text: SpannableStringBuilder, args: BBArgs): SpannableStringBuilder {
return when (val color = args[COLOR_ARGUMENT] as Int?) {
null -> text
else -> text.apply {
this[0..length] = ForegroundColorSpan(color)
}
}
}
}
| gpl-3.0 | bc077e6edff454b780338481dec10bf5 | 34.953488 | 94 | 0.672704 | 4.079156 | false | false | false | false |
googlearchive/android-SliceViewer | app/src/main/java/com/example/android/sliceviewer/util/UriKtx.kt | 1 | 2103 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sliceviewer.util
import android.net.Uri
/**
* Copy a URI but remove the "slice-" prefix from its scheme.
*/
fun Uri.convertToOriginalScheme(): Uri {
var builder = Uri.Builder()
.authority(authority)
.path(path)
.encodedQuery(query)
.fragment(fragment)
builder = when (scheme) {
"slice-http" -> builder.scheme("http")
"slice-https" -> builder.scheme("https")
"slice-content" -> builder.scheme("content")
else -> builder
}
return builder.build()
}
/**
* Copy a URI but add a "slice-" prefix to its scheme.
*/
fun Uri.convertToSliceViewerScheme(): Uri {
var builder = Uri.Builder()
.authority(authority)
.path(path)
.encodedQuery(query)
.fragment(fragment)
builder = when (scheme) {
"http" -> builder.scheme("slice-http")
"https" -> builder.scheme("slice-https")
"content" -> builder.scheme("slice-content")
else -> builder
}
return builder.build()
}
/**
* We have to have an explicit list of schemes in our manifest that our SingleSliceViewer listens
* to. Right now, these are "http", "https", and "content"; likely the only schemes used in the vast
* majority of cases.
*/
fun Uri.hasSupportedSliceScheme(): Boolean {
return scheme != null && (scheme.equals("slice-http", true)
|| scheme.equals("slice-https", true)
|| scheme.equals("slice-content", true))
} | apache-2.0 | 788a142bf0db52c01386b91f241c372f | 30.878788 | 100 | 0.65573 | 3.998099 | false | false | false | false |
bjzhou/Coolapk | app/src/main/kotlin/bjzhou/coolapk/app/ui/adapters/CommentAdapter.kt | 1 | 5769 | package bjzhou.coolapk.app.ui.adapters
import android.support.v4.app.FragmentActivity
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.ExpandableListView
import android.widget.ImageView
import android.widget.TextView
import bjzhou.coolapk.app.R
import bjzhou.coolapk.app.model.Comment
import bjzhou.coolapk.app.model.Reply
import bjzhou.coolapk.app.util.TimeUtility
import com.squareup.picasso.Picasso
import java.util.*
/**
* Created by bjzhou on 14-8-8.
*/
class CommentAdapter(private val mActivity: FragmentActivity, private val mListView: ExpandableListView) : BaseExpandableListAdapter() {
private var mCommentList: List<Comment> = ArrayList()
fun setCommentList(commentList: List<Comment>) {
mCommentList = commentList
}
override fun getGroupCount(): Int {
return mCommentList.size
}
override fun getChildrenCount(groupPosition: Int): Int {
if (mCommentList[groupPosition].subrows == null) {
return 0
}
return mCommentList[groupPosition].subrows?.size ?: 0
}
override fun getGroup(groupPosition: Int): Any {
return mCommentList[groupPosition]
}
override fun getChild(groupPosition: Int, childPosition: Int): Reply? {
return mCommentList[groupPosition].subrows?.get(childPosition)
}
override fun getGroupId(groupPosition: Int): Long {
return mCommentList[groupPosition].id
}
override fun getChildId(groupPosition: Int, childPosition: Int): Long {
return mCommentList[groupPosition].subrows?.get(childPosition)?.id ?: 0
}
override fun hasStableIds(): Boolean {
return false
}
override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View? {
val holder: ViewHolder
var view: View? = convertView
if (view == null) {
holder = ViewHolder()
view = mActivity.layoutInflater.inflate(R.layout.list_item_comment, parent, false)
holder.userIconView = view.findViewById(R.id.list_item_icon) as ImageView
holder.titleView = view.findViewById(R.id.list_item_title) as TextView
holder.timeView = view.findViewById(R.id.list_item_time) as TextView
holder.msgView = view.findViewById(R.id.list_item_message) as TextView
//holder.infoView = (TextView) convertView.findViewById(R.id.list_item_info);
holder.replyNumView = view.findViewById(R.id.list_item_reply_num) as TextView
view.tag = holder
} else {
holder = view.tag as ViewHolder
}
Picasso.with(mActivity)
.load(mCommentList[groupPosition].useravatar)
.placeholder(R.drawable.ic_default_avatar)
.into(holder.userIconView)
//holder.userIconView.setImageUrl(mCommentList.get(position).getUseravatar(), ApiManager.getInstance(mActivity).getImageLoader());
var title = mCommentList[groupPosition].title
title = title.split("来自".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()[0]
holder.titleView?.text = title
holder.timeView?.text = TimeUtility.getTime(mCommentList[groupPosition].lastupdate)
val msg = mCommentList[groupPosition].message
holder.msgView?.text = Html.fromHtml(msg)
holder.msgView?.movementMethod = LinkMovementMethod.getInstance()
//holder.msgView.setMovementMethod(LinkMovementMethod.getInstance());
//holder.infoView.setText(mCommentList.get(position).getInfo());
holder.replyNumView?.text = mCommentList[groupPosition].replynum.toString() + ""
holder.replyNumView?.setOnClickListener { mListView.performItemClick(convertView, groupPosition, mCommentList[groupPosition].id) }
return view
}
override fun getChildView(groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup): View? {
if (mCommentList[groupPosition].subrows != null && mCommentList[groupPosition].subrows?.size ?: 0 > 0) {
val holder: ReplyViewHolder
var view: View? = convertView
if (view == null) {
holder = ReplyViewHolder()
view = mActivity.layoutInflater.inflate(R.layout.list_item_comment_reply, parent, false)
holder.userIconView = view.findViewById(R.id.list_item_icon) as ImageView
holder.msgView = view.findViewById(R.id.list_item_message) as TextView
view.tag = holder
} else {
holder = view.tag as ReplyViewHolder
}
val reply = mCommentList[groupPosition].subrows?.get(childPosition)
Picasso.with(mActivity)
.load(reply?.useravatar)
.placeholder(R.drawable.ic_default_avatar)
.into(holder.userIconView)
holder.msgView?.text = Html.fromHtml(reply?.message)
holder.msgView?.movementMethod = LinkMovementMethod.getInstance()
return view
}
return null
}
override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
return false
}
internal class ViewHolder {
var userIconView: ImageView? = null
var titleView: TextView? = null
var timeView: TextView? = null
var msgView: TextView? = null
//TextView infoView;
var replyNumView: TextView? = null
}
internal class ReplyViewHolder {
var userIconView: ImageView? = null
var msgView: TextView? = null
}
}
| gpl-2.0 | 7b3588a4be3dfc8df43355e33427efe7 | 39.314685 | 139 | 0.670598 | 4.608313 | false | false | false | false |
ThomasVadeSmileLee/cyls | src/main/kotlin/org/smileLee/cyls/util/InitNonNullMap.kt | 1 | 1062 | package org.smileLee.cyls.util
class InitNonNullMap<K, V>(private val m: HashMap<K, V>, private val init: (K) -> V) : NonNullMap<K, V> {
override fun get(key: K): V = m[key] ?: let {
val value = init(key)
m.put(key, value)
value
}
override fun iterator()
= m.iterator()
override fun put(key: K, value: V)
= m.put(key, value)
override fun putAll(from: Map<out K, V>)
= m.putAll(from)
override fun containsKey(key: K)
= m.containsKey(key)
override fun containsValue(value: V)
= m.containsValue(value)
override fun isEmpty()
= m.isEmpty()
override fun clear()
= m.clear()
override fun remove(key: K)
= m.remove(key)
override val size: Int
get() = m.size
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() = m.entries
override val keys: MutableSet<K>
get() = m.keys
override val values: MutableCollection<V>
get() = m.values
} | mit | b3a634ef7d71c11519682346b3345d7b | 22.622222 | 105 | 0.559322 | 3.713287 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/donut/DonutService.kt | 1 | 4134 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.donut
import com.vk.api.sdk.requests.VKRequest
import com.vk.dto.common.id.UserId
import com.vk.sdk.api.GsonHolder
import com.vk.sdk.api.NewApiRequest
import com.vk.sdk.api.base.dto.BaseBoolInt
import com.vk.sdk.api.base.dto.BaseUserGroupFields
import com.vk.sdk.api.donut.dto.DonutDonatorSubscriptionInfo
import com.vk.sdk.api.donut.dto.DonutGetSubscriptionsResponse
import com.vk.sdk.api.groups.dto.GroupsGetMembersFieldsResponse
import kotlin.Int
import kotlin.String
import kotlin.collections.List
class DonutService {
/**
* @param ownerId
* @param offset
* @param count
* @param fields
* @return [VKRequest] with [GroupsGetMembersFieldsResponse]
*/
fun donutGetFriends(
ownerId: UserId,
offset: Int? = null,
count: Int? = null,
fields: List<String>? = null
): VKRequest<GroupsGetMembersFieldsResponse> = NewApiRequest("donut.getFriends") {
GsonHolder.gson.fromJson(it, GroupsGetMembersFieldsResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 100) }
fields?.let { addParam("fields", it) }
}
/**
* @param ownerId
* @return [VKRequest] with [DonutDonatorSubscriptionInfo]
*/
fun donutGetSubscription(ownerId: UserId): VKRequest<DonutDonatorSubscriptionInfo> =
NewApiRequest("donut.getSubscription") {
GsonHolder.gson.fromJson(it, DonutDonatorSubscriptionInfo::class.java)
}
.apply {
addParam("owner_id", ownerId)
}
/**
* Returns a list of user's VK Donut subscriptions.
*
* @param fields
* @param offset
* @param count
* @return [VKRequest] with [DonutGetSubscriptionsResponse]
*/
fun donutGetSubscriptions(
fields: List<BaseUserGroupFields>? = null,
offset: Int? = null,
count: Int? = null
): VKRequest<DonutGetSubscriptionsResponse> = NewApiRequest("donut.getSubscriptions") {
GsonHolder.gson.fromJson(it, DonutGetSubscriptionsResponse::class.java)
}
.apply {
val fieldsJsonConverted = fields?.map {
it.value
}
fieldsJsonConverted?.let { addParam("fields", it) }
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 100) }
}
/**
* @param ownerId
* @return [VKRequest] with [BaseBoolInt]
*/
fun donutIsDon(ownerId: UserId): VKRequest<BaseBoolInt> = NewApiRequest("donut.isDon") {
GsonHolder.gson.fromJson(it, BaseBoolInt::class.java)
}
.apply {
addParam("owner_id", ownerId)
}
}
| mit | b33ec905923837c8607812ef90896d04 | 35.910714 | 92 | 0.6582 | 4.089021 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/DefaultIOSystem.kt | 2 | 1395 | package assimp
import java.io.*
import java.nio.*
import java.nio.channels.*
import java.nio.file.Path
import java.nio.file.Paths
class DefaultIOSystem : IOSystem {
override fun exists(file: String) = File(file).exists()
override fun open(file: String): IOStream {
val path: Path = Paths.get(file)
if (!exists(file))
throw IOException("File doesn't exist: $file")
return FileIOStream(path, this)
}
class FileIOStream(private val pathObject: Path, override val osSystem: DefaultIOSystem) : IOStream {
override val path: String
get() = pathObject.toString()
override fun read() = FileInputStream(file)
override fun reader() = BufferedReader(FileReader(file))
override val filename: String
get() = pathObject.fileName.toString()
override val parentPath = pathObject.parent.toAbsolutePath().toString()
override val length: Long
get() = file.length()
override fun readBytes(): ByteBuffer =
RandomAccessFile(file, "r").use { ram ->
ram.channel.use { ch ->
ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size())
.order(ByteOrder.nativeOrder())
}
}
val file: File
get() = pathObject.toFile()
}
} | mit | c6e9469b40483924b5ad5fa6616b86d9 | 26.92 | 105 | 0.584946 | 4.543974 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/housenumber/AddHousenumber.kt | 1 | 9236 | package de.westnordost.streetcomplete.quests.housenumber
import de.westnordost.osmapi.map.MapDataWithGeometry
import de.westnordost.osmapi.map.data.*
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolygonsGeometry
import de.westnordost.streetcomplete.data.quest.AllCountriesExcept
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
import de.westnordost.streetcomplete.ktx.isArea
import de.westnordost.streetcomplete.util.LatLonRaster
import de.westnordost.streetcomplete.util.isCompletelyInside
import de.westnordost.streetcomplete.util.isInMultipolygon
class AddHousenumber : OsmElementQuestType<HousenumberAnswer> {
override val commitMessage = "Add housenumbers"
override val wikiLink = "Key:addr"
override val icon = R.drawable.ic_quest_housenumber
// See overview here: https://ent8r.github.io/blacklistr/?streetcomplete=housenumber/AddHousenumber.kt
override val enabledInCountries = AllCountriesExcept(
"LU", // https://github.com/westnordost/StreetComplete/pull/1943
"NL", // https://forum.openstreetmap.org/viewtopic.php?id=60356
"DK", // https://lists.openstreetmap.org/pipermail/talk-dk/2017-November/004898.html
"NO", // https://forum.openstreetmap.org/viewtopic.php?id=60357
"CZ", // https://lists.openstreetmap.org/pipermail/talk-cz/2017-November/017901.html
"IT", // https://lists.openstreetmap.org/pipermail/talk-it/2018-July/063712.html
"FR" // https://github.com/streetcomplete/StreetComplete/issues/2427 https://t.me/osmfr/26320
)
override fun getTitle(tags: Map<String, String>) = R.string.quest_address_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val bbox = mapData.boundingBox ?: return listOf()
val addressNodesById = mapData.nodes.filter { nodesWithAddressFilter.matches(it) }.associateBy { it.id }
val addressNodeIds = addressNodesById.keys
/** filter: only buildings with no address that usually should have an address
* ...that do not have an address node on their outline */
val buildings = mapData.filter {
buildingsWithMissingAddressFilter.matches(it)
&& !it.containsAnyNode(addressNodeIds, mapData)
}.toMutableList()
if (buildings.isEmpty()) return listOf()
/** exclude buildings which are included in relations that have an address */
val relationsWithAddress = mapData.relations.filter { nonMultipolygonRelationsWithAddressFilter.matches(it) }
buildings.removeAll { building ->
relationsWithAddress.any { it.containsWay(building.id) }
}
if (buildings.isEmpty()) return listOf()
/** exclude buildings that intersect with the bounding box because it is not possible to
ascertain for these if there is an address node within the building - it could be outside
the bounding box */
val buildingGeometriesById = buildings.associate {
it.id to mapData.getGeometry(it.type, it.id) as? ElementPolygonsGeometry
}
buildings.removeAll { building ->
val buildingBounds = buildingGeometriesById[building.id]?.getBounds()
(buildingBounds == null || !buildingBounds.isCompletelyInside(bbox))
}
if (buildings.isEmpty()) return listOf()
/** exclude buildings that contain an address node somewhere within their area */
val addressPositions = LatLonRaster(bbox, 0.0005)
for (node in addressNodesById.values) {
addressPositions.insert(node.position)
}
buildings.removeAll { building ->
val buildingGeometry = buildingGeometriesById[building.id]
if (buildingGeometry != null) {
val nearbyAddresses = addressPositions.getAll(buildingGeometry.getBounds())
nearbyAddresses.any { it.isInMultipolygon(buildingGeometry.polygons) }
} else true
}
if (buildings.isEmpty()) return listOf()
/** exclude buildings that are contained in an area that has an address tagged on itself
* or on a vertex on its outline */
val areasWithAddressesOnOutline = mapData
.filter { notABuildingFilter.matches(it) && it.isArea() && it.containsAnyNode(addressNodeIds, mapData) }
.mapNotNull { mapData.getGeometry(it.type, it.id) as? ElementPolygonsGeometry }
val areasWithAddresses = mapData
.filter { nonBuildingAreasWithAddressFilter.matches(it) }
.mapNotNull { mapData.getGeometry(it.type, it.id) as? ElementPolygonsGeometry }
val buildingsByCenterPosition: Map<LatLon?, Element> = buildings.associateBy { buildingGeometriesById[it.id]?.center }
val buildingPositions = LatLonRaster(bbox, 0.0005)
for (buildingCenterPosition in buildingsByCenterPosition.keys) {
if (buildingCenterPosition != null) buildingPositions.insert(buildingCenterPosition)
}
for (areaWithAddress in areasWithAddresses + areasWithAddressesOnOutline) {
val nearbyBuildings = buildingPositions.getAll(areaWithAddress.getBounds())
val buildingPositionsInArea = nearbyBuildings.filter { it.isInMultipolygon(areaWithAddress.polygons) }
val buildingsInArea = buildingPositionsInArea.mapNotNull { buildingsByCenterPosition[it] }
buildings.removeAll(buildingsInArea)
}
return buildings
}
override fun isApplicableTo(element: Element): Boolean? = null
override fun createForm() = AddHousenumberForm()
override fun applyAnswerTo(answer: HousenumberAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is NoHouseNumber -> changes.add("nohousenumber", "yes")
is HouseNumber -> changes.add("addr:housenumber", answer.number)
is HouseName -> changes.add("addr:housename", answer.name)
is ConscriptionNumber -> {
changes.add("addr:conscriptionnumber", answer.number)
if (answer.streetNumber != null) {
changes.add("addr:streetnumber", answer.streetNumber)
changes.add("addr:housenumber", answer.streetNumber)
} else {
changes.add("addr:housenumber", answer.number)
}
}
is HouseAndBlockNumber -> {
changes.add("addr:housenumber", answer.houseNumber)
changes.addOrModify("addr:block_number", answer.blockNumber)
}
}
}
}
private val notABuildingFilter by lazy { """
ways, relations with !building"
""".toElementFilterExpression()}
private val nonBuildingAreasWithAddressFilter by lazy { """
ways, relations with
!building and ~"addr:(housenumber|housename|conscriptionnumber|streetnumber)"
""".toElementFilterExpression()}
private val nonMultipolygonRelationsWithAddressFilter by lazy { """
relations with
type != multipolygon
and ~"addr:(housenumber|housename|conscriptionnumber|streetnumber)"
""".toElementFilterExpression()}
private val nodesWithAddressFilter by lazy { """
nodes with ~"addr:(housenumber|housename|conscriptionnumber|streetnumber)"
""".toElementFilterExpression()}
private val buildingsWithMissingAddressFilter by lazy { """
ways, relations with
building ~ ${buildingTypesThatShouldHaveAddresses.joinToString("|")}
and location != underground
and ruins != yes
and abandoned != yes
and !addr:housenumber
and !addr:housename
and !addr:conscriptionnumber
and !addr:streetnumber
and !noaddress
and !nohousenumber
""".toElementFilterExpression()}
private val buildingTypesThatShouldHaveAddresses = listOf(
"house", "residential", "apartments", "detached", "terrace", "dormitory", "semi",
"semidetached_house", "farm", "school", "civic", "college", "university", "public", "hospital",
"kindergarten", "train_station", "hotel", "retail", "commercial"
)
private fun Element.containsAnyNode(nodeIds: Set<Long>, mapData: MapDataWithGeometry): Boolean =
when (this) {
is Way -> this.nodeIds.any { it in nodeIds }
is Relation -> containsAnyNode(nodeIds, mapData)
else -> false
}
/** return whether any way contained in this relation contains any of the nodes with the given ids */
private fun Relation.containsAnyNode(nodeIds: Set<Long>, mapData: MapDataWithGeometry): Boolean =
members
.filter { it.type == Element.Type.WAY }
.any { member ->
val way = mapData.getWay(member.ref)
way?.nodeIds?.any { it in nodeIds } ?: false
}
/** return whether any of the ways with the given ids are contained in this relation */
private fun Relation.containsWay(wayId: Long): Boolean =
members.any { it.type == Element.Type.WAY && wayId == it.ref }
| gpl-3.0 | 2401520eefb5687221e7c5dc53a031b7 | 43.834951 | 126 | 0.687744 | 4.574542 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectImagePuzzle/app/src/main/java/me/liuqingwen/android/projectimagepuzzle/FragmentImagePuzzle.kt | 1 | 17504 | package me.liuqingwen.android.projectimagepuzzle
import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.view.animation.BounceInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.values
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.layout_fragment_puzzle.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.bundleOf
import org.jetbrains.anko.info
import java.util.*
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Created by Qingwen on 2018-8-1, project: ProjectImagePuzzle.
*
* @Author: Qingwen
* @DateTime: 2018-8-1
* @Package: me.liuqingwen.android.projectimagepuzzle in project: ProjectImagePuzzle
*
* Notice: If you are using this class or file, check it and do some modification.
*/
class FragmentImagePuzzle: Fragment(), AnkoLogger
{
interface IFragmentInteractionListener: IFragmentActivity
companion object
{
private const val PARAM_PATH = "path"
private const val PARAM_URI = "uri"
fun newInstance(path: String) = FragmentImagePuzzle().apply {
this.arguments = bundleOf(PARAM_PATH to path)
}
fun newInstance(uri: Uri) = FragmentImagePuzzle().apply {
this.arguments = bundleOf(PARAM_URI to uri)
}
}
private var listener: IFragmentInteractionListener? = null
private var imagePath: String? = null
private var imageUri: Uri? = null
private var rows = 4
private var columns = 3
private var cellWidth = 0
private var cellHeight = 0
private var minMarginLeft = 0
private var maxMarginLeft = 0
private var minMarginTop = 0
private var maxMarginTop = 0
private lateinit var pieces: Array<ImagePuzzleCell?>
override fun onAttach(context: Context?)
{
super.onAttach(context)
this.listener = if (context is FragmentImagePuzzle.IFragmentInteractionListener) context else throw RuntimeException(context.toString() + " must implement IFragmentInteractionListener")
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
this.arguments?.let {
this.imagePath = it.getString(FragmentImagePuzzle.PARAM_PATH, null)
this.imageUri = it.getParcelable(FragmentImagePuzzle.PARAM_URI)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.layout_fragment_puzzle, container, false)
override fun onStart()
{
super.onStart()
this.buttonReset.setOnClickListener { this.resetPuzzle() }
this.buttonResult.setOnClickListener { this.showResult() }
this.imagePuzzle.post {
fun processImage()
{
this.splitImage(this.context, this.imagePuzzle, rows = this.rows, columns = this.columns)
this.pieces.forEach { this.addImageView(it!!) }
}
val assetManager = this.listener?.assetManager
when
{
this.imagePath != null && assetManager != null -> {
val stream = assetManager.open("${MainActivity.ASSET_DIRECTORY_NAME}/${this.imagePath}")
val bitmap = sampleBitmapData(this.imagePuzzle.width, this.imagePuzzle.height, stream)
this.imagePuzzle.setImageBitmap(bitmap)
processImage()
}
this.imageUri != null -> {
this.imagePuzzle.setImageURI(this.imageUri!!)
processImage()
}
else -> {
this.disableButtons()
this.imagePuzzle.setImageResource(R.drawable.image_load_error)
Toast.makeText(this.context, "Incorrect image data!", Toast.LENGTH_LONG).show()
}
}
}
}
private fun disableButtons(disable: Boolean = true)
{
this.buttonReset.isEnabled = ! disable
this.buttonResult.isEnabled = ! disable
}
private fun showResult()
{
if (this.pieces.isEmpty() || this.pieces.filterNotNull().isEmpty())
{
return
}
this.disableButtons()
val duration = 500L
var count = this.pieces.size * 2
val listener = object: Animator.AnimatorListener{
override fun onAnimationRepeat(animation: Animator?) = Unit
override fun onAnimationCancel(animation: Animator?) = Unit
override fun onAnimationStart(animation: Animator?) = Unit
override fun onAnimationEnd(animation: Animator?)
{
count --
if(count <= 0)
{
[email protected](false)
}
}
}
this.pieces.forEach {image ->
image!!.isTouchable = false
val layoutParams = image.layoutParams as RelativeLayout.LayoutParams
val left = image.column * this.cellWidth - image.offsetX
val top = image.row * this.cellHeight - image.offsetY
ValueAnimator.ofInt(layoutParams.leftMargin, left).setDuration(duration).let {
it.addUpdateListener {
image.layoutParams = layoutParams.apply { this.leftMargin = it.animatedValue as Int }
}
it.interpolator = DecelerateInterpolator()
it.addListener(listener)
it.start()
}
ValueAnimator.ofInt(layoutParams.topMargin, top).setDuration(duration).let {
it.addUpdateListener {
image.layoutParams = layoutParams.apply { this.topMargin = it.animatedValue as Int }
}
it.interpolator = DecelerateInterpolator()
it.addListener(listener)
it.start()
}
}
}
private fun resetPuzzle() = this.pieces.forEach {imageView->
imageView!!.isTouchable = true
this.setRandomPosition(imageView, imageView.layoutParams as RelativeLayout.LayoutParams)
}
private fun setRandomPosition(imageView: ImagePuzzleCell, layoutParams: RelativeLayout.LayoutParams)
{
val random = Random()
imageView.layoutParams = layoutParams.also {
it.leftMargin = random.nextInt(this.maxMarginLeft - this.minMarginLeft) + this.minMarginLeft
it.topMargin = random.nextInt(this.maxMarginTop - this.minMarginTop) + this.minMarginTop
}
if (random.nextInt() % 2 == 0)
{
imageView.parent.bringChildToFront(imageView)
}
}
@SuppressLint("ClickableViewAccessibility")
private fun addImageView(imageView: ImagePuzzleCell)
{
this.layoutContainer.addView(imageView)
val layoutParams = imageView.layoutParams as RelativeLayout.LayoutParams
this.setRandomPosition(imageView, layoutParams)
this.testInGridLocation(imageView, layoutParams.leftMargin, layoutParams.topMargin)
var deltaX = 0.0f
var deltaY = 0.0f
imageView.setOnTouchListener { view, motionEvent ->
if (! (view as ImagePuzzleCell).isTouchable)
{
return@setOnTouchListener true
}
val x = motionEvent.rawX
val y = motionEvent.rawY
when(motionEvent.action and MotionEvent.ACTION_MASK)
{
MotionEvent.ACTION_DOWN -> {
deltaX = x - layoutParams.leftMargin
deltaY = y - layoutParams.topMargin
view.parent.bringChildToFront(view)
}
MotionEvent.ACTION_MOVE -> {
layoutParams.leftMargin = min(max((x - deltaX).roundToInt(), this.minMarginLeft), this.maxMarginLeft - view.offsetX)
layoutParams.topMargin = min(max((y - deltaY).roundToInt(), this.minMarginTop), this.maxMarginTop - view.offsetY)
view.layoutParams = layoutParams
}
MotionEvent.ACTION_UP -> {
val leftUp = min(max((x - deltaX).roundToInt(), this.minMarginLeft), this.maxMarginLeft - view.offsetX)
val topUp = min(max((y - deltaY).roundToInt(), this.minMarginTop), this.maxMarginTop - view.offsetY)
val (hasValue, left, top, row, column) = this.locatePrecision(leftUp, topUp, view.offsetX, view.offsetY)
if (hasValue)
{
view.locationRow = row
view.locationColumn = column
view.layoutParams = layoutParams.apply {
this.leftMargin = left
this.topMargin = top
}
this.triggerGameResult()
}
}
MotionEvent.ACTION_CANCEL -> {}
else -> {}
}
return@setOnTouchListener true
}
}
private fun testInGridLocation(imageView: ImagePuzzleCell, leftMargin: Int, topMargin: Int)
{
val (hasValue, _, _, row, column) = this.locatePrecision(leftMargin, topMargin, 0, 0, precision = 0)
if (hasValue)
{
imageView.locationRow = row
imageView.locationColumn = column
info("-----------------------------------Piece in right position: [$row, $column]")
}
}
private fun triggerGameResult()
{
val win = this.pieces.all { it?.isInRightLocation == true }
if (win)
{
Toast.makeText(this.context, "Winner, you are great!", Toast.LENGTH_LONG).show()
}
}
private fun locatePrecision(leftUp: Int, topUp: Int, offsetX: Int, offsetY: Int, precision: Int = 8): Tuple5
{
val slop = if(precision <= 0) 0 else (this.cellWidth * this.cellWidth + this.cellHeight * this.cellHeight) / precision / precision
val leftColumn = (((leftUp + offsetX - this.minMarginLeft)).toFloat() / this.cellWidth).roundToInt()
val leftRemainder = leftUp + offsetX - this.minMarginLeft - leftColumn * this.cellWidth
val topRow = (((topUp + offsetY - this.minMarginTop)).toFloat() / this.cellHeight).roundToInt()
val topRemainder = topUp + offsetY - this.minMarginTop - topRow * this.cellHeight
return if (leftRemainder * leftRemainder <= slop && topRemainder * topRemainder <= slop)
Tuple5(true, leftColumn * this.cellWidth + this.minMarginLeft - offsetX, topRow * this.cellHeight + this.minMarginTop - offsetY, topRow, leftColumn) else
Tuple5()
}
private fun splitImage(context: Context?, imageView: ImageView, rows: Int = 1, columns: Int = 1)
{
val matrix = imageView.imageMatrix.values()
val scaleX = matrix[Matrix.MSCALE_X]
val scaleY = matrix[Matrix.MSCALE_Y]
val imageDrawable = imageView.drawable!!
var imageBitmap = imageDrawable.toBitmap()
val originalWidth = imageDrawable.intrinsicWidth
val originalHeight = imageDrawable.intrinsicHeight
val actualWidth = (originalWidth * scaleX).roundToInt()
val actualHeight = (originalHeight * scaleY).roundToInt()
val displayWidth = imageView.width
val displayHeight = imageView.height
val paddingHorizontal = (actualWidth - displayWidth).absoluteValue / 2
val paddingVertical = (actualHeight - displayHeight).absoluteValue / 2
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, actualWidth, actualHeight, true)
imageBitmap = Bitmap.createBitmap(imageBitmap, paddingHorizontal, paddingVertical, displayWidth, displayHeight)
val cellWidth = displayWidth / columns
val cellHeight = displayHeight / rows
val bumpSize = min(cellWidth, cellHeight) / 4
//this.setMarginBorder(paddingHorizontal, paddingVertical, cellWidth, cellHeight, rows, columns)
this.setMarginBorder(0, 0, cellWidth, cellHeight, rows, columns)
this.pieces = arrayOfNulls<ImagePuzzleCell>(rows * columns)
val path = Path()
val paint = Paint()
for (i in 0 until rows)
{
for (j in 0 until columns)
{
val cellX = j * cellWidth
val cellY = i * cellHeight
val bumpLeft = if (j == 0) 0 else bumpSize
val bumpTop = if (i == 0) 0 else bumpSize
val sizedBitmap = Bitmap.createBitmap(imageBitmap, cellX - bumpLeft, cellY - bumpTop, cellWidth + bumpLeft, cellHeight + bumpTop)
val resultBitmap = Bitmap.createBitmap(sizedBitmap.width, sizedBitmap.height, Bitmap.Config.ARGB_8888)
val imageCell = ImagePuzzleCell(context, row = i, column = j).apply {
this.offsetX = bumpLeft
this.offsetY = bumpTop
this.imageWidth = cellWidth + bumpLeft
this.imageHeight = cellHeight + bumpTop
this.locationRow = -1
this.locationColumn = -1
}
val canvas = Canvas(resultBitmap)
with(path) {
val w = resultBitmap.width.toFloat()
val h = resultBitmap.height.toFloat()
val t = bumpTop.toFloat()
val l = bumpLeft.toFloat()
this.reset()
this.moveTo(w, t)
if (i != 0)
{
this.lineTo(w - (w - l) / 3, t)
this.cubicTo(w - (w - l) / 6, t - bumpSize, w - (w - l) * 5 / 6, t - bumpSize, w - (w - l) * 2 / 3, t)
}
this.lineTo(l, t)
if (j != 0)
{
this.lineTo(l, h - (h - t) * 2 / 3)
this.cubicTo(l - bumpSize, h - (h - t) * 5 / 6, l - bumpSize, h - (h - t) / 6, l, h - (h - t) / 3)
}
this.lineTo(l, h)
if (i != rows - 1)
{
this.lineTo(w - (w - l) * 2 / 3, h)
this.cubicTo(w - (w - l) * 5 / 6, h - bumpSize, w - (w - l) / 6, h - bumpSize, w - (w - l) / 3, h)
}
this.lineTo(w, h)
if (j != columns - 1)
{
this.lineTo(w, h - (h - t) / 3)
this.cubicTo(w - bumpSize, h - (h - t) / 6, w - bumpSize, h - (h - t) * 5 / 6, w, h - (h - t) * 2 / 3)
}
this.close()
}
paint.xfermode = null
paint.style = Paint.Style.FILL
paint.color = 0xFF000000.toInt()
canvas.drawPath(path, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
canvas.drawBitmap(sizedBitmap, 0.0f, 0.0f, paint.apply { })
paint.style = Paint.Style.STROKE
paint.strokeWidth = 8.0f
paint.color = 0x80FFFFFF.toInt()
canvas.drawPath(path, paint)
paint.strokeWidth = 3.0f
paint.color = 0x80000000.toInt()
canvas.drawPath(path, paint)
imageCell.setImageBitmap(resultBitmap)
this.pieces[i * columns + j] = imageCell
}
}
}
private fun setMarginBorder(leftStart: Int, topStart: Int, cellWidth: Int, cellHeight: Int, rows: Int, columns: Int)
{
this.minMarginLeft = leftStart
this.minMarginTop = topStart
this.maxMarginLeft = leftStart + (columns - 1) * cellWidth
this.maxMarginTop = topStart + (rows - 1) * cellHeight
this.cellWidth = cellWidth
this.cellHeight = cellHeight
}
}
data class Tuple5(val hasValue: Boolean = false, val v1: Int = 0, val v2: Int = 0, val v3: Int = 0, val v4: Int = 0)
class ImagePuzzleCell(context: Context?, val row: Int, val column: Int, val rotation: Int = 0): AppCompatImageView(context)
{
constructor(context: Context?):this(context, -1, -1)
var isInRightLocation: Boolean = false
get() = this.row == this.locationRow && this.column == this.locationColumn
var offsetX = 0
var offsetY = 0
var imageWidth = 0
var imageHeight = 0
var locationRow = -1
var locationColumn = -1
var currentRotation = 0
var isTouchable = true
} | mit | bf753a9e18602e410e1778677266f221 | 39.804196 | 193 | 0.571469 | 4.820711 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/extensions/HexByteArrayConversion.kt | 1 | 884 | package info.nightscout.androidaps.extensions
import java.util.*
private val HEX_CHARS = "0123456789abcdef".toCharArray()
fun ByteArray.toHex() : String{
val result = StringBuffer()
forEach {
val octet = it.toInt()
val firstIndex = (octet and 0xF0).ushr(4)
val secondIndex = octet and 0x0F
result.append(HEX_CHARS[firstIndex])
result.append(HEX_CHARS[secondIndex])
}
return result.toString()
}
fun String.hexStringToByteArray(): ByteArray {
val result = ByteArray(length / 2)
val lowerCased = this.lowercase(Locale.getDefault())
for (i in 0 until length step 2) {
val firstIndex = HEX_CHARS.indexOf(lowerCased[i])
val secondIndex = HEX_CHARS.indexOf(lowerCased[i + 1])
val octet = firstIndex.shl(4).or(secondIndex)
result[i.shr(1)] = octet.toByte()
}
return result
} | agpl-3.0 | 22d684ed76c13129d2a82563398fe085 | 24.285714 | 62 | 0.656109 | 3.894273 | false | false | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerState.kt | 1 | 4642 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.fileEditor.impl.EditorsSplitters
import com.intellij.openapi.observable.properties.AtomicProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.ComponentUtil
import com.intellij.ui.ExperimentalUI
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.util.*
@ApiStatus.Internal
interface ToolWindowManagerState : PersistentStateComponent<Element> {
var layout: DesktopLayout
val noStateLoaded: Boolean
val oldLayout: DesktopLayout?
var layoutToRestoreLater: DesktopLayout?
val recentToolWindows: LinkedList<String>
val scheduledLayout: AtomicProperty<DesktopLayout?>
val isEditorComponentActive: Boolean
var frame: ProjectFrameHelper?
}
private const val EDITOR_ELEMENT = "editor"
private const val ACTIVE_ATTR_VALUE = "active"
private const val LAYOUT_TO_RESTORE = "layout-to-restore"
private const val RECENT_TW_TAG = "recentWindows"
@ApiStatus.Internal
@State(name = "ToolWindowManager", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
class ToolWindowManagerStateImpl(private val project: Project) : ToolWindowManagerState {
private val isNewUi get() = ExperimentalUI.isNewUI()
override var layout = DesktopLayout()
override var noStateLoaded = false
private set
override var oldLayout: DesktopLayout? = null
private set
override var layoutToRestoreLater: DesktopLayout? = null
override val recentToolWindows = LinkedList<String>()
override val scheduledLayout = AtomicProperty<DesktopLayout?>(null)
private val focusManager: IdeFocusManager
get() = IdeFocusManager.getInstance(project)!!
override val isEditorComponentActive: Boolean
get() {
ApplicationManager.getApplication().assertIsDispatchThread()
return ComponentUtil.getParentOfType(EditorsSplitters::class.java, focusManager.focusOwner) != null
}
override var frame: ProjectFrameHelper? = null
override fun getState(): Element? {
if (frame == null) {
return null
}
val element = Element("state")
if (isEditorComponentActive) {
element.addContent(Element(EDITOR_ELEMENT).setAttribute(ACTIVE_ATTR_VALUE, "true"))
}
// save layout of tool windows
writeLayout(layout, element, isV2 = isNewUi)
oldLayout?.let {
writeLayout(it, element, isV2 = !isNewUi)
}
layoutToRestoreLater?.writeExternal(LAYOUT_TO_RESTORE)?.let {
element.addContent(it)
}
if (recentToolWindows.isNotEmpty()) {
val recentState = Element(RECENT_TW_TAG)
recentToolWindows.forEach {
recentState.addContent(Element("value").addContent(it))
}
element.addContent(recentState)
}
return element
}
override fun loadState(state: Element) {
var layoutIsScheduled = false
for (element in state.children) {
if (JDOMUtil.isEmpty(element)) {
// make sure that layoutIsScheduled is not set if empty layout for some reason is provided
continue
}
when (element.name) {
DesktopLayout.TAG -> {
val layout = DesktopLayout()
layout.readExternal(element, isNewUi = false)
if (isNewUi) {
oldLayout = layout
}
else {
scheduledLayout.set(layout)
layoutIsScheduled = true
}
}
"layoutV2" -> {
val layout = DesktopLayout()
layout.readExternal(element, isNewUi = true)
if (isNewUi) {
scheduledLayout.set(layout)
layoutIsScheduled = true
}
else {
oldLayout = layout
}
}
LAYOUT_TO_RESTORE -> {
layoutToRestoreLater = DesktopLayout().also { it.readExternal(element, isNewUi) }
}
RECENT_TW_TAG -> {
recentToolWindows.clear()
element.content.forEach {
recentToolWindows.add(it.value)
}
}
}
}
if (!layoutIsScheduled) {
noStateLoaded()
}
}
override fun noStateLoaded() {
noStateLoaded = true
}
private fun writeLayout(layout: DesktopLayout, parent: Element, isV2: Boolean) {
parent.addContent(layout.writeExternal(if (isV2) "layoutV2" else DesktopLayout.TAG) ?: return)
}
} | apache-2.0 | 9df2f165660d2332cfda28428b63aabc | 31.468531 | 120 | 0.696898 | 4.582428 | false | false | false | false |
blindpirate/gradle | .teamcity/src/main/kotlin/model/GradleSubprojectProvider.kt | 1 | 2252 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package model
import com.alibaba.fastjson.JSON
import java.io.File
val ignoredSubprojects = listOf(
"soak", // soak test
"distributions-integ-tests", // build distribution testing
"architecture-test" // sanity check
)
interface GradleSubprojectProvider {
val subprojects: List<GradleSubproject>
fun getSubprojectsFor(testConfig: TestCoverage, stage: Stage): List<GradleSubproject>
fun getSubprojectByName(name: String): GradleSubproject?
}
data class JsonBasedGradleSubprojectProvider(private val jsonFile: File) : GradleSubprojectProvider {
@Suppress("UNCHECKED_CAST")
override val subprojects = JSON.parseArray(jsonFile.readText()).map { toSubproject(it as Map<String, Any>) }
private val nameToSubproject = subprojects.map { it.name to it }.toMap()
override fun getSubprojectsFor(testConfig: TestCoverage, stage: Stage) =
subprojects.filter { it.hasTestsOf(testConfig.testType) }
.filterNot { testConfig.os.ignoredSubprojects.contains(it.name) }
override fun getSubprojectByName(name: String) = nameToSubproject[name]
private
fun toSubproject(subproject: Map<String, Any>): GradleSubproject {
val name = subproject["name"] as String
val unitTests = !ignoredSubprojects.contains(name) && subproject["unitTests"] as Boolean
val functionalTests = !ignoredSubprojects.contains(name) && subproject["functionalTests"] as Boolean
val crossVersionTests = !ignoredSubprojects.contains(name) && subproject["crossVersionTests"] as Boolean
return GradleSubproject(name, unitTests, functionalTests, crossVersionTests)
}
}
| apache-2.0 | 8c1df77ad4d9a657d845f3a8e0ac620d | 41.490566 | 112 | 0.742451 | 4.241055 | false | true | false | false |
Tiofx/semester_6 | TRPSV/src/main/kotlin/visualization/plotIt.kt | 1 | 2806 | package visualization
import golem.*
import task2.test.ParallelAndSequentialTime
import task2.test.ResultSet
val figureColors = mutableMapOf(0 to plotColors.iterator())
fun getNextColor(figure: Int): String {
if (!figureColors.contains(figure) || !figureColors[figure]!!.hasNext()) {
figureColors.put(figure, plotColors.iterator())
}
return figureColors[figure]!!.next().key
}
fun allEdgeProbabilityPlot(makeTest: ResultSet) {
val x = makeTest.results.map { it.input.vertexNumber }.distinct().toIntArray()
val groupByEdge = makeTest.results.groupBy { it.input.edgeProbability }
var seqPar = 2
var comparisonNumber = 2 + groupByEdge.keys.count() + 1
groupByEdge.forEach { edgeProbability, u ->
allEdgeProbabilityPlot(x, u.map { it.millisecondTime.second }.toDoubleArray(), edgeProbability, 0)
allEdgeProbabilityPlot(x, u.map { it.millisecondTime.first }.toDoubleArray(), edgeProbability, 1, true)
sequentialAndParallelPlot(x, u.map { it.millisecondTime }, edgeProbability, seqPar)
sequentialAndParallelComparisonPlot(x, u.map { it.millisecondTime }, edgeProbability, comparisonNumber)
seqPar++
}
}
fun allEdgeProbabilityPlot(x: IntArray, y: DoubleArray, edgeProbability: Double, figure: Int, isParallel: Boolean = false) {
figure(figure)
plot(x, y, getNextColor(figure), "разяженность графа: ${edgeProbability}")
ylabel("Время, мс")
xlabel("Количество вершин")
title("${if (isParallel) "Параллельный" else "Последовательный"} алгоритм")
}
fun sequentialAndParallelPlot(x: IntArray, y: List<ParallelAndSequentialTime>, edgeProbability: Double, figure: Int) {
figure(figure)
plot(x, y.map { it.first }.toDoubleArray(), getNextColor(figure), "параллельный алгоритм")
plot(x, y.map { it.second }.toDoubleArray(), getNextColor(figure), "последовательный алгоритм")
ylabel("Время, мс")
xlabel("Количество вершин")
title("Последовательный и параллельный алгоритм при разряженности графа: $edgeProbability")
}
fun sequentialAndParallelComparisonPlot(x: IntArray, y: List<ParallelAndSequentialTime>, edgeProbability: Double, figure: Int) {
figure(figure)
plot(x, y.map { (it.second - it.first) / it.first }.map { 100 * it }.toDoubleArray(),
getNextColor(figure), "разяженность графа: ${edgeProbability}")
ylabel("Проценты, %")
xlabel("Количество вершин")
title("Зависимость эффективности параллельного алгоритма от количества вершин")
} | gpl-3.0 | bd28b703b6985b03e8fb52954e95dd40 | 40 | 128 | 0.7232 | 3.28084 | false | true | false | false |
zzorn/mechaflow | src/main/kotlin/org/mechaflow2/PortDirection.kt | 1 | 614 | package org.mechaflow2
/**
* Represents the possible directions of energy, matter or information transmission in port.
*/
enum class PortDirection private constructor(val isInput: Boolean, val isOutput: Boolean) {
IN(true, false),
OUT(false, true),
INOUT(true, true);
fun canConnect(otherDirection: PortDirection): Boolean {
when (this) {
IN -> return otherDirection == OUT
OUT -> return otherDirection == IN
INOUT -> return otherDirection == INOUT
else -> throw IllegalStateException("Unknown PortDirection: " + this)
}
}
}
| gpl-3.0 | a93ca45cc213eb282fbf3bbf089613ab | 29.7 | 92 | 0.644951 | 4.514706 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/ManagementControlUseCase.kt | 1 | 2462 | package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.store.StatsStore.ManagementType
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.NavigationTarget.ViewInsightsManagement
import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem
import org.wordpress.android.ui.utils.ListItemInteraction.Companion
import org.wordpress.android.ui.stats.refresh.utils.NewsCardHandler
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.viewmodel.ResourceProvider
import javax.inject.Inject
import javax.inject.Named
class ManagementControlUseCase
@Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher,
private val newsCardHandler: NewsCardHandler,
private val resourceProvider: ResourceProvider,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) : StatelessUseCase<Boolean>(
ManagementType.CONTROL,
mainDispatcher,
backgroundDispatcher,
listOf()
) {
override suspend fun loadCachedData() = true
override suspend fun fetchRemoteData(forced: Boolean): State<Boolean> = State.Data(true)
override fun buildLoadingItem(): List<BlockListItem> = listOf()
override fun buildUiModel(domainModel: Boolean): List<BlockListItem> {
return listOf(
BlockListItem.ListItemWithIcon(
icon = R.drawable.ic_plus_white_24dp,
textResource = R.string.stats_management_add_new_stats_card,
navigationAction = Companion.create(this::onClick),
showDivider = false,
contentDescription = resourceProvider.getString(R.string.stats_management_add_new_stats_card)
)
)
}
private fun onClick() {
newsCardHandler.dismiss()
analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_MANAGEMENT_ACCESSED, mapOf("source" to "insightsCard"))
navigateTo(ViewInsightsManagement)
}
}
| gpl-2.0 | 1f243f0c5984d5797931c1ac16293a67 | 43.763636 | 117 | 0.750203 | 4.752896 | false | false | false | false |
ingokegel/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/MyCreateStandaloneTypeBindingVisitorBase.kt | 41 | 2177 | package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import org.jetbrains.protocolReader.appendEnums
internal class MyCreateStandaloneTypeBindingVisitorBase(private val generator: DomainGenerator, type: ProtocolMetaModel.StandaloneType, private val name: String) : CreateStandaloneTypeBindingVisitorBase(generator, type) {
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
return object : StandaloneTypeBinding {
override fun getJavaType() = subMessageType(generator.generator.naming.additionalParam.getFullName(generator.domain.domain(), name))
override fun generate() = generator.generateCommandAdditionalParam(type)
override fun getDirection() = TypeData.Direction.OUTPUT
}
}
override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding {
return object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType = StandaloneType(generator.generator.naming.additionalParam.getFullName(generator.domain.domain(), name), "writeEnum")
override fun generate() = appendEnums(enumConstants, name, false, generator.fileUpdater.out.newLine().newLine())
override fun getDirection() = TypeData.Direction.OUTPUT
}
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType) = generator.createTypedefTypeBinding(type, object : Target {
override fun resolve(context: Target.ResolveContext): BoxableType {
return ListType(generator.generator.resolveType(items, object : ResolveAndGenerateScope {
// This class is responsible for generating ad hoc type.
// If we ever are to do it, we should generate into string buffer and put strings inside TypeDef class
override fun getDomainName() = generator.domain.domain()
override fun getTypeDirection() = TypeData.Direction.OUTPUT
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = context.generateNestedObject("Item", description, properties)
}).type)
}
}, generator.generator.naming.outputTypedef, TypeData.Direction.OUTPUT)
}
| apache-2.0 | d9faf573ec0985cf0533df0d43c72cfb | 53.425 | 221 | 0.777676 | 5.283981 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/RecentProjectsWelcomeScreenActionBase.kt | 2 | 1738 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.welcomeScreen.projectActions
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.RecentProjectTreeItem
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.castSafelyTo
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
/**
* @author Konstantin Bulenkov
*/
abstract class RecentProjectsWelcomeScreenActionBase : DumbAwareAction(), LightEditCompatible {
override fun getActionUpdateThread() = ActionUpdateThread.EDT
companion object {
@JvmStatic
fun getDataModel(event: AnActionEvent): DefaultTreeModel? {
val tree = getTree(event)
if (tree != null) {
val model = tree.model
if (model is DefaultTreeModel) {
return model
}
}
return null
}
internal fun getSelectedItem(event: AnActionEvent): RecentProjectTreeItem? {
val tree = getTree(event)
val node = tree?.selectionPath?.lastPathComponent.castSafelyTo<DefaultMutableTreeNode>()
?: return null
return node.userObject as? RecentProjectTreeItem
}
@JvmStatic
fun getTree(event: AnActionEvent): Tree? {
val component = event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
return if (component is Tree) component
else null
}
}
} | apache-2.0 | 279e98480dd2ab5b2bcd30c26c2979d8 | 33.78 | 120 | 0.752589 | 4.951567 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidTaxonomies/src/main/kotlin/com/eden/orchid/taxonomies/TaxonomiesGenerator.kt | 2 | 11601 | package com.eden.orchid.taxonomies
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.ImpliedKey
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.resources.resource.StringResource
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.api.theme.permalinks.PermalinkStrategy
import com.eden.orchid.taxonomies.collections.CollectionArchiveLandingPagesCollection
import com.eden.orchid.taxonomies.collections.TaxonomyLandingPagesCollection
import com.eden.orchid.taxonomies.collections.TaxonomyTermItemsCollection
import com.eden.orchid.taxonomies.collections.TaxonomyTermsLandingPagesCollection
import com.eden.orchid.taxonomies.models.CollectionArchive
import com.eden.orchid.taxonomies.models.TaxonomiesModel
import com.eden.orchid.taxonomies.models.Taxonomy
import com.eden.orchid.taxonomies.models.Term
import com.eden.orchid.taxonomies.pages.CollectionArchivePage
import com.eden.orchid.taxonomies.pages.TaxonomyArchivePage
import com.eden.orchid.taxonomies.pages.TermArchivePage
import com.eden.orchid.taxonomies.utils.getSingleTermValue
import com.eden.orchid.taxonomies.utils.getTermValues
import javax.inject.Inject
@Description("Create custom archives from any logically-related content.", name = "Taxonomies")
class TaxonomiesGenerator
@Inject
constructor(
val permalinkStrategy: PermalinkStrategy
) : OrchidGenerator<TaxonomiesModel>(GENERATOR_KEY, Stage.COLLECTION) {
companion object {
const val GENERATOR_KEY = "taxonomies"
}
@Option
@ImpliedKey(typeKey = "key")
@Description("An array of Taxonomy configurations.")
lateinit var taxonomies: List<Taxonomy>
@Option
@Description("An array of CollectionArchive configurations.")
lateinit var collectionArchives: List<CollectionArchive>
override fun startIndexing(context: OrchidContext): TaxonomiesModel {
val model = TaxonomiesModel(context)
if (taxonomies.isNotEmpty()) {
taxonomies.forEach outerLoop@{ taxonomy ->
model.putTaxonomy(taxonomy)
val enabledGeneratorKeys = context.getGeneratorKeys(taxonomy.includeFrom, taxonomy.excludeFrom)
context.index.getChildIndices(enabledGeneratorKeys)
.flatMap { it.allPages }
.forEach innerLoop@{ page ->
if (page.getSingleTermValue("skipTaxonomy") == "true") {
return@innerLoop
}
val pageTerms = HashSet<String?>()
if (taxonomy.single) {
pageTerms.add(page.getSingleTermValue(taxonomy.key))
} else {
if (taxonomy.singleKey.isNotBlank()) {
pageTerms.add(page.getSingleTermValue(taxonomy.singleKey))
}
pageTerms.addAll(page.getTermValues(taxonomy.key))
}
pageTerms.forEach { term ->
if (term != null) {
model.addPage(taxonomy, term, page)
}
}
}
}
}
if(collectionArchives.isNotEmpty()) {
collectionArchives.forEach outerLoop@{ collectionArchive ->
model.putCollectionArchive(collectionArchive)
}
}
model.onIndexingTermsFinished()
model.allPages = buildAllTaxonomiesPages(context, model)
model.collections = getCollections(model)
return model
}
private fun getCollections(model: TaxonomiesModel): List<OrchidCollection<*>> {
val collections = ArrayList<OrchidCollection<*>>()
// a collection containing landing pages for each Taxonomy and collection archive
collections.add(TaxonomyLandingPagesCollection(this, model))
collections.add(CollectionArchiveLandingPagesCollection(this, model))
model.taxonomies.values.forEach { taxonomy ->
// a collection containing landing pages for each Taxonomy's terms
collections.add(TaxonomyTermsLandingPagesCollection(this, taxonomy))
taxonomy.terms.values.forEach { term ->
// a collection containing the individual items for each term
collections.add(TaxonomyTermItemsCollection(this, taxonomy, term))
}
}
return collections
}
// Archive Page Helpers
//----------------------------------------------------------------------------------------------------------------------
// build all pages for each taxonomy
private fun buildAllTaxonomiesPages(context: OrchidContext, model: TaxonomiesModel): List<OrchidPage> {
val archivePages = ArrayList<OrchidPage>()
model.taxonomies.values.forEach { taxonomy ->
buildTaxonomyLandingPages(context, model, taxonomy)
taxonomy.allTerms.forEach { term ->
archivePages.addAll(buildTermArchivePages(context, model, taxonomy, term))
}
archivePages.addAll(taxonomy.archivePages)
}
model.collectionArchives.values.forEach { collectionArchive ->
buildCollectionArchivePages(context, model, collectionArchive).also {
archivePages.addAll(it)
}
}
return archivePages
}
// build a set of pages that display all the terms in a given taxonomy
private fun buildTaxonomyLandingPages(
context: OrchidContext,
model: TaxonomiesModel,
taxonomy: Taxonomy
): List<OrchidPage> {
val terms = taxonomy.allTerms
val termPages = ArrayList<OrchidPage>()
val pages = Math.ceil((taxonomy.terms.size / taxonomy.pageSize).toDouble()).toInt()
for (i in 0..pages) {
val termList = terms.subList(i * taxonomy.pageSize, Math.min((i + 1) * taxonomy.pageSize, terms.size))
if (termList.isNotEmpty()) {
var title = taxonomy.title
if (i != 0) title += " (Page ${i + 1})"
val pageRef = OrchidReference(context, "taxonomy.html")
pageRef.title = title
val page = TaxonomyArchivePage(StringResource(pageRef, ""), model, taxonomy, i + 1)
permalinkStrategy.applyPermalink(page, page.taxonomy.permalink)
termPages.add(page)
}
}
linkPages(termPages)
taxonomy.archivePages = termPages
return termPages
}
// build a set of pages that display all the items in a given term within a taxonomy
private fun buildTermArchivePages(
context: OrchidContext,
model: TaxonomiesModel,
taxonomy: Taxonomy,
term: Term
): List<OrchidPage> {
val pagesList = term.allPages
val termArchivePages = ArrayList<OrchidPage>()
val pages = Math.ceil((pagesList.size / term.pageSize).toDouble()).toInt()
for (i in 0..pages) {
val termPageList = pagesList.subList(i * term.pageSize, Math.min((i + 1) * term.pageSize, pagesList.size))
if (termPageList.isNotEmpty()) {
var title = term.title
if (i != 0) title += " (Page ${i + 1})"
val pageRef = OrchidReference(context, "term.html")
pageRef.title = title
val page = TermArchivePage(
StringResource(pageRef, ""),
model,
termPageList,
taxonomy,
term,
i + 1
)
permalinkStrategy.applyPermalink(page, page.term.permalink)
page.parent = taxonomy.landingPage
termArchivePages.add(page)
}
}
linkPages(termArchivePages.reversed())
term.archivePages = termArchivePages
if (taxonomy.setAsPageParent) {
for (page in pagesList) {
page.parent = term.landingPage
}
}
return termArchivePages
}
// build a set of pages that display all the items in a given term within a taxonomy
private fun buildCollectionArchivePages(
context: OrchidContext,
model: TaxonomiesModel,
collectionArchive: CollectionArchive
): List<OrchidPage> {
val allArchivePages: List<Any?>
allArchivePages = if(collectionArchive.collectionType.isNotBlank()) {
context.findAll(collectionArchive.collectionType, collectionArchive.collectionId, null)
}
else if(collectionArchive.merge.isNotEmpty()) {
collectionArchive.merge.flatMap {
context.findAll(it.collectionType, it.collectionId, null)
}
}
else {
emptyList()
}
collectionArchive.pages = allArchivePages.filterIsInstance<OrchidPage>()
val pagesList = collectionArchive.allPages
val collectionArchivePages = ArrayList<OrchidPage>()
val pages = Math.ceil((pagesList.size / collectionArchive.pageSize).toDouble()).toInt()
for (i in 0..pages) {
val termPageList = pagesList.subList(i * collectionArchive.pageSize, Math.min((i + 1) * collectionArchive.pageSize, pagesList.size))
if (termPageList.isNotEmpty()) {
var title = collectionArchive.title
if (i != 0) title += " (Page ${i + 1})"
val pageRef = OrchidReference(context, "term.html")
pageRef.title = title
val page = CollectionArchivePage(
StringResource(pageRef, ""),
model,
termPageList,
collectionArchive,
i + 1
)
permalinkStrategy.applyPermalink(page, page.collectionArchive.permalink)
collectionArchivePages.add(page)
}
}
linkPages(collectionArchivePages.reversed())
collectionArchive.archivePages = collectionArchivePages
if (collectionArchive.setAsPageParent) {
for (page in pagesList) {
page.parent = collectionArchive.landingPage
}
}
return collectionArchivePages
}
// Other Utils
//----------------------------------------------------------------------------------------------------------------------
private fun linkPages(pages: List<OrchidPage>) {
var i = 0
for (post in pages) {
if (next(pages, i) != null) {
post.next = next(pages, i)
}
if (previous(pages, i) != null) {
post.previous = previous(pages, i)
}
i++
}
}
private fun previous(pages: List<OrchidPage>, i: Int): OrchidPage? {
if (pages.size > 1) {
if (i != 0) {
return pages[i - 1]
}
}
return null
}
private fun next(pages: List<OrchidPage>, i: Int): OrchidPage? {
if (pages.size > 1) {
if (i < pages.size - 1) {
return pages[i + 1]
}
}
return null
}
}
| mit | 635041b6cc35c61cdebe12f6fb38116a | 35.366771 | 144 | 0.59469 | 4.9747 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/tag/sideeffect/TagSideEffectHandler.kt | 1 | 4063 | package io.ipoli.android.tag.sideeffect
import io.ipoli.android.Constants
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.quest.Quest
import io.ipoli.android.tag.edit.EditTagAction
import io.ipoli.android.tag.edit.EditTagViewState
import io.ipoli.android.tag.list.TagListAction
import io.ipoli.android.tag.show.TagAction
import io.ipoli.android.tag.usecase.*
import kotlinx.coroutines.experimental.channels.Channel
import org.threeten.bp.LocalDate
import space.traversal.kapsule.required
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 4/5/18.
*/
object TagSideEffectHandler : AppSideEffectHandler() {
private val saveTagUseCase by required { saveTagUseCase }
private val questRepository by required { questRepository }
private val undoCompletedQuestUseCase by required { undoCompletedQuestUseCase }
private val createTagItemsUseCase by required { createTagItemsUseCase }
private val favoriteTagUseCase by required { favoriteTagUseCase }
private val unfavoriteTagUseCase by required { unfavoriteTagUseCase }
private val removeTagUseCase by required { removeTagUseCase }
private var tagQuestsChannel: Channel<List<Quest>>? = null
override suspend fun doExecute(action: Action, state: AppState) {
when (action) {
is TagAction.Load ->
listenForChanges(
oldChannel = tagQuestsChannel,
channelCreator = {
tagQuestsChannel = questRepository.listenByTag(action.tagId)
tagQuestsChannel!!
},
onResult = { qs ->
val items =
createTagItemsUseCase.execute(
CreateTagItemsUseCase.Params(
quests = qs,
currentDate = LocalDate.now()
)
)
dispatch(DataLoadedAction.TagItemsChanged(action.tagId, items))
}
)
EditTagAction.Save -> {
val subState = state.stateFor(EditTagViewState::class.java)
saveTagUseCase.execute(
SaveTagUseCase.Params(
id = subState.id,
name = subState.name,
icon = subState.icon,
color = subState.color,
isFavorite = subState.isFavorite
)
)
}
is TagListAction.Favorite ->
favorite(state, action.tag.id)
is TagAction.Favorite ->
favorite(state, action.tagId)
is TagAction.Unfavorite ->
unfavorite(action.tagId)
is TagListAction.Unfavorite ->
unfavorite(action.tag.id)
is TagAction.Remove ->
removeTagUseCase.execute(RemoveTagUseCase.Params(action.tagId))
is TagAction.UndoCompleteQuest ->
undoCompletedQuestUseCase.execute(
action.questId
)
}
}
private fun unfavorite(tagId: String) {
unfavoriteTagUseCase.execute(UnfavoriteTagUseCase.Params.WithTagId(tagId))
}
private fun favorite(
state: AppState,
tagId: String
) {
val tags = state.dataState.tags
if (tags.filter { it.isFavorite }.size >= Constants.MAX_FAVORITE_TAGS) {
dispatch(TagAction.TagCountLimitReached)
} else {
favoriteTagUseCase.execute(FavoriteTagUseCase.Params.WithTagId(tagId))
}
}
override fun canHandle(action: Action) = action is TagAction
|| action === EditTagAction.Save
|| action is TagListAction.Favorite
|| action is TagListAction.Unfavorite
} | gpl-3.0 | cf7dadd1b0c936b009c38dcee30f4d56 | 35.945455 | 87 | 0.597096 | 5.091479 | false | false | false | false |
jk1/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/framework/GuiTestSuiteParam.kt | 3 | 3077 | /*
* 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.framework
import com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher
import com.intellij.testGuiFramework.launcher.ide.Ide
import org.apache.log4j.Logger
import org.junit.runner.Runner
import org.junit.runner.notification.Failure
import org.junit.runner.notification.RunNotifier
import org.junit.runners.Parameterized
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters
import org.junit.runners.parameterized.TestWithParameters
class GuiTestSuiteParam(private val klass: Class<*>) : Parameterized(klass) {
//IDE type to run suite tests with
val myIde: Ide = getIdeFromAnnotation(klass)
var isFirstStart: Boolean = true
val UNDEFINED_FIRST_CLASS: String = "undefined"
val myFirstStartClassName: String by lazy {
val annotation = klass.getAnnotation(FirstStartWith::class.java)
val value = annotation?.value
if (value != null) value.java.canonicalName else UNDEFINED_FIRST_CLASS
}
val LOG: Logger = org.apache.log4j.Logger.getLogger("#com.intellij.testGuiFramework.framework.GuiTestSuiteParam")!!
override fun runChild(runner: Runner, notifier: RunNotifier?) {
try {
//let's start IDE to complete installation, import configs and etc before running tests
if (isFirstStart) firstStart()
val runnerWithParameters = runner as BlockJUnit4ClassRunnerWithParameters
val testNameField = BlockJUnit4ClassRunnerWithParameters::class.java.getDeclaredField("name")
testNameField.isAccessible = true
val testName: String = testNameField.get(runnerWithParameters) as String
val parametersListField = BlockJUnit4ClassRunnerWithParameters::class.java.getDeclaredField("parameters")
parametersListField.isAccessible = true
val parametersList = (parametersListField.get(runnerWithParameters) as Array<*>).toMutableList()
val testWithParams = TestWithParameters(testName, runner.testClass, parametersList)
val guiTestLocalRunnerParam = GuiTestLocalRunnerParam(testWithParams, myIde)
super.runChild(guiTestLocalRunnerParam, notifier)
}
catch (e: Exception) {
LOG.error(e)
notifier?.fireTestFailure(Failure(runner.description, e))
}
}
private fun firstStart() {
if (myFirstStartClassName == UNDEFINED_FIRST_CLASS) return
LOG.info("IDE is configuring for the first time...")
GuiTestLocalLauncher.firstStartIdeLocally(myIde, myFirstStartClassName)
isFirstStart = false
}
} | apache-2.0 | db250fe5979843f014f1b4118166ccc9 | 42.352113 | 117 | 0.770881 | 4.565282 | false | true | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/BaseTemplate.kt | 1 | 4883 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform
import com.demonwav.mcdev.util.MinecraftFileTemplateGroupFactory
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import java.util.Locale
import java.util.Properties
object BaseTemplate {
private val NEW_LINE = "\\n+".toRegex()
fun applyBuildGradleTemplate(project: Project,
file: VirtualFile,
groupId: String,
artifactId: String,
pluginVersion: String,
buildVersion: String): String? {
val buildGradleProps = Properties()
buildGradleProps.setProperty("BUILD_VERSION", buildVersion)
val manager = FileTemplateManager.getInstance(project)
val template = manager.getJ2eeTemplate(MinecraftFileTemplateGroupFactory.BUILD_GRADLE_TEMPLATE)
// This method should be never used for Sponge projects so we just pass false
applyGradlePropertiesTemplate(project, file, groupId, artifactId, pluginVersion, false)
return template.getText(buildGradleProps)
}
fun applyMultiModuleBuildGradleTemplate(project: Project,
file: VirtualFile,
prop: VirtualFile,
groupId: String,
artifactId: String,
pluginVersion: String,
buildVersion: String,
configurations: Map<PlatformType, ProjectConfiguration>) {
val properties = Properties()
properties.setProperty("BUILD_VERSION", buildVersion)
applyGradlePropertiesTemplate(project, prop, groupId, artifactId, pluginVersion, configurations.containsKey(PlatformType.SPONGE))
applyTemplate(project, file, MinecraftFileTemplateGroupFactory.MULTI_MODULE_BUILD_GRADLE_TEMPLATE, properties)
}
fun applyGradlePropertiesTemplate(project: Project,
file: VirtualFile,
groupId: String,
artifactId: String,
pluginVersion: String,
hasSponge: Boolean) {
val gradleProps = Properties()
gradleProps.setProperty("GROUP_ID", groupId)
gradleProps.setProperty("PLUGIN_VERSION", pluginVersion)
if (hasSponge) {
gradleProps.setProperty("PLUGIN_ID", artifactId.toLowerCase(Locale.ENGLISH))
}
// create gradle.properties
applyTemplate(project, file, MinecraftFileTemplateGroupFactory.GRADLE_PROPERTIES_TEMPLATE, gradleProps)
}
fun applySettingsGradleTemplate(project: Project,
file: VirtualFile,
projectName: String,
includes: String) {
val properties = Properties()
properties.setProperty("PROJECT_NAME", projectName)
properties.setProperty("INCLUDES", includes)
applyTemplate(project, file, MinecraftFileTemplateGroupFactory.SETTINGS_GRADLE_TEMPLATE, properties)
}
fun applySubmoduleBuildGradleTemplate(project: Project,
commonProjectName: String): String? {
val properties = Properties()
properties.setProperty("COMMON_PROJECT_NAME", commonProjectName)
val manager = FileTemplateManager.getInstance(project)
val template = manager.getJ2eeTemplate(MinecraftFileTemplateGroupFactory.SUBMODULE_BUILD_GRADLE_TEMPLATE)
return template.getText(properties)
}
fun applyTemplate(project: Project, file: VirtualFile, templateName: String, properties: Properties, trimNewlines: Boolean = false) {
val manager = FileTemplateManager.getInstance(project)
val template = manager.getJ2eeTemplate(templateName)
val allProperties = manager.defaultProperties
allProperties.putAll(properties)
var text = template.getText(allProperties)
if (trimNewlines) {
text = text.replace(NEW_LINE, "\n")
}
VfsUtil.saveText(file, text)
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile != null) {
ReformatCodeProcessor(project, psiFile, null, false).run()
}
}
}
| mit | 9dc6153e59707d86839514d7bc91bd39 | 37.753968 | 137 | 0.613967 | 5.711111 | false | false | false | false |
McMoonLakeDev/MoonLake | Core/src/main/kotlin/com/mcmoonlake/impl/service/ServicePacketListenerImpl.kt | 1 | 12706 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.impl.service
import com.google.common.collect.MapMaker
import com.mcmoonlake.api.*
import com.mcmoonlake.api.event.MoonLakeListener
import com.mcmoonlake.api.packet.*
import com.mcmoonlake.api.reflect.FuzzyReflect
import com.mcmoonlake.api.reflect.accessor.AccessorField
import com.mcmoonlake.api.reflect.accessor.Accessors
import com.mcmoonlake.api.service.ServiceConfig
import com.mcmoonlake.api.service.ServiceException
import com.mcmoonlake.api.service.ServicePacketListener
import com.mcmoonlake.api.utility.MinecraftConverters
import com.mcmoonlake.api.utility.MinecraftPlayerMembers
import com.mcmoonlake.api.utility.MinecraftReflection
import io.netty.channel.*
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.player.PlayerLoginEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.plugin.Plugin
import java.util.*
import java.util.logging.Level
open class ServicePacketListenerImpl : ServiceAbstractCore(), ServicePacketListener {
private var eventListener: MoonLakeListener? = null
override fun onInitialized() {
val listener = object: MoonLakeListener {
@EventHandler(priority = EventPriority.LOWEST)
fun onLogin(event: PlayerLoginEvent)
= try { injectChannelPlayer(event.player) } catch(e: Exception) { /* ignore */ }
@EventHandler(priority = EventPriority.LOWEST)
fun onQuit(event: PlayerQuitEvent)
= channelLookup.remove(event.player.name)
}
eventListener = listener
eventListener?.registerEvent(getMoonLake())
try {
if(!isLateBind()) {
injectChannelServer()
injectOnlinePlayers()
getMoonLake().logger.info("数据包监听器服务初始化工作完成.")
} else {
lateInject()
}
} catch(e: Exception) {
getMoonLake().logger.warning("数据包监听器服务首次初始化失败, 1秒后再次尝试.")
lateInject()
}
}
private fun isLateBind(): Boolean = try {
if(!isSpigotServer)
false
else {
val clazz = Class.forName("org.spigotmc.SpigotConfig")
FuzzyReflect.fromClass(clazz, true).getFieldByName("lateBind").getBoolean(null)
}
} catch(e: Exception) {
false
}
private fun lateInject() {
getMoonLake().runTask {
try {
injectChannelServer()
injectOnlinePlayers()
getMoonLake().logger.info("数据包监听器服务延迟初始化工作完成.")
} catch(e: Exception) {
throw ServiceException("数据包监听器服务延迟初始化工作失败, 服务不可用.", e) // if error
}
}
}
override fun onUnloaded() {
unloadEventListener()
unregisterListenerAll()
unInjectOnlinePlayers()
unInjectChannelServer()
channelLookup.clear()
}
override fun registrable(): Boolean
= getMoonLake().serviceManager.getService(ServiceConfig::class.java).hasPacketListener()
/** api */
private val listeners: MutableList<PacketListener> by lazy {
ArrayList<PacketListener>() }
override fun registerListener(listener: PacketListener): Boolean
= synchronized(listeners, { listeners.add(listener).also { if(it) sortListeners() } })
override fun unregisterListener(listener: PacketListener): Boolean
= synchronized(listeners, { listeners.remove(listener).also { if(it) sortListeners() } })
override fun unregisterListener(plugin: Plugin): Boolean
= synchronized(listeners, { val removeList = listeners.filter { it.plugin == plugin }; listeners.removeAll(removeList).also { if(it) sortListeners() } })
override fun unregisterListenerAll()
= synchronized(listeners, { listeners.clear() })
/** implements */
private fun sortListeners()
= listeners.sortWith(Comparator { o1, o2 -> o2.priority.compareTo(o1.priority) })
private fun sortListenersSync()
= synchronized(listeners, { listeners.sortWith(Comparator { o1, o2 -> o2.priority.compareTo(o1.priority) }) })
private fun unloadEventListener() {
if(eventListener != null) {
eventListener?.unregisterAll()
eventListener = null
}
}
private val serverChannels: MutableList<Channel> by lazy {
ArrayList<Channel>() }
private val networkManagers: MutableList<Any> by lazy {
val mcServer = MinecraftConverters.server.getGeneric(Bukkit.getServer())
val serverConnection = minecraftServerConnection.get(mcServer) ?: throw IllegalStateException("Null of Minecraft Server Connection.")
@Suppress("UNCHECKED_CAST")
Accessors.getAccessorMethod(serverConnection::class.java, List::class.java, true, arrayOf(serverConnection::class.java))
.invoke(serverConnection, serverConnection) as MutableList<Any> }
private val minecraftServerConnection: AccessorField by lazy {
Accessors.getAccessorField(MinecraftReflection.minecraftServerClass, MinecraftReflection.serverConnectionClass, true) }
private fun injectChannelServer() {
val mcServer = MinecraftConverters.server.getGeneric(Bukkit.getServer())
val serverConnection = minecraftServerConnection.get(mcServer) ?: return
for(field in FuzzyReflect.fromClass(serverConnection::class.java, true).getFieldListByType(List::class.java)) {
field.isAccessible = true
val list = field.get(serverConnection) as MutableList<*>
for(item in list) {
if(!ChannelFuture::class.java.isInstance(item))
break
val serverChannel = (item as ChannelFuture).channel()
serverChannels.add(serverChannel)
serverChannel.pipeline().addFirst(channelServerHandler)
}
}
}
private fun unInjectChannelServer() {
serverChannels.forEach {
val pipeline = it.pipeline()
it.eventLoop().execute {
try {
pipeline.remove(channelServerHandler)
} catch(e: Exception) {
//handlerException(e) // ignoreEx
}
}
}
}
private val channelLookup = MapMaker().weakValues().makeMap<String, Channel>()
private fun getChannelPlayer(player: Player): Channel
= channelLookup.getOrPut(player.name) { MinecraftPlayerMembers.CHANNEL.get(player) as Channel }
private fun injectChannelPlayer(player: Player)
{ injectChannel(getChannelPlayer(player))?.player = player }
private fun unInjectChannelPlayer(player: Player) {
val channel = getChannelPlayer(player)
channel.eventLoop().execute {
if(channel.pipeline()[NAME] != null)
channel.pipeline().remove(NAME)
}
}
private fun injectOnlinePlayers()
{ getOnlinePlayers().forEach { injectChannelPlayer(it) } }
private fun unInjectOnlinePlayers()
{ getOnlinePlayers().forEach { unInjectChannelPlayer(it) } }
private fun injectChannel(channel: Channel): ChannelPacketListenerHandler? = try {
var handler = channel.pipeline()[NAME] as ChannelPacketListenerHandler?
if(handler == null) {
handler = ChannelPacketListenerHandler(this)
channel.pipeline().addBefore(HANDLER, NAME, handler)
}
handler
} catch(e: Exception) {
channel.pipeline()[NAME] as ChannelPacketListenerHandler?
}
private val channelEndInitializer = object: ChannelInitializer<Channel>() {
override fun initChannel(channel: Channel) {
try {
synchronized(networkManagers) {
channel.eventLoop().submit { injectChannel(channel) }
}
} catch(e: Exception) {
handlerException(e)
}
}
}
private val channelBeginInitializer = object: ChannelInitializer<Channel>() {
override fun initChannel(channel: Channel) {
channel.pipeline().addLast(channelEndInitializer)
}
}
private val channelServerHandler = object: ChannelInboundHandlerAdapter() {
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
val serverChannel = msg as Channel
serverChannel.pipeline().addFirst(channelBeginInitializer)
ctx.fireChannelRead(msg)
}
}
internal fun handlerException(ex: Exception?) {
ex?.printStackTrace()
}
internal open fun onReceivingAsync(sender: Player?, channel: Channel, packet: Any): Any?
= onExecuteAndFilterPacketAsync(Direction.IN, sender, channel, packet)
internal open fun onSendingAsync(receiver: Player?, channel: Channel, packet: Any): Any?
= onExecuteAndFilterPacketAsync(Direction.OUT, receiver, channel, packet)
private fun onExecuteAndFilterPacketAsync(direction: Direction, player: Player?, channel: Channel, packet: Any): Any? {
val wrapped = Packets.createBufferPacketSafe(packet) ?: return packet
if(wrapped is PacketInLoginStart)
channelLookup[wrapped.profile.name] = channel
val event = PacketEvent(packet, wrapped, channel, player)
synchronized(listeners) {
if(listeners.isNotEmpty()) listeners.forEach {
val consume = if(it is PacketListenerAnyAdapter) {
true
} else {
val filter = if(direction == Direction.IN) it.receivingTypes else it.sendingTypes
filter.find { it.isInstance(wrapped) } != null
}
if(consume) try {
when(direction) {
Direction.IN -> it.onReceiving(event)
else -> it.onSending(event)
}
} catch(e: Exception) {
it.plugin.logger.log(Level.SEVERE, "[MoonLake] 插件 ${it.plugin} 的数据包监听器执行 $direction 时异常.")
it.handlerException(e)
}
}
}
return if(event.isCancelled) null else Packets.createBufferPacket(event.packet) // create new nms packet instance
}
internal enum class Direction {
IN { override fun toString(): String = "接收[onReceiving()]" },
OUT { override fun toString(): String = "发送[onSending()]" },
;
}
internal class ChannelPacketListenerHandler(private val service: ServicePacketListenerImpl) : ChannelDuplexHandler() {
@Volatile
@JvmField
internal var player: Player? = null
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
val channel = ctx.channel()
var packet: Any? = null
try {
packet = service.onReceivingAsync(player, channel, msg)
} catch(e: Exception) {
service.handlerException(e)
}
if(packet != null)
super.channelRead(ctx, packet)
}
override fun write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise) {
val channel = ctx.channel()
var packet: Any? = null
try {
packet = service.onSendingAsync(player, channel, msg)
} catch(e: Exception) {
service.handlerException(e)
}
if(packet != null)
super.write(ctx, packet, promise)
}
}
companion object {
private const val HANDLER = "packet_handler"
private const val NAME = "packet_moonlake"
}
}
| gpl-3.0 | fea3a4f8a5fddad8ac39d65b1bc74013 | 38.495268 | 165 | 0.6373 | 4.784104 | false | false | false | false |
mdanielwork/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsIgnoreFilesChecker.kt | 1 | 1262 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED
import com.intellij.openapi.vcs.VcsListener
import com.intellij.vcsUtil.VcsImplUtil
import com.intellij.vcsUtil.VcsUtil
class VcsIgnoreFilesChecker(private val project: Project) : ProjectComponent {
override fun projectOpened() =
project.messageBus
.connect()
.subscribe(VCS_CONFIGURATION_CHANGED, VcsListener {
generateVcsIgnoreFileIfNeeded(project)
})
private fun generateVcsIgnoreFileIfNeeded(project: Project) =
ApplicationManager.getApplication().executeOnPooledThread {
if (!project.isDisposed) {
val projectFile = project.projectFile ?: return@executeOnPooledThread
val projectVcsRoot = VcsUtil.getVcsRootFor(project, projectFile)
if (projectVcsRoot != null) {
VcsImplUtil.generateIgnoreFileIfNeeded(project, projectVcsRoot)
}
}
}
} | apache-2.0 | cec496709f105d534e3fc811fa4b8d00 | 38.46875 | 140 | 0.768621 | 4.816794 | false | true | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/relationship/internal/RelationshipImportHandler.kt | 1 | 3919 | /*
* 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.relationship.internal
import dagger.Reusable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.stores.internal.StoreUtils.getSyncState
import org.hisp.dhis.android.core.common.State
import org.hisp.dhis.android.core.common.internal.DataStatePropagator
import org.hisp.dhis.android.core.imports.internal.BaseImportSummaryHelper.getReferences
import org.hisp.dhis.android.core.imports.internal.RelationshipImportSummary
import org.hisp.dhis.android.core.relationship.Relationship
import org.hisp.dhis.android.core.relationship.RelationshipCollectionRepository
@Reusable class RelationshipImportHandler @Inject internal constructor(
private val relationshipStore: RelationshipStore,
private val dataStatePropagator: DataStatePropagator,
private val relationshipRepository: RelationshipCollectionRepository
) {
fun handleRelationshipImportSummaries(
importSummaries: List<RelationshipImportSummary?>?,
relationships: List<Relationship>
) {
importSummaries?.filterNotNull()?.forEach { importSummary ->
importSummary.reference()?.let { relationshipUid ->
val relationship = relationshipRepository.withItems().uid(relationshipUid).blockingGet()
val state = getSyncState(importSummary.status())
val handledState =
if (state == State.ERROR || state == State.WARNING) {
State.TO_UPDATE
} else {
state
}
relationshipStore.setSyncStateOrDelete(relationshipUid, handledState)
dataStatePropagator.propagateRelationshipUpdate(relationship)
}
}
processIgnoredRelationships(importSummaries, relationships)
}
private fun processIgnoredRelationships(
importSummaries: List<RelationshipImportSummary?>?,
relationships: List<Relationship>
) {
val processedRelationships = getReferences(importSummaries)
relationships.filterNot { processedRelationships.contains(it.uid()) }.forEach { relationship ->
relationshipStore.setSyncStateOrDelete(relationship.uid()!!, State.TO_UPDATE)
dataStatePropagator.propagateRelationshipUpdate(relationship)
}
}
}
| bsd-3-clause | 3ac4023e7d4ded6fd60dfd44def83eed | 46.216867 | 104 | 0.736412 | 5.011509 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRUpdateBranchAction.kt | 8 | 2804 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.action
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.project.DumbAwareAction
import git4idea.branch.GitBranchUtil
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRBranchesPanel
import org.jetbrains.plugins.github.util.GithubGitHelper
class GHPRUpdateBranchAction : DumbAwareAction(GithubBundle.messagePointer("pull.request.branch.update.action"),
GithubBundle.messagePointer("pull.request.branch.update.action.description"),
null) {
override fun update(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
val repository = e.getData(GHPRActionKeys.GIT_REPOSITORY)
val selection = e.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)
val loadedDetails = selection?.detailsData?.loadedDetails
val headRefName = loadedDetails?.headRefName
val httpUrl = loadedDetails?.headRepository?.url
val sshUrl = loadedDetails?.headRepository?.sshUrl
val isFork = loadedDetails?.headRepository?.isFork ?: false
e.presentation.isEnabled = project != null &&
!project.isDefault &&
selection != null &&
repository != null &&
GithubGitHelper.getInstance().findRemote(repository, httpUrl, sshUrl)?.let { remote ->
GithubGitHelper.getInstance().findLocalBranch(repository, remote, isFork, headRefName) != null
} ?: false
}
override fun actionPerformed(e: AnActionEvent) {
val repository = e.getRequiredData(GHPRActionKeys.GIT_REPOSITORY)
val project = repository.project
val loadedDetails = e.getRequiredData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER).detailsData.loadedDetails
val headRefName = loadedDetails?.headRefName
val httpUrl = loadedDetails?.headRepository?.url
val sshUrl = loadedDetails?.headRepository?.sshUrl
val isFork = loadedDetails?.headRepository?.isFork ?: false
val prRemote = GithubGitHelper.getInstance().findRemote(repository, httpUrl, sshUrl) ?: return
val localBranch = GithubGitHelper.getInstance().findLocalBranch(repository, prRemote, isFork, headRefName) ?: return
GitBranchUtil.updateBranches(project, listOf(repository), listOf(localBranch))
}
}
| apache-2.0 | b9d8bab29addf012261f50815341f2bc | 56.22449 | 140 | 0.714693 | 5.007143 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/markerblocks/providers/ListMarkerProvider.kt | 2 | 2226 | package org.intellij.markdown.parser.markerblocks.providers
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.impl.ListItemMarkerBlock
import org.intellij.markdown.parser.markerblocks.impl.ListMarkerBlock
import java.util.ArrayList
public class ListMarkerProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> {
override fun createMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder,
stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> {
// if (Character.isWhitespace(pos.char)) {
// return emptyList()
// }
// if (pos.offsetInCurrentLine != 0 && !Character.isWhitespace(pos.currentLine[pos.offsetInCurrentLine - 1])) {
// return emptyList()
// }
val currentConstraints = stateInfo.currentConstraints
val nextConstraints = stateInfo.nextConstraints
if (!MarkerBlockProvider.isStartOfLineWithConstraints(pos, currentConstraints)) {
return emptyList()
}
if (nextConstraints != currentConstraints
&& nextConstraints.getLastType() != '>' && nextConstraints.getLastExplicit() == true) {
val result = ArrayList<MarkerBlock>()
if (stateInfo.lastBlock !is ListMarkerBlock) {
result.add(ListMarkerBlock(nextConstraints, productionHolder.mark(), nextConstraints.getLastType()!!))
}
result.add(ListItemMarkerBlock(nextConstraints, productionHolder.mark()))
return result
} else {
return emptyList()
}
}
override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean {
// Actually, list item interrupts a paragraph, but we have MarkdownConstraints for these cases
return false
}
} | apache-2.0 | 55c51b3a982aab9f41aabd78b0514f7e | 44.44898 | 118 | 0.700809 | 5.350962 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/maskapp/view/CalculatorController.kt | 1 | 7323 | package org.secfirst.umbrella.feature.maskapp.view
import android.annotation.SuppressLint
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.tbouron.shakedetector.library.ShakeDetector
import kotlinx.android.synthetic.main.calculator_view.*
import kotlinx.android.synthetic.main.calculator_view.view.*
import org.secfirst.umbrella.R
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.PREF_NAME
import org.secfirst.umbrella.feature.base.view.BaseController
import org.secfirst.umbrella.feature.main.MainActivity
import org.secfirst.umbrella.feature.maskapp.DaggerMaskAppComponent
import org.secfirst.umbrella.feature.maskapp.interactor.MaskAppBaseInteractor
import org.secfirst.umbrella.feature.maskapp.presenter.MaskAppBasePresenter
import org.secfirst.umbrella.misc.setMaskMode
import java.text.DecimalFormat
import javax.inject.Inject
class CalculatorController : BaseController(), MaskAppView {
@Inject
internal lateinit var presenter: MaskAppBasePresenter<MaskAppView, MaskAppBaseInteractor>
companion object {
private const val ADDITION = '+'
private const val SUBTRACTION = '-'
private const val MULTIPLICATION = '*'
private const val DIVISION = '/'
private var CURRENT_ACTION: Char = ' '
private var valueOne = java.lang.Double.NaN
private var valueTwo: Double = 0.toDouble()
private var decimalFormat: DecimalFormat = DecimalFormat("#.##########")
}
override fun onInject() {
DaggerMaskAppComponent.builder()
.application(UmbrellaApplication.instance)
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
val view = inflater.inflate(R.layout.calculator_view, container, false)
init(view)
presenter.onAttach(this)
enableNavigation(false)
mainActivity.hideNavigation()
return view
}
@SuppressLint("SetTextI18n")
private fun init(view: View) {
view.buttonDot.setOnClickListener { editTextCalc.setText("${editTextCalc.text}.") }
view.buttonZero.setOnClickListener { editTextCalc.setText("${editTextCalc.text}0") }
view.buttonOne.setOnClickListener { editTextCalc.setText("${editTextCalc.text}1") }
view.buttonTwo.setOnClickListener { editTextCalc.setText("${editTextCalc.text}2") }
view.buttonThree.setOnClickListener { editTextCalc.setText("${editTextCalc.text}3") }
view.buttonFour.setOnClickListener { editTextCalc.setText("${editTextCalc.text}4") }
view.buttonFive.setOnClickListener { editTextCalc.setText("${editTextCalc.text}5") }
view.buttonSix.setOnClickListener { editTextCalc.setText("${editTextCalc.text}6") }
view.buttonSeven.setOnClickListener { editTextCalc.setText("${editTextCalc.text}7") }
view.buttonEight.setOnClickListener { editTextCalc.setText("${editTextCalc.text}8") }
view.buttonNine.setOnClickListener { editTextCalc.setText("${editTextCalc.text}9") }
view.buttonAdd.setOnClickListener {
computeCalculation()
CURRENT_ACTION = ADDITION
infoTextView.text = "${decimalFormat.format(valueOne)}+"
editTextCalc.text = null
}
view.buttonSubtract.setOnClickListener {
computeCalculation()
CURRENT_ACTION = SUBTRACTION
infoTextView.text = "${decimalFormat.format(valueOne)}-"
editTextCalc.text = null
}
view.buttonMultiply.setOnClickListener {
computeCalculation()
CURRENT_ACTION = MULTIPLICATION
infoTextView.text = "${decimalFormat.format(valueOne)}*"
editTextCalc.text = null
}
view.buttonDivide.setOnClickListener {
computeCalculation()
CURRENT_ACTION = DIVISION
infoTextView.text = "${decimalFormat.format(valueOne)}/"
editTextCalc.text = null
}
view.buttonEqual.setOnClickListener {
computeCalculation()
val formatValueOne = decimalFormat.format(valueOne)
val formatValueTwo = decimalFormat.format(valueTwo)
infoTextView.text = "${infoTextView.text}$formatValueTwo = $formatValueOne"
valueOne = Double.NaN
CURRENT_ACTION = '0'
}
view.buttonClear.setOnClickListener {
if (editTextCalc.text.isNotEmpty()) {
val currentText = editTextCalc.text
editTextCalc.setText(currentText.subSequence(0, currentText.length - 1))
} else {
valueOne = Double.NaN
valueTwo = Double.NaN
editTextCalc.setText("")
infoTextView.text = ""
}
}
}
override fun onAttach(view: View) {
ShakeDetector.create(context) { startShakeDetector() }
ShakeDetector.start()
mainActivity.hideNavigation()
super.onAttach(view)
}
override fun onDestroy() {
ShakeDetector.destroy()
super.onDestroy()
}
private fun setShowMockView() {
mainActivity.getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit().putBoolean(AppPreferenceHelper.EXTRA_SHOW_MOCK_VIEW, false).apply()
}
private fun startShakeDetector() {
activity?.let { safeActivity ->
setMaskMode(safeActivity, false)
setShowMockView()
val intent = Intent(safeActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
safeActivity.finish()
mainActivity.getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit().putBoolean(AppPreferenceHelper.EXTRA_MASK_APP, false).apply()
}
}
override fun handleBack(): Boolean {
mainActivity.finish()
return super.handleBack()
}
override fun isMaskApp(res: Boolean) {
activity?.let { safeActivity ->
val intent = Intent(safeActivity, MainActivity::class.java)
if (res) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
safeActivity.finish()
}
}
}
private fun computeCalculation() {
if (!java.lang.Double.isNaN(valueOne)) {
if (editTextCalc.text.toString().isNotBlank())
valueTwo = editTextCalc.text.toString().toDouble()
editTextCalc.text = null
when (CURRENT_ACTION) {
ADDITION -> valueOne += valueTwo
SUBTRACTION -> valueOne -= valueTwo
MULTIPLICATION -> valueOne *= valueTwo
DIVISION -> valueOne /= valueTwo
}
} else {
if (editTextCalc.text.toString().isNotBlank())
valueOne = editTextCalc.text.toString().toDouble()
}
}
} | gpl-3.0 | 631ccc66440f854a394575a8c3f9f6ec | 39.021858 | 141 | 0.65861 | 4.805118 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/columnviewholder/ViewHolderHeaderSearch.kt | 1 | 1303 | package jp.juggler.subwaytooter.columnviewholder
import android.view.View
import android.widget.TextView
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.column.Column
import jp.juggler.subwaytooter.column.getContentColor
import jp.juggler.subwaytooter.column.getHeaderDesc
import jp.juggler.subwaytooter.util.DecodeOptions
import jp.juggler.subwaytooter.view.MyLinkMovementMethod
import org.jetbrains.anko.textColor
internal class ViewHolderHeaderSearch(
activityArg: ActMain,
viewRoot: View,
) : ViewHolderHeaderBase(activityArg, viewRoot) {
private val tvSearchDesc: TextView
init {
this.tvSearchDesc = viewRoot.findViewById(R.id.tvSearchDesc)
tvSearchDesc.visibility = View.VISIBLE
tvSearchDesc.movementMethod = MyLinkMovementMethod
}
override fun showColor() {
}
override fun bindData(column: Column) {
super.bindData(column)
tvSearchDesc.textColor = column.getContentColor()
tvSearchDesc.text = DecodeOptions(
activity, accessInfo, decodeEmoji = true,
authorDomain = accessInfo
)
.decodeHTML(column.getHeaderDesc())
}
override fun onViewRecycled() {
}
}
| apache-2.0 | 6356a6a891e3417ca0b0b4e1af2c3757 | 27.613636 | 68 | 0.714505 | 4.477663 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/openvr/src/templates/kotlin/openvr/OpenVR.kt | 1 | 4367 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openvr
import org.lwjgl.generator.*
import openvr.templates.*
import java.io.*
private val NativeClass.capabilitiesClass get() = "I$className"
private val NativeClass.capabilitiesField get() = className
private fun PrintWriter.generateCapabilitiesClass(nativeClass: NativeClass) {
println("\n\n${t}public static final class ${nativeClass.capabilitiesClass} {\n")
println("$t${t}public final long")
println(nativeClass.functions
.map(Func::simpleName)
.joinToString(",\n$t$t$t", prefix = "$t$t$t", postfix = ";"))
println("\n$t${t}public ${nativeClass.capabilitiesClass}(long tableAddress) {")
println("$t$t${t}PointerBuffer table = memPointerBuffer(tableAddress, ${nativeClass.functions.count()});")
println(nativeClass.functions
.mapIndexed { i, function -> "${function.simpleName} = table.get($i);" }
.joinToString("\n$t$t$t", prefix = "$t$t$t"))
println("$t$t}")
print("\n$t}")
}
val OPENVR_FNTABLE_BINDING: APIBinding = Generator.register(object : APIBinding(Module.OPENVR, "OpenVR", APICapabilities.JAVA_CAPABILITIES) {
override fun generateFunctionAddress(writer: PrintWriter, function: Func) {
writer.println("$t${t}long $FUNCTION_ADDRESS = OpenVR.${function.nativeClass.capabilitiesField}.${function.simpleName};")
}
init {
javaImport(
"java.nio.*",
"java.util.function.*",
"javax.annotation.Nullable",
"org.lwjgl.*",
"static org.lwjgl.openvr.VR.*",
"static org.lwjgl.system.MemoryStack.*",
"static org.lwjgl.system.MemoryUtil.*"
)
documentation = "The OpenVR function tables."
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println("public final class OpenVR {\n")
// in COpenVRContext order
val interfaces = arrayOf(
VRSystem,
VRChaperone,
VRChaperoneSetup,
VRCompositor,
VRHeadsetView,
VROverlay,
VROverlayView,
VRResources,
VRRenderModels,
VRExtendedDisplay,
VRSettings,
VRApplications,
VRTrackedCamera,
VRScreenshots,
VRDriverManager,
VRInput,
VRIOBuffer,
VRSpatialAnchors,
VRDebug,
VRNotifications
)
println(interfaces.joinToString("\n$t", prefix = t) { "@Nullable public static ${it.capabilitiesClass} ${it.capabilitiesField};" })
// Common constructor
print("""
private static int token;
static {
String libName = Platform.mapLibraryNameBundled("lwjgl_openvr");
Library.loadSystem(System::load, System::loadLibrary, OpenVR.class, "org.lwjgl.openvr", libName);
}
private OpenVR() {
}
static void initialize() {
// intentionally empty to trigger static initializer
}
public static void create(int token) {
OpenVR.token = token;
""")
interfaces.forEach {
print("\n$t$t${it.capabilitiesField} = getGenericInterface(I${it.className}_Version, ${it.capabilitiesClass}::new);")
}
print("""
}
@Nullable
private static <T> T getGenericInterface(String interfaceNameVersion, LongFunction<T> supplier) {
try (MemoryStack stack = stackPush()) {
IntBuffer peError = stack.mallocInt(1);
long ivr = VR_GetGenericInterface("FnTable:" + interfaceNameVersion, peError);
return ivr != NULL && peError.get(0) == EVRInitError_VRInitError_None ? supplier.apply(ivr) : null;
}
}
public static void checkInitToken() {
if (token == 0) {
throw new IllegalStateException("The OpenVR API must be initialized first.");
}
int initToken = VR_GetInitToken();
if (token != initToken) {
destroy();
create(initToken);
}
}
public static void destroy() {
token = 0;
${interfaces.joinToString("\n$t$t") { "${it.capabilitiesField} = null;" }}
}""")
interfaces.forEach {
generateCapabilitiesClass(it)
}
print("\n\n}")
}
}) | bsd-3-clause | daea928b678a4e30541ade7159514933 | 29.978723 | 141 | 0.602244 | 4.402218 | false | false | false | false |
opst-miyatay/LightCalendarView | library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/DayLayout.kt | 1 | 5012 | /*
* Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.recruit_mp.android.lightcalendarview
import android.content.Context
import android.support.v4.view.ViewCompat
import android.text.format.DateUtils
import java.util.*
/**
* 月カレンダー内の日を表示する {@link ViewGroup}
* Created by masayuki-recruit on 8/18/16.
*/
class DayLayout(context: Context, settings: CalendarSettings, var month: Date) : CellLayout(context, settings) {
companion object {
val DEFAULT_WEEKS = 6
val DEFAULT_DAYS_IN_WEEK = WeekDay.values().size
}
override val rowNum: Int
get() = DEFAULT_WEEKS
override val colNum: Int
get() = DEFAULT_DAYS_IN_WEEK
internal var selectedDayView: DayView? = null
internal var onDateSelected: ((date: Date) -> Unit)? = null
private var firstDate: Calendar = CalendarKt.getInstance(settings)
private var dayOfWeekOffset: Int = -1
private val thisYear: Int
private val thisMonth: Int
init {
val cal: Calendar = CalendarKt.getInstance(settings).apply {
time = month
set(Calendar.DAY_OF_MONTH, 1)
}
thisYear = cal[Calendar.YEAR]
thisMonth = cal[Calendar.MONTH]
// update the layout
updateLayout()
// 今日を選択
setSelectedDay(Date())
}
private val observer = Observer { observable, any ->
updateLayout()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
settings.addObserver(observer)
}
override fun onDetachedFromWindow() {
settings.deleteObserver(observer)
super.onDetachedFromWindow()
}
private fun updateLayout() {
if (dayOfWeekOffset != settings.dayOfWeekOffset) {
dayOfWeekOffset = settings.dayOfWeekOffset
// calculate the date of top-left cell
val cal: Calendar = CalendarKt.getInstance(settings).apply {
time = month
set(Calendar.DAY_OF_MONTH, 1)
add(Calendar.DAY_OF_YEAR, (-this[Calendar.DAY_OF_WEEK] + dayOfWeekOffset + 1).let { offset ->
if (offset > 0) (offset - WeekDay.values().size) else offset
})
}
firstDate = cal
// remove all children
removeAllViews()
// populate children
populateViews()
}
}
private fun populateViews() {
val cal = firstDate.clone() as Calendar
// 7 x 6 マスの DayView を追加する
(0..rowNum - 1).forEach {
(0..colNum - 1).forEach {
when (cal[Calendar.MONTH]) {
thisMonth -> {
addView(instantiateDayView(cal.clone() as Calendar))
}
else -> {
if (settings.displayOutside) {
addView(instantiateDayView(cal.clone() as Calendar).setOutside())
} else {
addView(EmptyView(context, settings))
}
}
}
cal.add(Calendar.DAY_OF_YEAR, 1)
}
}
}
private fun instantiateDayView(cal: Calendar): DayView = DayView(context, settings, cal).apply {
setOnClickListener { setSelectedDay(this) }
}
internal fun invalidateDayViews() {
childList.map { it as? DayView }.filterNotNull().forEach {
it.updateState()
ViewCompat.postInvalidateOnAnimation(it)
}
}
/**
* 日付を選択する
* @param date 選択する日
*/
fun setSelectedDay(date: Date) {
setSelectedDay(getDayView(date))
}
private fun setSelectedDay(view: DayView?) {
selectedDayView?.apply {
if (!settings.fixToday || !DateUtils.isToday(selectedDayView?.date!!.time)) {
// 今日の場合は常に丸を表示させる
isSelected = false
updateState()
}
}
selectedDayView = view?.apply {
isSelected = true
updateState()
onDateSelected?.invoke(date)
}
}
/**
* 日付に対応する {@link DayView} を返す
*/
fun getDayView(date: Date): DayView? = childList.getOrNull(date.daysAfter(firstDate.time).toInt()) as? DayView
}
| apache-2.0 | 6b907af57074dd81bb44f1948827a232 | 29.335404 | 114 | 0.582924 | 4.476627 | false | false | false | false |
JetBrains/workshop-jb | src/iv_properties/n32Properties.kt | 7 | 467 | package iv_properties
import util.TODO
import util.doc32
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = todoTask32()
}
fun todoTask32(): Nothing = TODO(
"""
Task 32.
Add a custom setter to 'PropertyExample.propertyWithCounter' so that
the 'counter' property is incremented every time 'propertyWithCounter' is assigned to.
""",
documentation = doc32(),
references = { PropertyExample() }
)
| mit | 7fb8133dc487436e924a0547df3b022e | 23.578947 | 94 | 0.67666 | 4.284404 | false | false | false | false |
jmfayard/skripts | kotlin/dashboard/DashboardApp.kt | 1 | 5267 | package dashboard
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView
import javafx.beans.property.SimpleStringProperty
import javafx.scene.Parent
import javafx.scene.control.TextArea
import org.controlsfx.control.Notifications
import tornadofx.App
import tornadofx.Controller
import tornadofx.ItemViewModel
import tornadofx.Stylesheet
import tornadofx.View
import tornadofx.Workspace
import tornadofx.action
import tornadofx.addClass
import tornadofx.box
import tornadofx.button
import tornadofx.cssclass
import tornadofx.field
import tornadofx.fieldset
import tornadofx.form
import tornadofx.item
import tornadofx.launch
import tornadofx.listview
import tornadofx.menu
import tornadofx.menubar
import tornadofx.observable
import tornadofx.onUserSelect
import tornadofx.px
import tornadofx.required
import tornadofx.textarea
import tornadofx.textfield
import java.io.IOException
import java.io.OutputStream
import java.io.PrintStream
import java.nio.charset.Charset
import java.util.Arrays
fun main(args: Array<String>) {
launch<DashboardApp>(args)
}
class DashboardApp : App(DashboardView::class, DashboardStyles::class)
class MainController : Controller() {
val views = mapOf(
"New Account" to AccountForm(),
"Edit Account" to AccountForm(),
"Auth Token" to CategoryListView(),
"Accounts" to CategoryListView(),
"SmartCards" to CategoryListView()
)
}
class DashboardView : Workspace("Patronus") {
val controller = MainController()
init {
menubar {
menu("Views") {
for ((viewName, viewNode) in controller.views) {
item(viewName) {
action {
workspace.dock(viewNode)
}
}
}
}
with(bottomDrawer) {
item("Logs") {
textarea {
addClass("consola")
val ps = PrintStream(TextAreaOutputStream(this))
System.setErr(ps)
System.setOut(ps)
}
}
}
}
}
}
class CategoryListView : View() {
override val root: Parent = listview<String> {
items = listOf("1", "2", "3").observable()
prefWidth = 150.0
cellFormat { text = it }
onUserSelect {
println(it)
}
}
}
class DashboardStyles : Stylesheet() {
companion object {
val list by cssclass()
}
init {
select(list) {
padding = box(15.px)
vgap = 7.px
hgap = 10.px
}
}
}
data class Account(
val accountId: String = "",
val accountName: String = "",
val active: Boolean = false,
val activeCard: Boolean = false,
val role: String = "",
val firstName: String = "",
val middleNames: String = "",
val lastName: String = "",
val suffix: String = "",
val preferredName: String = "",
val gender: String = "",
val entityName: String = ""
)
class AccountModel : ItemViewModel<Account>(Account()) {
val accountId = bind { SimpleStringProperty(item?.accountId ?: "") }
val phoneNumber = bind { SimpleStringProperty(item?.accountId ?: "") }
val firstName = bind { SimpleStringProperty(item?.accountId ?: "") }
val lastName = bind { SimpleStringProperty(item?.accountId ?: "") }
}
class AccountForm : View("Account") {
val model: AccountModel by inject()
override val root = form {
fieldset("Personal Information", FontAwesomeIconView(FontAwesomeIcon.USER)) {
field("First Name") {
textfield(model.firstName).required()
}
field("Last Name") {
textfield(model.lastName).required()
}
field("Phone Number") {
textfield(model.phoneNumber).required()
}
field("AccountId") {
textfield(model.accountId).required()
}
}
button("Save") {
action {
model.commit {
val customer = model.item
Notifications.create()
.title("Customer saved!")
.text(customer.toString())
.owner(this)
.showInformation()
}
}
// enableWhen(model.valid)
}
}
}
class TextAreaOutputStream(val textArea: TextArea) : OutputStream() {
/**
* This doesn't support multibyte characters streams like utf8
*/
@Throws(IOException::class)
override fun write(b: Int) {
throw UnsupportedOperationException()
}
/**
* Supports multibyte characters by converting the array buffer to String
*/
@Throws(IOException::class)
override fun write(b: ByteArray, off: Int, len: Int) {
// redirects data to the text area
textArea.appendText(String(Arrays.copyOf(b, len), Charset.defaultCharset()))
// scrolls the text area to the end of data
textArea.scrollTop = java.lang.Double.MAX_VALUE
}
}
| apache-2.0 | 588c586fb32afb96c0f95d5ed47df65f | 26.432292 | 85 | 0.591228 | 4.788182 | false | false | false | false |
google/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/updateOldCode/after/gen/SimpleEntityImpl.kt | 1 | 6881 | //new comment
package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SimpleEntityImpl(val dataSource: SimpleEntityData) : SimpleEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val version: Int get() = dataSource.version
override val name: String
get() = dataSource.name
override val isSimple: Boolean get() = dataSource.isSimple
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SimpleEntityData?) : ModifiableWorkspaceEntityBase<SimpleEntity>(), SimpleEntity.Builder {
constructor() : this(SimpleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field SimpleEntity#name should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SimpleEntity
this.entitySource = dataSource.entitySource
this.version = dataSource.version
this.name = dataSource.name
this.isSimple = dataSource.isSimple
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var version: Int
get() = getEntityData().version
set(value) {
checkModificationAllowed()
getEntityData().version = value
changedProperty.add("version")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var isSimple: Boolean
get() = getEntityData().isSimple
set(value) {
checkModificationAllowed()
getEntityData().isSimple = value
changedProperty.add("isSimple")
}
override fun getEntityData(): SimpleEntityData = result ?: super.getEntityData() as SimpleEntityData
override fun getEntityClass(): Class<SimpleEntity> = SimpleEntity::class.java
}
}
class SimpleEntityData : WorkspaceEntityData<SimpleEntity>() {
var version: Int = 0
lateinit var name: String
var isSimple: Boolean = false
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SimpleEntity> {
val modifiable = SimpleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleEntity {
return getCached(snapshot) {
val entity = SimpleEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleEntity(version, name, isSimple, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | bce2c838a1d2a8d3e259e29faa804d1a | 29.856502 | 118 | 0.710217 | 5.244665 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/intentions-k1/src/org/jetbrains/kotlin/idea/intentions/InsertExplicitTypeArgumentsIntention.kt | 2 | 3913 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.inference.CapturedType
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.checker.NewCapturedType
class InsertExplicitTypeArgumentsIntention : SelfTargetingRangeIntention<KtCallExpression>(
KtCallExpression::class.java,
KotlinBundle.lazyMessage("add.explicit.type.arguments")
), LowPriorityAction {
override fun applicabilityRange(element: KtCallExpression): TextRange? =
if (isApplicableTo(element)) element.calleeExpression?.textRange else null
override fun applyTo(element: KtCallExpression, editor: Editor?) = applyTo(element)
companion object {
fun isApplicableTo(element: KtCallElement, bindingContext: BindingContext = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)): Boolean {
if (element.typeArguments.isNotEmpty()) return false
if (element.calleeExpression == null) return false
val resolvedCall = element.getResolvedCall(bindingContext) ?: return false
val typeArgs = resolvedCall.typeArguments
if (resolvedCall is NewResolvedCallImpl<*>) {
val valueParameterTypes = resolvedCall.resultingDescriptor.valueParameters.map { it.type }
if (valueParameterTypes.any { ErrorUtils.containsErrorType(it) }) {
return false
}
}
return typeArgs.isNotEmpty() && typeArgs.values.none { ErrorUtils.containsErrorType(it) || it is CapturedType || it is NewCapturedType }
}
fun applyTo(element: KtCallElement, argumentList: KtTypeArgumentList, shortenReferences: Boolean = true) {
val callee = element.calleeExpression ?: return
val newArgumentList = element.addAfter(argumentList, callee) as KtTypeArgumentList
if (shortenReferences) {
ShortenReferences.DEFAULT.process(newArgumentList)
}
}
fun applyTo(element: KtCallElement, shortenReferences: Boolean = true) {
val argumentList = createTypeArguments(element, element.analyze()) ?: return
applyTo(element, argumentList, shortenReferences)
}
fun createTypeArguments(element: KtCallElement, bindingContext: BindingContext): KtTypeArgumentList? {
val resolvedCall = element.getResolvedCall(bindingContext) ?: return null
val args = resolvedCall.typeArguments
val types = resolvedCall.candidateDescriptor.typeParameters
val text = types.joinToString(", ", "<", ">") {
IdeDescriptorRenderers.SOURCE_CODE.renderType(args.getValue(it))
}
return KtPsiFactory(element).createTypeArguments(text)
}
}
}
| apache-2.0 | c09a51f89a2354c1f7c1649168cb9d28 | 49.818182 | 157 | 0.742142 | 5.331063 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/code-insight/tests/test/org/jetbrains/kotlin/idea/base/codeInsight/test/KotlinNameSuggesterModeTest.kt | 2 | 2569 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.codeInsight.test
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggester.Case
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
class KotlinNameSuggesterModeTest : KotlinLightCodeInsightFixtureTestCase() {
fun testCamel() = test("Foo.Bar.Baz", Case.CAMEL, "baz", "barBaz", "fooBarBaz")
fun testPascal() = test("Foo.Bar.Baz", Case.PASCAL, "Baz", "BarBaz", "FooBarBaz")
fun testSnake() = test("Foo.Bar.Baz", Case.SNAKE, "baz", "bar_baz", "foo_bar_baz")
fun testScreamingSnake() = test("Foo.Bar.Baz", Case.SCREAMING_SNAKE, "BAZ", "BAR_BAZ", "FOO_BAR_BAZ")
fun testKebab() = test("Foo.Bar.Baz", Case.KEBAB, "baz", "bar-baz", "foo-bar-baz")
fun testRootPackage() = test(SpecialNames.ROOT_PACKAGE, Case.PASCAL, "Value")
fun testNoNameProvided() = test(SpecialNames.NO_NAME_PROVIDED, Case.CAMEL, "value")
fun testAnonymous() = test(SpecialNames.ANONYMOUS, Case.SCREAMING_SNAKE, "ANONYMOUS")
fun testSpecialInitCamel() = test(SpecialNames.INIT, Case.CAMEL, "init")
fun testSpecialInitPascal() = test(SpecialNames.INIT, Case.PASCAL, "Init")
fun testKeywordInit() = test("init", Case.CAMEL, "init")
fun testKeywordClassCamel() = test("class", Case.CAMEL, "klass", "clazz")
fun testKeywordClassPascal() = test("class", Case.PASCAL, "Class")
fun testKeywordPackageCamel() = test("package", Case.CAMEL, "pkg")
fun testKeywordPackagePascal() = test("package", Case.PASCAL, "Package")
fun testKeywordWhenCamel() = test("when", Case.CAMEL, "`when`")
fun testKeywordWhenPascal() = test("when", Case.PASCAL, "When")
private fun test(name: Name, case: Case, vararg names: String) {
test(ClassId.topLevel(FqName.topLevel(name)), case, *names)
}
private fun test(classIdString: String, case: Case, vararg names: String) {
test(ClassId.fromString(classIdString), case, *names)
}
private fun test(classId: ClassId, case: Case, vararg names: String) {
val actualNames = KotlinNameSuggester(case).suggestClassNames(classId).toList().sorted()
TestCase.assertEquals(names.sorted(), actualNames)
}
} | apache-2.0 | b292ec21377c1d71caeb8b22d4f0f566 | 54.869565 | 120 | 0.723628 | 3.633663 | false | true | false | false |
google/iosched | shared/src/main/java/com/google/samples/apps/iosched/shared/domain/speakers/LoadSpeakerSessionsUseCase.kt | 3 | 2244 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.speakers
import com.google.samples.apps.iosched.model.SessionId
import com.google.samples.apps.iosched.model.Speaker
import com.google.samples.apps.iosched.model.SpeakerId
import com.google.samples.apps.iosched.shared.data.ConferenceDataRepository
import com.google.samples.apps.iosched.shared.di.IoDispatcher
import com.google.samples.apps.iosched.shared.domain.UseCase
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
/**
* Loads a [Speaker] and the IDs of any [com.google.samples.apps.iosched.model.Session]s
* they are speaking in.
*/
open class LoadSpeakerUseCase @Inject constructor(
private val conferenceDataRepository: ConferenceDataRepository,
@IoDispatcher dispatcher: CoroutineDispatcher
) : UseCase<SpeakerId, LoadSpeakerUseCaseResult>(dispatcher) {
override suspend fun execute(parameters: SpeakerId): LoadSpeakerUseCaseResult {
val speaker = conferenceDataRepository.getOfflineConferenceData().speakers
.firstOrNull { it.id == parameters }
?: throw SpeakerNotFoundException("No speaker found with id $parameters")
val sessionIds = conferenceDataRepository.getOfflineConferenceData().sessions
.filter {
it.speakers.find { speaker -> speaker.id == parameters } != null
}
.map { it.id }
.toSet()
return LoadSpeakerUseCaseResult(speaker, sessionIds)
}
}
data class LoadSpeakerUseCaseResult(
val speaker: Speaker,
val sessionIds: Set<SessionId>
)
class SpeakerNotFoundException(message: String) : Throwable(message)
| apache-2.0 | 870ca38de460fda6c35ec4fc305dfe47 | 39.071429 | 88 | 0.746435 | 4.461233 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.