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
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/editor/SkinCompletionContributor.kt
1
23905
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.editor import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.BitmapFontFileType import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.* import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.escape import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.getRealClassNamesAsString import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.makeSafe import com.gmail.blueboxware.libgdxplugin.utils.* import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.completion.impl.CamelHumpMatcher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.icons.AllIcons import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.patterns.PlatformPatterns import com.intellij.psi.* import com.intellij.util.PlatformIcons import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtObjectDeclaration import java.util.* import javax.swing.Icon /* * Copyright 2016 Blue Box Ware * * 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. */ class SkinCompletionContributor : CompletionContributor() { init { extend(CompletionType.BASIC, PlatformPatterns.psiElement() .withParent(SkinStringLiteral::class.java) .withSuperParent(2, SkinResource::class.java), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { resourceAliasNameCompletion(parameters, result) } }) extend( CompletionType.BASIC, PlatformPatterns .psiElement() .withParent(SkinStringLiteral::class.java) .withSuperParent(2, SkinResourceName::class.java), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { resourceNameCompletion(parameters, result) } } ) extend( CompletionType.BASIC, PlatformPatterns .psiElement() .withParent(SkinStringLiteral::class.java) .withSuperParent(2, SkinClassName::class.java), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { classNameCompletion(parameters, result) } } ) extend( CompletionType.BASIC, PlatformPatterns .psiElement() .withParent(SkinStringLiteral::class.java) .withSuperParent(2, SkinPropertyName::class.java), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { propertyNameCompletion(parameters, result) } } ) extend( CompletionType.BASIC, PlatformPatterns .psiElement() .withParent(SkinStringLiteral::class.java) .withSuperParent(2, SkinPropertyValue::class.java), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { propertyValueCompletion(parameters, result) } } ) extend( CompletionType.BASIC, PlatformPatterns .psiElement() .withParent(SkinStringLiteral::class.java) .withSuperParent(2, SkinArray::class.java), object : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { propertyValueCompletion(parameters, result) } } ) } override fun beforeCompletion(context: CompletionInitializationContext) { if (context.file is SkinFile) { context.dummyIdentifier = CompletionUtil.DUMMY_IDENTIFIER_TRIMMED } val element = context.file.findElementAt(context.caret.offset) if ((element?.context as? SkinStringLiteral)?.isQuoted == true) { context.replacementOffset = context.replacementOffset - 1 } } private fun resourceAliasNameCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val resource = parameters.position.firstParent<SkinResource>() ?: return val classSpec = resource.classSpecification ?: return val originalClassSpec = parameters.originalPosition?.firstParent<SkinClassSpecification>() if (classSpec.getRealClassNamesAsString().none { it != TINTED_DRAWABLE_CLASS_NAME }) { // Aliases for TintedDrawables are not allowed return } (parameters.originalFile as? SkinFile) ?.getClassSpecifications(classSpec.getRealClassNamesAsString()) ?.forEach { cs -> cs.getResourcesAsList(resource).forEach { res -> if (res.name != resource.name || cs != originalClassSpec) { val icon = res .takeIf { cs.getRealClassNamesAsString().contains(COLOR_CLASS_NAME) } ?.asColor(true) ?.let { createColorIcon(it) } ?: ICON_RESOURCE doAdd( LookupElementBuilder .create(res.name.makeSafe()) .withIcon(icon) .withPresentableText(res.name.escape()), parameters, result ) } } } } private fun resourceNameCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val resource = parameters.position.firstParent<SkinResource>() ?: return val classSpec = resource.classSpecification ?: return val usedResourceNames = (resource.containingFile as? SkinFile) ?.getResources(classSpec.getRealClassNamesAsString()) ?.map { it.name } ?: listOf() if (!usedResourceNames.contains("default")) { doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder.create("default").withBoldness(true), HIGH_PRIORITY ), parameters, result ) } val strings = mutableSetOf<String>() (resource.containingFile as? SkinFile)?.getClassSpecifications()?.forEach { if (it != classSpec) { it.resourceNames.forEach { resourceName -> if (!usedResourceNames.contains(resourceName)) { strings.add(resourceName) } } } } strings.remove("default") strings.forEach { doAdd(LookupElementBuilder.create(it), parameters, result) } } private fun propertyValueCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val stringLiteral = parameters.position.parent as? SkinStringLiteral ?: return val property = stringLiteral.property ?: return val objectType = property.containingObject?.resolveToTypeString() if (objectType == BITMAPFONT_CLASS_NAME) { if (property.name == PROPERTY_NAME_FONT_FILE) { parameters.originalFile.virtualFile?.let { virtualFile -> for (file in virtualFile.getAssociatedFiles()) { VfsUtilCore.getRelativeLocation(file, virtualFile.parent)?.let { relativePath -> val prioritize = file.extension?.lowercase(Locale.getDefault()) == "fnt" || file.fileType == BitmapFontFileType.INSTANCE doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder .create(relativePath.makeSafe()) .withPresentableText(relativePath) .withBoldness(prioritize) .withIcon(file.fileType.icon), if (prioritize) HIGHEST_PRIORITY else MEDIUM_PRIORITY ), parameters, result ) } } } } else if (property.name == PROPERTY_NAME_FONT_MARKUP || property.name == PROPERTY_NAME_FONT_FLIP) { doAdd(LookupElementBuilder.create("true"), parameters, result) doAdd(LookupElementBuilder.create("false"), parameters, result) } return } else if (objectType == FREETYPE_FONT_PARAMETER_CLASS_NAME && property.name == "font") { parameters.originalFile.virtualFile?.let { virtualFile -> for (file in virtualFile.getAssociatedFiles()) { VfsUtilCore.getRelativeLocation(file, virtualFile.parent)?.let { relativePath -> val prioritize = file.extension?.lowercase(Locale.getDefault()) == "ttf" doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder .create(relativePath.makeSafe()) .withPresentableText(relativePath) .withBoldness(prioritize) .withIcon(file.fileType.icon), if (prioritize) HIGHEST_PRIORITY else MEDIUM_PRIORITY ), parameters, result ) } } } } val skinFile = parameters.originalFile as? SkinFile ?: return val elementType = stringLiteral.resolveToType() val elementClass = (elementType as? PsiClassType)?.resolve() val isParentProperty = stringLiteral.property?.name == PROPERTY_NAME_PARENT && parameters.position.project.isLibGDX199() val elementClassName = elementClass?.qualifiedName if (elementClass != null && elementClassName != "java.lang.Boolean") { skinFile.getResources(elementClass, null, stringLiteral, isParentProperty, isParentProperty) .forEach { resource -> val icon = resource.takeIf { elementClassName == COLOR_CLASS_NAME }?.asColor(true) ?.let { createColorIcon(it) } ?: ICON_RESOURCE doAdd(LookupElementBuilder.create(resource.name).withIcon(icon), parameters, result) } if (elementClassName == DRAWABLE_CLASS_NAME) { skinFile.getClassSpecifications(TINTED_DRAWABLE_CLASS_NAME).forEach { classSpec -> classSpec.getResourcesAsList(property).forEach { resource -> doAdd( LookupElementBuilder.create(resource.name).withIcon(ICON_TINTED_DRAWABLE), parameters, result ) } } } else if (elementClass.isEnum) { elementClass.fields.forEach { field -> if (field is PsiEnumConstant) { doAdd(LookupElementBuilder.create(field.name), parameters, result) } } } } else if (elementType == PsiType.BOOLEAN || elementClassName == "java.lang.Boolean") { doAdd(LookupElementBuilder.create("true"), parameters, result) doAdd(LookupElementBuilder.create("false"), parameters, result) } if (elementClassName == DRAWABLE_CLASS_NAME || (objectType == TINTED_DRAWABLE_CLASS_NAME && property.name == PROPERTY_NAME_TINTED_DRAWABLE_NAME) ) { skinFile.virtualFile?.let { virtualFile -> virtualFile.getAssociatedAtlas()?.let { atlas -> atlas.readImageNamesFromAtlas().forEach { doAdd(LookupElementBuilder.create(it).withIcon(ICON_ATLAS), parameters, result) } } } } } private fun propertyNameCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val stringLiteral = parameters.position.parent as? SkinStringLiteral ?: return val property = stringLiteral.property ?: return val containingObject = property.containingObject ?: return val objectType = containingObject.resolveToTypeString() val usedPropertyNames = containingObject.propertyNames if (!usedPropertyNames.contains(PROPERTY_NAME_PARENT) && parameters.position.project.isLibGDX199()) { val important = objectType !in listOf( COLOR_CLASS_NAME, BITMAPFONT_CLASS_NAME, TINTED_DRAWABLE_CLASS_NAME ) doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(PROPERTY_NAME_PARENT).withBoldness(important).withIcon(ICON_PARENT), if (important) HIGH_PRIORITY else 0.0 ), parameters, result ) } if (objectType == COLOR_CLASS_NAME) { if (!usedPropertyNames.contains("hex")) { var addHex = true listOf("r", "g", "b", "a").forEach { if (!usedPropertyNames.contains(it)) { doAdd(LookupElementBuilder.create(it).withIcon(ICON_FIELD), parameters, result) } else { addHex = false } } if (addHex) { doAdd(LookupElementBuilder.create("hex").withIcon(ICON_FIELD), parameters, result) } } } else if (objectType == BITMAPFONT_CLASS_NAME) { listOf( PROPERTY_NAME_FONT_FILE, PROPERTY_NAME_FONT_SCALED_SIZE, PROPERTY_NAME_FONT_FLIP, PROPERTY_NAME_FONT_MARKUP ).forEach { if (!usedPropertyNames.contains(it)) { doAdd(LookupElementBuilder.create(it).withIcon(ICON_FIELD), parameters, result) } } } else { val clazz = containingObject.resolveToClass() ?: return for (field: PsiField? in clazz.allFields) { if (field?.hasModifierProperty(PsiModifier.STATIC) == true) continue field?.name?.let { name -> if (!usedPropertyNames.contains(name)) { doAdd(LookupElementBuilder.create(field, name).withIcon(ICON_FIELD), parameters, result) } } } } } private fun classNameCompletion(parameters: CompletionParameters, result: CompletionResultSet) { val prefix = result .prefixMatcher .prefix .dropLastWhile { it != '.' } .dropLastWhile { it == '.' } .let { prefix -> if (prefix.firstOrNull() == '"') { prefix.substring(1) } else { prefix } } val project = parameters.position.project val psiFacade = project.psiFacade() val rootPackage = psiFacade.findPackage(prefix) ?: psiFacade.findPackage("") ?: return project.getSkinTag2ClassMap()?.getTags()?.forEach { tag -> doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(tag) .withIcon(ICON_TAG) .withBoldness(true), HIGHEST_PRIORITY ), parameters, result ) } for (subpackage in rootPackage.subPackages) { val priority = packagePriority(subpackage.qualifiedName) doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(subpackage, subpackage.qualifiedName) .withIcon(ICON_PACKAGE) .withBoldness(priority > 0.0), priority ), parameters, result ) } val dummyText = parameters.position.text val currentPackage = psiFacade.findPackage(prefix) val scope = project.allScope() if (currentPackage == null || currentPackage.name == null) { val prefixMatcher = CamelHumpMatcher( result .prefixMatcher .prefix .substring(if (dummyText.firstOrNull() == '"') 1 else 0) .takeWhile { it != '.' && it != '$' } ) AllClassesGetter.processJavaClasses(prefixMatcher, project, scope) { psiClass -> if ((psiClass.containingClass == null && (psiClass !is KtLightClass || psiClass.kotlinOrigin !is KtObjectDeclaration) ) ) { for (innerClass in psiClass.findAllStaticInnerClasses()) { if (!innerClass.isAnnotationType && !innerClass.isInterface && !innerClass.hasModifierProperty(PsiModifier.ABSTRACT) ) { val fqName = DollarClassName(innerClass) val priority = classPriority(fqName.dollarName) doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(psiClass, fqName.dollarName) .withPresentableText(fqName.dollarName) .withLookupString(StringUtil.getShortName(fqName.dollarName)) .withLookupString(fqName.plainName) .withIcon(ICON_CLASS) .withBoldness(priority > 0.0), priority ), parameters, result ) } } } true } return } for (clazz in currentPackage.getClasses(scope)) { for (innerClass in clazz.findAllStaticInnerClasses()) { if (!innerClass.isAnnotationType && !innerClass.isInterface && !innerClass.hasModifierProperty(PsiModifier.ABSTRACT) ) { val fqName = DollarClassName(innerClass) val priority = classPriority(fqName.dollarName) doAdd( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(innerClass, fqName.dollarName) .withIcon(ICON_CLASS) .withLookupString(fqName.plainName) .withBoldness(priority > 0.0), priority ), parameters, result ) } } } } private fun doAdd(element: LookupElement, parameters: CompletionParameters, result: CompletionResultSet) { val dummyText = parameters.position.text val prefix = if (dummyText.firstOrNull() == '"' && result.prefixMatcher.prefix.isNotEmpty()) { result.prefixMatcher.prefix.substring(1) } else { result.prefixMatcher.prefix } result.withPrefixMatcher(PlainPrefixMatcher(prefix)).addElement(element) } private fun packagePriority(packageName: String): Double { if ("com.badlogic.gdx.scenes.scene2d.ui".contains(packageName) || "com.badlogic.gdx.graphics".contains(packageName) ) { return MEDIUM_PRIORITY } return 0.0 } private fun classPriority(className: String): Double { if (prioritizedClasses.contains(className)) { return MEDIUM_PRIORITY } else if (className.contains("com.badlogic.gdx.scenes.scene2d.ui") && className.endsWith("Style")) { return MEDIUM_PRIORITY } return 0.0 } companion object { const val MEDIUM_PRIORITY = 50.0 const val HIGH_PRIORITY = 75.0 const val HIGHEST_PRIORITY = 100.0 val prioritizedClasses = listOf( "com.badlogic.gdx.scenes.scene2d.ui.Skin\$TintedDrawable", COLOR_CLASS_NAME, BITMAPFONT_CLASS_NAME ) val ICON_TAG: Icon = AllIcons.Ide.Link val ICON_CLASS: Icon = PlatformIcons.CLASS_ICON val ICON_PACKAGE: Icon = PlatformIcons.PACKAGE_ICON val ICON_RESOURCE: Icon = AllIcons.Nodes.KeymapOther val ICON_ATLAS: Icon = AllIcons.Nodes.ModuleGroup val ICON_TINTED_DRAWABLE: Icon = AllIcons.Nodes.KeymapOther val ICON_FIELD: Icon = PlatformIcons.FIELD_ICON val ICON_PARENT: Icon = AllIcons.Nodes.UpLevel } }
apache-2.0
fb16b4cf76fdc89aa6587b7a52a4fc9c
38.382208
135
0.535871
5.95689
false
false
false
false
firebase/quickstart-android
perf/app/src/main/java/com/google/firebase/quickstart/perfmon/kotlin/MainActivity.kt
1
7848
package com.google.firebase.quickstart.perfmon.kotlin import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.os.Bundle import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.widget.Toast import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.TaskCompletionSource import com.google.firebase.ktx.Firebase import com.google.firebase.perf.ktx.performance import com.google.firebase.perf.metrics.Trace import com.google.firebase.quickstart.perfmon.R import com.google.firebase.quickstart.perfmon.databinding.ActivityMainBinding import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.util.Random import java.util.concurrent.CountDownLatch class MainActivity : AppCompatActivity() { private lateinit var trace: Trace private val numStartupTasks = CountDownLatch(2) private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.button.setOnClickListener { // write 40 chars of random text to file val contentFile = File(this.filesDir, CONTENT_FILE) writeStringToFile(contentFile.absolutePath, "${getRandomString(40)}\n") .addOnCompleteListener { task -> if (!task.isSuccessful) { Log.e(TAG, "Unable to write to file", task.exception) return@addOnCompleteListener } loadFileFromDisk() } } // Begin tracing app startup tasks. trace = Firebase.performance.newTrace(STARTUP_TRACE_NAME) Log.d(TAG, "Starting trace") trace.start() loadImageFromWeb() // Increment the counter of number of requests sent in the trace. Log.d(TAG, "Incrementing number of requests counter in trace") trace.incrementMetric(REQUESTS_COUNTER_NAME, 1) loadFileFromDisk() // Wait for app startup tasks to complete asynchronously and stop the trace. Thread(Runnable { try { numStartupTasks.await() } catch (e: InterruptedException) { Log.e(TAG, "Unable to wait for startup task completion.") } finally { Log.d(TAG, "Stopping trace") trace.stop() runOnUiThread { Toast.makeText(this, "Trace completed", Toast.LENGTH_SHORT).show() } } }).start() } private fun loadImageFromWeb() { Glide.with(this).load(IMAGE_URL) .placeholder(ColorDrawable(ContextCompat.getColor(this, R.color.colorAccent))) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { numStartupTasks.countDown() // Signal end of image load task. return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { numStartupTasks.countDown() // Signal end of image load task. return false } }).into(binding.headerIcon) } private fun writeStringToFile(filename: String, content: String): Task<Void> { val taskCompletionSource = TaskCompletionSource<Void>() lifecycleScope.launch { withContext(Dispatchers.IO) { val fos = FileOutputStream(filename, true) fos.write(content.toByteArray()) fos.close() taskCompletionSource.setResult(null) } } return taskCompletionSource.task } private fun loadStringFromFile(): Task<String> { val taskCompletionSource = TaskCompletionSource<String>() lifecycleScope.launch { withContext(Dispatchers.IO) { val contentFile = File(filesDir, CONTENT_FILE) if (contentFile.createNewFile()) { // Content file exist did not exist in internal storage and new file was created. // Copy in the default content. val `is`: InputStream = assets.open(DEFAULT_CONTENT_FILE) val size = `is`.available() val buffer = ByteArray(size) `is`.read(buffer) `is`.close() val fos = FileOutputStream(contentFile) fos.write(buffer) fos.close() } val fis = FileInputStream(contentFile) val content = ByteArray(contentFile.length().toInt()) fis.read(content) taskCompletionSource.setResult(String(content)) } } return taskCompletionSource.task } private fun loadFileFromDisk() { loadStringFromFile() .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.e(TAG, "Couldn't read text file.") Toast.makeText( this, getString(R.string.text_read_error), Toast.LENGTH_LONG) .show() return@OnCompleteListener } val fileContent = task.result binding.textViewContent.text = task.result // Increment a counter with the file size that was read. Log.d(TAG, "Incrementing file size counter in trace") trace.incrementMetric( FILE_SIZE_COUNTER_NAME, fileContent!!.toByteArray().size.toLong()) numStartupTasks.countDown() }) } private fun getRandomString(length: Int): String { val chars = "abcdefghijklmnopqrstuvwxyz".toCharArray() val sb = StringBuilder() val random = Random() for (i in 0 until length) { val c = chars[random.nextInt(chars.size)] sb.append(c) } return sb.toString() } companion object { private const val TAG = "MainActivity" private const val DEFAULT_CONTENT_FILE = "default_content.txt" private const val CONTENT_FILE = "content.txt" private const val IMAGE_URL = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" private const val STARTUP_TRACE_NAME = "startup_trace" private const val REQUESTS_COUNTER_NAME = "requests sent" private const val FILE_SIZE_COUNTER_NAME = "file size" } }
apache-2.0
56c6856630d5bae267f1cb25a94a3253
38.437186
101
0.589832
5.242485
false
false
false
false
vjache/klips
src/main/java/org/klips/dsl/FacetBuilder.kt
1
1945
package org.klips.dsl import java.util.* /** * This abstract class is a context which support facet * creation operators.This class is not intended to be used directly. */ abstract class FacetBuilder { inner class FacetRefImpl<T : Comparable<T>>(id: String) : Facet.FacetRef<T>(id) private var idClock: Long = 0 private fun newId() = "${idClock++}" /** * Create facet constant. Facet constant wraps particular value. * * @see Facet */ fun <T : Comparable<T>> const(v:T): Facet<T> = Facet.ConstFacet(v) /** * Create named facet reference. Facet reference used to construct * a fact pattern. Several fact patterns form a complex pattern * in which all occurrences of the same reference must be bound to * the same value ([Facet.ConstFacet]). * * @see Facet */ fun <T : Comparable<T>> ref(id: String) : Facet.FacetRef<T> = FacetRefImpl(id) fun intRef() = intRef(newId()) fun intRef(id:String) = FacetRefImpl<Int>(id) fun intRefs(vararg ids: String) = Array(ids.size, { intRef(ids[it]) }) fun const(v : Int) = Facet.IntFacet(v) fun strRef() = strRef(newId()) fun strRef(id:String) = FacetRefImpl<String>(id) fun strRefs(vararg ids: String) = Array(ids.size, { strRef(ids[it]) }) fun const(v : String) = Facet.StringFacet(v) fun floatRef() = floatRef(newId()) fun floatRef(id:String) = FacetRefImpl<Float>(id) fun floatRefs(vararg ids: String) = Array(ids.size, { floatRef(ids[it]) }) fun const(v : Float) = Facet.FloatFacet(v) fun dateRef() = dateRef(newId()) fun dateRef(id:String) = FacetRefImpl<Float>(id) fun dateRefs(vararg ids: String) = Array(ids.size, { dateRef(ids[it]) }) fun const(v : Date) = Facet.DateFacet(v) }
apache-2.0
8e6d274da1bda6260141a82d0c42ab79
36.423077
83
0.592802
3.649156
false
false
false
false
dkhmelenko/Varis-Android
app-v3/src/main/java/com/khmelenko/lab/varis/repodetails/PullRequestsFragment.kt
2
4520
package com.khmelenko.lab.varis.repodetails import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.khmelenko.lab.varis.R import com.khmelenko.lab.varis.network.response.RequestData import com.khmelenko.lab.varis.network.response.Requests import kotlinx.android.synthetic.main.fragment_list_refreshable.list_refreshable_recycler_view import kotlinx.android.synthetic.main.fragment_list_refreshable.list_refreshable_swipe_view import kotlinx.android.synthetic.main.fragment_list_refreshable.progressbar import kotlinx.android.synthetic.main.view_empty.empty_text import java.util.ArrayList /** * Repository pull requests * * @author Dmytro Khmelenko */ class PullRequestsFragment : Fragment() { private lateinit var pullRequestsListAdapter: PullRequestsListAdapter private var requests: Requests? = null private var pullRequests: List<RequestData> = ArrayList() private var listener: PullRequestsListener? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_list_refreshable, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) list_refreshable_recycler_view.setHasFixedSize(true) val layoutManager = LinearLayoutManager(context) list_refreshable_recycler_view.layoutManager = layoutManager pullRequestsListAdapter = PullRequestsListAdapter(requests, { position -> val requestData = pullRequests[position] listener?.onPullRequestSelected(requestData.buildId) }) list_refreshable_recycler_view.adapter = pullRequestsListAdapter list_refreshable_swipe_view.setColorSchemeResources(R.color.swipe_refresh_progress) list_refreshable_swipe_view.setOnRefreshListener { listener!!.onReloadPullRequests() } progressbar.visibility = View.VISIBLE } /** * Fetches pull requests */ private fun fetchPullRequests(requests: Requests): List<RequestData> { val pullRequest = ArrayList<RequestData>() for (request in requests.requests) { if (request.isPullRequest && !pullRequest.contains(request)) { pullRequest.add(request) } } return pullRequest } /** * Checks whether data existing or not */ private fun checkIfEmpty() { empty_text.setText(R.string.repo_details_pull_request_empty) if (pullRequests.isEmpty()) { empty_text.visibility = View.VISIBLE } else { empty_text.visibility = View.GONE } } override fun onAttach(context: Context) { super.onAttach(context) try { listener = context as PullRequestsListener? } catch (e: ClassCastException) { throw ClassCastException("$context must implement PullRequestsListener") } } override fun onDetach() { super.onDetach() listener = null } /** * Sets pull request data * * @param requests Pull requests */ fun setPullRequests(requests: Requests?) { list_refreshable_swipe_view.isRefreshing = false progressbar.visibility = View.GONE if (requests != null) { this.requests = requests pullRequests = fetchPullRequests(requests) pullRequestsListAdapter.setRequests(requests, pullRequests) pullRequestsListAdapter.notifyDataSetChanged() } checkIfEmpty() } /** * Interface for communication with this fragment */ interface PullRequestsListener { /** * Handles selection of the pull request * * @param buildId ID of the build of the pull request */ fun onPullRequestSelected(buildId: Long) /** * Handles reload action for pull request */ fun onReloadPullRequests() } companion object { /** * Creates new instance of the fragment * * @return Fragment instance */ fun newInstance(): PullRequestsFragment { return PullRequestsFragment() } } }
apache-2.0
56c897a3e4a4e393605de2fda15b8159
30.388889
94
0.670354
5.039019
false
false
false
false
willowtreeapps/assertk
assertk/src/commonTest/kotlin/test/assertk/assertions/NumberTest.kt
1
2233
package test.assertk.assertions import assertk.assertThat import assertk.assertions.* import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails class NumberTest { //region isZero @Test fun isZero_value_zero_passes() { assertThat(0).isZero() } @Test fun isZero_value_non_zero_fails() { val error = assertFails { assertThat(1).isZero() } assertEquals("expected to be 0 but was:<1>", error.message) } //endregion //region isNonZero @Test fun isNonZero_value_non_zero_passes() { assertThat(1).isNotZero() } @Test fun isNonZero_value_zero_fails() { val error = assertFails { assertThat(0).isNotZero() } assertEquals("expected to not be 0", error.message) } //endregion //region isPositive @Test fun isPositive_value_positive_passes() { assertThat(1).isPositive() } @Test fun isPositive_value_zero_fails() { val error = assertFails { assertThat(0).isPositive() } assertEquals("expected to be positive but was:<0>", error.message) } @Test fun isPositive_value_negative_fails() { val error = assertFails { assertThat(-1).isPositive() } assertEquals("expected to be positive but was:<-1>", error.message) } //endregion //region isNegative @Test fun isNegative_value_negative_passes() { assertThat(-1).isNegative() } @Test fun isNegative_value_zero_fails() { val error = assertFails { assertThat(0).isNegative() } assertEquals("expected to be negative but was:<0>", error.message) } @Test fun isNegative_value_positive_fails() { val error = assertFails { assertThat(1).isNegative() } assertEquals("expected to be negative but was:<1>", error.message) } //endregion //region isEqualTo @Test fun isEqualTo_number_literal_is_inferred_based_on_type() { assertThat(1.toByte()).isEqualTo(1) assertThat(1.toShort()).isEqualTo(1) assertThat(1).isEqualTo(1) assertThat(1L).isEqualTo(1) } //endregion }
mit
394c76e6c117c58e16d24d0ede6eeca4
25.270588
75
0.608598
4.310811
false
true
false
false
cketti/k-9
app/core/src/main/java/com/fsck/k9/mailstore/AutoExpandFolderBackendFoldersRefreshListener.kt
2
1637
package com.fsck.k9.mailstore import com.fsck.k9.Account import com.fsck.k9.Preferences /** * Update an Account's auto-expand folder after the folder list has been refreshed. */ class AutoExpandFolderBackendFoldersRefreshListener( private val preferences: Preferences, private val account: Account, private val folderRepository: FolderRepository ) : BackendFoldersRefreshListener { private var isFirstSync = false override fun onBeforeFolderListRefresh() { isFirstSync = account.inboxFolderId == null } override fun onAfterFolderListRefresh() { checkAutoExpandFolder() removeImportedAutoExpandFolder() saveAccount() } private fun checkAutoExpandFolder() { account.importedAutoExpandFolder?.let { folderName -> if (folderName.isEmpty()) { account.autoExpandFolderId = null } else { val folderId = folderRepository.getFolderId(account, folderName) account.autoExpandFolderId = folderId } return } account.autoExpandFolderId?.let { autoExpandFolderId -> if (!folderRepository.isFolderPresent(account, autoExpandFolderId)) { account.autoExpandFolderId = null } } if (isFirstSync && account.autoExpandFolderId == null) { account.autoExpandFolderId = account.inboxFolderId } } private fun removeImportedAutoExpandFolder() { account.importedAutoExpandFolder = null } private fun saveAccount() { preferences.saveAccount(account) } }
apache-2.0
cf9f40a017c1eaa69683a4d3c7b9d0ad
28.232143
83
0.6573
5.068111
false
false
false
false
nfrankel/kaadin
kaadin-core/src/main/kotlin/ch/frankel/kaadin/Size.kt
1
1910
/* * Copyright 2016 Nicolas Fränkel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.frankel.kaadin import com.vaadin.server.* fun Sizeable.height(height: String) = setHeight(height) fun Sizeable.height(height: Float, unit: Sizeable.Unit) = setHeight(height, unit) fun Sizeable.height(height: Height) = setHeight(height.size, height.unit) fun Sizeable.heightUndefined() = setHeightUndefined() fun Sizeable.width(width: String) = setWidth(width) fun Sizeable.width(width: Float, unit: Sizeable.Unit) = setWidth(width, unit) fun Sizeable.width(width: Width) = setWidth(width.size, width.unit) fun Sizeable.widthUndefined() = setWidthUndefined() fun Sizeable.size(width: String, height: String) { width(width) height(height) } fun Sizeable.size(width: Float, height: Float, unit: Sizeable.Unit) { width(width, unit) height(height, unit) } fun Sizeable.size(width: Float, widthUnit: Sizeable.Unit, height: Float, heightUnit: Sizeable.Unit) { width(width, widthUnit) height(height, heightUnit) } fun Sizeable.size(width: Width, height: Height) { width(width) height(height) } fun Sizeable.sizeUndefined() = setSizeUndefined() fun Sizeable.sizeFull() = setSizeFull() open class Size(val size: Float, val unit: Sizeable.Unit) class Height(size: Float, unit: Sizeable.Unit) : Size(size, unit) class Width(size: Float, unit: Sizeable.Unit) : Size(size, unit)
apache-2.0
ab1fc6925406a43acb46a48601bc0a22
37.979592
101
0.742797
3.541744
false
false
false
false
ujpv/intellij-rust
src/test/kotlin/org/rust/lang/core/resolve/RustUseResolveTest.kt
1
8888
package org.rust.lang.core.resolve class RustUseResolveTest : RustResolveTestBase() { fun testViewPath() = checkByCode(""" mod foo { use ::bar::hello; //^ } pub mod bar { pub fn hello() { } //X } """) fun testUsePath() = checkByCode(""" fn foo() { } //X mod inner { use foo; fn inner() { foo(); //^ } } """) fun testChildFromParent() = checkByCode(""" mod foo { // This visits `mod foo` twice during resolve use foo::bar::baz; pub mod bar { pub fn baz() {} //X } fn main() { baz(); //^ } } """) fun testPathRename() = checkByCode(""" fn foo() {} //X mod inner { use foo as bar; fn main() { bar(); //^ 3 } } """) fun testDeepRedirection() = checkByCode(""" mod foo { pub fn a() {} //X pub use bar::b as c; pub use bar::d as e; } mod bar { pub use foo::a as b; pub use foo::c as d; } fn main() { foo::e(); //^ 21 } """) fun testRelativeChild() = checkByCode(""" mod a { use self::b::foo; //^ mod b { pub fn foo() {} //X } } """) fun testViewPathGlobIdent() = checkByCode(""" mod foo { use bar::{hello as h}; //^ } pub mod bar { pub fn hello() { } //X } """) fun testViewPathGlobSelf() = checkByCode(""" mod foo { use bar::{self}; //^ 62 } pub mod bar { } //X """) fun testViewPathGlobSelfFn() = checkByCode(""" fn f() {} //X mod foo { // This looks strange, but is allowed by the Rust Language use f::{self}; //^ } """) fun testUseGlobIdent() = checkByCode(""" mod foo { pub fn hello() {} //X } mod bar { use foo::{hello}; fn main() { hello(); //^ } } """) fun testUseGlobSelf() = checkByCode(""" mod foo { pub fn hello() {} //X } mod bar { use foo::{self}; fn main() { foo::hello(); //^ } } """) fun testUseGlobAlias() = checkByCode(""" mod foo { pub fn hello() {} //X } mod bar { use foo::{hello as spam}; fn main() { spam(); //^ } } """) fun testUseGlobRedirection() = checkByCode(""" mod foo { pub fn a() {} //X pub use bar::{b as c, d as e}; } mod bar { pub use foo::{a as b, c as d}; } use foo::e; fn main() { e(); //^ } """) fun testEnumVariant() = checkByCode(""" mod foo { use bar::E::{X}; //^ } mod bar { pub enum E { X //X } } """) fun testSuperPart() = checkByCode(""" // resolve to the whole file //X fn foo() {} mod inner { use super::foo; //^ } """) fun testWildcard() = checkByCode(""" mod a { fn foo() {} //X fn bar() {} } mod b { use a::*; fn main() { foo(); //^ } } """) fun testSuperWildcard() = checkByCode(""" fn foo() {} //X #[cfg(test)] mod tests { use super::*; fn test_foo() { foo(); //^ } } """) fun testTwoWildcards() = checkByCode(""" mod a { pub fn foo() {} } mod b { pub fn bar() {} //X } mod c { use a::*; use b::*; fn main() { bar() //^ } } """) fun testNestedWildcards() = checkByCode(""" mod a { pub fn foo(){} //X } mod b { pub use a::*; } mod c { use b::*; fn main() { foo() //^ } } """) fun testOnlyBraces() = checkByCode(""" struct Spam; //X mod foo { use {Spam}; fn main() { let _: Spam = unimplemented!(); //^ } } """) fun testColonBraces() = checkByCode(""" struct Spam; //X mod foo { use ::{Spam}; fn main() { let _: Spam = unimplemented!(); //^ } } """) fun testLocalUse() = checkByCode(""" mod foo { pub struct Bar; //X } fn main() { use foo::Bar; let _ = Bar; //^ } """) fun testWildcardPriority() = checkByCode(""" mod a { pub struct S; } mod b { pub struct S; //X } mod c { pub struct S; } use a::*; use b::S; use c::*; fn main() { let _ = S; //^ } """) // fun testUseSelfCycle() = checkByCode(""" //X use self; //^ """) fun testImportFromSelf() = checkByCode(""" use self::{foo as bar}; fn foo() {} //X fn main() { bar() } //^ """) fun testNoUse() = checkByCode(""" fn foo() { } mod inner { fn inner() { foo(); //^ unresolved } } """) fun testCycle() = checkByCode(""" // This is a loop: it simultaneously defines and imports `foo`. use foo; use bar::baz; fn main() { foo(); //^ unresolved } """) fun testUseGlobCycle() = checkByCode(""" mod foo { pub use bar::{b as a}; } mod bar { pub use foo::{a as b}; fn main() { b(); //^ unresolved } } """) fun testEmptyGlobList() = checkByCode(""" mod foo { pub fn f() {} } mod inner { use foo::{}; fn main() { foo::f(); //^ unresolved } } """) fun testWildcardCycle() = checkByCode(""" use inner::*; mod inner { use super::*; fn main() { foo() //^ unresolved } } """) fun testStarImportsDoNotLeak() = checkByCode(""" fn foo() {} mod m { use super::*; } fn bar() { m::foo(); //^ unresolved } """) fun testCircularMod() = checkByCode(""" use baz::bar; //^ unresolved // This "self declaration" should not resolve // but it once caused a stack overflow in the resolve. mod circular_mod; """) // This won't actually fail if the resolve is O(N^2) or worse, // but this is a helpful test for debugging! fun testQuadraticBehavior() = checkByCode(""" use self::a::*; use self::b::*; use self::c::*; use self::d::*; const X1: i32 = 0; mod a { pub const X2: i32 = ::X1; } mod b { pub const X3: i32 = ::X1; } mod c { pub const X4: i32 = ::X1; } mod d { pub const X5: i32 = ::X1; //X } const Z: i32 = X5; //^ """) }
mit
c4ace93ec3f7359a9b1dc5e9db02fde2
17.325773
71
0.314469
5.075957
false
true
false
false
nfrankel/kaadin
kaadin-core/src/test/kotlin/ch/frankel/kaadin/datainput/DateFieldTest.kt
1
2316
/* * Copyright 2016 Nicolas Fränkel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.frankel.kaadin.datainput import ch.frankel.kaadin.* import com.vaadin.data.util.* import com.vaadin.ui.* import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test import java.util.* class DateFieldTest { @Test fun `date field should be added to layout`() { val layout = horizontalLayout { dateField() } assertThat(layout.componentCount).isEqualTo(1) val component = layout.getComponent(0) assertThat(component).isNotNull.isInstanceOf(DateField::class.java) } @Test(dependsOnMethods = ["date field should be added to layout"]) fun `date field value can be initialized`() { val date = Date() val layout = horizontalLayout { dateField(value = date) } val component = layout.getComponent(0) as DateField assertThat(component.value).isEqualTo(date) } @Test(dependsOnMethods = ["date field should be added to layout"]) fun `date field value can be initialized via property`() { val date = Date() val property = ObjectProperty(date) val layout = horizontalLayout { dateField(dataSource = property) } val component = layout.getComponent(0) as DateField assertThat(component.value).isEqualTo(date) } @Test(dependsOnMethods = ["date field should be added to layout"]) fun `date field should be configurable`() { val date = Date() val layout = horizontalLayout { dateField { value = date } } val component = layout.getComponent(0) as DateField assertThat(component.value).isEqualTo(date) } }
apache-2.0
4e6bcf116480ece62212b5a34786504e
32.565217
75
0.663499
4.521484
false
true
false
false
MaibornWolff/codecharta
analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/AddedLinesTest.kt
1
2020
package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics import de.maibornwolff.codecharta.importer.gitlogparser.input.Modification import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class AddedLinesTest { private val FILENAME = "filename" @Test fun should_have_initial_value_zero() { // when val metric = AddedLines() // then assertThat(metric.value()).isEqualTo(0L) } @Test fun should_increase_by_single_modification_if_more_additions() { // given val metric = AddedLines() // when metric.registerModification(Modification(FILENAME, 7, 2)) // then assertThat(metric.value()).isEqualTo(5L) } @Test fun should_not_increase_by_single_modification_if_more_deletes() { // given val metric = AddedLines() // when metric.registerModification(Modification(FILENAME, 2, 7)) // then assertThat(metric.value()).isEqualTo(0L) } @Test fun should_increase_by_multiple_modification_if_more_additions() { // given val metric = AddedLines() // when metric.registerModification(Modification(FILENAME, 7, 2)) metric.registerModification(Modification(FILENAME, 0, 2)) metric.registerModification(Modification(FILENAME, 1, 1)) metric.registerModification(Modification(FILENAME, 6, 2)) // then assertThat(metric.value()).isEqualTo(7L) } @Test fun should_not_increase_by_multiple_modification_if_more_deletes() { // given val metric = AddedLines() // when metric.registerModification(Modification(FILENAME, 2, 7)) metric.registerModification(Modification(FILENAME, 2, 0)) metric.registerModification(Modification(FILENAME, 1, 1)) metric.registerModification(Modification(FILENAME, 2, 6)) // then assertThat(metric.value()).isEqualTo(0L) } }
bsd-3-clause
2864874202986dc69ac6b0ec39622645
26.671233
74
0.645545
4.307036
false
true
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/Dailies.kt
1
371
package net.perfectdreams.loritta.cinnamon.pudding.tables import org.jetbrains.exposed.dao.id.LongIdTable object Dailies : LongIdTable() { val receivedById = long("received_by").index() val receivedAt = long("received_at").index() val ip = text("ip").index() val email = text("email").index() val userAgent = text("user_agent") .nullable() }
agpl-3.0
795612bde8cc76a6c49413d8ea5eecbc
30
57
0.681941
3.71
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/widgets/ActionWidgets.kt
1
6854
package com.androidvip.hebf.widgets import android.app.Activity import android.content.Context import android.graphics.Typeface import android.os.Bundle import android.provider.Settings import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.androidvip.hebf.R import com.androidvip.hebf.ui.base.BaseActivity import com.androidvip.hebf.utils.* import com.androidvip.hebf.utils.Utils.dpToPx import com.androidvip.hebf.utils.gb.GameBoosterImpl import com.androidvip.hebf.utils.gb.GameBoosterNutellaImpl import com.androidvip.hebf.utils.vip.VipBatterySaverImpl import com.androidvip.hebf.utils.vip.VipBatterySaverNutellaImpl import com.topjohnwu.superuser.Shell import kotlinx.coroutines.launch import java.lang.ref.WeakReference private fun generateLogView(context: Context) : ViewGroup { val rootView = LinearLayout(context) rootView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) rootView.orientation = LinearLayout.VERTICAL val logHolder = TextView(context) logHolder.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) logHolder.setPadding( dpToPx(context, 16), dpToPx(context, 16), dpToPx(context, 16), dpToPx(context, 16) ) logHolder.id = R.id.log_holder logHolder.setTypeface(Typeface.MONOSPACE, Typeface.NORMAL) rootView.addView(logHolder) return rootView } private inline fun toggleServices(activityRef: WeakReference<Activity>, rootedAction: () -> Unit, unRootedAction: () -> Unit) { val rooted = UserPrefs(activityRef.get()!!).getBoolean(K.PREF.USER_HAS_ROOT, true) if (rooted) { rootedAction() } else { unRootedAction() } activityRef.get()?.finish() } class WidgetFstrim : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(generateLogView(this)) val logHolder = findViewById<TextView>(R.id.log_holder) logHolder.setText(R.string.enabling) lifecycleScope.launch (workerContext) { val result = if (Shell.rootAccess()) { RootUtils.executeWithOutput("busybox fstrim -v /data && busybox fstrim /cache", "", this@WidgetFstrim) } else { "Only for rooted users!" } runSafeOnUiThread { logHolder.text = result } } } } class WidgetBoost : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(generateLogView(this)) lifecycleScope.launch (workerContext) { val toastText = if (Shell.rootAccess()) { RootUtils.executeSync("sync && sysctl -w vm.drop_caches=3") "Cache cleaned" } else { throw NotImplementedError() } runSafeOnUiThread { Toast.makeText(this@WidgetBoost, toastText, Toast.LENGTH_SHORT).show() finish() } } } } class WidgetVipBatterySaver : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extras = intent.extras if (extras != null) { val turnOn = extras.getBoolean("ativar") val settingsUtils = SettingsUtils(applicationContext) val prefs = Prefs(applicationContext) if (turnOn) { Toast.makeText(this, getString(R.string.vip_battery_saver_on), Toast.LENGTH_SHORT).show() toggleServices(WeakReference(this), { lifecycleScope.launch { VipBatterySaverImpl(applicationContext).enable() } }, { prefs.putBoolean(K.PREF.BATTERY_IMPROVE, true) lifecycleScope.launch { VipBatterySaverNutellaImpl(applicationContext).enable() } settingsUtils.changeBrightness(0) settingsUtils.putInt(Settings.System.SCREEN_OFF_TIMEOUT, 6000) //disable game booster lifecycleScope.launch { GameBoosterNutellaImpl(applicationContext).disable() } }) } else { Toast.makeText(this, getString(R.string.vip_battery_saver_off), Toast.LENGTH_SHORT).show() toggleServices(WeakReference(this), { lifecycleScope.launch { VipBatterySaverImpl(applicationContext).disable() } VipPrefs(applicationContext).putBoolean(K.PREF.VIP_SHOULD_STILL_ACTIVATE, false) }, { prefs.putBoolean(K.PREF.BATTERY_IMPROVE, false) settingsUtils.changeBrightness(150) settingsUtils.putInt(Settings.System.SCREEN_OFF_TIMEOUT, 100000) lifecycleScope.launch { VipBatterySaverImpl(applicationContext).disable() } }) } } else { finish() } } } class WidgetGameBooster : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extras = intent.extras if (extras != null) { val turnOn = extras.getBoolean("ativar") if (turnOn) { Toast.makeText(this, "Boosting...", Toast.LENGTH_SHORT).show() toggleServices(WeakReference(this), { lifecycleScope.launch { GameBoosterImpl(applicationContext).enable() } }, { lifecycleScope.launch { GameBoosterNutellaImpl(applicationContext).enable() } }) } else { Toast.makeText(this, "Disabling Game Booster", Toast.LENGTH_SHORT).show() toggleServices(WeakReference(this), { lifecycleScope.launch { GameBoosterImpl(applicationContext).disable() } }, { lifecycleScope.launch { GameBoosterNutellaImpl(applicationContext).disable() } }) } } else { finish() } } }
apache-2.0
765a98bedb91d7bfeb56178f06ff8652
34.512953
127
0.594397
5.024927
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hil/psi/helpers.kt
1
3775
/* * 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.intellij.plugins.hil.psi import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.intellij.plugins.hcl.psi.HCLBlock import org.intellij.plugins.hcl.psi.HCLElement import org.intellij.plugins.hcl.psi.getNameElementUnquoted import org.intellij.plugins.hcl.terraform.config.model.Module import org.intellij.plugins.hcl.terraform.config.model.Variable import org.intellij.plugins.hcl.terraform.config.model.getTerraformModule import org.intellij.plugins.hil.psi.impl.getHCLHost fun getTerraformModule(element: ILExpression): Module? { val host = element.getHCLHost() ?: return null val module = host.getTerraformModule() return module } fun getLocalDefinedVariables(element: ILExpression): List<Variable> { return getTerraformModule(element)?.getAllVariables()?.map { it.first } ?: emptyList() } fun getLocalDefinedLocals(element: ILExpression): List<String> { return getTerraformModule(element)?.getAllLocals()?.map { it.first } ?: emptyList() } fun getProvisionerResource(position: ILExpression): HCLBlock? { val host = position.getHCLHost() ?: return null // For now 'self' allowed only for provisioners inside resources return if (host is HCLElement) getProvisionerResource(host) else null } fun getProvisionerResource(host: HCLElement): HCLBlock? { val provisioner = PsiTreeUtil.getParentOfType(host, HCLBlock::class.java) ?: return null if (provisioner.getNameElementUnquoted(0) == "connection") return getProvisionerResource(provisioner) if (provisioner.getNameElementUnquoted(0) != "provisioner") return null val resource = PsiTreeUtil.getParentOfType(provisioner, HCLBlock::class.java, true) ?: return null if (resource.getNameElementUnquoted(0) != "resource") return null return resource } fun getConnectionResource(host: HCLElement): HCLBlock? { val provisioner = PsiTreeUtil.getParentOfType(host, HCLBlock::class.java) ?: return null if (provisioner.getNameElementUnquoted(0) != "connection") return null val resource = PsiTreeUtil.getParentOfType(provisioner, HCLBlock::class.java, true) ?: return null if (resource.getNameElementUnquoted(0) != "resource") return null return resource } fun getResource(position: ILExpression): HCLBlock? { val host = position.getHCLHost() ?: return null // For now 'self' allowed only for provisioners inside resources val resource = PsiTreeUtil.getParentOfType(host, HCLBlock::class.java, true) ?: return null if (resource.getNameElementUnquoted(0) != "resource") return null return resource } fun getDataSource(position: ILExpression): HCLBlock? { val host = position.getHCLHost() ?: return null val dataSource = PsiTreeUtil.getParentOfType(host, HCLBlock::class.java, true) ?: return null if (dataSource.getNameElementUnquoted(0) != "data") return null return dataSource } fun <T : PsiElement> PsiElement.getNthChild(n: Int, clazz: Class<ILExpression>): T? { var child: PsiElement? = this.firstChild var i: Int = 0 while (child != null) { if (clazz.isInstance(child)) { i++ @Suppress("UNCHECKED_CAST") if (i == n) return child as T? } child = child.nextSibling } return null }
apache-2.0
6acaec4507cf113b16571aa051f2da5d
38.333333
103
0.757351
3.961175
false
false
false
false
NuclearCoder/nuclear-bot
src/nuclearbot/util/ArgumentFormatter.kt
1
4240
package nuclearbot.util import java.util.regex.Matcher /* * Copyright (C) 2017 NuclearCoder * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * String formatter for command arguments. Inspired by java.util.Formatter.<br></br> * <br></br> * NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br> * @author NuclearCoder (contact on the GitHub repo) */ class ArgumentFormatter /** * Constructs an argument formatter with the specified format. * Tokens "$n" or "{$n}" are replaced with their corresponding argument. * The zero-th token is the sender's username. * @param format the format string */ (format: String) { private val formatStringArray = parse(format) private val out = StringBuilder(20) private fun parse(format: String): Array<FormatString> { val matcher = PATTERN_ARG.matcher(format) val list = mutableListOf<FormatString>() var i = 0 while (i < format.length) { if (matcher.find(i)) { // Anything between the start of the string and the beginning // of the format specifier is either fixed text or contains // an invalid format string. if (matcher.start() != i) { // Assume previous characters were fixed text list.add(FixedString(format.substring(i, matcher.start()))) } list.add(FormatSpecifier(matcher)) i = matcher.end() } else { // The rest of the string is fixed text list.add(FixedString(format.substring(i))) break } } return list.toTypedArray() } /** * Returns the formatted string corresponding to the given list of arguments. * @param username the sender's username, token zero * * * @param args the argument array as given by the onCommand method * * * @return the formatted string */ fun format(username: String, args: Array<String>): String? { out.setLength(0) for (formatString in formatStringArray) { val index = formatString.index val arg: String? when (index) { // fixed text -2 -> arg = null // error in index parse -1 -> return null // sender username 0 -> arg = username // regular index else -> { if (index >= args.size) return null arg = args[index] } } formatString.print(arg) } return out.toString() } private interface FormatString { val index: Int fun print(arg: String?) } private inner class FixedString(private val m_str: String) : FormatString { override val index = -2 override fun print(arg: String?) { out.append(m_str) } } private inner class FormatSpecifier(matcher: Matcher) : FormatString { override val index = (matcher.group(1) ?: matcher.group(2)).let { if (it != null) { try { Integer.parseInt(it) } catch (e: NumberFormatException) { -1 } } else { -1 } } override fun print(arg: String?) { out.append(arg) } } companion object { private val PATTERN_ARG = "\\{\\$([0-9]+)}|\\$([0-9]+)".toPattern() } }
agpl-3.0
adb3cca993025c3555c04515cec77b1e
29.285714
84
0.563679
4.628821
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/utils/_Math.kt
2
6460
package ir.iais.utilities.javautils.utils import java.math.BigDecimal val Long.abs: Long get() = Math.abs(this) val Int.abs: Int get() = Math.abs(this) val Double.abs: Double get() = Math.abs(this) val Float.abs: Float get() = Math.abs(this) val Number.BD: BigDecimal get() = BigDecimal("$this") operator fun <T : Number> T.times(number: T): Number = when (this) { is Short -> this * number.toShort() is Int -> this * number.toInt() is Long -> this * number.toLong() is Float -> this * number.toFloat() is Double -> this * number.toDouble() else -> throw IllegalArgumentException("Format of number ${this.javaClass.name} no supported.") } /** From a gist of MichaelRocks/MathExtensions.kt : [https://gist.github.com/MichaelRocks/f8f66230707bcd88a239] **************************/ fun Double.sin(): Double = Math.sin(this) fun Double.cos(): Double = Math.cos(this) fun Double.tan(): Double = Math.tan(this) fun Double.asin(): Double = Math.asin(this) fun Double.acos(): Double = Math.acos(this) fun Double.atan(): Double = Math.atan(this) fun Double.toRadians(): Double = Math.toRadians(this) fun Double.toDegrees(): Double = Math.toDegrees(this) fun Double.exp(): Double = Math.exp(this) fun Double.log(): Double = Math.log(this) fun Double.log10(): Double = Math.log10(this) fun Double.sqrt(): Double = Math.sqrt(this) fun Double.cbrt(): Double = Math.cbrt(this) fun Double.IEEEremainder(divisor: Double): Double = Math.IEEEremainder(this, divisor) fun Double.ceil(): Double = Math.ceil(this) fun Double.floor(): Double = Math.floor(this) fun Double.rint(): Double = Math.rint(this) fun Double.atan2(x: Double): Double = Math.atan2(this, x) fun Double.pow(exp: Double): Double = Math.pow(this, exp) fun Double.round(): Long = Math.round(this) fun Double.abs(): Double = Math.abs(this) fun Double.ulp(): Double = Math.ulp(this) fun Double.signum(): Double = Math.signum(this) fun Double.sinh(): Double = Math.sinh(this) fun Double.cosh(): Double = Math.cosh(this) fun Double.tanh(): Double = Math.tanh(this) fun Double.expm1(): Double = Math.expm1(this) fun Double.log1p(): Double = Math.log1p(this) fun Double.copySign(sign: Double): Double = Math.copySign(this, sign) fun Double.exponent(): Int = Math.getExponent(this) fun Double.next(direction: Double): Double = Math.nextAfter(this, direction) fun Double.nextUp(): Double = Math.nextUp(this) fun Double.scalb(scaleFactor: Int): Double = Math.scalb(this, scaleFactor) fun Double.clamp(min: Double, max: Double): Double = Math.max(min, Math.min(this, max)) fun Float.sin(): Float = FloatMath.sin(this) fun Float.cos(): Float = FloatMath.cos(this) fun Float.tan(): Float = FloatMath.tan(this) fun Float.asin(): Float = FloatMath.asin(this) fun Float.acos(): Float = FloatMath.acos(this) fun Float.atan(): Float = FloatMath.atan(this) fun Float.toRadians(): Float = FloatMath.toRadians(this) fun Float.toDegrees(): Float = FloatMath.toDegrees(this) fun Float.exp(): Float = FloatMath.exp(this) fun Float.log(): Float = FloatMath.log(this) fun Float.log10(): Float = FloatMath.log10(this) fun Float.sqrt(): Float = FloatMath.sqrt(this) fun Float.cbrt(): Float = FloatMath.cbrt(this) fun Float.IEEEremainder(divisor: Float): Float = FloatMath.IEEEremainder(this, divisor) fun Float.ceil(): Float = FloatMath.ceil(this) fun Float.floor(): Float = FloatMath.floor(this) fun Float.rint(): Float = FloatMath.rint(this) fun Float.atan2(x: Float): Float = FloatMath.atan2(this, x) fun Float.pow(exp: Float): Float = FloatMath.pow(this, exp) fun Float.round(): Int = Math.round(this) fun Float.abs(): Float = Math.abs(this) fun Float.ulp(): Float = Math.ulp(this) fun Float.signum(): Float = Math.signum(this) fun Float.sinh(): Float = FloatMath.sinh(this) fun Float.cosh(): Float = FloatMath.cosh(this) fun Float.tanh(): Float = FloatMath.tanh(this) fun Float.expm1(): Float = FloatMath.expm1(this) fun Float.log1p(): Float = FloatMath.log1p(this) fun Float.copySign(sign: Float): Float = Math.copySign(this, sign) fun Float.exponent(): Int = Math.getExponent(this) fun Float.next(direction: Float): Float = FloatMath.nextAfter(this, direction) fun Float.next(direction: Double): Float = Math.nextAfter(this, direction) fun Float.nextUp(): Float = Math.nextUp(this) fun Float.scalb(scaleFactor: Int): Float = Math.scalb(this, scaleFactor) fun Float.clamp(min: Float, max: Float): Float = Math.max(min, Math.min(this, max)) object FloatMath { val PI: Float = Math.PI.toFloat() val E: Float = Math.E.toFloat() fun sin(value: Float): Float = Math.sin(value.toDouble()).toFloat() fun cos(value: Float): Float = Math.cos(value.toDouble()).toFloat() fun tan(value: Float): Float = Math.tan(value.toDouble()).toFloat() fun sqrt(value: Float): Float = Math.sqrt(value.toDouble()).toFloat() fun acos(value: Float): Float = Math.acos(value.toDouble()).toFloat() fun asin(value: Float): Float = Math.asin(value.toDouble()).toFloat() fun atan(value: Float): Float = Math.atan(value.toDouble()).toFloat() fun atan2(x: Float, y: Float): Float = Math.atan2(x.toDouble(), y.toDouble()).toFloat() fun pow(x: Float, y: Float): Float = Math.pow(x.toDouble(), y.toDouble()).toFloat() fun ceil(x: Float): Float = Math.ceil(x.toDouble()).toFloat() fun floor(x: Float): Float = Math.floor(x.toDouble()).toFloat() fun toRadians(angdeg: Float): Float = Math.toRadians(angdeg.toDouble()).toFloat() fun toDegrees(angrad: Float): Float = Math.toDegrees(angrad.toDouble()).toFloat() fun exp(x: Float): Float = Math.exp(x.toDouble()).toFloat() fun log(x: Float): Float = Math.log(x.toDouble()).toFloat() fun log10(x: Float): Float = Math.log10(x.toDouble()).toFloat() fun cbrt(x: Float): Float = Math.cbrt(x.toDouble()).toFloat() fun IEEEremainder(x: Float, y: Float): Float = Math.IEEEremainder(x.toDouble(), y.toDouble()).toFloat() fun rint(x: Float): Float = Math.rint(x.toDouble()).toFloat() fun sinh(x: Float): Float = Math.sinh(x.toDouble()).toFloat() fun cosh(x: Float): Float = Math.cosh(x.toDouble()).toFloat() fun tanh(x: Float): Float = Math.tanh(x.toDouble()).toFloat() fun expm1(x: Float): Float = Math.expm1(x.toDouble()).toFloat() fun log1p(x: Float): Float = Math.log1p(x.toDouble()).toFloat() fun nextAfter(start: Float, direction: Float): Float = Math.nextAfter(start, direction.toDouble()) fun clamp(value: Float, min: Float, max: Float): Float = Math.max(min, Math.min(value, max)) }
gpl-3.0
ef2ecd9da0bfb24d91cfeb040566abf3
51.104839
139
0.698762
3.166667
false
false
false
false
apgv/skotbuvel-portal
src/main/kotlin/no/skotbuvel/portal/membershiptype/MembershipTypeRepository.kt
1
2805
package no.skotbuvel.portal.membershiptype import no.skotbuvel.portal.helper.DbHelper import no.skotbuvel.portal.jooq.Sequences.MEMBERSHIP_TYPE_ID_SEQ import no.skotbuvel.portal.jooq.tables.MembershipType.MEMBERSHIP_TYPE import no.skotbuvel.portal.util.JavaTimeUtil import org.jooq.Record import org.jooq.TransactionalRunnable class MembershipTypeRepository(private val dbHelper: DbHelper) { fun findAll(activeOnly: Boolean): List<MembershipType> { return when { activeOnly -> findAll().filter { it -> it.active } else -> findAll() } } private fun findAll(): List<MembershipType> { return dbHelper.dslContext() .select( MEMBERSHIP_TYPE.ID, MEMBERSHIP_TYPE.ACTIVE, MEMBERSHIP_TYPE.TYPE, MEMBERSHIP_TYPE.YEAR, MEMBERSHIP_TYPE.PRICE, MEMBERSHIP_TYPE.CREATED_BY, MEMBERSHIP_TYPE.CREATED_DATE ) .from(MEMBERSHIP_TYPE) .fetch() .map { toMembershipType(it) } } fun save(membershipTypeRegistration: MembershipTypeRegistration, createdBy: String) { val dslContext = dbHelper.dslContext() dslContext.transaction(TransactionalRunnable { dslContext.insertInto(MEMBERSHIP_TYPE, MEMBERSHIP_TYPE.ID, MEMBERSHIP_TYPE.ORIGINAL_ID, MEMBERSHIP_TYPE.ACTIVE, MEMBERSHIP_TYPE.TYPE, MEMBERSHIP_TYPE.YEAR, MEMBERSHIP_TYPE.PRICE, MEMBERSHIP_TYPE.CREATED_BY, MEMBERSHIP_TYPE.CREATED_DATE ).values( dslContext.nextval(MEMBERSHIP_TYPE_ID_SEQ).toInt(), dslContext.currval(MEMBERSHIP_TYPE_ID_SEQ).toInt(), true, membershipTypeRegistration.type, membershipTypeRegistration.year, membershipTypeRegistration.price, createdBy, JavaTimeUtil.nowEuropeOslo() ) .execute() }) } private fun toMembershipType(record: Record) = MembershipType( id = record[MEMBERSHIP_TYPE.ID], active = record[MEMBERSHIP_TYPE.ACTIVE], type = record[MEMBERSHIP_TYPE.TYPE], year = record[MEMBERSHIP_TYPE.YEAR], price = record[MEMBERSHIP_TYPE.PRICE], createdBy = record[MEMBERSHIP_TYPE.CREATED_BY], createdDate = record[MEMBERSHIP_TYPE.CREATED_DATE].toZonedDateTime() ) }
mit
23baf617764e65ef02abffd59a3efae3
37.972222
89
0.549733
4.878261
false
false
false
false
kotlintest/kotlintest
kotest-extensions/kotest-extensions-allure/src/jvmMain/kotlin/io/kotest/extensions/allure/AllureTestListener.kt
1
4004
package io.kotest.extensions.allure import io.kotest.assertions.log import io.kotest.core.listeners.ProjectListener import io.kotest.core.listeners.TestListener import io.kotest.core.spec.AutoScan import io.kotest.core.test.Description import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.core.test.TestStatus import io.qameta.allure.* import io.qameta.allure.model.Label import io.qameta.allure.model.Status import io.qameta.allure.model.StatusDetails import io.qameta.allure.util.ResultsUtils.* import java.nio.file.Paths import java.util.* import kotlin.reflect.full.findAnnotation fun TestCase.epic(): Label? = this.spec::class.findAnnotation<Epic>()?.let { createEpicLabel(it.value) } fun TestCase.feature(): Label? = this.spec::class.findAnnotation<Feature>()?.let { createFeatureLabel(it.value) } fun TestCase.severity(): Label? = this.spec::class.findAnnotation<Severity>()?.let { createSeverityLabel(it.value) } fun TestCase.story(): Label? = this.spec::class.findAnnotation<Story>()?.let { createStoryLabel(it.value) } fun TestCase.owner(): Label? = this.spec::class.findAnnotation<Owner>()?.let { createOwnerLabel(it.value) } fun TestCase.issue() = spec::class.findAnnotation<Issue>()?.let { createIssueLink(it.value) } fun TestCase.description() = spec::class.findAnnotation<io.qameta.allure.Description>()?.value @AutoScan object AllureTestListener : TestListener, ProjectListener { internal val uuids = mutableMapOf<Description, UUID>() /** * Loads the [AllureLifecycle] object which is used to report test lifecycle events. */ internal fun allure(): AllureLifecycle = try { Allure.getLifecycle() ?: throw IllegalStateException() } catch (t: Throwable) { log("Error getting allure lifecycle", t) t.printStackTrace() throw t } override fun beforeProject() { Paths.get("./allure-results").toFile().deleteRecursively() } private fun safeId(description: Description): String = description.id().replace('/', ' ').replace("[^\\sa-zA-Z0-9]".toRegex(), "") override suspend fun beforeTest(testCase: TestCase) { log("Allure beforeTest $testCase") val uuid = UUID.randomUUID() uuids[testCase.description] = uuid val labels = listOfNotNull( createSuiteLabel(testCase.description.spec().name), createThreadLabel(), createHostLabel(), createLanguageLabel("kotlin"), createFrameworkLabel("kotest"), createPackageLabel(testCase.spec::class.java.`package`.name), testCase.epic(), testCase.story(), testCase.feature(), testCase.severity(), testCase.owner() ) val links = listOfNotNull( testCase.issue() ) val result = io.qameta.allure.model.TestResult() .setFullName(testCase.description.fullName()) .setName(testCase.name) .setUuid(uuid.toString()) .setTestCaseId(safeId(testCase.description)) .setHistoryId(testCase.description.name) .setLabels(labels) .setLinks(links) .setDescription(testCase.description()) allure().scheduleTestCase(result) allure().startTestCase(uuid.toString()) } override suspend fun afterTest(testCase: TestCase, result: TestResult) { log("Allure afterTest $testCase") val uuid = uuids[testCase.description] val status = when (result.status) { // what we call an error, allure calls a failure TestStatus.Error -> Status.BROKEN TestStatus.Failure -> Status.FAILED TestStatus.Ignored -> Status.SKIPPED TestStatus.Success -> Status.PASSED } val details = StatusDetails() details.message = result.error?.message allure().updateTestCase(uuid.toString()) { it.status = status it.statusDetails = details } allure().stopTestCase(uuid.toString()) allure().writeTestCase(uuid.toString()) } }
apache-2.0
9ed2e7a9a970dfd61e282e0cc212ccd1
34.75
116
0.686314
4.132095
false
true
false
false
jaychang0917/SimpleApiClient
library/src/main/java/com/jaychang/sac/util/Utils.kt
1
997
package com.jaychang.sac.util import android.content.Context import android.webkit.MimeTypeMap import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.io.StringWriter internal object Utils { fun toText(context: Context, file: Int): String { val inputStream = context.resources.openRawResource(file) val writer = StringWriter() val buffer = CharArray(1024) inputStream.use { input -> val reader = BufferedReader(InputStreamReader(input, "UTF-8")) var line: Int = -1 while ({ line = reader.read(buffer); line }() != -1) { writer.write(buffer, 0, line) } } return writer.toString() } fun getMimeType(file: File): String { var type: String? = null val extension = MimeTypeMap.getFileExtensionFromUrl(file.path) if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) } println("getMimeType: $type") return type ?: "*/*" } }
apache-2.0
5892b37b17c5f5a8198d64e8203f3761
25.972973
75
0.683049
4.154167
false
false
false
false
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/Crypto.kt
1
3268
package com.mcxiaoke.koi import android.util.Base64 import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.security.SecureRandom /** * @author mcxiaoke * * * @version 1.0 2013.03.16 */ private object Helper { fun getRandomString(): String = SecureRandom().nextLong().toString() fun getRandomBytes(size: Int): ByteArray { val random = SecureRandom() val bytes = ByteArray(size) random.nextBytes(bytes) return bytes } fun getRawBytes(text: String): ByteArray { try { return text.toByteArray(Charsets.UTF_8) } catch (e: UnsupportedEncodingException) { return text.toByteArray() } } fun getString(data: ByteArray): String { try { return String(data, Charsets.UTF_8) } catch (e: UnsupportedEncodingException) { return String(data) } } fun base64Decode(text: String): ByteArray { return Base64.decode(text, Base64.NO_WRAP) } fun base64Encode(data: ByteArray): String { return Base64.encodeToString(data, Base64.NO_WRAP) } } object HASH { private val MD5 = "MD5" private val SHA_1 = "SHA-1" private val SHA_256 = "SHA-256" private val DIGITS_LOWER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') private val DIGITS_UPPER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') fun md5(data: ByteArray): String { return String(encodeHex(md5Bytes(data))) } fun md5(text: String): String { return String(encodeHex(md5Bytes(Helper.getRawBytes(text)))) } fun md5Bytes(data: ByteArray): ByteArray { return getDigest(MD5).digest(data) } fun sha1(data: ByteArray): String { return String(encodeHex(sha1Bytes(data))) } fun sha1(text: String): String { return String(encodeHex(sha1Bytes(Helper.getRawBytes(text)))) } fun sha1Bytes(data: ByteArray): ByteArray { return getDigest(SHA_1).digest(data) } fun sha256(data: ByteArray): String { return String(encodeHex(sha256Bytes(data))) } fun sha256(text: String): String { return String(encodeHex(sha256Bytes(Helper.getRawBytes(text)))) } fun sha256Bytes(data: ByteArray): ByteArray { return getDigest(SHA_256).digest(data) } fun getDigest(algorithm: String): MessageDigest { try { return MessageDigest.getInstance(algorithm) } catch (e: NoSuchAlgorithmException) { throw IllegalArgumentException(e) } } fun encodeHex(data: ByteArray, toLowerCase: Boolean = true): CharArray { return encodeHex(data, if (toLowerCase) DIGITS_LOWER else DIGITS_UPPER) } fun encodeHex(data: ByteArray, toDigits: CharArray): CharArray { val l = data.size val out = CharArray(l shl 1) var i = 0 var j = 0 while (i < l) { out[j++] = toDigits[(240 and data[i].toInt()).ushr(4)] out[j++] = toDigits[15 and data[i].toInt()] i++ } return out } }
apache-2.0
c6f366ee0586d95187655d3308974296
25.786885
122
0.599755
3.822222
false
false
false
false
gprince/kotlin-sandbox
graph-dsl/src/main/kotlin/fr/gprince/kotlin/sandbox/graph/dsl/DGraph.kt
1
4396
package fr.gprince.kotlin.sandbox.graph.dsl import fr.gprince.kotlin.sandbox.graph.dsl.DEdge.Companion.createEdge import fr.gprince.kotlin.sandbox.graph.dsl.Vertex.Companion.createVertex /** * # Empty String */ val String.Companion.EMPTY: String get() = "" /** * # Vertex is the fundamental unit of which graphs are formed * @constructor Private constructor to enforce the use of [createVertex] method * @property name A name for the [Vertex] * @property graph The [DGraph] that holds this [Vertex] */ class Vertex private constructor(val name: String, val graph: DGraph) { val incomingEdges = hashMapOf<String, DEdge>() val outgoingEdges = hashMapOf<String, DEdge>() companion object { /** * # A NULL [Vertex] has empty [String] name and is associated to [DGraph.NULL] */ val NULL = Vertex(String.EMPTY, DGraph.NULL) /** * # Factory that create a new [Vertex] * @param name A name for the Vertex to create * @param graph The graph that hold this [Vertex] */ fun createVertex(name: String, graph: DGraph): Vertex { return Vertex(name, graph) } } infix fun to(other: Vertex): Vertex { val edge = createEdge(DEdge.EDGE_NAME_PATTERN.format(this.name, other.name), this.graph) from this to other graph.edges.put(edge.name, edge) return other } } /** * # A edge connects two vertices named : source and target * @constructor Private constructor to enforce the use of [createEdge] method * @property name A name for the [DEdge] * @property graph The [DGraph] that holds this [DEdge] */ class DEdge protected constructor(val name: String, val graph: DGraph) { private var _source: Vertex? = null val source: Vertex get() = this._source ?: Vertex.NULL private var _target: Vertex? = null val target: Vertex get() = this._target ?: Vertex.NULL companion object { val EDGE_NAME_PATTERN = "%s-To-%s" /** * # Factory that create a new [DEdge] * @param name A name for the [DEdge] to create * @param graph The graph that hold this [DEdge] */ fun createEdge(name: String, graph: DGraph): DEdge { return DEdge(name, graph) } } /** * */ infix fun from(source: Vertex): DEdge { this._source = source source.outgoingEdges.put(this.name, this) return this } infix fun to(target: Vertex): DEdge { this._target = target target.incomingEdges.put(this.name, this) return this } } /** * # A Directed Graph is a triple consisting of a set of vertices connected by edges, where the edges have a direction associated with them. * @constructor Create a new empty [DGraph] * @property name A name for the [DGraph] */ class DGraph(val name: String) { val vertices = hashMapOf<String, Vertex>() val edges = hashMapOf<String, DEdge>() companion object { /** * A null [DGraph] */ val NULL = DGraph(String.EMPTY) /** * # Create a new [DGraph] with the given name and builder function. * @param name A name for the [DGraph] to build * @param build A builder extension function to initialize the new [DGraph], default {} */ fun graph(name: String, build: DGraph.() -> Unit = {}): DGraph { val graph = DGraph(name) graph.build() return graph } } /** * # Build a new [Vertex] with the given name in this [DGraph]. * @param name A name for the [Vertex] to build * @param build A builder extension function to initialize the new [Vertex], default {} */ fun vertex(name: String, build: Vertex.() -> Unit = {}): Vertex { val vertex = createVertex(name, this) vertex.build() vertices.put(name, vertex) return vertex } /** * # Build a new [DEdge] with the given name in this [DGraph]. * @param name A name for the [DEdge] to build * @param build A builder extension function to initialize the new [DEdge], default {} */ fun edge(name: String, build: DEdge.() -> Unit = {}): DEdge { val edge = createEdge(name, this) edge.build() edges.put(name, edge) return edge } }
apache-2.0
f6e54ec38b845d636d04ad5c99c181b2
28.313333
140
0.607825
3.904085
false
false
false
false
askeron/fluentxmlwrapper
src/main/kotlin/de/drbunsen/common/fluentxmlwrapper/FluentXmlWrapper.kt
1
5575
package de.drbunsen.common.fluentxmlwrapper import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.NodeList import org.xml.sax.InputSource import java.io.File import java.io.FileInputStream import java.io.StringReader import java.io.StringWriter import java.util.* import javax.xml.parsers.DocumentBuilderFactory import javax.xml.transform.OutputKeys import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult class FluentXmlWrapper private constructor(private val w3cElement: Element) { fun addElement(name: String): FluentXmlWrapper { val newChild = w3cElement.ownerDocument.createElement(name) w3cElement.appendChild(newChild) return of(newChild) } fun addElementBefore(name: String, referenceElement: FluentXmlWrapper): FluentXmlWrapper { val newChild = w3cElement.ownerDocument.createElement(name) w3cElement.insertBefore(newChild, referenceElement.w3cElement) return of(newChild) } fun getElement(name: String): FluentXmlWrapper = getElementOrNull(name)!! fun getElementOrNull(name: String): FluentXmlWrapper? { val nodeList = w3cElement.getElementsByTagName(name) if (nodeList.length > 0) { val node = nodeList.item(0) return of(node) } return null } fun getElements(name: String): List<FluentXmlWrapper> = getXmlElementWrapperList(w3cElement.getElementsByTagName(name)) fun hasElement(name: String): Boolean = getElementCount(name) > 0 fun removeElement(name: String): FluentXmlWrapper { val nodeList = w3cElement.getElementsByTagName(name) if (nodeList.length > 0) { w3cElement.removeChild(nodeList.item(0)) } return this } fun getElementCount(name: String): Int = w3cElement.getElementsByTagName(name).length fun getAllElements(): List<FluentXmlWrapper> { val nodeList = w3cElement.childNodes return getXmlElementWrapperList(nodeList) } fun hasAttribute(name: String): Boolean = w3cElement.hasAttribute(name) fun getAttribute(name: String): String = w3cElement.getAttribute(name) fun setAttribute(name: String, value: String): FluentXmlWrapper { w3cElement.setAttribute(name, value) return this } fun removeAttribute(name: String): FluentXmlWrapper { w3cElement.removeAttribute(name) return this } fun getName(): String = w3cElement.tagName fun getText(): String = w3cElement.textContent fun setText(value: String): FluentXmlWrapper { w3cElement.textContent = value return this } fun getParentElement(): FluentXmlWrapper = of(w3cElement.parentNode) fun getRootElement(): FluentXmlWrapper = of(w3cElement.ownerDocument.documentElement) fun toXmlWithDefaultUtf8Header(intend: Boolean): String = toXmlWithCustomHeader("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", intend) fun toXmlWithoutHeader(intend: Boolean): String = toXmlWithCustomHeader(null, intend) private fun toXmlWithCustomHeader(header: String?, intend: Boolean): String { val tf = TransformerFactory.newInstance() val transformer = tf.newTransformer() transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") if (intend) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } val writer = StringWriter() if (header != null) { writer.append(header) writer.append("\n") } transformer.transform(DOMSource(w3cElement), StreamResult(writer)) return writer.buffer.toString() } companion object { private fun getXmlElementWrapperList(nodeList: NodeList): List<FluentXmlWrapper> { val result: MutableList<FluentXmlWrapper> = ArrayList() for (i in 0 until nodeList.length) { val newElement = nodeList.item(i) if (newElement.nodeType == Node.ELEMENT_NODE) { result.add(of(newElement)) } } return result } fun of(element: Element): FluentXmlWrapper = FluentXmlWrapper(element) fun of(xmlString: String): FluentXmlWrapper = of(getXmlDocument(xmlString).documentElement) fun of(file: File): FluentXmlWrapper = of(getXmlDocument(file).documentElement) fun of(inputSource: InputSource): FluentXmlWrapper = of(getXmlDocument(inputSource).documentElement) fun ofNewRootElement(rootElementName: String): FluentXmlWrapper { val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() val rootElement = document.createElement(rootElementName) document.appendChild(rootElement) return of(rootElement) } private fun of(node: Node): FluentXmlWrapper { require(node.nodeType == Node.ELEMENT_NODE) { "not an element" } return of(node as Element) } private fun getXmlDocument(xmlString: String): Document = getXmlDocument(InputSource(StringReader(xmlString))) private fun getXmlDocument(file: File): Document = getXmlDocument(InputSource(FileInputStream(file))) private fun getXmlDocument(inputSource: InputSource): Document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputSource) .also { it.documentElement.normalize() } } }
mit
48f1924910455328b8c1e422fab3b0ef
35.927152
138
0.690404
4.506871
false
false
false
false
Nyubis/Pomfshare
app/src/main/kotlin/science/itaintrocket/pomfshare/HostListActivity.kt
1
3030
package science.itaintrocket.pomfshare import android.support.v4.app.DialogFragment import android.content.Intent import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.app.FragmentActivity import android.widget.AdapterView.OnItemClickListener import android.widget.ListAdapter import android.widget.ListView import android.widget.Toast import java.util.* class HostListActivity() : FragmentActivity(), RequestAuthenticationDialog.RequestAuthenticationDialogListener { private val hosts: MutableList<Host> = ArrayList() private lateinit var authManager: AuthManager private var hostRequestingAuthentication: Host? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_hostlist) authManager = AuthManager(PreferenceManager.getDefaultSharedPreferences(applicationContext)) // This should probably be stored in a proper format at some point, but cba now hosts.add(Host("Pomf.cat", "https://pomf.cat/upload.php?output=gyazo", "75MiB", Host.Type.POMF)) hosts.add(Host("SICP", "https://sicp.me/", "25MiB", Host.Type.UGUU, authRequired = true)) hosts.add(Host("Uguu", "https://uguu.se/api.php?d=upload-tool", "100MiB, 24 hours", Host.Type.UGUU)) // If authentication data exists for a host, load it loadHostAuthentications() val listView = findViewById<ListView>(R.id.host_list_view) val adapter: ListAdapter = HostListAdapter(this, hosts) listView.adapter = adapter listView.onItemClickListener = OnItemClickListener { _, _, position, _ -> val selectedHost: Host = hosts[position] if (selectedHost.authRequired == true && authManager.findAuthKey(selectedHost) == null) { hostRequestingAuthentication = selectedHost RequestAuthenticationDialog().show(supportFragmentManager, "fragment_request_authentication") } else { val data = Intent() data.putExtra("Host", hosts[position].toBundle()) setResult(RESULT_OK, data) super.finish() } } } override fun onDialogSubmit(dialog: DialogFragment, text: String?) { if (text != null) { hostRequestingAuthentication?.let { authManager.addAuthKey(it, text) Toast.makeText(applicationContext, "Added authentication key to ${it.name}", Toast.LENGTH_SHORT).show() } } loadHostAuthentications() hostRequestingAuthentication = null } override fun onDialogCancel(dialog: DialogFragment) { hostRequestingAuthentication = null } private fun loadHostAuthentications() { for (host in hosts) { if (host.authRequired == true) { val auth: String? = authManager.findAuthKey(host) auth.let { host.authKey = it } } } } }
gpl-2.0
04a0c8e1e0f22f36c8e0f6a03d60e91e
38.881579
119
0.668317
4.604863
false
false
false
false
AlmasB/EasyIO
src/main/kotlin/com/almasb/easyio/FS.kt
1
7195
package com.almasb.easyio import org.apache.logging.log4j.LogManager import java.io.* import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.util.stream.Collectors /** * A collection of static methods to access IO via IO tasks. * * @author Almas Baimagambetov ([email protected]) */ class FS { companion object { private val log = LogManager.getLogger(FS::class.java) private fun errorIfAbsent(path: Path) { if (!Files.exists(path)) { log.warn ( "Path $path does not exist" ) throw FileNotFoundException("Path $path does not exist") } } /** * Writes data to file, creating required directories. * * @param data data object to save * @param fileName to save as * @return IO task */ @JvmStatic fun writeDataTask(data: Serializable, fileName: String) = voidTaskOf("writeDataTask($fileName)", { val file = Paths.get(fileName) // if file.parent is null we will use current dir, which exists if (file.parent != null && !Files.exists(file.parent)) { log.debug ( "Creating directories to: ${file.parent}" ) Files.createDirectories(file.parent) } ObjectOutputStream(Files.newOutputStream(file)).use { log.debug ( "Writing to: $file" ) it.writeObject(data) } }) /** * Loads data from file into an object. * * @param fileName file to load from * * @return IO task */ @Suppress("UNCHECKED_CAST") @JvmStatic fun <T> readDataTask(fileName: String) = taskOf("readDataTask($fileName)") { val file = Paths.get(fileName) errorIfAbsent(file) ObjectInputStream(Files.newInputStream(file)).use { log.debug ( "Reading from: $file" ) return@taskOf it.readObject() as T } } /** * Loads file names from given directory. * Searches subdirectories if recursive flag is on. * * @param dirName directory name * @param recursive recursive flag * @return IO task */ @JvmStatic fun loadFileNamesTask(dirName: String, recursive: Boolean) = taskOf("loadFileNamesTask($dirName, $recursive)") { val dir = Paths.get(dirName) errorIfAbsent(dir) return@taskOf Files.walk(dir, if (recursive) Int.MAX_VALUE else 1) .filter { Files.isRegularFile(it) } .map { dir.relativize(it).toString().replace("\\", "/") } .collect(Collectors.toList<String>()) } /** * Loads file names from given directory. * Searches subdirectories if recursive flag is on. * Only names from extensions list will be reported. * * @param dirName directory name * @param recursive recursive flag * @param extensions file extensions to include * @return IO task */ @JvmStatic fun loadFileNamesTask(dirName: String, recursive: Boolean, extensions: List<FileExtension>) = taskOf("loadFileNamesTask($dirName, $recursive, $extensions)") { val dir = Paths.get(dirName) errorIfAbsent(dir) return@taskOf Files.walk(dir, if (recursive) Int.MAX_VALUE else 1) .filter { file -> Files.isRegularFile(file) && extensions.filter { "$file".endsWith(it.extension) }.isNotEmpty() } .map { dir.relativize(it).toString().replace("\\", "/") } .collect(Collectors.toList<String>()) } /** * Loads directory names from [dirName]. * Searches subdirectories if [recursive]. * * @param dirName directory name * @param recursive recursive flag * @return IO task */ @JvmStatic fun loadDirectoryNamesTask(dirName: String, recursive: Boolean) = taskOf("loadDirectoryNamesTask($dirName, $recursive)", { val dir = Paths.get(dirName) errorIfAbsent(dir) return@taskOf Files.walk(dir, if (recursive) Int.MAX_VALUE else 1) .filter { Files.isDirectory(it) } .map { dir.relativize(it).toString().replace("\\", "/") } .filter { it.isNotEmpty() } .collect(Collectors.toList<String>()) }) /** * Loads (deserializes) last modified file from given [dirName] directory. * Searches subdirectories if [recursive]. * * @param dirName directory name * @param recursive recursive flag * @return IO task */ @JvmStatic fun <T> loadLastModifiedFileTask(dirName: String, recursive: Boolean) = taskOf("loadLastModifiedFileTask($dirName, $recursive)") { val dir = Paths.get(dirName) errorIfAbsent(dir) return@taskOf Files.walk(dir, if (recursive) Int.MAX_VALUE else 1) .filter { Files.isRegularFile(it) } .sorted { file1, file2 -> Files.getLastModifiedTime(file2).compareTo(Files.getLastModifiedTime(file1)) } .findFirst() .map { dir.relativize(it).toString().replace("\\", "/") } .orElseThrow { FileNotFoundException("No files found in $dir") } }.then { fileName -> readDataTask<T>(dirName + fileName) } /** * Delete file [fileName]. * * @param fileName name of file to delete * @return IO task */ @JvmStatic fun deleteFileTask(fileName: String) = voidTaskOf("deleteFileTask($fileName)") { val file = Paths.get(fileName) errorIfAbsent(file) log.debug ( "Deleting file: $file" ) Files.delete(file) } /** * Delete directory [dirName] and its contents. * * @param dirName directory name to delete * @return IO task */ @JvmStatic fun deleteDirectoryTask(dirName: String) = voidTaskOf("deleteDirectoryTask($dirName)") { val dir = Paths.get(dirName) errorIfAbsent(dir) Files.walkFileTree(dir, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, p1: BasicFileAttributes): FileVisitResult { log.debug ( "Deleting file: $file" ) Files.delete(file) return FileVisitResult.CONTINUE } override fun postVisitDirectory(dir: Path, e: IOException?): FileVisitResult { if (e == null) { log.debug ( "Deleting directory: $dir" ) Files.delete(dir) return FileVisitResult.CONTINUE } else { throw e } } }) } } }
mit
77bf22991470b65a7c5ec3ce7a774d08
33.763285
177
0.54524
4.901226
false
false
false
false
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/BookContent.kt
1
1298
package de.ph1b.audiobook.data import java.util.UUID data class BookContent( val id: UUID, val chapters: List<Chapter>, val settings: BookSettings ) { inline fun updateSettings(update: BookSettings.() -> BookSettings) = copy( settings = update(settings) ) init { chapters.forEach { require(it.bookId == id) { "Wrong chapter book id in $this" } } require(chapters.any { it.file == settings.currentFile }) { "Wrong currentFile in $this" } } val currentChapter = chapters.first { it.file == settings.currentFile } val currentChapterIndex = chapters.indexOf(currentChapter) val previousChapter = chapters.getOrNull(currentChapterIndex - 1) val nextChapter = chapters.getOrNull(currentChapterIndex + 1) val duration = chapters.sumBy { it.duration } val position: Long = chapters.take(currentChapterIndex).sumBy { it.duration } + settings.positionInChapter val currentFile = settings.currentFile val positionInChapter = settings.positionInChapter val loudnessGain = settings.loudnessGain val skipSilence = settings.skipSilence val playbackSpeed = settings.playbackSpeed } private inline fun <T> Iterable<T>.sumBy(selector: (T) -> Long): Long { var sum = 0L forEach { element -> sum += selector(element) } return sum }
lgpl-3.0
ab1e11f860072f71dbe3ba2df9dc6740
29.186047
108
0.719569
4.146965
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/libs/image/BackgroundImageLoaderUseCase.kt
1
1079
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.libs.image import android.widget.ImageView import coil.load import java.io.File /** * @author toastkidjp */ class BackgroundImageLoaderUseCase(private val fileResolver: (String) -> File = { File(it) }) { private var lastPath: String? = null operator fun invoke(target: ImageView, backgroundImagePath: String?) { if (backgroundImagePath.isNullOrEmpty() || backgroundImagePath.equals(lastPath)) { return } lastPath = backgroundImagePath target.load(fileResolver(backgroundImagePath)) { if (target.measuredWidth == 0 || target.measuredHeight == 0) { return@load } size(target.measuredWidth, target.measuredHeight) } } }
epl-1.0
1c0181036dbda3c3824910ff19431313
29.857143
95
0.682113
4.477178
false
false
false
false
DadosAbertosBrasil/android-radar-politico
app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/VotosDeputadosTabFragment.kt
1
4329
package br.edu.ifce.engcomp.francis.radarpolitico.controllers import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import br.edu.ifce.engcomp.francis.radarpolitico.R import br.edu.ifce.engcomp.francis.radarpolitico.helpers.VolleySharedQueue import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.CDUrlFormatter import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.adapters.VotosDeputadosRecyclerViewAdapter import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.database.DeputadoDAO import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.parsers.CDXmlParser import br.edu.ifce.engcomp.francis.radarpolitico.models.Proposicao import br.edu.ifce.engcomp.francis.radarpolitico.models.Voto import com.android.volley.Request import com.android.volley.VolleyError import com.android.volley.toolbox.StringRequest import java.util.* /** * A simple [Fragment] subclass. */ class VotosDeputadosTabFragment : Fragment() { private lateinit var votosDeputadosRecyclerView: RecyclerView private lateinit var loadingVotosProgressBar: ProgressBar private lateinit var proposicao: Proposicao private lateinit var adapter:VotosDeputadosRecyclerViewAdapter val votosDatasource: ArrayList<Voto> init { votosDatasource = ArrayList() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val parentActivity = activity as ProposicaoVotadaActivity proposicao = parentActivity.proposicao adapter = VotosDeputadosRecyclerViewAdapter(parentActivity, votosDatasource) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_votos_deputados, container, false) loadingVotosProgressBar = view.findViewById(R.id.loadingVotosProgressBar) as ProgressBar votosDeputadosRecyclerView = view.findViewById(R.id.votosDeputadosRecyclerView) as RecyclerView initVotosRecyclerView() requestVotosIfNeeded() return view } private fun initVotosRecyclerView() { val layoutManager = LinearLayoutManager(activity) votosDeputadosRecyclerView.setHasFixedSize(true) votosDeputadosRecyclerView.layoutManager = layoutManager votosDeputadosRecyclerView.adapter = adapter votosDeputadosRecyclerView.itemAnimator = DefaultItemAnimator() } private fun requestVotosIfNeeded(){ if (votosDatasource.isEmpty()) { votosDeputadosRecyclerView.hideView() requestVotosDosDeputados() } else { loadingVotosProgressBar.hideView() } } private fun requestVotosDosDeputados() { val urlString = CDUrlFormatter.obterVotacaoProposicao(proposicao.sigla, proposicao.numero, proposicao.ano) val request = StringRequest(Request.Method.GET, urlString, { stringResponse: String -> val votacao = CDXmlParser.parseVotacaoFromXML(stringResponse.byteInputStream()) val deputados = DeputadoDAO(activity).listAll() val filteredVotos = ArrayList<Voto>() for (deputado in deputados) { val votos = votacao.votos.filter { it.idCadastro.equals(deputado.idCadastro) } filteredVotos.addAll(votos) } Log.i("VOTOS DEPUTADOS", filteredVotos.toString()) votosDatasource.clear() votosDatasource.addAll(filteredVotos) adapter.notifyDataSetChanged() loadingVotosProgressBar.hideView() votosDeputadosRecyclerView.showView() }, { volleyError: VolleyError -> volleyError.printStackTrace() }) VolleySharedQueue.getQueue(activity)?.add(request) } fun View.hideView() { this.visibility = View.GONE } fun View.showView() { this.visibility = View.VISIBLE } }
gpl-2.0
03d2a7d044874292f90a75d83a8c8296
33.357143
117
0.731578
4.350754
false
false
false
false
Kotlin/dokka
runners/gradle-plugin/src/test/kotlin/org/jetbrains/dokka/gradle/DokkaCollectorTaskTest.kt
1
3018
package org.jetbrains.dokka.gradle import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.withType import org.gradle.testfixtures.ProjectBuilder import org.jetbrains.dokka.DokkaConfigurationImpl import org.jetbrains.dokka.DokkaException import java.io.File import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue class DokkaCollectorTaskTest { @Test fun buildDokkaConfiguration() { val rootProject = ProjectBuilder.builder().build() val childProject = ProjectBuilder.builder().withParent(rootProject).build() childProject.plugins.apply("org.jetbrains.kotlin.jvm") rootProject.allprojects { project -> project.plugins.apply("org.jetbrains.dokka") project.tasks.withType<AbstractDokkaTask>().configureEach { task -> task.plugins.withDependencies { dependencies -> dependencies.clear() } } project.tasks.withType<DokkaTask>().configureEach { task -> task.dokkaSourceSets.configureEach { sourceSet -> sourceSet.classpath.setFrom(emptyList<Any>()) } } } val collectorTasks = rootProject.tasks.withType<DokkaCollectorTask>() collectorTasks.configureEach { task -> task.moduleName by "custom Module Name" task.outputDirectory by File("customOutputDirectory") task.cacheRoot by File("customCacheRoot") task.failOnWarning by true task.offlineMode by true } assertTrue(collectorTasks.isNotEmpty(), "Expected at least one collector task") collectorTasks.toList().forEach { task -> val dokkaConfiguration = task.buildDokkaConfiguration() assertEquals( DokkaConfigurationImpl( moduleName = "custom Module Name", outputDir = File("customOutputDirectory"), cacheRoot = File("customCacheRoot"), failOnWarning = true, offlineMode = true, sourceSets = task.childDokkaTasks .map { it.buildDokkaConfiguration() } .map { it.sourceSets } .reduce { acc, list -> acc + list }, pluginsClasspath = task.childDokkaTasks .map { it.plugins.resolve().toList() } .reduce { acc, mutableSet -> acc + mutableSet } ), dokkaConfiguration ) } } @Test fun `with no child tasks throws DokkaException`() { val project = ProjectBuilder.builder().build() val collectorTask = project.tasks.create<DokkaCollectorTask>("collector") project.configurations.all { configuration -> configuration.withDependencies { it.clear() } } assertFailsWith<DokkaException> { collectorTask.generateDocumentation() } } }
apache-2.0
00fa582abc0ccbce8e26a6cc3a126ae4
39.783784
101
0.616634
5.389286
false
true
false
false
tinypass/piano-sdk-for-android
composer/src/main/java/io/piano/android/composer/model/CustomParameters.kt
1
895
package io.piano.android.composer.model class CustomParameters { val content = mutableMapOf<String, MutableList<String>>() val user = mutableMapOf<String, MutableList<String>>() val request = mutableMapOf<String, MutableList<String>>() fun isEmpty(): Boolean = content.isEmpty() && user.isEmpty() && request.isEmpty() fun content(key: String, value: String): CustomParameters = apply { content.putValueForKey(key, value) } fun user(key: String, value: String): CustomParameters = apply { user.putValueForKey(key, value) } fun request(key: String, value: String): CustomParameters = apply { request.putValueForKey(key, value) } private fun MutableMap<String, MutableList<String>>.putValueForKey(key: String, value: String) { val values = get(key) ?: mutableListOf<String>().also { put(key, it) } values.add(value) } }
apache-2.0
a5a1f735fb2d7a7a230e2364b612009d
39.681818
108
0.686034
4.221698
false
false
false
false
Reyurnible/gitsalad-android
app/src/main/kotlin/com/hosshan/android/salad/repository/github/service/body/EditRepositoryBody.kt
1
1221
package com.hosshan.android.salad.repository.github.service.body import com.google.gson.annotations.SerializedName data class EditRepositoryBody( val name: String, val description: String? = null, // A short description of the repository val homepage: String? = null, // A URL with more information about the repository @SerializedName("private") val isPrivate: Boolean = false, // Either true to create a private repository, or false to create a public one. Creating private publicRepositories requires a paid GitHub account. Default: false @SerializedName("has_issues") val issues: Boolean = true, // Either true to enable issues for this repository, false to disable them. Default: true @SerializedName("has_wiki") val wiki: Boolean = true, // Either true to enable the wiki for this repository, false to disable it. Default: true @SerializedName("has_downloads") val downloads: Boolean = true, // Either true to enable downloads for this repository, false to disable them. Default: true @SerializedName("default_branch") val defaultBranch: String? = null // Updates the default branch for this repository. )
mit
89502d8aab14a5f2cca01f31a28672a9
63.263158
202
0.71335
4.845238
false
false
false
false
petrbalat/jlib
src/main/java/cz/softdeluxe/jlib/utils.kt
1
860
package cz.softdeluxe.jlib import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* /** * Created by balat on 13.1.2016. */ fun Boolean.toBooleanInt(): Int = if(this) 1 else 0 fun Throwable.causeSequence(): Sequence<Throwable> = generateSequence(this, { if (it.cause == it) { return@generateSequence null } it.cause }) inline fun <T> safeUsing(logger: Logger? = null, action: () -> T?): T? = try { action() } catch (ex: Throwable) { logger?.error(ex.message, ex) null } infix fun Double.relativelyEqual(other:Double):Boolean = Math.abs(this - other) <= 1E-8 fun <R : Any> R.logger(): Lazy<Logger> = lazy { LoggerFactory.getLogger(getClassName(this.javaClass)) } fun <T : Any> getClassName(clazz: Class<T>): String = clazz.name.removeSuffix("\$Companion") fun <T> Optional<T>.orNull(): T? = orElse(null)
apache-2.0
afa615bc982f4c6b0961d968379a20eb
26.774194
103
0.675581
3.257576
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/CommandDocumentationGenerator.kt
1
1716
package me.mrkirby153.KirBot.command import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.tree.CommandNode import java.io.File object CommandDocumentationGenerator { fun generate(output: File) { val commands = Bot.applicationContext.get(CommandExecutor::class.java).getAllLeaves() val builder = StringBuilder() builder.appendln("# Command List") val byCategory = mutableMapOf<CommandCategory, MutableList<CommandNode>>() commands.forEach { byCategory.getOrPut(it.metadata!!.category) { mutableListOf() }.add(it) } byCategory.forEach { category, cmds -> if(cmds.none { it.metadata?.admin == false }) { return@forEach } builder.appendln("## ${category.friendlyName}") builder.append(getHeader()) for(c in cmds) { if(c.metadata?.admin == true) continue val h = c.method?.getAnnotation( CommandDescription::class.java)?.value ?: "No description provided" builder.appendln("| `${c.parentString} ${c.name} ${c.metadata!!.arguments.joinToString(" ")}` | ${c.metadata!!.clearance} | $h |") } builder.appendln() } output.writeText(builder.toString()) Bot.LOG.info("Command documentation written to ${output.canonicalPath}") } private fun getHeader(): String { return buildString { appendln("| Command | Clearance Level | Description |") appendln("|---------|-----------------|-------------|") } } }
mit
68347a926c05566412513800e4e7cbc8
38.022727
146
0.58683
4.806723
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/tournament/TournamentInfoView.kt
1
2472
package com.garpr.android.features.tournament import android.content.Context import android.util.AttributeSet import android.view.View.OnClickListener import android.widget.LinearLayout import com.garpr.android.R import com.garpr.android.data.models.AbsRegion import com.garpr.android.data.models.BracketSource import com.garpr.android.data.models.FullTournament import com.garpr.android.extensions.verticalPositionInWindow import kotlinx.android.synthetic.main.item_tournament_info.view.* import java.text.NumberFormat class TournamentInfoView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : LinearLayout(context, attrs) { private var _tournament: FullTournament? = null val tournament: FullTournament get() = checkNotNull(_tournament) val dateVerticalPositionInWindow: Int get() = date.verticalPositionInWindow var listeners: Listeners? = null private val openLinkClickListener = OnClickListener { listeners?.onOpenLinkClick(this) } private val shareClickListener = OnClickListener { listeners?.onShareClick(this) } interface Listeners { fun onOpenLinkClick(v: TournamentInfoView) fun onShareClick(v: TournamentInfoView) } companion object { private val NUMBER_FORMAT = NumberFormat.getIntegerInstance() } init { orientation = VERTICAL inflate(context, R.layout.item_tournament_info, this) openLink.setOnClickListener(openLinkClickListener) share.setOnClickListener(shareClickListener) } fun setContent(tournament: FullTournament, region: AbsRegion) { _tournament = tournament name.text = tournament.name date.text = tournament.date.fullForm this.region.text = region.displayName val entrants = tournament.players?.size ?: 0 entrantsCount.text = resources.getQuantityString(R.plurals.x_entrants, entrants, NUMBER_FORMAT.format(entrants)) if (tournament.url.isNullOrBlank()) { actionButtons.visibility = GONE } else { openLink.setText(when (BracketSource.fromUrl(tournament.url)) { BracketSource.CHALLONGE -> R.string.open_challonge_link BracketSource.SMASH_GG -> R.string.open_smash_gg_link else -> R.string.open_bracket_link }) actionButtons.visibility = VISIBLE } } }
unlicense
443bcf8edf3921cef37e37136ef39913
29.9
88
0.697411
4.620561
false
false
false
false
Fitbit/MvRx
mvrx/src/main/kotlin/com/airbnb/mvrx/MavericksViewModelExtensions.kt
1
7220
@file:Suppress("FunctionName") package com.airbnb.mvrx import androidx.annotation.RestrictTo import androidx.lifecycle.LifecycleOwner import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlin.reflect.KProperty1 /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState> VM._internal( owner: LifecycleOwner?, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (S) -> Unit ) = stateFlow.resolveSubscription(owner, deliveryMode, action) /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A> VM._internal1( owner: LifecycleOwner?, prop1: KProperty1<S, A>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A) -> Unit ) = stateFlow .map { MavericksTuple1(prop1.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1)) { (a) -> action(a) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A, B> VM._internal2( owner: LifecycleOwner?, prop1: KProperty1<S, A>, prop2: KProperty1<S, B>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A, B) -> Unit ) = stateFlow .map { MavericksTuple2(prop1.get(it), prop2.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1, prop2)) { (a, b) -> action(a, b) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A, B, C> VM._internal3( owner: LifecycleOwner?, prop1: KProperty1<S, A>, prop2: KProperty1<S, B>, prop3: KProperty1<S, C>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A, B, C) -> Unit ) = stateFlow .map { MavericksTuple3(prop1.get(it), prop2.get(it), prop3.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1, prop2, prop3)) { (a, b, c) -> action(a, b, c) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A, B, C, D> VM._internal4( owner: LifecycleOwner?, prop1: KProperty1<S, A>, prop2: KProperty1<S, B>, prop3: KProperty1<S, C>, prop4: KProperty1<S, D>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A, B, C, D) -> Unit ) = stateFlow .map { MavericksTuple4(prop1.get(it), prop2.get(it), prop3.get(it), prop4.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1, prop2, prop3, prop4)) { (a, b, c, d) -> action(a, b, c, d) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A, B, C, D, E> VM._internal5( owner: LifecycleOwner?, prop1: KProperty1<S, A>, prop2: KProperty1<S, B>, prop3: KProperty1<S, C>, prop4: KProperty1<S, D>, prop5: KProperty1<S, E>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A, B, C, D, E) -> Unit ) = stateFlow .map { MavericksTuple5(prop1.get(it), prop2.get(it), prop3.get(it), prop4.get(it), prop5.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1, prop2, prop3, prop4, prop5)) { (a, b, c, d, e) -> action(a, b, c, d, e) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A, B, C, D, E, F> VM._internal6( owner: LifecycleOwner?, prop1: KProperty1<S, A>, prop2: KProperty1<S, B>, prop3: KProperty1<S, C>, prop4: KProperty1<S, D>, prop5: KProperty1<S, E>, prop6: KProperty1<S, F>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A, B, C, D, E, F) -> Unit ) = stateFlow .map { MavericksTuple6(prop1.get(it), prop2.get(it), prop3.get(it), prop4.get(it), prop5.get(it), prop6.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1, prop2, prop3, prop4, prop5, prop6)) { (a, b, c, d, e, f) -> action(a, b, c, d, e, f) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onEach. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, A, B, C, D, E, F, G> VM._internal7( owner: LifecycleOwner?, prop1: KProperty1<S, A>, prop2: KProperty1<S, B>, prop3: KProperty1<S, C>, prop4: KProperty1<S, D>, prop5: KProperty1<S, E>, prop6: KProperty1<S, F>, prop7: KProperty1<S, G>, deliveryMode: DeliveryMode = RedeliverOnStart, action: suspend (A, B, C, D, E, F, G) -> Unit ) = stateFlow .map { MavericksTuple7(prop1.get(it), prop2.get(it), prop3.get(it), prop4.get(it), prop5.get(it), prop6.get(it), prop7.get(it)) } .distinctUntilChanged() .resolveSubscription(owner, deliveryMode.appendPropertiesToId(prop1, prop2, prop3, prop4, prop5, prop6, prop7)) { (a, b, c, d, e, f, g) -> action(a, b, c, d, e, f, g) } /** * This name is obfuscated because @RestrictTo doesn't actually work. It would be named onAsync. * https://issuetracker.google.com/issues/168357308 */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <VM : MavericksViewModel<S>, S : MavericksState, T> VM._internalSF( owner: LifecycleOwner?, asyncProp: KProperty1<S, Async<T>>, deliveryMode: DeliveryMode = RedeliverOnStart, onFail: (suspend (Throwable) -> Unit)? = null, onSuccess: (suspend (T) -> Unit)? = null ) = _internal1(owner, asyncProp, deliveryMode.appendPropertiesToId(asyncProp)) { asyncValue -> if (onSuccess != null && asyncValue is Success) { onSuccess(asyncValue()) } else if (onFail != null && asyncValue is Fail) { onFail(asyncValue.error) } }
apache-2.0
e2d79bee0874536dc7ba47b647c394d4
37.404255
142
0.689889
3.429929
false
false
false
false
empros-gmbh/kmap
data/src/test/kotlin/ch/empros/kmap/TestDb.kt
1
5466
package ch.empros.kmap import java.math.BigDecimal import java.sql.Date import java.sql.Timestamp import java.text.SimpleDateFormat import java.util.* typealias Close = () -> Unit object H2MemoryDatabaseData { private const val DB_DRIVER = "org.h2.Driver" private const val DB_CONNECTION = "jdbc:h2:mem:test" private const val DB_USER = "" private const val DB_PASSWORD = "" const val SQL_SELECT_PERSON = "select * from PERSON" /** * These field names correspond to the Data in the in-memory db. */ val ID = "id".uppercase(Locale.getDefault()) val FIRSTNAME = "firstName".uppercase(Locale.getDefault()) val LASTNAME = "lastName".uppercase(Locale.getDefault()) val ACTIVE = "active".uppercase(Locale.getDefault()) val BIRTH_DATE = "birthdate".uppercase(Locale.getDefault()) val FLOAT_DISCOUNT = "float_discount".uppercase(Locale.getDefault()) val DOUBLE_DISCOUNT = "double_discount".uppercase(Locale.getDefault()) val SIZE = "size".uppercase(Locale.getDefault()) val VALUATION = "valuation".uppercase(Locale.getDefault()) val DOC = "doc".uppercase(Locale.getDefault()) val TIMESTAMP = "time_stamp".uppercase(Locale.getDefault()) const val VAL_BIRTH_DATE = "1966-01-17" const val VAL_FIRSTNAME = "Vorname" const val VAL_LASTNAME = "Nachname" private const val VAL_ACTIVE = true private const val VAL_DOUBLE_DISCOUNT = 1.5 private const val VAL_FLOAT_DISCOUNT = .5f const val VAL_SIZE = 10L private val VAL_VALUATION = BigDecimal(2.5) private const val VAL_DOC = "Clob-Inhalt, z.B. XML, HTML, etc." val VAL_TIMESTAMP: Timestamp = Calendar.getInstance().let { calendar -> calendar.set(2018, 2, 10, 10, 11, 30) Timestamp(calendar.timeInMillis) } @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { try { val (rs, close) = getCloseableResultSet() while (rs.next()) { println( "Id '${rs.getInt("id")}' Name: '${rs.getString("firstname")} ${rs.getString("lastname")}' active = '${ rs.getString( "active" ) }' Birthdate: '${rs.getDate("birthdate")}' Float Discount = '${rs.getFloat("float_discount")}' Double Discount = '${ rs.getDouble( "double_discount" ) }' Size: '${rs.getLong("size")}'" ) } close() } catch (e: java.sql.SQLException) { e.printStackTrace() } } @Throws(java.sql.SQLException::class) fun setupTestDb(size: Int): java.sql.Connection { val connection = dbConnection runSetupQueries(connection, size) return connection } @Throws(java.sql.SQLException::class) fun getCloseableResultSet(size: Int = 5): Pair<java.sql.ResultSet, Close> { val connection = dbConnection runSetupQueries(connection, size) val selectPreparedStatement = connection.prepareStatement(SQL_SELECT_PERSON) val resultSet = selectPreparedStatement.executeQuery() return Pair(resultSet) { selectPreparedStatement.close() connection.close() } } private fun runSetupQueries(connection: java.sql.Connection, size: Int) { val createQuery = "CREATE TABLE PERSON($ID int primary key, $FIRSTNAME varchar(100), $LASTNAME varchar(100), $ACTIVE boolean, $BIRTH_DATE date, $FLOAT_DISCOUNT real, $DOUBLE_DISCOUNT double, $SIZE bigint, $VALUATION decimal, $DOC clob, $TIMESTAMP timestamp)" val insertQuery = "INSERT INTO PERSON ($ID, $FIRSTNAME, $LASTNAME, $ACTIVE, $BIRTH_DATE, $FLOAT_DISCOUNT, $DOUBLE_DISCOUNT, $SIZE, $VALUATION, $DOC, $TIMESTAMP) values (?,?,?,?,?,?,?,?,?,?,?)" connection.autoCommit = false val createPreparedStatement = connection.prepareStatement(createQuery) createPreparedStatement!!.executeUpdate() createPreparedStatement.close() with(connection.prepareStatement(insertQuery)) { for (i in 1..size) { setInt(1, i) setString(2, "$VAL_FIRSTNAME $i") setString(3, "$VAL_LASTNAME $i") setBoolean(4, VAL_ACTIVE) setDate(5, toSqlDate(VAL_BIRTH_DATE)) setFloat(6, VAL_FLOAT_DISCOUNT) setDouble(7, VAL_DOUBLE_DISCOUNT) setLong(8, VAL_SIZE) setBigDecimal(9, VAL_VALUATION) setClob(10, VAL_DOC.reader()) setTimestamp(11, VAL_TIMESTAMP) executeUpdate() } close() } connection.commit() } private val dbConnection: java.sql.Connection get() { try { Class.forName(DB_DRIVER) } catch (e: ClassNotFoundException) { println(e.message) } return java.sql.DriverManager.getConnection( DB_CONNECTION, DB_USER, DB_PASSWORD ) } } fun toSqlDate(dateString: String, format: String = "yyyy-MM-dd"): Date { val simpleDateFormat = SimpleDateFormat(format) simpleDateFormat.timeZone = TimeZone.getTimeZone("UTC") return Date(simpleDateFormat.parse(dateString).time) }
mit
c50c1e7201c0bba42143e8969266eba8
35.684564
252
0.595499
4.29717
false
false
false
false
pnemonic78/RemoveDuplicates
duplicates-android/app/src/main/java/com/github/duplicates/contact/ContactData.kt
1
2652
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.duplicates.contact /** * Contact data. * * @author moshe.w */ open class ContactData { var id: Long = 0 var contactId: Long = 0 var rawContactId: Long = 0 var data1: String? = null var data2: String? = null var data3: String? = null var data4: String? = null var data5: String? = null var data6: String? = null var data7: String? = null var data8: String? = null var data9: String? = null var data10: String? = null var data11: String? = null var data12: String? = null var data13: String? = null var data14: String? = null open var data15: String? = null var dataVersion: Int = 0 var mimeType: String? = null open val isEmpty: Boolean get() = data1 == null override fun hashCode(): Int { return id.toInt() } override fun toString(): String { return data1 ?: "" } open fun containsAny(s: CharSequence, ignoreCase: Boolean = false): Boolean { return (data1?.contains(s, ignoreCase) ?: false) || (data2?.contains(s, ignoreCase) ?: false) || (data3?.contains(s, ignoreCase) ?: false) || (data4?.contains(s, ignoreCase) ?: false) || (data5?.contains(s, ignoreCase) ?: false) || (data6?.contains(s, ignoreCase) ?: false) || (data7?.contains(s, ignoreCase) ?: false) || (data8?.contains(s, ignoreCase) ?: false) || (data9?.contains(s, ignoreCase) ?: false) || (data10?.contains(s, ignoreCase) ?: false) || (data11?.contains(s, ignoreCase) ?: false) || (data12?.contains(s, ignoreCase) ?: false) || (data13?.contains(s, ignoreCase) ?: false) || (data14?.contains(s, ignoreCase) ?: false) || (data15?.contains(s, ignoreCase) ?: false) } protected fun parseInt(s: String?): Int { return s?.toInt() ?: 0 } protected operator fun contains(s: String): Boolean { return containsAny(s, true) } }
apache-2.0
5ead497d9dc17f77dd4dccab2549c010
31.341463
81
0.604072
3.877193
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/render/nodes/ParticleRenderNode.kt
1
2586
package com.binarymonks.jj.core.render.nodes import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.ParticleEffect import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.utils.ObjectMap import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.properties.PropOverride import com.binarymonks.jj.core.render.ShaderSpec import com.binarymonks.jj.core.specs.render.RenderGraphType class ParticleRenderNode( priority: Int, color: PropOverride<Color>, renderGraphType: RenderGraphType, name: String?, shaderSpec: ShaderSpec?, internal var particleEffect: ParticleEffect, internal var offsetX: Float, internal var offsetY: Float, internal var scale: Float, internal var rotationD: Float ) : BatchBasedRenderNode(priority, color, renderGraphType, name, shaderSpec) { private var started = false private var emitterSnapshots: ObjectMap<String, EmitterAngles> = ObjectMap() init { particleEffect.emitters.forEach { val angle = it.angle emitterSnapshots.put(it.name, EmitterAngles( angle.highMin, angle.highMax, angle.lowMin, angle.lowMax )) } } override fun render(camera: OrthographicCamera) { JJ.B.renderWorld.switchToBatch() updateParticle() particleEffect.draw(JJ.B.renderWorld.polyBatch) } private fun updateParticle() { if (!started) { started = true particleEffect.start() particleEffect.scaleEffect(scale) } val bodyRotation=me().physicsRoot.rotationR() * MathUtils.radDeg val combinedRotation = bodyRotation+rotationD emitterSnapshots.forEach { val emitter = particleEffect.findEmitter(it.key) val snapshot = it.value emitter.angle.setHigh(snapshot.highMin+combinedRotation, snapshot.highMax+combinedRotation) emitter.angle.setLow(snapshot.lowMin+combinedRotation, snapshot.lowMax+combinedRotation) } val position = me().physicsRoot.position().add(offsetX, offsetY) particleEffect.setPosition(position.x, position.y) particleEffect.update(JJ.clock.deltaFloat) } override fun dispose() { particleEffect.dispose() } } class EmitterAngles( val highMin: Float, val highMax: Float, val lowMin: Float, val lowMax: Float )
apache-2.0
60becc5f6d3578bed1b8013472341077
31.3375
103
0.66396
4.481802
false
false
false
false
NooAn/bytheway
app/src/main/java/ru/a1024bits/bytheway/ui/activity/RegistrationActivity.kt
1
12817
package ru.a1024bits.bytheway.ui.activity import android.app.Dialog import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.util.Log import android.widget.EditText import android.widget.Toast import com.google.android.gms.auth.api.Auth import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.auth.api.signin.GoogleSignInResult import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.firebase.FirebaseException import com.google.firebase.FirebaseTooManyRequestsException import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.auth.* import com.google.firebase.crash.FirebaseCrash import ru.a1024bits.bytheway.App import ru.a1024bits.bytheway.R import ru.a1024bits.bytheway.ui.dialogs.ErrorStandartRegistrationDialog import ru.a1024bits.bytheway.viewmodel.RegistrationViewModel import java.util.concurrent.TimeUnit import javax.inject.Inject class RegistrationActivity : AppCompatActivity(), GoogleApiClient.OnConnectionFailedListener { override fun onConnectionFailed(p0: ConnectionResult) { mFirebaseAnalytics.logEvent("RegistrationScreen_Connect_Fail", null) FirebaseCrash.report(Exception(p0.errorMessage + " " + p0.errorCode)) } private var viewModel: RegistrationViewModel? = null @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val RC_SIGN_IN = 9001 private val mAuth = FirebaseAuth.getInstance() private var mGoogleApiClient: GoogleApiClient? = null lateinit var mFirebaseAnalytics: FirebaseAnalytics override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) App.component.inject(this) mFirebaseAnalytics = FirebaseAnalytics.getInstance(this) mAuth.useAppLanguage() val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(resources.getString(R.string.default_web_client_id)) .requestId() .requestEmail() .build() mGoogleApiClient = GoogleApiClient.Builder(this) .enableAutoManage(this /* Activity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build() viewModel = ViewModelProviders.of(this, viewModelFactory).get(RegistrationViewModel::class.java) mFirebaseAnalytics.setUserId(mAuth?.currentUser.toString()) mFirebaseAnalytics.setCurrentScreen(this, "Registration", this.javaClass.getSimpleName()) mFirebaseAnalytics.logEvent("RegistrationScreen_Enter", null) viewModel?.load?.observe(this, Observer<Boolean> { upload -> if (upload == true) { mFirebaseAnalytics.logEvent("RegistrationScreen_Success", null) startActivity(Intent(this@RegistrationActivity, MenuActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)) } else { mFirebaseAnalytics.logEvent("RegistrationScreen_Error_Checkin", null) updateUI(false) Toast.makeText(this@RegistrationActivity, "Error for registration", Toast.LENGTH_SHORT).show() } }) if (!isNetworkAvailable()) { showDialogInternet() return } signIn() } var snackbar: Snackbar? = null private fun showDialogInternet() { val alertDialog = AlertDialog.Builder(this).create(); alertDialog.setTitle("Info"); alertDialog.setMessage(resources.getString(R.string.no_internet)); alertDialog.setButton(Dialog.BUTTON_POSITIVE, "OK") { _, _ -> signIn() alertDialog.dismiss() } alertDialog.show(); } private fun isNetworkAvailable(): Boolean { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } private fun signIn() { val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient) startActivityForResult(signInIntent, RC_SIGN_IN) } override fun onStart() { super.onStart() } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) try { if (requestCode == RC_SIGN_IN) { val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data) result?.let { handleSignInResult(it) } } else { updateUI(false) } } catch (e: Exception) { e.printStackTrace() updateUI(false) } } private fun handleSignInResult(result: GoogleSignInResult) { if (result.isSuccess) { // Signed in successfully, show authenticated UI. val acct = result.signInAccount acct?.let { account -> firebaseAuthWithGoogle(account) } //maybe not this variant } else { // Signed out, show unauthenticated UI. if (result.status.statusCode != 200) { mFirebaseAnalytics.logEvent("RegistrationScreen_Error_Not200", null) mFirebaseAnalytics.logEvent("RegistrationScreen_status_${result.status.statusCode}", null) } else { mFirebaseAnalytics.logEvent("RegistrationScreen_Error_NotKnow", null) } when (result.status.statusCode) { 12501, 12502 -> { Toast.makeText(this, "Проблемы с гугл аккаунтом", Toast.LENGTH_SHORT).show() //startActivity(Intent(this, RegistrationActivity::class.java)) } 8 -> { Toast.makeText(this, R.string.error_registration, Toast.LENGTH_SHORT).show() showPhoneDialog() } } updateUI(false) } } private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) { val credential = GoogleAuthProvider.getCredential(acct.idToken, null) signInGoogle(credential) } fun signInGoogle(credential: AuthCredential, errorDialog: ErrorStandartRegistrationDialog? = null) { try { mAuth?.signInWithCredential(credential) ?.addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information errorDialog?.dismissAllowingStateLoss() updateUI(true) } else { // If sign in fails, display a message to the user. Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show() mFirebaseAnalytics.logEvent("RegistrationScreen_Error_Login", null) updateUI(false) } } ?.addOnFailureListener { Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show() mFirebaseAnalytics.logEvent("RegistrationScreen_Error_Login", null) FirebaseCrash.report(it) showPhoneDialog() } } catch (e: Exception) { FirebaseCrash.report(e) showPhoneDialog() } } private fun updateUI(signedIn: Boolean) { if (signedIn) { mFirebaseAnalytics.logEvent("RegistrationScreen_Success_Login", null) viewModel?.ifUserNotExistThenSave(mAuth.currentUser) } else { showPhoneDialog() Toast.makeText(this, R.string.problem_google_acc, Toast.LENGTH_SHORT).show() } } private fun showPhoneDialog() { if (!isNetworkAvailable()) showDialogInternet() else ErrorStandartRegistrationDialog.newInstance(this).show(supportFragmentManager, "dialogRegistrationOnNumber") } fun validatePhoneNumber(phone: EditText): Boolean { val phoneNumber = phone.text.toString() val bundle = Bundle() bundle.putString("number", phone.toString()) mFirebaseAnalytics.logEvent("Registration_number", bundle) if (phoneNumber.isBlank() || !phoneNumber.matches(Regex("^\\+?\\d{10,12}$"))) { phone.error = "Invalid phone number."//falseui return false } return true } override fun onBackPressed() { super.onBackPressed() finish() } var mVerificationId: String? = null fun authPhone(phone: EditText) { PhoneAuthProvider.getInstance().verifyPhoneNumber( phone.text.toString(), // Phone number to verify 30, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(authCred: PhoneAuthCredential?) { // This callback will be invoked in two situations: // 1 - Instant verification. In some cases the phone number can be instantly // verified without needing to send or enter a verification code. // 2 - Auto-retrieval. On some devices Google Play services can automatically // detect the incoming verification SMS and perform verification without // user action. if (authCred is AuthCredential) signInGoogle(authCred) } override fun onVerificationFailed(e: FirebaseException?) { // This callback is invoked in an invalid request for verification is made, // for instance if the the phone number format is not valid. if (e is FirebaseAuthInvalidCredentialsException) { // Invalid request Log.w("LOG", "Invalid Credintial"); mFirebaseAnalytics.logEvent("RegistrationScreen_invalid_sms", null) snackbar = Snackbar.make(findViewById(android.R.id.content), R.string.invalid_sms, Snackbar.LENGTH_LONG) snackbar?.show() } else if (e is FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded Log.w("LOG", "many request", e); snackbar = Snackbar.make(findViewById(android.R.id.content), R.string.many_request, Snackbar.LENGTH_LONG) snackbar?.show() mFirebaseAnalytics.logEvent("RegistrationScreen_error_lot_req", null) } else { mFirebaseAnalytics.logEvent("RegistrationScreen_error_doesnknow", null) Toast.makeText(this@RegistrationActivity, R.string.just_error, Toast.LENGTH_SHORT).show() } } override fun onCodeSent(verificationId: String?, token: PhoneAuthProvider.ForceResendingToken?) { super.onCodeSent(verificationId, token) // The SMS verification code has been sent to the provided phone number, we // now need to ask the user to enter the code and then construct a credential // by combining the code with a verification ID. mVerificationId = verificationId; // Save verification ID and resending token so we can use them later } }); } }
mit
cc47c15a29c5b950c1cbbece945be2de
44.212014
172
0.612036
5.302528
false
false
false
false
vovagrechka/k2php
k2php/src/org/jetbrains/kotlin/js/translate/expression/InlineMetadata.kt
2
2354
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.translate.expression import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.translate.context.Namer private val METADATA_PROPERTIES_COUNT = 2 class InlineMetadata(val tag: JsStringLiteral, val function: JsFunction) { companion object { @JvmStatic fun compose(function: JsFunction, descriptor: CallableDescriptor): InlineMetadata { val program = function.scope.program val tag = program.getStringLiteral(Namer.getFunctionTag(descriptor)) return InlineMetadata(tag, function) } @JvmStatic fun decompose(expression: JsExpression?): InlineMetadata? = when (expression) { is JsInvocation -> decomposeCreateFunctionCall(expression) else -> null } private fun decomposeCreateFunctionCall(call: JsInvocation): InlineMetadata? { val qualifier = call.qualifier if (qualifier !is JsNameRef || qualifier.ident != Namer.DEFINE_INLINE_FUNCTION) return null val arguments = call.arguments if (arguments.size != METADATA_PROPERTIES_COUNT) return null val tag = arguments[0] as? JsStringLiteral val function = arguments[1] as? JsFunction if (tag == null || function == null) return null return InlineMetadata(tag, function) } } val functionWithMetadata: JsExpression get() { val propertiesList = listOf(tag, function) function.shouldPrintName = false return JsInvocation(Namer.createInlineFunction(), propertiesList) } }
apache-2.0
e7eb97dd7094452b7ffcc124e3193bea
35.215385
103
0.673747
4.853608
false
false
false
false
NooAn/bytheway
app/src/main/java/ru/a1024bits/bytheway/util/LatLngInterpolator.kt
1
3563
package ru.a1024bits.aviaanimation.ui.util /** * This class from https://gist.github.com/broady/6314689 */ import com.google.android.gms.maps.model.LatLng interface LatLngInterpolator { fun interpolate(fraction: Float, fromLocation: LatLng, endLocation: LatLng): LatLng class Linear : LatLngInterpolator { override fun interpolate(fraction: Float, a: LatLng, b: LatLng): LatLng { val lat = (b.latitude - a.latitude) * fraction + a.latitude val lng = (b.longitude - a.longitude) * fraction + a.longitude return LatLng(lat, lng) } } class CurveBezie : LatLngInterpolator { override fun interpolate(fraction: Float, fromLocation: LatLng, endLocation: LatLng): LatLng = calculateBezierFunction(fraction.toDouble(), fromLocation, endLocation) fun calculateBezierFunction(t: Double, fromLocation: LatLng, endLocation: LatLng): LatLng { val lat1 = fromLocation.latitude val lat2 = endLocation.latitude val lon1 = fromLocation.longitude val lon2 = endLocation.longitude val angle = findArctg(lat1, lat2, lon1, lon2) val module = module(lat1, lat2, lon1, lon2) val latCentral = (lat2+lat1)/2 val lonCentral = (lon2+lon1)/2 val latTop = latCentral + module / 4 val lonTop = lonCentral val latBottom = latCentral - module / 4 val lonBottom = lonCentral val rotatedTop = rotatePoint(lonTop, latTop, lonCentral, latCentral, Math.toRadians(90-(90-angle))) val rotatedBottom = rotatePoint(lonBottom, latBottom, lonCentral, latCentral, Math.toRadians(90-(90-angle))) val point2 = LatLng(rotatedTop[1], rotatedTop[0]) val point3 = LatLng(rotatedBottom[1], rotatedBottom[0]) // x == lat, y == lon val a1 = fromLocation.latitude * Math.pow(1 - t, 3.0) val b1 = 3 * point2.latitude * t * (Math.pow(t, 2.0) - 2 * t + 1) val c1 = 3 * point3.latitude * Math.pow(t, 2.0) * (1 - t) val d1 = endLocation.latitude * Math.pow(t, 3.0) val x = a1 + b1 + c1 + d1 val a2 = fromLocation.longitude * Math.pow(1 - t, 3.0) val b2 = 3 * point2.longitude * t * (Math.pow(t, 2.0) - 2 * t + 1) val c2 = 3 * point3.longitude * Math.pow(t, 2.0) * (1 - t) val d2 = endLocation.longitude * Math.pow(t, 3.0) val y = a2 + b2 + c2 + d2 return LatLng(x, y); } private fun findArctg(lat1: Double, lat2: Double, lon1: Double, lon2: Double) : Double { val arctg = Math.atan( (lat2-lat1) / (lon2-lon1) ) return Math.toDegrees(arctg) } /* Apply rotation matrix to the point(x,y) * x, y: point that should be rotated; * x0, y0: point that should be center of rotation * angle: angle of rotation * */ private fun rotatePoint(x: Double, y: Double, x0: Double, y0: Double, angle: Double) : Array<Double> { val x1 = - (y - y0) * Math.sin(angle) + Math.cos(angle) * (x - x0) + x0 val y1 = (y - y0) * + Math.cos(angle) + Math.sin(angle) * (x - x0) + y0 return arrayOf(x1, y1) } /* * length of vector */ private fun module(lat1: Double, lat2: Double, lon1: Double, lon2: Double) : Double { return Math.sqrt((lat2-lat1)*(lat2-lat1) + (lon2-lon1)*(lon2-lon1)) } } }
mit
bcc55e4b1380dd33769c0df77363980b
37.322581
120
0.574797
3.489716
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/ktx/Collections.kt
1
3036
package de.westnordost.streetcomplete.ktx /** Return the first and last element of this list. If it contains only one element, just that one */ fun <E> List<E>.firstAndLast() = if (size == 1) listOf(first()) else listOf(first(), last()) /** Return all except the first and last element of this list. If it contains less than two elements, * it returns an empty list */ fun <E> List<E>.allExceptFirstAndLast() = if (size > 2) subList(1, size - 1) else listOf() /** Returns whether the collection contains any of the [elements] */ fun <E> Collection<E>.containsAny(elements: Collection<E>) = elements.any { contains(it) } /** * Starting at [index] (exclusive), iterating the list in reverse, returns the first element that * matches the given [predicate], or `null` if no such element was found. */ inline fun <T> List<T>.findPrevious(index: Int, predicate: (T) -> Boolean): T? { val iterator = this.listIterator(index) while (iterator.hasPrevious()) { val element = iterator.previous() if (predicate(element)) return element } return null } /** * Starting at [index] (inclusive), iterating the list, returns the first element that * matches the given [predicate], or `null` if no such element was found. */ inline fun <T> List<T>.findNext(index: Int, predicate: (T) -> Boolean): T? { val iterator = this.listIterator(index) while (iterator.hasNext()) { val element = iterator.next() if (predicate(element)) return element } return null } /** Iterate through the given list of points in pairs, so [predicate] is called for every line */ inline fun <T> Iterable<T>.forEachLine(predicate: (first: T, second: T) -> Unit) { val it = iterator() if (!it.hasNext()) return var item1 = it.next() while (it.hasNext()) { val item2 = it.next() predicate(item1, item2) item1 = item2 } } /** returns the index of the first element yielding the largest value of the given function or -1 * if there are no elements. Analogous to the maxBy extension function. */ inline fun <T, R : Comparable<R>> Iterable<T>.indexOfMaxBy(selector: (T) -> R): Int { val iterator = iterator() if (!iterator.hasNext()) return -1 var indexOfMaxElem = 0 var i = 0 var maxValue = selector(iterator.next()) while (iterator.hasNext()) { ++i val v = selector(iterator.next()) if (maxValue < v) { indexOfMaxElem = i maxValue = v } } return indexOfMaxElem } inline fun <T> Iterable<T>.sumByFloat(selector: (T) -> Float): Float { var sum: Float = 0f for (element in this) { sum += selector(element) } return sum } fun <T> Collection<T>.containsExactlyInAnyOrder(other: Collection<T>): Boolean = other.size == size && containsAll(other) /** Returns a new read-only array only of those given [elements] that are not null. */ inline fun <reified T> arrayOfNotNull(vararg elements: T?): Array<T> = elements.filterNotNull().toTypedArray()
gpl-3.0
0d993b2d6dac092f4cdfcd3448c7ec67
35.578313
101
0.655138
3.809285
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/world/LanternBlockChangeFlag.kt
1
3017
/* * 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>. */ package org.lanternpowered.server.world import org.lanternpowered.api.util.ToStringHelper import org.lanternpowered.api.world.BlockChangeFlag import org.spongepowered.api.world.BlockChangeFlag.Factory as BlockChangeFlagFactory import java.util.Objects class LanternBlockChangeFlag private constructor(private val flags: Int) : BlockChangeFlag { companion object Factory : BlockChangeFlagFactory { private const val MASK_NEIGHBOR = 0x1 private const val MASK_PHYSICS = 0x2 private const val MASK_OBSERVER = 0x4 private const val MASK_ALL = MASK_NEIGHBOR or MASK_PHYSICS or MASK_OBSERVER private val FLAGS: Array<LanternBlockChangeFlag> init { val flags = mutableListOf<LanternBlockChangeFlag>() for (i in 0..MASK_ALL) flags += LanternBlockChangeFlag(i) FLAGS = flags.toTypedArray() } override fun empty(): BlockChangeFlag = FLAGS[0] } override fun updateNeighbors(): Boolean = this.flags and MASK_NEIGHBOR != 0 override fun performBlockPhysics(): Boolean = this.flags and MASK_PHYSICS != 0 override fun notifyObservers(): Boolean = this.flags and MASK_OBSERVER != 0 override fun withUpdateNeighbors(updateNeighbors: Boolean): LanternBlockChangeFlag = if (updateNeighbors) andFlag(MASK_NEIGHBOR) else andNotFlag(MASK_NEIGHBOR) override fun withPhysics(performBlockPhysics: Boolean): LanternBlockChangeFlag = if (performBlockPhysics) andFlag(MASK_PHYSICS) else andNotFlag(MASK_PHYSICS) override fun withNotifyObservers(notifyObservers: Boolean): LanternBlockChangeFlag = if (notifyObservers) andFlag(MASK_OBSERVER) else andNotFlag(MASK_OBSERVER) override fun inverse(): LanternBlockChangeFlag = FLAGS[this.flags.inv() and MASK_ALL] override fun andFlag(flag: BlockChangeFlag): LanternBlockChangeFlag = andFlag((flag as LanternBlockChangeFlag).flags) override fun andNotFlag(flag: BlockChangeFlag): LanternBlockChangeFlag = andNotFlag((flag as LanternBlockChangeFlag).flags) private fun andFlag(flags: Int): LanternBlockChangeFlag = FLAGS[this.flags or flags] private fun andNotFlag(flags: Int): LanternBlockChangeFlag = FLAGS[this.flags and flags.inv()] override fun toString(): String = ToStringHelper(this) .add("updateNeighbors", updateNeighbors()) .add("performBlockPhysics", performBlockPhysics()) .add("notifyObservers", notifyObservers()) .toString() override fun equals(other: Any?): Boolean = other is LanternBlockChangeFlag && other.flags == flags override fun hashCode(): Int = Objects.hash(this.flags) }
mit
e59b44bec658fcb7535c7b7852f96e14
43.367647
127
0.723566
4.316166
false
false
false
false
jskierbi/bundle-helper
app/src/main/java/com/jskierbi/bundle_helper_sample/OtherActivity.kt
1
1458
package com.jskierbi.bundle_helper_sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import com.jskierbi.bundle_helper.lazyExtra /** * Created by q on 04/05/16. */ class OtherActivity : AppCompatActivity() { companion object { val EXTRA_STRING = "EXTRA_STRING" val EXTRA_BOOLEAN = "EXTRA_BOOLEAN" val EXTRA_FLOAT = "EXTRA_FLOAT" val EXTRA_COMPLEX_PARAMETER = "EXTRA_COMPLEX_PARAMETER" val EXTRA_OPTIONAL = "EXTRA_OPTIONAL" } val extraString by lazyExtra<String>(EXTRA_STRING) val extraFloat by lazyExtra<Float>(EXTRA_FLOAT) val extraBoolean by lazyExtra<Boolean>(EXTRA_BOOLEAN) val extraComplex by lazyExtra<ComplexObj>(EXTRA_COMPLEX_PARAMETER) val extraOptional by lazyExtra<String?>(EXTRA_OPTIONAL) // Optional by nullable type val extraComplexOptional by lazyExtra<ComplexObj?>(EXTRA_OPTIONAL) // Complex optional by nullable type override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_other) Log.d("OtherActivity", "extraString: $extraString") Log.d("OtherActivity", "extraBoolean: $extraBoolean") Log.d("OtherActivity", "extraFloat: $extraFloat") Log.d("OtherActivity", "extraComplex: ${extraComplex.a}, ${extraComplex.b}") Log.d("OtherActivity", "extraOptional: $extraOptional") Log.d("OtherActivity", "extraComplexOptional: $extraComplexOptional") } }
apache-2.0
d57fccc66d24cabd2b490195c3fa1a63
36.410256
105
0.748285
3.806789
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/sync/scheduler/SeasonTaskScheduler.kt
1
4115
/* * Copyright (C) 2013 Simon Vig Therkildsen * * 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 net.simonvt.cathode.sync.scheduler import android.content.Context import androidx.work.WorkManager import kotlinx.coroutines.launch import net.simonvt.cathode.api.body.SyncItems import net.simonvt.cathode.api.util.TimeUtils import net.simonvt.cathode.jobqueue.JobManager import net.simonvt.cathode.provider.helper.SeasonDatabaseHelper import net.simonvt.cathode.provider.helper.ShowDatabaseHelper import net.simonvt.cathode.remote.action.shows.AddSeasonToHistory import net.simonvt.cathode.remote.action.shows.CollectSeason import net.simonvt.cathode.remote.action.shows.RemoveSeasonFromHistory import net.simonvt.cathode.settings.TraktLinkSettings import net.simonvt.cathode.work.enqueueNow import net.simonvt.cathode.work.user.SyncWatchedShowsWorker import javax.inject.Inject import javax.inject.Singleton @Singleton class SeasonTaskScheduler @Inject constructor( context: Context, jobManager: JobManager, private val workManager: WorkManager, private val showHelper: ShowDatabaseHelper, private val seasonHelper: SeasonDatabaseHelper ) : BaseTaskScheduler(context, jobManager) { fun addToHistoryNow(seasonId: Long) { addToHistory(seasonId, System.currentTimeMillis()) } fun addToHistoryOnRelease(seasonId: Long) { addToHistory(seasonId, SyncItems.TIME_RELEASED) } fun addToHistory(seasonId: Long, watchedAt: Long) { val isoWhen = TimeUtils.getIsoTime(watchedAt) addToHistory(seasonId, isoWhen) } fun addToHistory( seasonId: Long, year: Int, month: Int, day: Int, hour: Int, minute: Int ) { addToHistory(seasonId, TimeUtils.getMillis(year, month, day, hour, minute)) } fun addToHistory(seasonId: Long, watchedAt: String) { scope.launch { var watched = SeasonDatabaseHelper.WATCHED_RELEASE if (SyncItems.TIME_RELEASED != watchedAt) { watched = TimeUtils.getMillis(watchedAt) } seasonHelper.addToHistory(seasonId, watched) if (TraktLinkSettings.isLinked(context)) { val showId = seasonHelper.getShowId(seasonId) val traktId = showHelper.getTraktId(showId) val seasonNumber = seasonHelper.getNumber(seasonId) queue(AddSeasonToHistory(traktId, seasonNumber, watchedAt)) // No documentation on how exactly the trakt endpoint is implemented, so sync after. workManager.enqueueNow(SyncWatchedShowsWorker::class.java) } } } fun removeFromHistory(seasonId: Long) { scope.launch { seasonHelper.removeFromHistory(seasonId) if (TraktLinkSettings.isLinked(context)) { val showId = seasonHelper.getShowId(seasonId) val traktId = showHelper.getTraktId(showId) val seasonNumber = seasonHelper.getNumber(seasonId) queue(RemoveSeasonFromHistory(traktId, seasonNumber)) } } } fun setInCollection(seasonId: Long, inCollection: Boolean) { scope.launch { var collectedAt: String? = null var collectedAtMillis = 0L if (inCollection) { collectedAt = TimeUtils.getIsoTime() collectedAtMillis = TimeUtils.getMillis(collectedAt) } seasonHelper.setIsInCollection(seasonId, inCollection, collectedAtMillis) if (TraktLinkSettings.isLinked(context)) { val showId = seasonHelper.getShowId(seasonId) val traktId = showHelper.getTraktId(showId) val seasonNumber = seasonHelper.getNumber(seasonId) queue(CollectSeason(traktId, seasonNumber, inCollection, collectedAt)) } } } }
apache-2.0
2f1bce45fb806e4edd5e0a0f00be3dc6
33.008264
92
0.740948
4.340717
false
false
false
false
Mauin/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/DetektFacade.kt
1
2635
package io.gitlab.arturbosch.detekt.core import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.FileProcessListener import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Notification import io.gitlab.arturbosch.detekt.api.RuleSetProvider import org.jetbrains.kotlin.psi.KtFile import java.nio.file.Path /** * @author Artur Bosch */ class DetektFacade( private val detektor: Detektor, settings: ProcessingSettings, private val processors: List<FileProcessListener>) { private val saveSupported = settings.config.valueOrDefault("autoCorrect", false) private val pathsToAnalyze = settings.project private val compiler = KtTreeCompiler.instance(settings) fun run(): Detektion { val notifications = mutableListOf<Notification>() val ktFiles = mutableListOf<KtFile>() val findings = HashMap<String, List<Finding>>() for (current in pathsToAnalyze) { val files = compiler.compile(current) processors.forEach { it.onStart(files) } findings.mergeSmells(detektor.run(files)) if (saveSupported) { KtFileModifier(current).saveModifiedFiles(files) { notifications.add(it) } } ktFiles.addAll(files) } val result = DetektResult(findings.toSortedMap()) processors.forEach { it.onFinish(ktFiles, result) } return result } fun run(project: Path, files: List<KtFile>): Detektion = runOnFiles(project, files) private fun runOnFiles(current: Path, files: List<KtFile>): DetektResult { processors.forEach { it.onStart(files) } val findings = detektor.run(files) val detektion = DetektResult(findings.toSortedMap()) if (saveSupported) { KtFileModifier(current).saveModifiedFiles(files) { detektion.add(it) } } processors.forEach { it.onFinish(files, detektion) } return detektion } companion object { fun create(settings: ProcessingSettings): DetektFacade { val providers = RuleSetLocator(settings).load() val processors = FileProcessorLocator(settings).load() return create(settings, providers, processors) } fun create(settings: ProcessingSettings, vararg providers: RuleSetProvider): DetektFacade { return create(settings, providers.toList(), emptyList()) } fun create(settings: ProcessingSettings, vararg processors: FileProcessListener): DetektFacade { return create(settings, emptyList(), processors.toList()) } fun create(settings: ProcessingSettings, providers: List<RuleSetProvider>, processors: List<FileProcessListener>): DetektFacade { return DetektFacade(Detektor(settings, providers, processors), settings, processors) } } }
apache-2.0
e3f14f918541e20a637d50e7451246a6
29.639535
98
0.75408
3.909496
false
false
false
false
asher-stern/word2vec
preprocess_kotlin/word2vec/src/main/kotlin/com/github/asher_stern/word2vec/corpora/BncDocumentLoader.kt
1
5751
package com.github.asher_stern.word2vec.corpora import com.github.asher_stern.word2vec.utilities.BeginEnd import com.github.asher_stern.word2vec.utilities.XmlDomElement import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token import org.apache.uima.jcas.JCas import java.io.File import java.util.* /** * Created by Asher Stern on October-19 2017. */ class BncDocumentLoader(private val cas: JCas, private val file: File, private val includeHeads: Boolean = false) { fun load() { readXml() setCasContents() } private fun readXml() { val root = XmlDomElement.fromFile(file) val wtext = root.getChildElements("wtext") val stext = root.getChildElements("stext") var textElement: XmlDomElement? = null if ( (wtext.size==1) && (stext.size==0) ) { textElement=wtext.first() } else if ( (wtext.size==0) && (stext.size==1) ) { textElement=stext.first() } else throw RuntimeException("Cannot detect text element. wtext.size = ${wtext.size}. stext.size = ${stext.size}") for (paragraph in xmlListParagraphs(textElement!!)) { addParagraph(paragraph) } } private fun xmlListParagraphs(base: XmlDomElement): List<XmlDomElement> { val ret = mutableListOf<XmlDomElement>() xmlListParagraphs(base, ret) return ret } private fun xmlListParagraphs(base: XmlDomElement, list: MutableList<XmlDomElement>) { for (element in base.childElements) { val tag = element.element.tagName when (tag) { "head" -> if (includeHeads) { list.add(element) } "p", "item" -> list.add(element) else -> xmlListParagraphs(element, list) } } } private fun addParagraph(paragraph: XmlDomElement) { for (sentence in paragraph.getChildElements("s")) { if (text.length > 0) { text.append(" ") } val beginSentence = text.length var firstIteration = true for (word in xmlListWords(sentence)) { val tag = word.element.tagName if (firstIteration) { firstIteration = false } else { if (tag != "c") { text.append(" ") } } val surface: String? = word.getText(true, false, false, "") if (surface != null) { val lemma = if (tag == "c") surface else word.element.getAttribute("hw")._ifEmpty(surface) var pos = if (tag == "c") "PUNC" else word.element.getAttribute("pos")._ifEmpty("O") pos = mapPos(pos) tokens.add(TokenToAnnotate(BeginEnd(text.length, text.length + surface.length), pos, lemma)) text.append(surface) } } sentences.add(BeginEnd(beginSentence, text.length)) } } private fun setCasContents() { cas.reset() cas.documentLanguage = "en" cas.documentText = text.toString() for (sentence in sentences) { Sentence(cas, sentence.begin, sentence.end).addToIndexes() } for (token in tokens) { val tokenAnnotation = Token(cas, token.beginEnd.begin, token.beginEnd.end) val posAnnotation = Class.forName(POS_PACKAGE+token.pos).getConstructor(JCas::class.java, java.lang.Integer.TYPE, java.lang.Integer.TYPE).newInstance(cas, token.beginEnd.begin, token.beginEnd.end) as POS val lemmaAnnotation = Lemma(cas, token.beginEnd.begin, token.beginEnd.end) lemmaAnnotation.value = token.lemma posAnnotation.addToIndexes() lemmaAnnotation.addToIndexes() tokenAnnotation.pos = posAnnotation tokenAnnotation.lemma = lemmaAnnotation tokenAnnotation.addToIndexes() } } private data class TokenToAnnotate( val beginEnd: BeginEnd, val pos: String, val lemma: String ) companion object { val POS_PACKAGE = POS::class.java.`package`.name+"." } private val text = StringBuilder() private val tokens = mutableListOf<TokenToAnnotate>() private val sentences = mutableListOf<BeginEnd>() } private fun xmlListWords(sentence: XmlDomElement): List<XmlDomElement> { val ret = mutableListOf<XmlDomElement>() val stack = Stack<XmlDomElement>() stack.push(sentence) while (!stack.empty()) { val element = stack.pop() val tag = element.element.tagName if ( (tag == "w") || (tag == "c") ) { ret.add(element) } else { for (child in element.childElements.reversed()) { stack.push(child) } } } return ret } private fun String._ifEmpty(other: String): String { if (this.isEmpty()) return other return this } private fun mapPos(given: String): String { return when(given) { "CONJ" -> "CONJ" "SUBST" -> "N" "VERB" -> "V" "ART" -> "ART" "ADJ" -> "ADJ" "PREP" -> "PP" "ADV" -> "ADV" "PRON" -> "PR" "PUNC" -> "PUNC" "UNC" -> "O" "INTERJ" -> "O" else -> throw RuntimeException("Unrecognized POS: $given") } }
mit
cc998ad6c3fe00efad7bd9c8ce76575e
28.492308
215
0.567032
3.901628
false
false
false
false
benkyokai/tumpaca
app/src/main/kotlin/com/tumpaca/tp/util/Extensions.kt
1
7093
package com.tumpaca.tp.util import android.content.* import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.ConnectivityManager import android.os.AsyncTask import android.util.DisplayMetrics import android.util.Log import android.view.View import android.view.ViewGroup import com.google.android.gms.ads.AdRequest import com.tumblr.jumblr.types.Photo import com.tumblr.jumblr.types.PhotoSize import com.tumblr.jumblr.types.Post import com.tumpaca.tp.BuildConfig import com.tumpaca.tp.R import com.tumpaca.tp.model.AdPost import com.tumpaca.tp.model.TPRuntime import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.net.URL fun Context.editSharedPreferences(name: String, mode: Int = Context.MODE_PRIVATE, actions: (SharedPreferences.Editor) -> Unit) { val editor = getSharedPreferences(name, mode).edit() actions(editor) val committed = editor.commit() assert(committed) } fun Post.likeAsync(callback: (Post, Boolean) -> Unit) { if (this.isLiked) { TPToastManager.show(TPRuntime.mainApplication.resources.getString(R.string.unlike)) } else { TPToastManager.show(TPRuntime.mainApplication.resources.getString(R.string.like)) } object : AsyncTask<Unit, Unit, Boolean>() { override fun doInBackground(vararg args: Unit): Boolean { try { if (isLiked) { unlike() } else { like() } return true } catch (e: Exception) { Log.e("LikeTask", e.message.orEmpty(), e) return false } } override fun onPostExecute(result: Boolean) { callback(this@likeAsync, result) } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } fun Post.reblogAsync(blogName: String, comment: String?): Observable<Post> { TPToastManager.show(TPRuntime.mainApplication.resources.getString(R.string.reblog)) return Observable .create { emitter: ObservableEmitter<Post> -> try { val option = if (comment == null) { emptyMap<String, String>() } else { mapOf("comment" to comment) } val post = reblog(blogName, option) post?.let { emitter.onNext(it) } emitter.onComplete() } catch (e: Exception) { Log.e("ReblogTask", e.message.orEmpty(), e) emitter.onError(e) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun Post.blogAvatar(): Observable<Bitmap?> { return Observable .create { emitter: ObservableEmitter<String> -> try { val url = TPRuntime.avatarUrlCache.getIfNoneAndSet(blogName, { client.blogInfo(blogName).avatar() }) Log.d("blogAvatar", "url=" + url) url?.let { emitter.onNext(it) } emitter.onComplete() } catch (e: Exception) { Log.e("blogAvatar", e.message.orEmpty(), e) emitter.onError(e) } } .map { url -> Log.d("avatar", "url=" + url) val avatar = TPRuntime.bitMapCache.getIfNoneAndSet(url, { val stream = URL(url).openStream() val options = BitmapFactory.Options() options.inDensity = DisplayMetrics.DENSITY_MEDIUM BitmapFactory.decodeStream(stream, null, options) }) avatar } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } /** * PHOTO ポストの写真に対し、最適なサイズと最高解像度のサイズの2つを取得する。 * * 最適なサイズの仕様: * 高画質写真設定がtrueの場合: * 画面解像度の幅を超える最小の画像を取得 * 高画質写真設定がfalseの場合: * 幅500px以下の最大の画像を取得 * 上記条件で取得できない場合: * サイズリストの最大の画像を取得 * * 返り値:Pair<PhotoSize, PhotoSize> * first: 最適サイズ * second: 最高サイズ */ fun Photo.getBestSizeForScreen(metrics: DisplayMetrics): Pair<PhotoSize, PhotoSize> { val w = metrics.widthPixels val biggest = sizes.first() val optimal = sizes.lastOrNull { it.width >= w } val better = sizes.firstOrNull { it.width <= 500 } if (optimal != null && optimal != biggest) { Log.d("Util", "画面の解像度:${metrics.widthPixels}x${metrics.heightPixels} 採択した解像度:") sizes.forEach { Log.d("Util", it.debugString() + (if (it == optimal) " optimal" else if (it == better) " better" else "")) } } if (TPRuntime.settings.highResolutionPhoto) { return Pair(optimal ?: biggest, biggest) } else { return Pair(better ?: biggest, biggest) } } fun PhotoSize.debugString(): String { return "${width}x${height}" } fun ViewGroup.children(): List<View> { return (0 until childCount).map { getChildAt(it) } } fun <T> List<T>.enumerate(): List<Pair<Int, T>> { return (0 until size).map { it to get(it) } } fun Context.isOnline(): Boolean { val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connMgr.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } fun Context.onNetworkRestored(callback: () -> Unit): BroadcastReceiver { val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { context?.let { if (it.isOnline()) { Log.d("Util", "インターネット接続が復活した") callback() } } } } registerReceiver(receiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) return receiver } /** * バージョン名取得 */ fun Context.getVersionName(): String { val pm = this.packageManager try { val packageInfo = pm.getPackageInfo(this.packageName, 0) return packageInfo.versionName } catch (e: Exception) { Log.e("Context", "not found version name", e) return "" } } fun List<Post>.lastNonAdId(): Long? { return findLast { it !is AdPost }?.id } fun AdRequest.Builder.configureForTest() { val deviceId = if (BuildConfig.ADMOB_TESTDEVICE.isEmpty()) { AdRequest.DEVICE_ID_EMULATOR } else { BuildConfig.ADMOB_TESTDEVICE } addTestDevice(deviceId) }
gpl-3.0
15cb350305e40ea69dd7e6f83596fb9a
31.399038
132
0.591779
4.037747
false
false
false
false
ademar111190/Studies
Projects/Reddit/app/src/main/java/ademar/study/reddit/view/home/HomeActivity.kt
1
4015
package ademar.study.reddit.view.home import ademar.study.reddit.R import ademar.study.reddit.injection.LifeCycleModule import ademar.study.reddit.model.ErrorViewModel import ademar.study.reddit.model.home.PostViewModel import ademar.study.reddit.plataform.ext.inflate import ademar.study.reddit.presenter.home.HomePresenter import ademar.study.reddit.presenter.home.HomeView import ademar.study.reddit.view.base.BaseActivity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import com.github.ybq.endless.Endless import kotlinx.android.synthetic.main.home_activity.* import kotlinx.android.synthetic.main.load_item.view.* import javax.inject.Inject class HomeActivity : BaseActivity(), HomeView { @Inject lateinit var presenter: HomePresenter @Inject lateinit var adapter: PostAdapter private lateinit var endless: Endless private var loadView: View? = null override fun makeLifeCycleModule(): LifeCycleModule { return LifeCycleModule(getBaseActivity()) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.home_activity) prepareTaskDescription() component.inject(this) presenter.onAttachView(this) toolbar.inflateMenu(R.menu.home) toolbar.setOnMenuItemClickListener { menu -> val isReload = menu.itemId == R.id.refresh if (isReload) { presenter.onReloadClick() } isReload } reload.setOnClickListener { presenter.onReloadClick() } list.layoutManager = LinearLayoutManager(this) adapter.listener = { link -> presenter.onLinkClicked(link) } list.adapter = adapter loadView = list.inflate(R.layout.load_item) loadView?.retry?.setOnClickListener { presenter.onPreviousPageClick() } endless = Endless.applyTo(list, loadView) endless.setLoadMoreListener { presenter.onPreviousPageClick() } presenter.onStart() } override fun onDestroy() { super.onDestroy() presenter.onDetachView() } override fun showLoading() { list.visibility = GONE load.visibility = VISIBLE reload.visibility = GONE } override fun showRetry() { list.visibility = GONE load.visibility = GONE reload.visibility = VISIBLE } override fun showContent() { list.visibility = VISIBLE load.visibility = GONE reload.visibility = GONE } override fun clearPosts() { adapter.posts.clear() adapter.notifyDataSetChanged() } override fun bindPost(viewModel: PostViewModel) { endless.loadMoreComplete() adapter.posts.add(viewModel) adapter.notifyItemInserted(adapter.posts.size - 1) } override fun showUnloadedPosts() { endless.isLoadMoreAvailable = true } override fun hideUnloadedPosts() { endless.isLoadMoreAvailable = false } override fun showUnloadedError(viewModel: ErrorViewModel) { loadView?.let { loadView -> loadView.text.text = viewModel.message loadView.load.visibility = GONE loadView.text.visibility = VISIBLE loadView.retry.visibility = VISIBLE } } override fun hideUnloadedError() { loadView?.let { loadView -> loadView.load.visibility = VISIBLE loadView.text.visibility = GONE loadView.retry.visibility = GONE } } companion object { fun populateIntent(intent: Intent, context: Context): Intent { intent.setClassName(context, HomeActivity::class.java.name) return intent } } }
mit
95ba6f3e3075a7e1161ae80007d8e0d1
27.076923
71
0.662765
4.73467
false
false
false
false
trinhlbk1991/vivid
library/src/main/java/com/icetea09/vivid/adapter/FolderPickerAdapter.kt
1
2194
package com.icetea09.vivid.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.icetea09.vivid.GlideApp import com.icetea09.vivid.R import com.icetea09.vivid.model.Folder class FolderPickerAdapter(private val context: Context, private val folderClickListener: FolderPickerAdapter.OnFolderClickListener?) : RecyclerView.Adapter<FolderPickerAdapter.FolderViewHolder>() { private val inflater: LayoutInflater = LayoutInflater.from(this.context) private var folders: List<Folder>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FolderViewHolder { val itemView = inflater.inflate(R.layout.imagepicker_item_folder, parent, false) return FolderViewHolder(itemView) } override fun onBindViewHolder(holder: FolderViewHolder, position: Int) { val folder = folders?.get(position) folder?.let { GlideApp.with(context) .load(folder.images[0].path) .placeholder(R.drawable.folder_placeholder) .error(R.drawable.folder_placeholder) .into(holder.image) holder.name.text = folder.folderName holder.number.text = folder.images.size.toString() holder.itemView.setOnClickListener { folderClickListener?.onFolderClick(folder) } } } fun setData(folders: List<Folder>) { this.folders = folders notifyDataSetChanged() } override fun getItemCount(): Int { return folders?.let { (folders as List<Folder>).size } ?: 0 } class FolderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal val image: ImageView = itemView.findViewById(R.id.image) internal val name: TextView = itemView.findViewById(R.id.tv_name) internal val number: TextView = itemView.findViewById(R.id.tv_number) } interface OnFolderClickListener { fun onFolderClick(folder: Folder) } }
mit
ff0ddf94c2a1ff794481df4b65915357
33.825397
132
0.691431
4.523711
false
false
false
false
henrikfroehling/timekeeper
storage/src/main/kotlin/de/froehling/henrik/timekeeper/storage/local/LocalLocationsRepository.kt
1
2735
package de.froehling.henrik.timekeeper.storage.local import de.froehling.henrik.timekeeper.domain.repository.ILocationsRepository import de.froehling.henrik.timekeeper.models.Location import de.froehling.henrik.timekeeper.models.Project import de.froehling.henrik.timekeeper.models.Task import io.realm.Realm import io.realm.RealmAsyncTask import io.realm.Sort import rx.Observable class LocalLocationsRepository(private val realm: Realm) : ILocationsRepository { override fun getLocationsFilteredByName(ascending: Boolean): Observable<List<Location>> { val locations = realm.where(Location::class.java) .findAllSortedAsync("name", if (ascending) Sort.ASCENDING else Sort.DESCENDING) return locations.asObservable().filter { it.isLoaded }.map { it.toList() } } override fun getLocationsFilteredByCreated(ascending: Boolean): Observable<List<Location>> { val locations = realm.where(Location::class.java) .findAllSortedAsync("created", if (ascending) Sort.ASCENDING else Sort.DESCENDING) return locations.asObservable().filter { it.isLoaded }.map { it.toList() } } override fun getLocationDetails(locationID: String): Observable<Location> { return realm.where(Location::class.java).equalTo("uuid", locationID) .findFirstAsync().asObservable() } override fun getLocationProjects(locationID: String): Observable<List<Project>> { val projects = realm.where(Project::class.java).equalTo("location.uuid", locationID) .findAllAsync() return projects.asObservable().filter { it.isLoaded }.map { it.toList() } } override fun getLocationTasks(locationID: String): Observable<List<Task>> { val tasks = realm.where(Task::class.java).equalTo("location.uuid", locationID) .findAllAsync() return tasks.asObservable().filter { it.isLoaded }.map { it.toList() } } override fun getAll(): Observable<List<Location>> = getLocationsFilteredByName(true) override fun create(obj: Location): Observable<RealmAsyncTask> { return Observable.just( realm.executeTransaction({ realm -> realm.copyToRealmOrUpdate(obj) }, null) ) } override fun update(obj: Location): Observable<RealmAsyncTask> { return create(obj) } override fun delete(uuid: String): Observable<RealmAsyncTask> { return Observable.just( realm.executeTransaction({ realm -> val location = realm.where(Location::class.java).equalTo("uuid", uuid).findFirst() location.removeFromRealm() }, null) ) } }
gpl-3.0
47137cdb7180f073749ca84d0142d652
38.637681
102
0.676051
4.513201
false
false
false
false
rsiebert/TVHClient
data/src/main/java/org/tvheadend/data/source/ServerStatusDataSource.kt
1
3438
package org.tvheadend.data.source import androidx.lifecycle.LiveData import androidx.lifecycle.Transformations import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.tvheadend.data.db.AppRoomDatabase import org.tvheadend.data.entity.ServerStatus import org.tvheadend.data.entity.ServerStatusEntity import timber.log.Timber import java.util.* class ServerStatusDataSource(private val db: AppRoomDatabase) : DataSourceInterface<ServerStatus> { private val ioScope = CoroutineScope(Dispatchers.IO) val liveDataActiveItem: LiveData<ServerStatus> get() = Transformations.map(db.serverStatusDao.loadActiveServerStatus()) { entity -> Timber.d("Loading active server status as live data is null ${entity == null}") entity?.toServerStatus() ?: activeItem } val activeItem: ServerStatus get() { var serverStatus = ServerStatus() runBlocking(Dispatchers.IO) { val newServerStatus = db.serverStatusDao.loadActiveServerStatusSync() if (newServerStatus == null) { Timber.d("Active server status is null") val connection = db.connectionDao.loadActiveConnectionSync() serverStatus.serverName = "Unknown" serverStatus.serverVersion = "Unknown" if (connection != null) { Timber.d("Loaded active connection for empty server status") serverStatus.connectionId = connection.id serverStatus.connectionName = connection.name Timber.d("Inserting new server status information for connection ${connection.name}") db.serverStatusDao.insert(ServerStatusEntity.from(serverStatus)) } } else { serverStatus = newServerStatus.toServerStatus() } } return serverStatus } override fun addItem(item: ServerStatus) { ioScope.launch { db.serverStatusDao.insert(ServerStatusEntity.from(item)) } } override fun updateItem(item: ServerStatus) { ioScope.launch { db.serverStatusDao.update(ServerStatusEntity.from(item)) } } override fun removeItem(item: ServerStatus) { ioScope.launch { db.serverStatusDao.delete(ServerStatusEntity.from(item)) } } override fun getLiveDataItemCount(): LiveData<Int> { return db.serverStatusDao.serverStatusCount } override fun getLiveDataItems(): LiveData<List<ServerStatus>> { return Transformations.map(db.serverStatusDao.loadAllServerStatus()) { entities -> entities.map { it.toServerStatus() } } } override fun getLiveDataItemById(id: Any): LiveData<ServerStatus> { return Transformations.map(db.serverStatusDao.loadServerStatusById(id as Int)) { entity -> entity.toServerStatus() } } override fun getItemById(id: Any): ServerStatus? { var serverStatus: ServerStatus? runBlocking(Dispatchers.IO) { serverStatus = db.serverStatusDao.loadServerStatusByIdSync(id as Int)?.toServerStatus() } return serverStatus } override fun getItems(): List<ServerStatus> { return ArrayList() } }
gpl-3.0
ff0dd245a26da5c7c9bbcc4604426c64
38.068182
109
0.655614
5.162162
false
false
false
false
blakelee/CoinProfits
app/src/main/java/net/blakelee/coinprofits/base/BaseAdapter.kt
1
964
package net.blakelee.coinprofits.base import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup abstract class BaseAdapter<D, VH : BaseViewHolder<D>> : RecyclerView.Adapter<VH>() { var dataSource: List<D> = emptyList() set(value) { field = value notifyDataSetChanged() } override fun getItemCount() = dataSource.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): VH { val inflater = LayoutInflater.from(parent?.context) val view = inflater.inflate(getItemViewId(), parent, false) return instantiateViewHolder(view) } abstract fun getItemViewId() : Int abstract fun instantiateViewHolder(view: View?): VH override fun onBindViewHolder(holder: VH, position: Int) { holder.onBind(getItem(position)) } fun getItem(position: Int) = dataSource[position] }
mit
f19c3717754f0097a02d21ca1ecbea7b
30.129032
84
0.698133
4.61244
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/AccountManagerParser.kt
2
3857
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2021 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.util.Log import android.util.Xml import edu.berkeley.boinc.utils.Logging import org.xml.sax.Attributes import org.xml.sax.SAXException class AccountManagerParser : BaseParser() { val accountManagerInfos: MutableList<AccountManager> = mutableListOf() private var mAcctMgrInfo: AccountManager? = null @Throws(SAXException::class) override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) { super.startElement(uri, localName, qName, attributes) if (localName.equals(ACCOUNT_MANAGER, ignoreCase = true)) { mAcctMgrInfo = AccountManager() } else { mElementStarted = true mCurrentElement.setLength(0) } } @Throws(SAXException::class) override fun endElement(uri: String?, localName: String, qName: String?) { super.endElement(uri, localName, qName) try { if (mAcctMgrInfo != null) { // inside <acct_mgr_info> // Closing tag of <account_manager> - add to list and be ready for next one if (localName.equals(ACCOUNT_MANAGER, ignoreCase = true)) { if (mAcctMgrInfo!!.name.isNotEmpty()) { // name is a must accountManagerInfos.add(mAcctMgrInfo!!) } mAcctMgrInfo = null } else { // Not the closing tag - we decode possible inner tags trimEnd() when { localName.equals(NAME, ignoreCase = true) -> { //project name mAcctMgrInfo!!.name = mCurrentElement.toString() } localName.equals(URL, ignoreCase = true) -> { mAcctMgrInfo!!.url = mCurrentElement.toString() } localName.equals(DESCRIPTION, ignoreCase = true) -> { mAcctMgrInfo!!.description = mCurrentElement.toString() } localName.equals(IMAGE_TAG, ignoreCase = true) -> { mAcctMgrInfo!!.imageUrl = mCurrentElement.toString() } } } } } catch (e: Exception) { Logging.logException(Logging.Category.XML, "AccountManagerParser.endElement error: ", e) } mElementStarted = false } companion object { const val IMAGE_TAG = "image" @JvmStatic fun parse(rpcResult: String?): List<AccountManager> { return try { val parser = AccountManagerParser() Xml.parse(rpcResult, parser) parser.accountManagerInfos } catch (e: SAXException) { Logging.logException(Logging.Category.RPC, "AccountManagerParser: malformed XML ", e) Logging.logDebug(Logging.Category.XML, "AccountManagerParser: $rpcResult") emptyList() } } } }
lgpl-3.0
d1d80831925e1cc34471ce3feef723ac
40.473118
105
0.587503
4.863808
false
false
false
false
kotlin-graphics/uno-sdk
core/src/main/kotlin/uno/kotlin/util.kt
1
2210
package uno.kotlin import glm_.i import java.awt.event.KeyEvent import java.io.File import java.nio.IntBuffer import java.util.* import kotlin.reflect.KMutableProperty0 import kotlin.reflect.KProperty /** * Created by GBarbieri on 30.03.2017. */ infix fun <T> (() -> Any).shallThrow(exClass: Class<T>) { try { this() } catch (e: Throwable) { if (exClass.isInstance(e)) return else throw Error("Exception type different") } throw Error("No exception") } val String.uri get() = url.toURI()!! val String.url get() = ClassLoader.getSystemResource(this)!! val String.stream get() = ClassLoader.getSystemResourceAsStream(this)!! val String.file get() = File(uri) val Char.isPrintable: Boolean get() = with(Character.UnicodeBlock.of(this)) { (!Character.isISOControl(this@isPrintable)) && this@isPrintable != KeyEvent.CHAR_UNDEFINED && this != null && this != Character.UnicodeBlock.SPECIALS } fun Char.parseInt() = java.lang.Character.getNumericValue(this) operator fun <K> HashSet<K>.plusAssign(element: K) { add(element) } operator fun <K> HashSet<K>.minusAssign(element: K) { remove(element) } infix operator fun Appendable.plusAssign(char: Char) { append(char) } infix operator fun Appendable.plusAssign(charSequence: CharSequence) { append(charSequence) } infix operator fun <T>StringBuilder.plusAssign(element: T) { append(element) } fun <T> treeSetOf() = TreeSet<T>() fun <K, V> SortedMap<K, V>.getOrfirst(key: K): V? = get(key) ?: first val <K, V>SortedMap<K, V>.first: V? get() = get(firstKey()) operator fun <R> KMutableProperty0<R>.setValue(host: Any?, property: KProperty<*>, value: R) = set(value) operator fun <R> KMutableProperty0<R>.getValue(host: Any?, property: KProperty<*>): R = get() operator fun <T> KMutableProperty0<T>.invoke(t: T): KMutableProperty0<T> { set(t) return this } operator fun IntBuffer.plusAssign(bool: Boolean) = plusAssign(bool.i) operator fun IntBuffer.plusAssign(i: Int) { put(i) } const val NUL = '\u0000' val isNotCI: Boolean get() = System.getenv("GITHUB_ACTIONS") != "true" && System.getenv("TRAVIS") != "true"
mit
6033da4976e8e974aa34e2ffc22aab15
26.296296
105
0.676471
3.46395
false
false
false
false
d9n/intellij-rust
src/test/kotlin/org/rust/lang/core/parser/RsPartialParsingTestCase.kt
1
1217
package org.rust.lang.core.parser import com.intellij.psi.PsiFile import org.assertj.core.api.Assertions.assertThat /** * Tests parser recovery (`pin` and `recoverWhile` attributes from `rust.bnf`) * by constructing PSI trees from syntactically invalid files. */ class RsPartialParsingTestCase : RsParsingTestCaseBase("partial") { fun testFn() = doTest(true) fun testUseItem() = doTest(true) fun testShifts() = doTest(true) fun testStructPat() = doTest(true) fun testStructDef() = doTest(true) fun testEnumVis() = doTest(true) fun testImplBody() = doTest(true) fun testTraitBody() = doTest(true) fun testMatchExpr() = doTest(true) fun testStructExprFields() = doTest(true) fun testHrtbForLifetimes() = doTest(true) fun testNoLifetimeBoundsInGenericArgs() = doTest(true) fun testRequireCommas() = doTest(true) override fun checkResult(targetDataName: String?, file: PsiFile) { checkHasError(file) super.checkResult(targetDataName, file) } private fun checkHasError(file: PsiFile) { assertThat(hasError(file)) .withFailMessage("Invalid file was parsed successfully: ${file.name}") .isTrue() } }
mit
8c1fc98d0118861080eca9c658ac30de
32.805556
82
0.695152
4.016502
false
true
false
false
chimbori/crux
src/main/kotlin/com/chimbori/crux/extractors/ImageHelpers.kt
1
1810
package com.chimbori.crux.extractors import com.chimbori.crux.articles.Article import com.chimbori.crux.common.Log import com.chimbori.crux.common.isAdImage import okhttp3.HttpUrl import org.jsoup.nodes.Element import org.jsoup.select.Elements /** * Extracts a set of images from the article content itself. This extraction must be run before * the postprocess step, because that step removes tags that are useful for image extraction. */ internal fun extractImages(baseUrl: HttpUrl, topNode: Element?): List<Article.Image> { val images = mutableListOf<Article.Image>() if (topNode == null) { return images } val imgElements: Elements = when { topNode.select("img").isEmpty() && topNode.parent() != null -> topNode.parent()!!.select("img") else -> topNode.select("img") } var maxWeight = 0 var score = 1.0 for (imgElement in imgElements) { val image = Article.Image.from(baseUrl, imgElement) if (image.srcUrl == null || image.srcUrl?.isAdImage() == true) { continue } image.weight += if (image.height >= 50) 20 else -20 image.weight += if (image.width >= 50) 20 else -20 image.weight += if (image.srcUrl?.scheme == "data") -50 else 0 image.weight += if (image.srcUrl?.encodedPath?.endsWith(".gif") == true) -20 else 0 image.weight += if (image.srcUrl?.encodedPath?.endsWith(".jpg") == true) 5 else 0 image.weight += if ((image.alt?.length ?: 0) > 35) 20 else 0 image.weight += if ((image.title?.length ?: 0) > 35) 20 else 0 image.weight += if (image.noFollow) -40 else 0 image.weight = (image.weight * score).toInt() if (image.weight > maxWeight) { maxWeight = image.weight score = score / 2 } images.add(image) } Log.i("images: %s", images) return images.sortedByDescending { it.weight } }
apache-2.0
963a1eb13bafa9f3f02f07d4bedd03e1
35.938776
99
0.672376
3.612774
false
false
false
false
KyuBlade/kotlin-discord-bot
src/main/kotlin/com/omega/discord/bot/command/CommandHandler.kt
1
2079
package com.omega.discord.bot.command import com.omega.discord.bot.BotManager import com.omega.discord.bot.ext.getNameAndDiscriminator import com.omega.discord.bot.permission.Permission import com.omega.discord.bot.permission.PermissionManager import org.slf4j.Logger import org.slf4j.LoggerFactory import sx.blah.discord.handle.impl.obj.ReactionEmoji import sx.blah.discord.handle.obj.IMessage import sx.blah.discord.util.RequestBuffer import java.lang.Exception object CommandHandler { private val LOGGER: Logger = LoggerFactory.getLogger(CommandHandler.javaClass) fun handle(commandName: String, message: IMessage) { val command: Command? = CommandRegistry.get(commandName) if (command == null) { LOGGER.info("Command $commandName not found") RequestBuffer.request { message.addReaction(ReactionEmoji.of("⁉")) } } else { val permission: Permission? = command.permission if (permission == null || message.author == BotManager.applicationOwner || PermissionManager.getPermissions(message.guild, message.author).has(permission)) { if (!command.allowPrivate && message.channel.isPrivate) { RequestBuffer.request { message.addReaction(ReactionEmoji.of("\uD83D\uDEB7")) } } else { try { command.execute(message.author, message.channel, message, message.content.split(' ').drop(1)) } catch (e: Exception) { LOGGER.warn("Command execution failed", e) RequestBuffer.request { message.addReaction(ReactionEmoji.of("\uD83C\uDD98")) } } } } else {// No permission LOGGER.info("User ${message.author.getNameAndDiscriminator()} doesn't have permission ${command.permission} to run command $commandName") RequestBuffer.request { message.addReaction(ReactionEmoji.of("⛔")) } } } } }
gpl-3.0
170560130c4663bdc51b8524b81ac427
44.130435
153
0.635181
4.631696
false
false
false
false
JavaProphet/JASM
src/main/java/com/protryon/jasm/Method.kt
1
2297
package com.protryon.jasm import com.protryon.jasm.instruction.Instruction import com.protryon.jasm.instruction.psuedoinstructions.CatchLabel import com.protryon.jasm.instruction.psuedoinstructions.Label import java.util.ArrayList import java.util.LinkedHashMap import java.util.LinkedList class Method(val parent: Klass, var name: String, var descriptor: MethodDescriptor) { var isPublic = false var isPrivate = false var isProtected = false var isStatic = false var isFinal = false var isSynchronized = false var isBridge = false var isVarargs = false var isNative = false var isAbstract = false var isStrict = false var isSynthetic = false // set for created methods in things like stdlib or unincluded libs var isDummy = false var tempVariableCounter = 0 var code = LinkedList<Instruction>() var labels = LinkedHashMap<String, Label>() fun getOrMakeLabel(name: String): Label { if (labels.containsKey(name)) { return labels[name]!! } val label = Label(name) labels[name] = label return label } fun makeCatch(name: String): CatchLabel { if (labels.containsKey(name)) { return labels[name] as CatchLabel } val label = CatchLabel(name) labels[name] = label return label } override fun toString(): String { val sb = StringBuilder() if (this.isPublic) { sb.append("public ") } if (this.isPrivate) { sb.append("private ") } if (this.isProtected) { sb.append("protected ") } if (this.isStatic) { sb.append("static ") } if (this.isFinal) { sb.append("final ") } if (this.isSynchronized) { sb.append("synchronized ") } if (this.isNative) { sb.append("native ") } if (this.isAbstract) { sb.append("abstract ") } sb.append(this.descriptor.niceString(this.name)).append(" {\n") for (instruction in this.code) { sb.append(" ").append(instruction.toString()).append("\n") } sb.append("}\n") return sb.toString() } }
gpl-3.0
4809a9ec94ab9c7aaf04424a9a25e5bb
26.023529
85
0.588158
4.358634
false
false
false
false
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/donate/DonateActivity.kt
1
7105
package de.saschahlusiak.freebloks.donate import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.MenuItem import android.view.animation.* import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.interpolator.view.animation.FastOutSlowInInterpolator import dagger.hilt.android.AndroidEntryPoint import de.saschahlusiak.freebloks.Global import de.saschahlusiak.freebloks.databinding.DonateActivityBinding import de.saschahlusiak.freebloks.utils.AnalyticsProvider import de.saschahlusiak.freebloks.utils.toPixel import de.saschahlusiak.freebloks.utils.viewBinding import javax.inject.Inject @AndroidEntryPoint class DonateActivity : AppCompatActivity() { private val binding by viewBinding(DonateActivityBinding::inflate) @Inject lateinit var analytics: AnalyticsProvider override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) analytics.logEvent("donate_show", null) supportActionBar?.setDisplayHomeAsUpEnabled(true) with(binding) { donationFreebloksVip.setOnClickListener { onFreebloksVIPClick() } donationPaypal.setOnClickListener { onPayPalClick() } donationLitecoin.setOnClickListener { onLitecoinClick() } if (Global.IS_GOOGLE) { // Google does not allow to pay with any other payment provider, so we fast track to // FreebloksVIP. donateThankYou.isVisible = true donationsGroup.isVisible = true donationPaypal.isVisible = false donationLitecoin.isVisible = false donateButtonGroup.isVisible = false next.setOnClickListener { onFreebloksVIPClick() } skip.setOnClickListener { onSkipButtonPress() } } else { next.setOnClickListener { onYesButtonPress() } skip.setOnClickListener { onSkipButtonPress() } } if (savedInstanceState == null) { donateIcon.scaleX = 0.0f donateIcon.scaleY = 0.0f donateIcon.animate() .setStartDelay(200) .setDuration(1100) .setInterpolator(OvershootInterpolator()) .scaleX(1.0f) .scaleY(1.0f) .start() donateQuestion.alpha = 0.0f donateQuestion.translationY = (-16.0f).toPixel(this@DonateActivity) donateQuestion.animate() .setStartDelay(700) .setDuration(800) .setInterpolator(FastOutSlowInInterpolator()) .alpha(1.0f) .translationY(0.0f) .start() donateButtonGroup.alpha = 0.0f donateButtonGroup.translationY = (-16.0f).toPixel(this@DonateActivity) donateButtonGroup.animate() .setStartDelay(750) .setDuration(800) .setInterpolator(FastOutSlowInInterpolator()) .alpha(1.0f) .translationY(0.0f) .start() if (Global.IS_GOOGLE) { donationsGroup.alpha = 0.0f donationsGroup.animate() .setStartDelay(1300) .setDuration(2500) .setInterpolator(FastOutSlowInInterpolator()) .alpha(1.0f) .start() donateThankYou.alpha = 0.0f donateThankYou.animate() .setStartDelay(1300) .setDuration(2500) .setInterpolator(FastOutSlowInInterpolator()) .alpha(1.0f) .start() } } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } } private fun onYesButtonPress() { analytics.logEvent("donate_yes", null) with(binding) { block1.isVisible = false donateButtonGroup.isVisible = false donationsGroup.isVisible = true donateThankYou.isVisible = true } } private fun onSkipButtonPress() { analytics.logEvent("donate_skip", null) finish() } private fun onFreebloksVIPClick() { analytics.logEvent("donate_freebloksvip", null) startActivity(freebloksVipIntent) } private fun onBitcoinClick() { analytics.logEvent("donate_bitcoin", null) try { startActivity(bitcoinIntent) } catch (e: Exception) { startActivity(bitcoinFallbackIntent) } } private fun onLitecoinClick() { analytics.logEvent("donate_litecoin", null) try { startActivity(litecoinIntent) } catch (e: Exception) { startActivity(litecoinFallbackIntent) } } private fun onPayPalClick() { analytics.logEvent("donate_paypal", null) startActivity(paypalIntent) } internal val bitcoinIntent get() = Intent(Intent.ACTION_VIEW, Uri.parse(URL_BITCOIN)) internal val bitcoinFallbackIntent get() = Intent(Intent.ACTION_VIEW, Uri.parse(URL_BITCOIN_EXPLORER)) internal val litecoinIntent get() = Intent(Intent.ACTION_VIEW, Uri.parse(URL_LITECOIN)) internal val litecoinFallbackIntent get() = Intent(Intent.ACTION_VIEW, Uri.parse(URL_LITECOIN_EXPLORER)) internal val freebloksVipIntent get() = Intent(Intent.ACTION_VIEW, Uri.parse(URL_FREEBLOKS_VIP)) internal val paypalIntent get() = Intent(Intent.ACTION_VIEW, Uri.parse(URL_PAYPAL)) companion object { // F-Droid does not have a Freebloks VIP, so redirect the user to the Google Play Store. private val URL_FREEBLOKS_VIP = if (Global.IS_FDROID) "https://play.google.com/store/apps/details?id=de.saschahlusiak.freebloksvip" else Global.getMarketURLString("de.saschahlusiak.freebloksvip") private const val URL_PAYPAL = "https://paypal.me/saschahlusiak/3eur" private const val BITCOIN_WALLET_ADDRESS = "bc1qdgm2zvlc6qzqh8qs44wv8l622tfrhvkjqn0fkl" private const val LITECOIN_WALLET_ADDRESS = "Lh3YTC7Tv4edEe48kHMbyhgE6BNH22bqBt" private const val URL_BITCOIN = "bitcoin:$BITCOIN_WALLET_ADDRESS?amount=0.0002" private const val URL_BITCOIN_EXPLORER = "https://www.blockchain.com/btc/address/$BITCOIN_WALLET_ADDRESS" private const val URL_LITECOIN = "litecoin:$LITECOIN_WALLET_ADDRESS?amount=0.005" private const val URL_LITECOIN_EXPLORER = "https://www.blockchain.com/ltc/address/$LITECOIN_WALLET_ADDRESS" } }
gpl-2.0
fc97925a7ce6bb12ac8b9979bfe60291
37
115
0.60943
4.634703
false
false
false
false
Jasper-Hilven/dynamic-extensions-for-alfresco
alfresco-integration/src/main/kotlin/com/github/dynamicextensionsalfresco/osgi/FileExtensions.kt
1
1501
package com.github.dynamicextensionsalfresco.osgi import aQute.bnd.osgi.Analyzer import java.io.File import java.io.InputStream import java.util.jar.Attributes import java.util.jar.JarFile fun File.jarAttributes(): Attributes { val jarFile = JarFile(this) try { val manifest = jarFile.manifest return manifest.mainAttributes } finally { jarFile.close() } } fun InputStream.toTempFile(prefix: String, suffix: String): File { this.use { iStream -> val tempFile = File.createTempFile(prefix, suffix) tempFile.deleteOnExit() tempFile.outputStream().use { iStream.copyTo(it) } return tempFile } } fun File.convertToBundle(fileName: String): File { val jar = JarFile(this) val analyzer = Analyzer() val manifestVersion = ManifestUtils.getImplementationVersion(jar) if (manifestVersion != null) { analyzer.bundleVersion = manifestVersion } var name = ManifestUtils.getImplementationTitle(jar) if (name == null) { name = fileName.replaceFirst("^(.+)\\.\\w+$".toRegex(), "$1") } analyzer.setBundleSymbolicName(name) analyzer.setJar(this) analyzer.setImportPackage("*;resolution:=optional") analyzer.setExportPackage("*") analyzer.analyze() val manifest = analyzer.calcManifest() analyzer.jar.manifest = manifest val wrappedTempFile = File.createTempFile("bundled", ".jar") analyzer.save(wrappedTempFile, true) return wrappedTempFile }
apache-2.0
53162fed920d38adc7b563ab4f56df48
27.339623
69
0.688874
4.252125
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/DataImportActivity.kt
1
6905
/* * 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.activity import android.content.Intent import android.os.AsyncTask import android.os.Bundle import android.support.v4.app.DialogFragment import android.util.Log import org.mariotaku.ktextension.dismissDialogFragment import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.fragment.DataExportImportTypeSelectorDialogFragment import de.vanita5.twittnuker.fragment.ProgressDialogFragment import de.vanita5.twittnuker.util.DataImportExportUtils import java.io.File import java.io.IOException class DataImportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFragment.Callback { private var importSettingsTask: ImportSettingsTask? = null private var openImportTypeTask: OpenImportTypeTask? = null private var resumeFragmentsRunnable: Runnable? = null override fun onCancelled(df: DialogFragment) { if (!isFinishing) { finish() } } override fun onDismissed(df: DialogFragment) { if (df is DataExportImportTypeSelectorDialogFragment) { finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_PICK_FILE -> { resumeFragmentsRunnable = Runnable { if (resultCode == RESULT_OK && data != null) { val path = data.data.path if (openImportTypeTask == null || openImportTypeTask!!.status != AsyncTask.Status.RUNNING) { openImportTypeTask = OpenImportTypeTask(this@DataImportActivity, path) openImportTypeTask!!.execute() } } else { if (!isFinishing) { finish() } } } return } } super.onActivityResult(requestCode, resultCode, data) } override fun onResumeFragments() { super.onResumeFragments() if (resumeFragmentsRunnable != null) { resumeFragmentsRunnable!!.run() } } override fun onPositiveButtonClicked(path: String?, flags: Int) { if (path == null || flags == 0) { finish() return } if (importSettingsTask == null || importSettingsTask!!.status != AsyncTask.Status.RUNNING) { importSettingsTask = ImportSettingsTask(this, path, flags) importSettingsTask!!.execute() } } override fun onStart() { super.onStart() setVisible(true) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { val intent = Intent(this, FileSelectorActivity::class.java) intent.action = INTENT_ACTION_PICK_FILE startActivityForResult(intent, REQUEST_PICK_FILE) } } internal class ImportSettingsTask( private val activity: DataImportActivity, private val path: String?, private val flags: Int ) : AsyncTask<Any, Any, Boolean>() { override fun doInBackground(vararg params: Any): Boolean? { if (path == null) return false val file = File(path) if (!file.isFile) return false try { DataImportExportUtils.importData(activity, file, flags) return true } catch (e: IOException) { Log.w(LOGTAG, e) return false } } override fun onPostExecute(result: Boolean?) { activity.executeAfterFragmentResumed { activity -> activity.supportFragmentManager.dismissDialogFragment(FRAGMENT_TAG) } if (result != null && result) { activity.setResult(RESULT_OK) } else { activity.setResult(RESULT_CANCELED) } activity.finish() } override fun onPreExecute() { activity.executeAfterFragmentResumed { ProgressDialogFragment.show(it.supportFragmentManager, FRAGMENT_TAG).isCancelable = false } } companion object { private val FRAGMENT_TAG = "import_settings_dialog" } } internal class OpenImportTypeTask(private val activity: DataImportActivity, private val path: String?) : AsyncTask<Any, Any, Int>() { override fun doInBackground(vararg params: Any): Int? { if (path == null) return 0 val file = File(path) if (!file.isFile) return 0 try { return DataImportExportUtils.getImportedSettingsFlags(file) } catch (e: IOException) { return 0 } } override fun onPostExecute(flags: Int?) { activity.executeAfterFragmentResumed { activity -> activity.supportFragmentManager.dismissDialogFragment(FRAGMENT_TAG) } val df = DataExportImportTypeSelectorDialogFragment() val args = Bundle() args.putString(EXTRA_PATH, path) args.putString(EXTRA_TITLE, activity.getString(R.string.import_settings_type_dialog_title)) if (flags != null) { args.putInt(EXTRA_FLAGS, flags) } else { args.putInt(EXTRA_FLAGS, 0) } df.arguments = args df.show(activity.supportFragmentManager, "select_import_type") } override fun onPreExecute() { activity.executeAfterFragmentResumed { ProgressDialogFragment.show(it.supportFragmentManager, FRAGMENT_TAG).isCancelable = false } } companion object { private val FRAGMENT_TAG = "read_settings_data_dialog" } } }
gpl-3.0
37f0707e2aebff2db88d934fc19f37e3
33.53
137
0.607386
4.989162
false
false
false
false
ice1000/OI-codes
codewars/authoring/kotlin/ParseMolecule.kt
1
1970
import java.util.* import java.util.regex.* private lateinit var tokenIter: Iterator<String> private lateinit var bracketStk: Stack<Int> private val AT_NUM = "[A-Z][a-z]?\\d*" private val OPEN_BRA = "[{(\\[]" private val CLOSE_BRA = "[)}\\]]\\d*" private val TOKENIZER = Pattern.compile(String.format("%s|%s|%s", AT_NUM, OPEN_BRA, CLOSE_BRA)) private val P_AT_NUM = Pattern.compile("(?<at>[A-Z][a-z]*)(?<num>\\d*)") private val rawFormula: RawForm get() { val raw = RawForm() while (tokenIter.hasNext()) { val tok = tokenIter.next() if (tok.matches(OPEN_BRA.toRegex())) { bracketStk.push(tok[0].toInt()) raw.concatWith(rawFormula) } else if (tok.matches(AT_NUM.toRegex())) { val m = P_AT_NUM.matcher(tok) m.find() raw.addAtom(m.group("at"), if (m.group("num").isEmpty()) 1 else Integer.parseInt(m.group("num"))) } else if (tok.matches(CLOSE_BRA.toRegex())) { if (bracketStk.empty() || bracketStk.peek() + 1 != tok[0].toInt() && bracketStk.peek() + 2 != tok[0].toInt()) throw IllegalArgumentException("Invalid formula") bracketStk.pop() if (tok.length > 1) raw.mulBy(Integer.parseInt(tok.substring(1))) break } } return raw } fun getAtoms(formula: String): Map<String, Int> { val tokens = ArrayList<String>() val m = TOKENIZER.matcher(formula) while (m.find()) tokens.add(m.group()) if (tokens.joinToString("") != formula) throw IllegalArgumentException("Invalid formula") bracketStk = Stack() tokenIter = tokens.iterator() val ans = rawFormula if (!bracketStk.empty()) throw IllegalArgumentException("Invalid formula") return ans } internal class RawForm : HashMap<String, Int>() { fun addAtom(atom: String, n: Int) { this[atom] = n + getOrDefault(atom, 0) } fun mulBy(n: Int): RawForm { this.forEach { at, v -> this[at] = v * n } return this } fun concatWith(other: RawForm): RawForm { other.forEach { at, v -> this[at] = v + getOrDefault(at, 0) } return this } }
agpl-3.0
80df60e687b4b451c350c02456ff23e9
27.550725
113
0.650761
2.927192
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sensors/modules/AccelerometerModule.kt
2
1899
// Copyright 2015-present 650 Industries. All rights reserved. package abi43_0_0.expo.modules.sensors.modules import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorManager import android.os.Bundle import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface import abi43_0_0.expo.modules.interfaces.sensors.services.AccelerometerServiceInterface import abi43_0_0.expo.modules.core.Promise import abi43_0_0.expo.modules.core.interfaces.ExpoMethod class AccelerometerModule(reactContext: Context?) : BaseSensorModule(reactContext) { override val eventName: String = "accelerometerDidUpdate" override fun getName(): String = "ExponentAccelerometer" override fun getSensorService(): SensorServiceInterface { return moduleRegistry.getModule(AccelerometerServiceInterface::class.java) } override fun eventToMap(sensorEvent: SensorEvent): Bundle { return Bundle().apply { putDouble("x", (sensorEvent.values[0] / SensorManager.GRAVITY_EARTH).toDouble()) putDouble("y", (sensorEvent.values[1] / SensorManager.GRAVITY_EARTH).toDouble()) putDouble("z", (sensorEvent.values[2] / SensorManager.GRAVITY_EARTH).toDouble()) } } @ExpoMethod fun startObserving(promise: Promise) { super.startObserving() promise.resolve(null) } @ExpoMethod fun stopObserving(promise: Promise) { super.stopObserving() promise.resolve(null) } @ExpoMethod fun setUpdateInterval(updateInterval: Int, promise: Promise) { super.setUpdateInterval(updateInterval) promise.resolve(null) } @ExpoMethod fun isAvailableAsync(promise: Promise) { val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null promise.resolve(isAvailable) } }
bsd-3-clause
e2acf65d59ed78e7a03cbfe8fb861bf1
33.527273
90
0.771985
4.32574
false
false
false
false
codeka/wwmmo
planet-render/src/main/kotlin/au/com/codeka/warworlds/planetrender/Atmosphere.kt
1
7893
package au.com.codeka.warworlds.planetrender import au.com.codeka.warworlds.common.* import au.com.codeka.warworlds.common.Colour.Companion.TRANSPARENT import au.com.codeka.warworlds.common.Vector3.Companion.dot import au.com.codeka.warworlds.planetrender.Template.* import au.com.codeka.warworlds.planetrender.Template.AtmosphereTemplate.InnerOuterTemplate import au.com.codeka.warworlds.planetrender.Template.AtmosphereTemplate.StarTemplate import java.util.* import kotlin.math.abs import kotlin.math.acos /** This class will generate an atmosphere around a planet. */ open class Atmosphere protected constructor() { open val blendMode: AtmosphereTemplate.BlendMode? get() = AtmosphereTemplate.BlendMode.Alpha open fun getOuterPixelColour(u: Double, v: Double, normal: Vector3, distanceToSurface: Double, sunDirection: Vector3?, north: Vector3?): Colour { return Colour(TRANSPARENT) } open fun getInnerPixelColour(u: Double, v: Double, pt: Vector3?, normal: Vector3?, sunDirection: Vector3?, north: Vector3?): Colour { return Colour(TRANSPARENT) } class InnerAtmosphere(tmpl: InnerOuterTemplate?, rand: Random) : Atmosphere() { private val colourGradient: ColourGradient? private val sunShadowFactor: Double private val sunStartShadow: Double private var noisiness = 0.0 override val blendMode: AtmosphereTemplate.BlendMode? private var perlin: PerlinNoise? = null override fun getInnerPixelColour(u: Double, v: Double, pt: Vector3?, normal: Vector3?, sunDirection: Vector3?, north: Vector3?): Colour { if (colourGradient == null) { return Colour(TRANSPARENT) } val cameraDirection = Vector3(0.0, 0.0, 0.0) cameraDirection.subtract(pt!!) cameraDirection.normalize() var dot = dot(cameraDirection, normal!!) val baseColour = colourGradient.getColour(1.0 - dot) // if we've on the dark side of the planet, we'll want to factor in the shadow dot = dot(normal, sunDirection!!) val sunFactor = getSunShadowFactor(dot, sunStartShadow, sunShadowFactor) baseColour.reset( baseColour.a * sunFactor, baseColour.r, baseColour.g, baseColour.b) if (perlin != null) { val noiseFactor = getNoiseFactor(u, v, perlin!!, noisiness) baseColour.reset( baseColour.a * noiseFactor, baseColour.r * noiseFactor, baseColour.r * noiseFactor, baseColour.b * noiseFactor) } return baseColour } init { colourGradient = tmpl!!.getParameter(ColourGradientTemplate::class.java)!!.colourGradient sunShadowFactor = tmpl.sunShadowFactor sunStartShadow = tmpl.sunStartShadow val perlinTemplate = tmpl.getParameter(PerlinNoiseTemplate::class.java) if (perlinTemplate != null) { perlin = TemplatedPerlinNoise(perlinTemplate, rand) noisiness = tmpl.noisiness } blendMode = tmpl.blendMode } } open class OuterAtmosphere(tmpl: InnerOuterTemplate?, rand: Random) : Atmosphere() { private val colourGradient: ColourGradient? private val sunShadowFactor: Double private val sunStartShadow: Double private val atmosphereSize: Double private var noisiness = 0.0 private var perlin: PerlinNoise? = null override val blendMode: AtmosphereTemplate.BlendMode? override fun getOuterPixelColour(u: Double, v: Double, normal: Vector3, distanceToSurface: Double, sunDirection: Vector3?, north: Vector3?): Colour { var dist = distanceToSurface if (colourGradient == null) { return Colour(TRANSPARENT) } dist /= atmosphereSize val baseColour = colourGradient.getColour(dist) val dot = dot(normal, sunDirection!!) val sunFactor = getSunShadowFactor(dot, sunStartShadow, sunShadowFactor) baseColour.reset( baseColour.a * sunFactor, baseColour.r, baseColour.g, baseColour.b) if (perlin != null) { val noiseFactor = getNoiseFactor(u, v, perlin!!, noisiness) baseColour.reset( baseColour.a * noiseFactor, baseColour.r, baseColour.g, baseColour.b) } return baseColour } init { colourGradient = tmpl!!.getParameter(ColourGradientTemplate::class.java)!!.colourGradient sunShadowFactor = tmpl.sunShadowFactor sunStartShadow = tmpl.sunStartShadow atmosphereSize = tmpl.size val perlinTemplate = tmpl.getParameter(PerlinNoiseTemplate::class.java) if (perlinTemplate != null) { perlin = TemplatedPerlinNoise(perlinTemplate, rand) noisiness = tmpl.noisiness } blendMode = tmpl.blendMode } } class StarAtmosphere(tmpl: StarTemplate?, rand: Random) : OuterAtmosphere(tmpl, rand) { private val mNumPoints: Int private val mBaseWidth: Double override fun getOuterPixelColour(u: Double, v: Double, normal: Vector3, distanceToSurface: Double, sunDirection: Vector3?, north: Vector3?): Colour { val baseColour = super.getOuterPixelColour( u, v, normal, distanceToSurface, sunDirection, north) normal.z = 0.0 normal.normalize() val dot = dot(north!!, normal) var angle = acos(dot) val pointAngle = Math.PI * 2.0 / mNumPoints.toDouble() while (angle > pointAngle) { angle -= pointAngle } angle /= pointAngle var distanceToPoint = angle if (distanceToPoint > 0.5) { distanceToPoint = 1.0 - distanceToPoint } distanceToPoint *= 2.0 distanceToPoint *= mBaseWidth if (distanceToPoint > 1.0) distanceToPoint = 1.0 baseColour.reset( baseColour.a * (1.0 - distanceToPoint), baseColour.r, baseColour.g, baseColour.b) return baseColour } init { mNumPoints = tmpl!!.numPoints mBaseWidth = tmpl.baseWidth } } companion object { fun getAtmospheres(tmpl: AtmosphereTemplate?, rand: Random): List<Atmosphere> { val atmospheres = ArrayList<Atmosphere>() getAtmospheres(atmospheres, tmpl, rand) return atmospheres } fun getAtmospheres(atmospheres: MutableList<Atmosphere>, tmpl: AtmosphereTemplate?, rand: Random) { if (tmpl!!.innerTemplate != null) { atmospheres.add(InnerAtmosphere(tmpl.innerTemplate, rand)) } if (tmpl.outerTemplate != null) { atmospheres.add(OuterAtmosphere(tmpl.outerTemplate, rand)) } if (tmpl.starTemplate != null) { atmospheres.add(StarAtmosphere(tmpl.starTemplate, rand)) } } protected fun getSunShadowFactor(dot: Double, sunStartShadow: Double, sunFactor: Double): Double { var d = dot if (d < 0.0) { d = abs(d) // normally, the dot product will be 1.0 if we're on the exact opposite side of // the planet to the sun, and 0.0 when we're 90 degrees to the sun. We want to swap // that around. d = 1.0 - d } else { // if it's positive, then it's on the sun side of the planet. We'll still allow you to // start chopping off the atmosphere on the sun side of the planet if you want. d += 1.0 } if (d < sunStartShadow) { val min = sunStartShadow * sunFactor d = if (d < min) { 0.0 } else { (d - min) / (sunStartShadow - min) } return d } return 1.0 } protected fun getNoiseFactor(u: Double, v: Double, perlin: PerlinNoise, noisiness: Double): Double { val noise = perlin.getNoise(u, v) return 1.0 - noise * noisiness } } }
mit
f9cab6e5e9e8255755e07a4f504bc971
36.770335
114
0.643482
4.018839
false
false
false
false
pdvrieze/darwin-android-auth
src/main/java/uk/ac/bournemouth/darwin/auth/AuthTokenPermissionActivity.kt
1
3552
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package uk.ac.bournemouth.darwin.auth import android.accounts.Account import android.accounts.AccountManager import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager.NameNotFoundException import android.databinding.DataBindingUtil import android.os.Bundle import android.util.Log import android.view.View import android.view.View.OnClickListener import uk.ac.bournemouth.darwin.auth.databinding.GetPermissionBinding /** * Activity for permitting access to the darwin token. */ class AuthTokenPermissionActivity : Activity(), OnClickListener { private lateinit var binding: GetPermissionBinding private var callerUid: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.get_permission) binding.account = intent.account callerUid = intent.callerUid val pm = packageManager val packageName = intent.packageName?: pm.getPackagesForUid(callerUid)?.get(0) val packageLabel: String = try { val packageInfo = pm.getPackageInfo(packageName, 0) val labelRes = packageInfo.applicationInfo.labelRes pm.getResourcesForApplication(packageInfo.applicationInfo).getString(labelRes) } catch (e: NameNotFoundException) { Log.w(TAG, "onCreate: ", e) packageName ?: "<MISSING PACKAGE, UNSAFE>".also { binding.okbutton.isEnabled = false } } binding.callerName = "$packageName:\n $packageLabel" binding.cancelbutton.setOnClickListener(this) binding.okbutton.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.okbutton -> { DarwinAuthenticator.addAllowedUid(AccountManager.get(this), binding.account!!, callerUid) finish() } // fall-through R.id.cancelbutton -> finish() } } companion object { private val Intent.account: Account? get() = getParcelableExtra(DarwinAuthenticator.KEY_ACCOUNT) private val Intent.callerUid: Int get() = getIntExtra(AccountManager.KEY_CALLER_UID, -1) private val Intent.packageName:String? get() = getStringExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME) private const val TAG = "AuthTokenPermissionAct" } } fun Context.authTokenPermissionActivity(account: Account, callerUid: Int, packageName: String?): Intent { return Intent(this, AuthTokenPermissionActivity::class.java).apply { putExtra(DarwinAuthenticator.KEY_ACCOUNT, account) putExtra(AccountManager.KEY_CALLER_UID, callerUid) packageName?.let { putExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME, it) } } }
lgpl-2.1
c73b64dc1beb1bd800ff4ac260cf9ec4
37.193548
114
0.708052
4.583226
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/maps/management/StandardMapItemController.kt
1
1642
package nl.rsdt.japp.jotial.maps.management import android.os.Bundle import android.os.Parcelable import nl.rsdt.japp.jotial.maps.management.transformation.AbstractTransducer import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.osm.OsmJotiMap import java.util.* /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 4-9-2016 * Description... */ abstract class StandardMapItemController<I : Parcelable, O : AbstractTransducer.StandardResult<I>>(jotiMap: IJotiMap) : MapItemController<ArrayList<I>, O>(jotiMap) { protected var items: ArrayList<I> = ArrayList() override fun onIntentCreate(bundle: Bundle) { super.onIntentCreate(bundle) val result = bundle.getParcelable<O>(bundleId) if (result != null) { this.items = result.items } } override fun onCreate(savedInstanceState: Bundle?) { if (savedInstanceState?.containsKey(bundleId)== true) { this.items = savedInstanceState.getParcelableArrayList(bundleId)!! val result = transducer.generate(items) processResult(result) } } override fun onSaveInstanceState(saveInstanceState: Bundle?) { saveInstanceState?.putParcelableArrayList(bundleId, items) } override fun merge(other: O) { clear() processResult(other) } override fun processResult(result: O) { super.processResult(result) this.items.addAll(result.items) } override fun clear() { super.clear() items.clear() } override fun onDestroy() { super.onDestroy() } }
apache-2.0
c998bd030fe50162ddb8c6b08b225d71
27.310345
165
0.671742
4.242894
false
false
false
false
androidx/androidx
paging/paging-common/src/main/kotlin/androidx/paging/WrapperPageKeyedDataSource.kt
3
3144
/* * Copyright 2019 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.paging import androidx.arch.core.util.Function @Suppress("DEPRECATION") internal class WrapperPageKeyedDataSource<K : Any, A : Any, B : Any>( private val source: PageKeyedDataSource<K, A>, private val listFunction: Function<List<A>, List<B>> ) : PageKeyedDataSource<K, B>() { override val isInvalid get() = source.isInvalid override fun addInvalidatedCallback(onInvalidatedCallback: InvalidatedCallback) { source.addInvalidatedCallback(onInvalidatedCallback) } override fun removeInvalidatedCallback(onInvalidatedCallback: InvalidatedCallback) { source.removeInvalidatedCallback(onInvalidatedCallback) } override fun invalidate() = source.invalidate() override fun loadInitial(params: LoadInitialParams<K>, callback: LoadInitialCallback<K, B>) { source.loadInitial( params, object : LoadInitialCallback<K, A>() { override fun onResult( data: List<A>, position: Int, totalCount: Int, previousPageKey: K?, nextPageKey: K? ) { val convertedData = convert(listFunction, data) callback.onResult( convertedData, position, totalCount, previousPageKey, nextPageKey ) } override fun onResult(data: List<A>, previousPageKey: K?, nextPageKey: K?) { val convertedData = convert(listFunction, data) callback.onResult(convertedData, previousPageKey, nextPageKey) } } ) } override fun loadBefore(params: LoadParams<K>, callback: LoadCallback<K, B>) { source.loadBefore( params, object : LoadCallback<K, A>() { override fun onResult(data: List<A>, adjacentPageKey: K?) = callback.onResult(convert(listFunction, data), adjacentPageKey) } ) } override fun loadAfter(params: LoadParams<K>, callback: LoadCallback<K, B>) { source.loadAfter( params, object : LoadCallback<K, A>() { override fun onResult(data: List<A>, adjacentPageKey: K?) = callback.onResult(convert(listFunction, data), adjacentPageKey) } ) } }
apache-2.0
a78d6e4ec9e30f974721969d2db40915
35.137931
97
0.594466
5.120521
false
false
false
false
androidx/androidx
lifecycle/lifecycle-viewmodel-compose/src/main/java/androidx/lifecycle/viewmodel/compose/ViewModel.kt
3
9344
/* * 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.lifecycle.viewmodel.compose import androidx.compose.runtime.Composable import androidx.lifecycle.HasDefaultViewModelProviderFactory import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.CreationExtras import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory /** * Returns an existing [ViewModel] or creates a new one in the given owner (usually, a fragment or * an activity), defaulting to the owner provided by [LocalViewModelStoreOwner]. * * The created [ViewModel] is associated with the given [viewModelStoreOwner] and will be retained * as long as the owner is alive (e.g. if it is an activity, until it is * finished or process is killed). * * @param viewModelStoreOwner The owner of the [ViewModel] that controls the scope and lifetime * of the returned [ViewModel]. Defaults to using [LocalViewModelStoreOwner]. * @param key The key to use to identify the [ViewModel]. * @param factory The [ViewModelProvider.Factory] that should be used to create the [ViewModel] * or null if you would like to use the default factory from the [LocalViewModelStoreOwner] * @return A [ViewModel] that is an instance of the given [VM] type. */ @Deprecated( "Superseded by viewModel that takes CreationExtras", level = DeprecationLevel.HIDDEN ) @Suppress("MissingJvmstatic") @Composable public inline fun <reified VM : ViewModel> viewModel( viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null, factory: ViewModelProvider.Factory? = null ): VM = viewModel(VM::class.java, viewModelStoreOwner, key, factory) /** * Returns an existing [ViewModel] or creates a new one in the given owner (usually, a fragment or * an activity), defaulting to the owner provided by [LocalViewModelStoreOwner]. * * The created [ViewModel] is associated with the given [viewModelStoreOwner] and will be retained * as long as the owner is alive (e.g. if it is an activity, until it is * finished or process is killed). * * If default arguments are provided via the [CreationExtras], they will be available to the * appropriate factory when the [ViewModel] is created. * * @param viewModelStoreOwner The owner of the [ViewModel] that controls the scope and lifetime * of the returned [ViewModel]. Defaults to using [LocalViewModelStoreOwner]. * @param key The key to use to identify the [ViewModel]. * @param factory The [ViewModelProvider.Factory] that should be used to create the [ViewModel] * or null if you would like to use the default factory from the [LocalViewModelStoreOwner] * @param extras The default extras used to create the [ViewModel]. * @return A [ViewModel] that is an instance of the given [VM] type. * * @sample androidx.lifecycle.viewmodel.compose.samples.CreationExtrasViewModel */ @Suppress("MissingJvmstatic") @Composable public inline fun <reified VM : ViewModel> viewModel( viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null, factory: ViewModelProvider.Factory? = null, extras: CreationExtras = if (viewModelStoreOwner is HasDefaultViewModelProviderFactory) { viewModelStoreOwner.defaultViewModelCreationExtras } else { CreationExtras.Empty } ): VM = viewModel(VM::class.java, viewModelStoreOwner, key, factory, extras) /** * Returns an existing [ViewModel] or creates a new one in the scope (usually, a fragment or * an activity) * * The created [ViewModel] is associated with the given [viewModelStoreOwner] and will be retained * as long as the scope is alive (e.g. if it is an activity, until it is * finished or process is killed). * * @param modelClass The class of the [ViewModel] to create an instance of it if it is not * present. * @param viewModelStoreOwner The scope that the created [ViewModel] should be associated with. * @param key The key to use to identify the [ViewModel]. * @return A [ViewModel] that is an instance of the given [VM] type. */ @Deprecated( "Superseded by viewModel that takes CreationExtras", level = DeprecationLevel.HIDDEN ) @Suppress("MissingJvmstatic") @Composable public fun <VM : ViewModel> viewModel( modelClass: Class<VM>, viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null, factory: ViewModelProvider.Factory? = null ): VM = viewModelStoreOwner.get(modelClass, key, factory) /** * Returns an existing [ViewModel] or creates a new one in the scope (usually, a fragment or * an activity) * * The created [ViewModel] is associated with the given [viewModelStoreOwner] and will be retained * as long as the scope is alive (e.g. if it is an activity, until it is * finished or process is killed). * * If default arguments are provided via the [CreationExtras], they will be available to the * appropriate factory when the [ViewModel] is created. * * @param modelClass The class of the [ViewModel] to create an instance of it if it is not * present. * @param viewModelStoreOwner The scope that the created [ViewModel] should be associated with. * @param key The key to use to identify the [ViewModel]. * @param extras The default extras used to create the [ViewModel]. * @return A [ViewModel] that is an instance of the given [VM] type. * * @sample androidx.lifecycle.viewmodel.compose.samples.CreationExtrasViewModel */ @Suppress("MissingJvmstatic") @Composable public fun <VM : ViewModel> viewModel( modelClass: Class<VM>, viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null, factory: ViewModelProvider.Factory? = null, extras: CreationExtras = if (viewModelStoreOwner is HasDefaultViewModelProviderFactory) { viewModelStoreOwner.defaultViewModelCreationExtras } else { CreationExtras.Empty } ): VM = viewModelStoreOwner.get(modelClass, key, factory, extras) /** * Returns an existing [ViewModel] or creates a new one in the scope (usually, a fragment or * an activity) * * The created [ViewModel] is associated with the given [viewModelStoreOwner] and will be retained * as long as the scope is alive (e.g. if it is an activity, until it is * finished or process is killed). * * If the [viewModelStoreOwner] implements [HasDefaultViewModelProviderFactory] its default * [CreationExtras] are the ones that will be provided to the receiver scope from the [initializer] * * @param viewModelStoreOwner The scope that the created [ViewModel] should be associated with. * @param key The key to use to identify the [ViewModel]. * @param initializer lambda used to create an instance of the ViewModel class * @return A [ViewModel] that is an instance of the given [VM] type. * * @sample androidx.lifecycle.viewmodel.compose.samples.CreationExtrasViewModelInitializer */ @Composable public inline fun <reified VM : ViewModel> viewModel( viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null, noinline initializer: CreationExtras.() -> VM ): VM = viewModel( VM::class.java, viewModelStoreOwner, key, viewModelFactory { initializer(initializer) }, if (viewModelStoreOwner is HasDefaultViewModelProviderFactory) { viewModelStoreOwner.defaultViewModelCreationExtras } else { CreationExtras.Empty } ) private fun <VM : ViewModel> ViewModelStoreOwner.get( javaClass: Class<VM>, key: String? = null, factory: ViewModelProvider.Factory? = null, extras: CreationExtras = if (this is HasDefaultViewModelProviderFactory) { this.defaultViewModelCreationExtras } else { CreationExtras.Empty } ): VM { val provider = if (factory != null) { ViewModelProvider(this.viewModelStore, factory, extras) } else if (this is HasDefaultViewModelProviderFactory) { ViewModelProvider(this.viewModelStore, this.defaultViewModelProviderFactory, extras) } else { ViewModelProvider(this) } return if (key != null) { provider[key, javaClass] } else { provider[javaClass] } }
apache-2.0
fb0d5e1b0268468db7f877bd79779432
42.059908
99
0.746896
4.518375
false
false
false
false
hkokocin/google-android-architecture-sample
app/src/main/java/com/example/hkokocin/gaa/users/UserSearchViewModel.kt
1
1487
package com.example.hkokocin.gaa.users import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import com.example.hkokocin.gaa.R import com.example.hkokocin.gaa.data.GitHubRepository import com.example.hkokocin.gaa.data.GitHubUser import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers data class UserSearchViewState( val users: List<GitHubUser> = emptyList(), val showProgress: Boolean = false, val errorResourceId: Int = 0 ) class UserSearchViewModel( private val repository: GitHubRepository ) : ViewModel() { val state = MutableLiveData<UserSearchViewState>() private val disposables = CompositeDisposable() fun searchUsers(search: String) { repository.searchUser(search) .map { (items) -> UserSearchViewState(items) } .subscribeOn(Schedulers.io()) .startWith(state.value.progress()) .onErrorReturn { state.value.error() } .observeOn(AndroidSchedulers.mainThread()) .subscribe { state.value = it } } override fun onCleared() { super.onCleared() disposables.clear() } } fun UserSearchViewState?.progress() = this?.copy(showProgress = true) ?: UserSearchViewState(showProgress = false) fun UserSearchViewState?.error() = UserSearchViewState(this?.users ?: emptyList(), false, R.string.search_failed)
mit
5f109956ee12fc3170f1322049edfa57
33.604651
114
0.71688
4.589506
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/share/plugin/StaticSharePlugin.kt
1
2090
package com.tomclaw.drawa.share.plugin import android.graphics.Bitmap import com.tomclaw.cache.DiskLruCache import com.tomclaw.drawa.R import com.tomclaw.drawa.core.Journal import com.tomclaw.drawa.draw.ImageProvider import com.tomclaw.drawa.share.SharePlugin import com.tomclaw.drawa.share.ShareResult import com.tomclaw.drawa.util.safeClose import com.tomclaw.drawa.util.uniqueKey import io.reactivex.Observable import io.reactivex.Single import java.io.File import java.io.FileOutputStream import java.io.OutputStream class StaticSharePlugin( recordId: Int, journal: Journal, imageProvider: ImageProvider, private val cache: DiskLruCache ) : SharePlugin { override val weight: Int get() = 1 override val image: Int get() = R.drawable.image override val title: Int get() = R.string.static_share_title override val description: Int get() = R.string.static_share_description override val progress: Observable<Float> get() = Single.just(1f).toObservable() override val operation: Single<ShareResult> = journal.load() .map { journal.get(recordId) } .flatMap { record -> val key = "static-${record.uniqueKey()}" val cached = cache.get(key) if (cached != null) { Single.just(ShareResult(cached, MIME_TYPE)) } else { imageProvider.readImage(recordId) .map { bitmap -> val imageFile: File = createTempFile("stat", ".png") var stream: OutputStream? = null try { stream = FileOutputStream(imageFile) bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream) } finally { stream.safeClose() } val file = cache.put(key, imageFile) ShareResult(file, MIME_TYPE) } } } } private const val MIME_TYPE = "image/png"
apache-2.0
5e52e4ac320dc242261eeb6fbb2efcd5
32.709677
82
0.594258
4.514039
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/editor/completion/LuaDocCompletionContributor.kt
2
9409
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.editor.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.lang.Language import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ProcessingContext import com.intellij.util.Processor import com.tang.intellij.lua.comment.LuaCommentUtil import com.tang.intellij.lua.comment.psi.* import com.tang.intellij.lua.comment.psi.api.LuaComment import com.tang.intellij.lua.lang.LuaIcons import com.tang.intellij.lua.lang.LuaParserDefinition import com.tang.intellij.lua.psi.LuaClassField import com.tang.intellij.lua.psi.LuaFuncBodyOwner import com.tang.intellij.lua.psi.search.LuaShortNamesManager import com.tang.intellij.lua.search.SearchContext import com.tang.intellij.lua.ty.ITyClass /** * doc 相关代码完成 * Created by tangzx on 2016/12/2. */ class LuaDocCompletionContributor : CompletionContributor() { init { extend(CompletionType.BASIC, SHOW_DOC_TAG, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { val set = LuaParserDefinition.DOC_TAG_TOKENS for (type in set.types) { completionResultSet.addElement(LookupElementBuilder.create(type).withIcon(LuaIcons.ANNOTATION)) } ADDITIONAL_TAGS.forEach { tagName -> completionResultSet.addElement(LookupElementBuilder.create(tagName).withIcon(LuaIcons.ANNOTATION)) } completionResultSet.stopHere() } }) extend(CompletionType.BASIC, SHOW_OPTIONAL, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { completionResultSet.addElement(LookupElementBuilder.create("optional")) } }) extend(CompletionType.BASIC, AFTER_PARAM, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { var element = completionParameters.originalFile.findElementAt(completionParameters.offset - 1) if (element != null && element !is LuaDocPsiElement) element = element.parent if (element is LuaDocPsiElement) { val owner = LuaCommentUtil.findOwner(element) if (owner is LuaFuncBodyOwner) { val body = owner.funcBody if (body != null) { val parDefList = body.paramNameDefList for (def in parDefList) { completionResultSet.addElement( LookupElementBuilder.create(def.text) .withIcon(LuaIcons.PARAMETER) ) } } } } } }) extend(CompletionType.BASIC, SHOW_CLASS, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { val project = completionParameters.position.project LuaShortNamesManager.getInstance(project).processAllClassNames(project, Processor{ completionResultSet.addElement(LookupElementBuilder.create(it).withIcon(LuaIcons.CLASS)) true }) LuaShortNamesManager.getInstance(project).processAllAlias(project, Processor { key -> completionResultSet.addElement(LookupElementBuilder.create(key).withIcon(LuaIcons.Alias)) true }) completionResultSet.stopHere() } }) extend(CompletionType.BASIC, SHOW_ACCESS_MODIFIER, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { completionResultSet.addElement(LookupElementBuilder.create("protected")) completionResultSet.addElement(LookupElementBuilder.create("public")) } }) // 属性提示 extend(CompletionType.BASIC, SHOW_FIELD, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { val position = completionParameters.position val comment = PsiTreeUtil.getParentOfType(position, LuaComment::class.java) val classDef = PsiTreeUtil.findChildOfType(comment, LuaDocTagClass::class.java) if (classDef != null) { val classType = classDef.type val ctx = SearchContext.get(classDef.project) classType.processMembers(ctx) { _, member -> if (member is LuaClassField) completionResultSet.addElement(LookupElementBuilder.create(member.name!!).withIcon(LuaIcons.CLASS_FIELD)) Unit } } } }) // @see member completion extend(CompletionType.BASIC, SHOW_SEE_MEMBER, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { val position = completionParameters.position val seeRefTag = PsiTreeUtil.getParentOfType(position, LuaDocTagSee::class.java) if (seeRefTag != null) { val classType = seeRefTag.classNameRef?.resolveType() as? ITyClass val ctx = SearchContext.get(seeRefTag.project) classType?.processMembers(ctx) { _, member -> completionResultSet.addElement(LookupElementBuilder.create(member.name!!).withIcon(LuaIcons.CLASS_FIELD)) Unit } } completionResultSet.stopHere() } }) extend(CompletionType.BASIC, SHOW_LAN, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(completionParameters: CompletionParameters, processingContext: ProcessingContext, completionResultSet: CompletionResultSet) { Language.getRegisteredLanguages().forEach { val fileType = it.associatedFileType var lookupElement = LookupElementBuilder.create(it.id) if (fileType != null) lookupElement = lookupElement.withIcon(fileType.icon) completionResultSet.addElement(lookupElement) } completionResultSet.stopHere() } }) } companion object { // 在 @ 之后提示 param class type ... private val SHOW_DOC_TAG = psiElement(LuaDocTypes.TAG_NAME) // 在 @param 之后提示方法的参数 private val AFTER_PARAM = psiElement().withParent(LuaDocParamNameRef::class.java) // 在 @param 之后提示 optional private val SHOW_OPTIONAL = psiElement().afterLeaf( psiElement(LuaDocTypes.TAG_NAME_PARAM)) // 在 extends 之后提示类型 private val SHOW_CLASS = psiElement().withParent(LuaDocClassNameRef::class.java) // 在 @field 之后提示 public / protected private val SHOW_ACCESS_MODIFIER = psiElement().afterLeaf( psiElement().withElementType(LuaDocTypes.TAG_NAME_FIELD) ) private val SHOW_FIELD = psiElement(LuaDocTypes.ID).inside(LuaDocTagField::class.java) //@see type#MEMBER private val SHOW_SEE_MEMBER = psiElement(LuaDocTypes.ID).inside(LuaDocTagSee::class.java) private val SHOW_LAN = psiElement(LuaDocTypes.ID).inside(LuaDocTagLan::class.java) private val ADDITIONAL_TAGS = arrayOf("deprecated", "author", "version", "since") } }
apache-2.0
986273a640f5b084463353cf06517c04
48.86631
165
0.646863
5.540701
false
false
false
false
czyzby/ktx
box2d/src/main/kotlin/ktx/box2d/worlds.kt
2
6888
package ktx.box2d import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.BodyDef.BodyType import com.badlogic.gdx.physics.box2d.Fixture import com.badlogic.gdx.physics.box2d.World import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * [World] factory function. * @param gravity world's gravity applied to bodies on each step. Defaults to no gravity (0f, 0f). * @param allowSleep if true, inactive bodies will not be simulated. Improves performance. Defaults to true. * @return a new [World] instance with given parameters. */ fun createWorld(gravity: Vector2 = Vector2.Zero, allowSleep: Boolean = true) = World(gravity, allowSleep) /** * Type-safe [Body] building DSL. * @param type [BodyType] of the constructed [Body]. Matches libGDX default of [BodyType.StaticBody]. * @param init inlined. Invoked on a [BodyDefinition] instance, which provides access to [Body] properties, as well as * fixture building DSL. Defaults to no-op. * @return a fully constructed [Body] instance with all defined fixtures. * @see BodyDefinition * @see FixtureDefinition */ @Box2DDsl @OptIn(ExperimentalContracts::class) inline fun World.body(type: BodyType = BodyType.StaticBody, init: BodyDefinition.() -> Unit = {}): Body { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } val bodyDefinition = BodyDefinition() bodyDefinition.type = type bodyDefinition.init() return create(bodyDefinition) } /** * Handles additional building properties provided by [BodyDefinition] and [FixtureDefinition]. Prefer this method * over [World.createBody] when using [BodyDefinition] directly. * @param bodyDefinition stores [Body] properties and optional [Fixture] definitions. * @return a fully constructed [Body] instance with all defined fixtures. * @see BodyDefinition * @see FixtureDefinition * @see body */ fun World.create(bodyDefinition: BodyDefinition): Body { val body = createBody(bodyDefinition) body.userData = bodyDefinition.userData for (fixtureDefinition in bodyDefinition.fixtureDefinitions) { val fixture = body.createFixture(fixtureDefinition) fixture.userData = fixtureDefinition.userData fixtureDefinition.creationCallback?.let { it(fixture) } if (fixtureDefinition.disposeOfShape) { fixtureDefinition.shape.dispose() } } bodyDefinition.creationCallback?.let { it(body) } return body } /** * Roughly matches Earth gravity of 9.80665 m/s^2. Moves bodies down on the Y axis. * * Note that [Vector2] class is mutable, so this vector can be modified. Use this property in read-only mode. * * Usage example: * val world = createWorld(gravity = earthGravity) * @see createWorld */ val earthGravity = Vector2(0f, -9.8f) /** * Callback lambda for ray-casts. * * This lambda is called for each fixture the ray-cast hits. * * There is no guarantee on the order of the callback is called, e.g. the first call to the lambda * is not necessarily the nearest to the start point of the ray. * * The lambda accepts these parameters: * - [Fixture], the fixture hit by the ray. * - [Vector2], the point of initial intersection. * - [Vector2], the normal vector at the point of intersection. * - [Float], the fraction of the distance from `start` to `end` that the intersection point is at. * * The lambda returns the new length of the ray as a fraction of the distance between the start and * end or the ray. Common values are: * - `-1f`, ignore this fixture and continue. * - `0f`, terminate the ray cast. * - A fraction, clip the length of the ray to this point. * - `1f`, don't clip the ray and continue. * * Can be used in place of [com.badlogic.gdx.physics.box2d.RayCastCallback] via Kotlin SAM conversion. * * @see RayCast * @see rayCast */ typealias KtxRayCastCallback = ( fixture: Fixture, point: Vector2, normal: Vector2, fraction: Float ) -> Float /** * Stores constants that can be returned by [KtxRayCastCallback] to control its behavior. * @see rayCast */ object RayCast { /** * Indicates to ignore the hit fixture and continue. * @see KtxRayCastCallback */ const val IGNORE = -1f /** * Indicates to terminate the ray cast. * @see KtxRayCastCallback */ const val TERMINATE = 0f /** * Indicates to not clip the ray and continue. * @see KtxRayCastCallback */ const val CONTINUE = 1f } /** * Ray-cast the world for all fixtures in the path of the ray. * * The ray-cast ignores shapes that contain the starting point. * * @param start the ray starting point. * @param end the ray ending point. * @param callback a user implemented callback called on every fixture hit. * @see RayCast */ fun World.rayCast( start: Vector2, end: Vector2, callback: KtxRayCastCallback ) { rayCast(callback, start, end) } /** * Ray-cast the world for all fixtures in the path of the ray. * * The ray-cast ignores shapes that contain the starting point. * * @param startX the ray starting point X. * @param startY the ray starting point Y. * @param endX the ray ending point X. * @param endY the ray ending point Y. * @param callback a user implemented callback called on every fixture hit. * @see RayCast */ fun World.rayCast( startX: Float, startY: Float, endX: Float, endY: Float, callback: KtxRayCastCallback ) { rayCast(callback, startX, startY, endX, endY) } /** * Query the world for all fixtures that potentially overlap the provided AABB (Axis-Aligned Bounding Box). * * @param lowerX the x coordinate of the lower left corner * @param lowerY the y coordinate of the lower left corner * @param upperX the x coordinate of the upper right corner * @param upperY the y coordinate of the upper right corner * @param callback a user implemented callback that is called for every fixture overlapping the AABB. * @see Query */ fun World.query( lowerX: Float, lowerY: Float, upperX: Float, upperY: Float, callback: KtxQueryCallback ) { QueryAABB(callback, lowerX, lowerY, upperX, upperY) } /** * Stores constants that can be returned by [KtxQueryCallback] to control its behavior. * @see query */ object Query { /** * Stop querying the world. * @see KtxQueryCallback */ const val STOP = false /** * Continue querying for the next match. * @see KtxQueryCallback */ const val CONTINUE = true } /** * Callback lambda for querying with an AABB. * * This lambda is called for each fixture the AABB overlaps. * * There is no guarantee on the order of the callback is called. * * The lambda returns whether to terminate the query. * * Can be used in place of [com.badlogic.gdx.physics.box2d.QueryCallback] via Kotlin SAM conversion. * * @see Query * @see query */ typealias KtxQueryCallback = (fixture: Fixture) -> Boolean
cc0-1.0
2a20f46f2055e62a7a7f2e57877d2e5c
29.887892
118
0.724303
3.782537
false
false
false
false
grueni75/GeoDiscoverer
Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/activity/viewmap/ViewContentNavigationDrawer.kt
1
7756
//============================================================================ // Name : ViewContentNavigationDrawer.kt // Author : Matthias Gruenewald // Copyright : Copyright 2010-2021 Matthias Gruenewald // // This file is part of GeoDiscoverer. // // GeoDiscoverer 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. // // GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>. // //============================================================================ package com.untouchableapps.android.geodiscoverer.ui.activity.viewmap import androidx.compose.animation.* import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.icons.filled.* import androidx.compose.material.ripple.rememberRipple import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.* import com.untouchableapps.android.geodiscoverer.R import com.untouchableapps.android.geodiscoverer.ui.component.* import kotlinx.coroutines.* @ExperimentalGraphicsApi @ExperimentalMaterial3Api @ExperimentalMaterialApi @ExperimentalAnimationApi @ExperimentalComposeUiApi class ViewContentNavigationDrawer(viewContent: ViewContent) { // Parameters val viewContent=viewContent val viewMap=viewContent.viewMap val layoutParams=viewContent.layoutParams // Navigation drawer item class NavigationItem(imageVector: ImageVector? = null, title: String, onClick: () -> Unit) { val imageVector = imageVector val title = title val onClick = onClick } // Content of the navigation drawer @Composable fun content( appVersion: String, innerPadding: PaddingValues, navigationItems: List<NavigationItem>, closeDrawer: () -> Unit ): @Composable() (ColumnScope.() -> Unit) = { Column( modifier = Modifier .width(layoutParams.drawerWidth) ) { Box( modifier = Modifier .background(MaterialTheme.colorScheme.surfaceVariant) .fillMaxWidth(), contentAlignment = Alignment.CenterStart ) { /*Image( modifier = Modifier.fillMaxWidth(), painter = painterResource(R.drawable.nav_header), contentDescription = null, contentScale = ContentScale.FillWidth )*/ Row( verticalAlignment = Alignment.CenterVertically ) { Column( modifier = Modifier .width(layoutParams.iconWidth), horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(R.mipmap.ic_launcher_foreground), contentDescription = null ) } Column() { Text( text = stringResource(id = R.string.app_name), style = MaterialTheme.typography.headlineSmall ) Text( text = appVersion, style = MaterialTheme.typography.bodyMedium ) Spacer(Modifier.height(4.dp)) } } } LazyColumn( modifier = Modifier .padding(innerPadding) .fillMaxWidth() ) { itemsIndexed(navigationItems) { index, item -> navigationItem(index, item, closeDrawer) } } } } // Sets the width of the navigation drawer correctly fun drawerShape() = object : Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { val cornerRadius = with(density) { layoutParams.drawerCornerRadius.toPx() } return Outline.Rounded( RoundRect( left = 0f, top = 0f, right = with(density) { layoutParams.drawerWidth.toPx() }, bottom = size.height, topRightCornerRadius = CornerRadius(cornerRadius), bottomRightCornerRadius = CornerRadius(cornerRadius) ) ) } } // Creates a navigation item for the drawer @Composable fun navigationItem(index: Int, item: NavigationItem, closeDrawer: () -> Unit) { if (item.imageVector == null) { if (index != 0) { separator() } Row( modifier = Modifier .fillMaxWidth() .padding(vertical = layoutParams.itemPadding), verticalAlignment = Alignment.CenterVertically ) { Column( modifier = Modifier .absolutePadding(left = layoutParams.titleIndent) ) { Text( text = item.title, style = MaterialTheme.typography.titleSmall ) } } } else { val interactionSource = remember { MutableInteractionSource() } Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = layoutParams.itemPadding) .clip(shape = RoundedCornerShape(layoutParams.drawerCornerRadius)) .clickable( onClick = { item.onClick() closeDrawer() }, interactionSource = interactionSource, indication = rememberRipple(bounded = true) ) ) { Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Spacer( Modifier .width(0.dp) .height(layoutParams.drawerItemHeight) ) Column( modifier = Modifier .width(layoutParams.iconWidth), horizontalAlignment = Alignment.CenterHorizontally ) { Icon( imageVector = item.imageVector, contentDescription = null ) } Column( modifier = Modifier .weight(1f) ) { Text( text = item.title, style = MaterialTheme.typography.bodyMedium ) } } } } } // Creates a seperator @Composable private fun separator() { Box( modifier = Modifier .fillMaxWidth() .padding(layoutParams.itemPadding) .height(1.dp) .background(MaterialTheme.colorScheme.outline) ) } }
gpl-3.0
7706b9e21f2433c0fd53aabd84f9f91b
30.917695
94
0.619134
5.139828
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/lesson/routing/LessonDeepLinkHandler.kt
2
2036
package org.stepik.android.view.lesson.routing import android.content.Intent import org.stepic.droid.util.HtmlHelper import org.stepik.android.domain.lesson.model.LessonDeepLinkData import ru.nobird.android.view.base.ui.extension.getPathSegmentParameter private const val PATH_SEGMENT_LESSON = "lesson" private const val PATH_SEGMENT_STEP = "step" private const val QUERY_PARAMETER_UNIT = "unit" private const val QUERY_PARAMETER_DISCUSSION = "discussion" private const val QUERY_PARAMETER_THREAD = "thread" fun Intent.getLessonIdFromDeepLink(): Long? { val data = this.data ?: return null val path = data .getPathSegmentParameter(PATH_SEGMENT_LESSON) ?: return null return HtmlHelper.parseIdFromSlug(path) } fun Intent.getStepPositionFromDeepLink(): Int? { val data = this.data ?: return null val path = data .getPathSegmentParameter(PATH_SEGMENT_STEP) ?: return null return HtmlHelper.parseIdFromSlug(path)?.toInt() } fun Intent.getUnitIdFromDeepLink(): Long? { val data = this.data ?: return null val path = data .getQueryParameter(QUERY_PARAMETER_UNIT) ?: return null return HtmlHelper.parseIdFromSlug(path) } fun Intent.getDiscussionIdFromDeepLink(): Long? { val data = this.data ?: return null val path = data .getQueryParameter(QUERY_PARAMETER_DISCUSSION) ?: return null return HtmlHelper.parseIdFromSlug(path) } fun Intent.getThreadTypeFromDeepLink(): String? = this.data?.getQueryParameter(QUERY_PARAMETER_THREAD) fun Intent.getLessonDeepLinkData(): LessonDeepLinkData? = getLessonIdFromDeepLink() ?.let { lessonId -> LessonDeepLinkData( lessonId = lessonId, stepPosition = getStepPositionFromDeepLink() ?: 1, unitId = getUnitIdFromDeepLink(), discussionId = getDiscussionIdFromDeepLink(), // todo: handle discussion id discussionThread = getThreadTypeFromDeepLink() ) }
apache-2.0
b454c1c4b008a2904a1362af498b6fb0
28.955882
91
0.697937
4.268344
false
false
false
false
alangibson27/plus-f
plus-f/src/main/kotlin/com/socialthingy/p2p/Data.kt
1
1040
package com.socialthingy.p2p import java.nio.ByteBuffer import java.util.concurrent.atomic.AtomicLong private val timestamper = AtomicLong(0) data class RawData(val content: Any, private val batchPosition: Int = 0) { val timestamp = if (batchPosition == 0) { timestamper.getAndIncrement() } else { timestamper.get() } val wrap = WrappedData(timestamp, System.currentTimeMillis(), content) } interface Deserialiser { fun deserialise(bytes: ByteBuffer): Any } interface Serialiser { fun serialise(obj: Any, byteStringBuilder: ByteBuffer) } class WrappedData(val timestamp: Long, val systemTime: Long, val content: Any) { constructor(bytes: ByteBuffer, deserialiser: Deserialiser) : this(bytes.long, bytes.long, deserialiser.deserialise(bytes)) fun pack(serialiser: Serialiser): ByteBuffer { val buf = ByteBuffer.allocate(32768) buf.putLong(timestamp) buf.putLong(systemTime) serialiser.serialise(content, buf) buf.flip() return buf } }
mit
b7d9763e11200198adeba35bbe21fb4f
27.916667
126
0.705769
4.015444
false
false
false
false
walleth/walleth
app/src/online/java/org/walleth/dataprovider/EtherScanAPI.kt
1
4313
package org.walleth.dataprovider import okhttp3.Call import okhttp3.OkHttpClient import okhttp3.Request import org.json.JSONException import org.json.JSONObject import org.kethereum.extensions.transactions.getTokenRelevantTo import org.kethereum.model.ChainId import org.kethereum.rpc.EthereumRPC import org.ligi.kaxt.letIf import org.walleth.data.AppDatabase import org.walleth.data.chaininfo.ChainInfo import org.walleth.data.rpc.RPCProvider import org.walleth.data.transactions.TransactionEntity import org.walleth.data.transactions.TransactionState import org.walleth.kethereum.etherscan.getEtherScanAPIBaseURL import timber.log.Timber import java.io.IOException import java.security.cert.CertPathValidatorException class EtherScanAPI(private val appDatabase: AppDatabase, private val rpcProvider: RPCProvider, private val okHttpClient: OkHttpClient) { private var lastSeenTransactionsBlock = 0L suspend fun queryTransactions(addressHex: String, networkDefinition: ChainInfo) { rpcProvider.getForChain(ChainId(networkDefinition.chainId))?.let {rpc -> val startBlock = lastSeenTransactionsBlock requestList(addressHex, networkDefinition, "txlist", rpc, startBlock) requestList(addressHex, networkDefinition, "tokentx", rpc, startBlock) } } private fun requestList(addressHex: String, currentChain: ChainInfo, action: String, rpc: EthereumRPC, startBlock: Long) { val requestString = "module=account&action=$action&address=$addressHex&startblock=$startBlock&sort=asc" try { val result = getEtherscanResult(requestString, currentChain) if (result != null && result.has("result")) { val jsonArray = result.getJSONArray("result") val newTransactions = parseEtherscanTransactionList(jsonArray) lastSeenTransactionsBlock = newTransactions.highestBlock newTransactions.list.forEach { val oldEntry = appDatabase.transactions.getByHash(it) if (oldEntry == null || oldEntry.transactionState.isPending) { rpc.getTransactionByHash(it)?.let { newTransaction -> val newEntity = TransactionEntity(it, newTransaction.transaction.getTokenRelevantTo(), transaction = newTransaction.transaction.copy( chain = currentChain.chainId, creationEpochSecond = System.currentTimeMillis() / 1000 ), signatureData = newTransaction.signatureData, transactionState = TransactionState(isPending = false) ) appDatabase.transactions.upsert(newEntity) } } } } } catch (e: JSONException) { Timber.w("Problem with JSON from EtherScan: %s", e.message) } } private fun getEtherscanResult(requestString: String, chainInfo: ChainInfo) = try { getEtherscanResult(requestString, chainInfo, false) } catch (e: CertPathValidatorException) { getEtherscanResult(requestString, chainInfo, true) } private fun getEtherscanResult(requestString: String, chainInfo: ChainInfo, httpFallback: Boolean): JSONObject? { val baseURL = getEtherScanAPIBaseURL(ChainId(chainInfo.chainId)).letIf(httpFallback) { replace("https://", "http://") // :-( https://github.com/walleth/walleth/issues/134 ) } val urlString = "$baseURL/api?$requestString" val request = Request.Builder().url(urlString).build() val newCall: Call = okHttpClient.newCall(request) try { val resultString = newCall.execute().body().use { it?.string() } resultString?.let { return JSONObject(resultString) } } catch (ioe: IOException) { ioe.printStackTrace() } catch (jsonException: JSONException) { jsonException.printStackTrace() } return null } }
gpl-3.0
dcffb4615318535da57d43de05ba534b
39.698113
126
0.631347
5.044444
false
false
false
false
mgramin/sql-boot
src/main/kotlin/com/github/mgramin/sqlboot/model/connection/SimpleDbConnection.kt
1
2859
/* * The MIT License (MIT) * <p> * Copyright (c) 2016-2019 Maksim Gramin * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * <p> * 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.mgramin.sqlboot.model.connection import com.fasterxml.jackson.annotation.JsonIgnore import org.apache.tomcat.jdbc.pool.DataSource import org.json.JSONObject import org.springframework.core.io.Resource /** * @author Maksim Gramin ([email protected]) * @version $Id: f221782080d430e77aed80ef8446745687c350f4 $ * @since 0.1 */ open class SimpleDbConnection( var name: String? = null, @JsonIgnore var baseFolder: Resource? = null, var url: String? = null, var user: String? = null, @JsonIgnore var password: String? = null, var driverClassName: String? = null, var properties: String? = null, var paginationQueryTemplate: String? = null ) : DbConnection { override fun name() = this.name!! override fun paginationQueryTemplate() = this.paginationQueryTemplate!! override fun health() = "UNKNOWN" private var dataSource: DataSource? = null override fun properties() = JSONObject(properties).toMap() @JsonIgnore override fun getDataSource(): DataSource { if (dataSource != null) { return dataSource!! } else { val dataSourceNew = DataSource() if (driverClassName != null) { dataSourceNew.driverClassName = driverClassName } if (url != null) { dataSourceNew.url = url } if (user != null) { dataSourceNew.username = user } if (password != null) { dataSourceNew.password = password } dataSource = dataSourceNew return dataSourceNew } } }
mit
ccf7d1365d524c30cc3fd23a13ec48ad
33.865854
80
0.665617
4.398462
false
false
false
false
modcrafters/Bush-Master-Core
src/main/kotlin/net/ndrei/bushmaster/BushMasterCore.kt
1
2041
package net.ndrei.bushmaster import com.mojang.authlib.GameProfile import net.minecraft.world.WorldServer import net.minecraftforge.common.util.FakePlayerFactory import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.SidedProxy import net.minecraftforge.fml.common.event.* import net.ndrei.bushmaster.api.BushMasterApi import net.ndrei.bushmaster.cmd.HarvestableCommand import org.apache.logging.log4j.Logger import java.util.* /** * Created by CF on 2017-06-28. */ @Mod(modid = MOD_ID, version = MOD_VERSION, name = MOD_NAME, acceptedMinecraftVersions = MOD_MC_VERSION, dependencies = MOD_DEPENDENCIES, certificateFingerprint = MOD_SIGN_FINGERPRINT, useMetadata = true, modLanguage = "kotlin", modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter") object BushMasterCore { @SidedProxy(clientSide = "net.ndrei.bushmaster.ClientProxy", serverSide = "net.ndrei.bushmaster.ServerProxy") lateinit var proxy: CommonProxy lateinit var logger: Logger @Suppress("unused") val isClientSide get() = net.minecraftforge.fml.common.FMLCommonHandler.instance().effectiveSide?.isClient ?: false private val gameProfile by lazy { GameProfile(UUID.fromString("5198ed9d-5108-46c6-a684-50bb29e011e6"), "_BushMaster_") } fun getFakePlayer(world: WorldServer) = FakePlayerFactory.get(world, gameProfile).also { it.inventory.clear() } @Mod.EventHandler fun construct(event: FMLConstructionEvent) { BushMasterApi.harvestableFactory = HarvestableFactory } @Mod.EventHandler fun preInit(event: FMLPreInitializationEvent) { logger = event.modLog proxy.preInit(event) } @Mod.EventHandler fun init(event: FMLInitializationEvent) { proxy.init(event) } @Mod.EventHandler fun postInit(event: FMLPostInitializationEvent) { proxy.postInit(event) } @Mod.EventHandler fun onServerStarting(event: FMLServerStartingEvent) { event.registerServerCommand(HarvestableCommand) } }
mit
4431a72ee14cdfb147ff89a541411f1f
33.59322
124
0.744733
3.932563
false
false
false
false
PolymerLabs/arcs
javatests/arcs/android/e2e/testapp/PersonHostService.kt
1
3185
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.android.e2e.testapp // TODO(b/170962663) Disabled due to different ordering after copybara transformations. /* ktlint-disable import-ordering */ import androidx.lifecycle.Lifecycle import android.content.Context import android.content.Intent import arcs.core.data.Plan import arcs.core.host.HandleManagerFactory import arcs.core.host.ParticleRegistration import arcs.core.host.SimpleSchedulerProvider import arcs.core.host.toRegistration import arcs.jvm.util.JvmTime import arcs.sdk.android.labs.host.AndroidHost import arcs.sdk.android.labs.host.ArcHostService import arcs.sdk.android.storage.AndroidStorageServiceEndpointManager import arcs.sdk.android.storage.service.DefaultBindHelper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job /** * Service which wraps an ArcHost containing person.arcs related particles. */ @OptIn(ExperimentalCoroutinesApi::class) class PersonHostService : ArcHostService() { private val coroutineContext = Job() + Dispatchers.Main private val handleManagerFactory = HandleManagerFactory( SimpleSchedulerProvider(coroutineContext), AndroidStorageServiceEndpointManager( CoroutineScope(Dispatchers.Default), DefaultBindHelper(this) ), JvmTime ) override val arcHost = MyArcHost( this, this.lifecycle, handleManagerFactory, ::ReadPerson.toRegistration(), ::WritePerson.toRegistration() ) override val arcHosts = listOf(arcHost) @OptIn(ExperimentalCoroutinesApi::class) inner class MyArcHost( context: Context, lifecycle: Lifecycle, handleManagerFactory: HandleManagerFactory, vararg initialParticles: ParticleRegistration ) : AndroidHost( context = context, lifecycle = lifecycle, coroutineContext = Dispatchers.Default, arcSerializationContext = Dispatchers.Default, handleManagerFactory = handleManagerFactory, particles = initialParticles ) { override suspend fun stopArc(partition: Plan.Partition) { super.stopArc(partition) if (isArcHostIdle()) { sendResult("ArcHost is idle") } } } inner class ReadPerson : AbstractReadPerson() { override fun onStart() { handles.person.onUpdate { delta -> delta.new?.name?.let { sendResult(it) } } } override fun onReady() { sendResult(handles.person.fetch()?.name ?: "") } } inner class WritePerson : AbstractWritePerson() { override fun onFirstStart() { handles.person.store(WritePerson_Person("John Wick")) } } private fun sendResult(result: String) { val intent = Intent(this, TestActivity::class.java) .apply { putExtra(TestActivity.RESULT_NAME, result) flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } }
bsd-3-clause
79e60f1700e5536ee7664ce607b378bb
28.220183
96
0.740345
4.51773
false
false
false
false
PolymerLabs/arcs
java/arcs/core/policy/proto/PolicyProto.kt
1
5296
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.policy.proto import arcs.core.data.FieldName import arcs.core.data.proto.PolicyConfigProto import arcs.core.data.proto.PolicyFieldProto import arcs.core.data.proto.PolicyProto import arcs.core.data.proto.PolicyRetentionProto import arcs.core.data.proto.PolicyTargetProto import arcs.core.data.proto.decode import arcs.core.data.proto.encode import arcs.core.policy.Policy import arcs.core.policy.PolicyField import arcs.core.policy.PolicyRetention import arcs.core.policy.PolicyTarget import arcs.core.policy.StorageMedium import arcs.core.policy.UsageType fun PolicyProto.decode(): Policy { require(name.isNotEmpty()) { "Policy name is missing." } require(egressType.isNotEmpty()) { "Egress type is missing." } return Policy( name = name, description = description, egressType = egressType, targets = targetsList.map { it.decode() }, configs = configsList.associateBy( keySelector = { it.name }, valueTransform = { it.metadataMap } ), annotations = annotationsList.map { it.decode() } ) } fun Policy.encode(): PolicyProto { return PolicyProto.newBuilder() .setName(name) .setDescription(description) .setEgressType(egressType) .addAllTargets(targets.map { it.encode() }) .addAllConfigs( configs.map { (name, metadata) -> PolicyConfigProto.newBuilder().setName(name).putAllMetadata(metadata).build() } ) .addAllAnnotations(annotations.map { it.encode() }) .build() } private fun PolicyTargetProto.decode(): PolicyTarget { return PolicyTarget( schemaName = schemaType, maxAgeMs = maxAgeMs, retentions = retentionsList.map { it.decode() }, fields = fieldsList.map { it.decode() }, annotations = annotationsList.map { it.decode() } ) } fun PolicyTarget.encode(): PolicyTargetProto { return PolicyTargetProto.newBuilder() .setSchemaType(schemaName) .setMaxAgeMs(maxAgeMs) .addAllRetentions(retentions.map { it.encode() }) .addAllFields(fields.map { it.encode() }) .addAllAnnotations(annotations.map { it.encode() }) .build() } private fun PolicyFieldProto.decode(parentFieldPath: List<FieldName> = emptyList()): PolicyField { val rawUsages = mutableSetOf<UsageType>() val redactedUsages = mutableMapOf<String, MutableSet<UsageType>>() for (usage in usagesList) { if (usage.redactionLabel.isEmpty()) { rawUsages.add(usage.usage.decode()) } else { redactedUsages.getOrPut(usage.redactionLabel) { mutableSetOf() }.add(usage.usage.decode()) } } val fieldPath = parentFieldPath + name return PolicyField( fieldPath = fieldPath, rawUsages = rawUsages, redactedUsages = redactedUsages, subfields = subfieldsList.map { it.decode(fieldPath) }, annotations = annotationsList.map { it.decode() } ) } fun PolicyField.encode(): PolicyFieldProto { val rawUsages = rawUsages.map { usage -> PolicyFieldProto.AllowedUsage.newBuilder().setUsage(usage.encode()).build() } val redactedUsages = redactedUsages.flatMap { (label, usages) -> usages.map { usage -> PolicyFieldProto.AllowedUsage.newBuilder() .setRedactionLabel(label) .setUsage(usage.encode()) .build() } } val allUsages = rawUsages + redactedUsages return PolicyFieldProto.newBuilder() .setName(fieldPath.last()) .addAllUsages(allUsages) .addAllSubfields(subfields.map { it.encode() }) .addAllAnnotations(annotations.map { it.encode() }) .build() } private fun PolicyRetentionProto.decode(): PolicyRetention { return PolicyRetention( medium = medium.decode(), encryptionRequired = encryptionRequired ) } private fun PolicyRetention.encode(): PolicyRetentionProto { return PolicyRetentionProto.newBuilder() .setMedium(medium.encode()) .setEncryptionRequired(encryptionRequired) .build() } private fun PolicyFieldProto.UsageType.decode() = when (this) { PolicyFieldProto.UsageType.ANY -> UsageType.ANY PolicyFieldProto.UsageType.EGRESS -> UsageType.EGRESS PolicyFieldProto.UsageType.JOIN -> UsageType.JOIN PolicyFieldProto.UsageType.USAGE_TYPE_UNSPECIFIED, PolicyFieldProto.UsageType.UNRECOGNIZED -> throw UnsupportedOperationException("Unknown usage type: $this") } private fun UsageType.encode() = when (this) { UsageType.ANY -> PolicyFieldProto.UsageType.ANY UsageType.EGRESS -> PolicyFieldProto.UsageType.EGRESS UsageType.JOIN -> PolicyFieldProto.UsageType.JOIN } private fun PolicyRetentionProto.Medium.decode() = when (this) { PolicyRetentionProto.Medium.RAM -> StorageMedium.RAM PolicyRetentionProto.Medium.DISK -> StorageMedium.DISK PolicyRetentionProto.Medium.MEDIUM_UNSPECIFIED, PolicyRetentionProto.Medium.UNRECOGNIZED -> throw UnsupportedOperationException("Unknown retention medium: $this") } private fun StorageMedium.encode() = when (this) { StorageMedium.RAM -> PolicyRetentionProto.Medium.RAM StorageMedium.DISK -> PolicyRetentionProto.Medium.DISK }
bsd-3-clause
f6e8507bd91680f30be7f934af8c03c2
31.89441
98
0.730551
4.15047
false
false
false
false
Tandrial/Advent_of_Code
src/aoc2017/kot/Day03.kt
1
1805
package aoc2017.kot import itertools.cartProd object Day03 { fun partOne(input: Int): Int { val size = Math.ceil(Math.sqrt(input.toDouble())).toInt() val start: Pair<Int, Int> = Pair(size / 2, size / 2) var len = 1 var x = start.first var y = start.second var value = 1 loop@ while (true) { for ((x_off, y_off) in listOf(Pair(1, -1), Pair(-1, 1))) { for (idx in 0 until len) { value++ x += x_off if (value == input) { break@loop } } for (idx in 0 until len) { value++ y += y_off if (value == input) { break@loop } } len++ } } return Math.abs(x - start.first) + Math.abs(y - start.second) } fun partTwo(input: Int): Int { val size = Math.ceil(Math.sqrt(input.toDouble())).toInt() val grid = Array(size) { IntArray(size) } var x = size / 2 var y = size / 2 var len = 1 grid[x][y] = 1 while (true) { for ((x_off, y_off) in listOf(Pair(1, -1), Pair(-1, 1))) { for (idx in 0 until len) { x += x_off grid[x][y] = getValue(grid, x, y) if (grid[x][y] >= input) { return grid[x][y] } } for (idx in 0 until len) { y += y_off grid[x][y] = getValue(grid, x, y) if (grid[x][y] >= input) { return grid[x][y] } } len++ } } } private fun getValue(grid: Array<IntArray>, x: Int, y: Int): Int { return (-1..1).cartProd(2).map { grid[x + it[0]][y + it[1]] }.sum() } } fun main(args: Array<String>) { val input = 361527 println("Part One = ${Day03.partOne(input)}") println("Part Two = ${Day03.partTwo(input)}") }
mit
b6707ad6ada574173273b6f739ed9e1f
22.75
71
0.47313
3.19469
false
false
false
false
SnakeEys/MessagePlus
app/src/main/java/info/fox/messup/contacts/ContactAdapter.kt
1
1905
package info.fox.messup.contacts import android.content.Context import android.database.Cursor import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER import android.widget.ImageView import android.widget.TextView import info.fox.messup.R import info.fox.messup.base.RecyclerViewCursorAdapter import info.fox.messup.listener.RecyclerItemClickListener import info.fox.messup.listener.RecyclerItemLongClickListener /** * Created by snake * on 17/6/28. */ class ContactAdapter(context: Context) : RecyclerViewCursorAdapter<ContactAdapter.Holder>(context, null, FLAG_REGISTER_CONTENT_OBSERVER) { private var mClickListener: RecyclerItemClickListener? = null private var mLongClickListener: RecyclerItemLongClickListener? = null override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): Holder { val view = LayoutInflater.from(parent?.context)?.inflate(R.layout.item_messages, parent, false) return Holder(view!!) } override fun onBindViewHolder(holder: Holder, cursor: Cursor?) { } inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) { val icon = itemView.findViewById(R.id.iv_icon) as ImageView val person = itemView.findViewById(R.id.tv_person) as TextView val body = itemView.findViewById(R.id.tv_body) as TextView val count = itemView.findViewById(R.id.tv_count) as TextView val date = itemView.findViewById(R.id.tv_date) as TextView init { itemView.setOnClickListener { mClickListener?.onRecyclerItemClicked(it, adapterPosition) } itemView.setOnLongClickListener { mLongClickListener?.onRecyclerItemLongClicked(it, adapterPosition) true } } } }
mit
116184a71fe9d700b84cf4dc113d602f
36.372549
138
0.742782
4.546539
false
false
false
false
y20k/transistor
app/src/main/java/org/y20k/transistor/search/RadioBrowserSearch.kt
1
4741
/* * RadioBrowserSearch.kt * Implements the RadioBrowserSearch class * A RadioBrowserSearch performs searches on the radio-browser.info database * * This file is part of * TRANSISTOR - Radio App for Android * * Copyright (c) 2015-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT */ package org.y20k.transistor.search import android.content.Context import com.android.volley.* import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.Volley import com.google.gson.GsonBuilder import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.json.JSONArray import org.y20k.transistor.BuildConfig import org.y20k.transistor.Keys import org.y20k.transistor.helpers.LogHelper import org.y20k.transistor.helpers.NetworkHelper import org.y20k.transistor.helpers.PreferencesHelper /* * RadioBrowserSearch class */ class RadioBrowserSearch(private var radioBrowserSearchListener: RadioBrowserSearchListener) { /* Interface used to send back search results */ interface RadioBrowserSearchListener { fun onRadioBrowserSearchResults(results: Array<RadioBrowserResult>) { } } /* Define log tag */ private val TAG: String = LogHelper.makeLogTag(RadioBrowserSearch::class.java) /* Main class variables */ private var radioBrowserApi: String private lateinit var requestQueue: RequestQueue /* Init constructor */ init { // get address of radio-browser.info api and update it in background radioBrowserApi = PreferencesHelper.loadRadioBrowserApiAddress() updateRadioBrowserApi() } /* Searches station(s) on radio-browser.info */ fun searchStation(context: Context, query: String, searchType: Int) { LogHelper.v(TAG, "Search - Querying $radioBrowserApi for: $query") // create queue and request requestQueue = Volley.newRequestQueue(context) val requestUrl: String when (searchType) { // CASE: single station search - by radio browser UUID Keys.SEARCH_TYPE_BY_UUID -> requestUrl = "https://${radioBrowserApi}/json/stations/byuuid/${query}" // CASE: multiple results search by search term else -> requestUrl = "https://${radioBrowserApi}/json/stations/search?name=${query.replace(" ", "+")}" } // request data from request URL val stringRequest = object: JsonArrayRequest(Method.GET, requestUrl, null, responseListener, errorListener) { @Throws(AuthFailureError::class) override fun getHeaders(): Map<String, String> { val params = HashMap<String, String>() params["User-Agent"] = "$Keys.APPLICATION_NAME ${BuildConfig.VERSION_NAME}" return params } } // override retry policy stringRequest.retryPolicy = object : RetryPolicy { override fun getCurrentTimeout(): Int { return 30000 } override fun getCurrentRetryCount(): Int { return 30000 } @Throws(VolleyError::class) override fun retry(error: VolleyError) { LogHelper.w(TAG, "Error: $error") } } // add to RequestQueue. requestQueue.add(stringRequest) } fun stopSearchRequest() { if (this::requestQueue.isInitialized) { requestQueue.stop() } } /* Converts search result JSON string */ private fun createRadioBrowserResult(result: String): Array<RadioBrowserResult> { val gsonBuilder = GsonBuilder() gsonBuilder.setDateFormat("M/d/yy hh:mm a") val gson = gsonBuilder.create() return gson.fromJson(result, Array<RadioBrowserResult>::class.java) } /* Updates the address of the radio-browser.info api */ private fun updateRadioBrowserApi() { GlobalScope.launch { val deferred: Deferred<String> = async { NetworkHelper.getRadioBrowserServerSuspended() } radioBrowserApi = deferred.await() } } /* Listens for (positive) server responses to search requests */ private val responseListener: Response.Listener<JSONArray> = Response.Listener<JSONArray> { response -> if (response != null) { radioBrowserSearchListener.onRadioBrowserSearchResults(createRadioBrowserResult(response.toString())) } } /* Listens for error response from server */ private val errorListener: Response.ErrorListener = Response.ErrorListener { error -> LogHelper.w(TAG, "Error: $error") } }
mit
a4208a12b60f141f3b3bf2e1fd4b6374
32.160839
117
0.670112
4.638943
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/DateSelectorViewUtils.kt
1
1486
package org.wordpress.android.ui.stats.refresh.utils import android.view.View import org.wordpress.android.databinding.StatsListFragmentBinding import org.wordpress.android.ui.stats.refresh.StatsViewModel.DateSelectorUiModel fun StatsListFragmentBinding.drawDateSelector(dateSelectorUiModel: DateSelectorUiModel?) { val dateSelectorVisibility = if (dateSelectorUiModel?.isVisible == true) View.VISIBLE else View.GONE if (dateSelectionToolbar.visibility != dateSelectorVisibility) { dateSelectionToolbar.visibility = dateSelectorVisibility } with(dateSelector) { selectedDateTextView.text = dateSelectorUiModel?.date ?: "" val timeZone = dateSelectorUiModel?.timeZone if (currentSiteTimeZone.visibility == View.GONE && timeZone != null) { currentSiteTimeZone.visibility = View.VISIBLE currentSiteTimeZone.text = timeZone } else if (currentSiteTimeZone.visibility == View.VISIBLE && timeZone == null) { currentSiteTimeZone.visibility = View.GONE } val enablePreviousButton = dateSelectorUiModel?.enableSelectPrevious == true if (previousDateButton.isEnabled != enablePreviousButton) { previousDateButton.isEnabled = enablePreviousButton } val enableNextButton = dateSelectorUiModel?.enableSelectNext == true if (nextDateButton.isEnabled != enableNextButton) { nextDateButton.isEnabled = enableNextButton } } }
gpl-2.0
ebffb56e6b22bb10c26a41fe6fe9b2ea
48.533333
104
0.730148
4.986577
false
false
false
false
ingokegel/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLines.kt
1
2346
package org.jetbrains.plugins.notebooks.visualization import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.editor.Editor import com.intellij.util.EventDispatcher import java.util.* val NOTEBOOK_CELL_LINES_INTERVAL_DATA_KEY = DataKey.create<NotebookCellLines.Interval>("NOTEBOOK_CELL_LINES_INTERVAL") /** * Incrementally iterates over Notebook document, calculates line ranges of cells using lexer. * Fast enough for running in EDT, but could be used in any other thread. * * Note: there's a difference between this model and the PSI model. * If a document starts not with a cell marker, this class treat the text before the first cell marker as a raw cell. * PSI model treats such cell as a special "stem" cell which is not a Jupyter cell at all. * We haven't decided which model is correct and which should be fixed. So, for now avoid using stem cells in tests, * while UI of PyCharm DS doesn't allow to create a stem cell at all. */ interface NotebookCellLines { enum class CellType { CODE, MARKDOWN, RAW } data class Marker( val ordinal: Int, val type: CellType, val offset: Int, val length: Int ) : Comparable<Marker> { override fun compareTo(other: Marker): Int = offset - other.offset } enum class MarkersAtLines(val hasTopLine: Boolean, val hasBottomLine: Boolean) { NO(false, false), TOP(true, false), BOTTOM(false, true), TOP_AND_BOTTOM(true, true) } data class Interval( val ordinal: Int, val type: CellType, val lines: IntRange, val markers: MarkersAtLines, ) : Comparable<Interval> { override fun compareTo(other: Interval): Int = lines.first - other.lines.first } interface IntervalListener : EventListener { /** Called when document is changed. */ fun segmentChanged(event: NotebookCellLinesEvent) } fun intervalsIterator(startLine: Int = 0): ListIterator<Interval> val intervals: List<Interval> val intervalListeners: EventDispatcher<IntervalListener> val modificationStamp: Long companion object { fun get(editor: Editor): NotebookCellLines = editor.notebookCellLinesProvider?.create(editor.document) ?: error("Can't get for $editor with document ${editor.document}") fun hasSupport(editor: Editor): Boolean = editor.notebookCellLinesProvider != null } }
apache-2.0
975f59d9185b609f5c8bb8299a1a5b18
32.056338
118
0.730179
4.288848
false
false
false
false
mdaniel/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/InlaysManager.kt
9
1980
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.notebooks.visualization.r.inlays import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.util.Key /** * Manages inlays. * * On project load subscribes * on editor opening/closing. * on adding/removing notebook cells * on any document changes * on folding actions * * On editor open checks the PSI structure and restores saved inlays. * * ToDo should be split into InlaysManager with all basics and NotebookInlaysManager with all specific. */ private val logger = Logger.getInstance(InlaysManager::class.java) class InlaysManager : EditorFactoryListener { companion object { private val KEY = Key.create<EditorInlaysManager>("org.jetbrains.plugins.notebooks.visualization.r.inlays.editorInlaysManager") fun getEditorManager(editor: Editor): EditorInlaysManager? = editor.getUserData(KEY) private fun getDescriptor(editor: Editor): InlayElementDescriptor? { return InlayDescriptorProvider.EP.extensionList .asSequence() .mapNotNull { it.getInlayDescriptor(editor) } .firstOrNull() } } override fun editorCreated(event: EditorFactoryEvent) { val editor = event.editor val project = editor.project ?: return val descriptor = getDescriptor(editor) ?: return InlayDimensions.init(editor as EditorImpl) editor.putUserData(KEY, EditorInlaysManager(project, editor, descriptor)) } override fun editorReleased(event: EditorFactoryEvent) { event.editor.getUserData(KEY)?.let { manager -> manager.dispose() event.editor.putUserData(KEY, null) } } }
apache-2.0
c2e5256641854090723472d0d9b88985
32.576271
140
0.75303
4.439462
false
false
false
false
austinv11/D4JBot
src/main/kotlin/com/austinv11/d4j/bot/scripting/Scripting.kt
1
2623
package com.austinv11.d4j.bot.scripting import java.io.InputStream import java.io.OutputStream val JAVA_IMPORTS = arrayOf("java.io", "java.lang", "java.lang.reflect", "java.math", "java.nio", "java.nio.file", "java.time", "java.net", "java.time.format", "java.util", "java.util.concurrent", "java.util.concurrent.atomic", "java.util.function", "java.util.regex", "java.util.stream") val KOTLIN_IMPORTS = arrayOf("kotlin", "kotlin.annotation", "kotlin.collections", "kotlin.comparisons", "kotlin.concurrent", "kotlin.coroutines", "kotlin.io", "kotlin.jvm", "kotlin.jvm.functions", "kotlin.properties", "kotlin.ranges", "kotlin.reflect", "kotlin.reflect.jvm", "kotlin.system", "kotlin.text") val DISCORD4J_IMPORTS = arrayOf("sx.blah.discord", "sx.blah.discord.util", "sx.blah.discord.util.audio", "sx.blah.discord.util.audio.events", "sx.blah.discord.util.audio.processors", "sx.blah.discord.util.audio.providers", "sx.blah.discord.modules", "sx.blah.discord.handle.obj", "sx.blah.discord.handle.impl.events.user", "sx.blah.discord.handle.impl.events.shard", "sx.blah.discord.handle.impl.events.module", "sx.blah.discord.handle.impl.events.guild", "sx.blah.discord.handle.impl.events.guild.voice", "sx.blah.discord.handle.impl.events.guild.voice.user", "sx.blah.discord.handle.impl.events.guild.role", "sx.blah.discord.handle.impl.events.guild.member", "sx.blah.discord.handle.impl.events.guild.channel", "sx.blah.discord.handle.impl.events.guild.channel.message", "sx.blah.discord.handle.impl.events.guild.channel.message.reaction", "sx.blah.discord.handle.impl.events.guild.channel.webhook", "sx.blah.discord.api", "sx.blah.discord.api.events", "sx.blah.discord.util.cache", "com.austinv11.rx") val REACTOR_IMPORTS = arrayOf("reactor.core", "reactor.core.publisher", "reactor.core.scheduler") val FUEL_IMPORTS = arrayOf("com.github.kittinunf.fuel", "com.github.kittinunf.fuel", "com.github.kittinunf.fuel.core") val BOT_IMPORTS = arrayOf("com.austinv11.d4j.bot", "com.austinv11.d4j.bot.scripting", "com.austinv11.d4j.bot.extensions", "com.austinv11.d4j.bot.command", "com.austinv11.d4j.bot.util", "com.austinv11.d4j.bot.db", "com.austinv11.d4j.bot.audio") interface IScriptCompiler { fun compile(script: String): ICompiledScript } interface ICompiledScript { fun execute(): Any? fun bind(key: String, value: Any?) fun setIn(inputStream: InputStream) fun setErr(outputStream: OutputStream) fun setOut(outputStream: OutputStream) }
gpl-3.0
baa3a854809ddf49043f738f50b6b9c2
51.46
129
0.703393
3.206601
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/feedback/kotlinRejecters/state/KotlinRejectersInfoService.kt
8
964
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.feedback.kotlinRejecters.state import com.intellij.openapi.components.* import kotlinx.serialization.Serializable @Service(Service.Level.APP) @State(name = "KotlinRejectersInfoService", storages = [Storage("KotlinRejectersInfoService.xml")]) class KotlinRejectersInfoService : PersistentStateComponent<KotlinRejectersInfoState> { companion object { @JvmStatic fun getInstance(): KotlinRejectersInfoService = service() } private var state = KotlinRejectersInfoState() override fun getState(): KotlinRejectersInfoState = state override fun loadState(state: KotlinRejectersInfoState) { this.state = state } } @Serializable data class KotlinRejectersInfoState( var feedbackSent: Boolean = false, var showNotificationAfterRestart: Boolean = false, var numberNotificationShowed: Int = 0 )
apache-2.0
62aeb598be2995a9d634ab1ad702f515
32.275862
120
0.789419
4.590476
false
false
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/Task.kt
4
1979
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.core.entity import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import kotlin.reflect.KProperty1 sealed class Task : EntityBase() data class Task1<A, B : Any>( override val path: String, val action: Writer.(A) -> TaskResult<B> ) : Task() { class Builder<A, B : Any>(private val name: String) { private var action: Writer.(A) -> TaskResult<B> = { Failure() } fun withAction(action: Writer.(A) -> TaskResult<B>) { this.action = action } fun build(): Task1<A, B> = Task1(name, action) } } data class PipelineTask( override val path: String, val action: Writer.() -> TaskResult<Unit>, val before: List<PipelineTask>, val after: List<PipelineTask>, val phase: GenerationPhase, val isAvailable: Checker, @Nls val title: String? ) : Task() { class Builder( private val name: String, private val phase: GenerationPhase ) { private var action: Writer.() -> TaskResult<Unit> = { UNIT_SUCCESS } private val before = mutableListOf<PipelineTask>() private val after = mutableListOf<PipelineTask>() var isAvailable: Checker = ALWAYS_AVAILABLE_CHECKER @Nls var title: String? = null fun withAction(action: Writer.() -> TaskResult<Unit>) { this.action = action } fun runBefore(vararg before: PipelineTask) { this.before.addAll(before) } fun runAfter(vararg after: PipelineTask) { this.after.addAll(after) } fun build(): PipelineTask = PipelineTask(name, action, before, after, phase, isAvailable, title) } }
apache-2.0
de9de445079a33962d7848fc7d01448f
30.428571
158
0.648307
4.210638
false
false
false
false
GunoH/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffComponentFactory.kt
6
10753
// 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.diff.tools.combined import com.intellij.diff.* import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.diff.impl.DiffSettingsHolder import com.intellij.diff.requests.DiffRequest import com.intellij.diff.tools.combined.CombinedDiffModel.NewRequestData import com.intellij.diff.tools.fragmented.UnifiedDiffTool import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.util.Disposer import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.EdtInvocationManager.invokeAndWaitIfNeeded import java.awt.Dimension import kotlin.math.min private val LOG = logger<CombinedDiffComponentFactory>() interface CombinedDiffComponentFactoryProvider { fun create(model: CombinedDiffModel): CombinedDiffComponentFactory } abstract class CombinedDiffComponentFactory(val model: CombinedDiffModel) { internal val ourDisposable = Disposer.newCheckedDisposable() private val mainUi: CombinedDiffMainUI private var combinedViewer: CombinedDiffViewer init { if (model.haveParentDisposable) { Disposer.register(model.ourDisposable, ourDisposable) } else { Disposer.register(ourDisposable, model.ourDisposable) } model.addListener(ModelListener(), ourDisposable) mainUi = createMainUI() combinedViewer = createCombinedViewer() buildCombinedDiffChildBlocks() } internal fun getPreferredFocusedComponent() = mainUi.getPreferredFocusedComponent() internal fun getMainComponent() = mainUi.getComponent() private fun createMainUI(): CombinedDiffMainUI { return CombinedDiffMainUI(model, ::createGoToChangeAction).also { ui -> Disposer.register(ourDisposable, ui) model.context.putUserData(COMBINED_DIFF_MAIN_UI, ui) } } private fun createCombinedViewer(): CombinedDiffViewer { val context = model.context return CombinedDiffViewer(context).also { viewer -> Disposer.register(ourDisposable, viewer) context.putUserData(COMBINED_DIFF_VIEWER_KEY, viewer) viewer.addBlockListener(MyBlockListener()) mainUi.setContent(viewer) } } protected abstract fun createGoToChangeAction(): AnAction? private inner class ModelListener : CombinedDiffModelListener { override fun onProgressBar(visible: Boolean) { runInEdt { if (visible) mainUi.startProgress() else mainUi.stopProgress() } } override fun onModelReset() { Disposer.dispose(combinedViewer) combinedViewer = createCombinedViewer() buildCombinedDiffChildBlocks() } override fun onContentReloadRequested(requests: Map<CombinedBlockId, DiffRequest>) { model.loadRequestContents(requests.keys.toList(), null) } @RequiresEdt override fun onRequestsLoaded(requests: Map<CombinedBlockId, DiffRequest>, blockIdToSelect: CombinedBlockId?) { for ((blockId, request) in requests) { buildBlockContent(mainUi, model.context, request, blockId)?.let { newContent -> combinedViewer.diffBlocks[blockId]?.let { block -> mainUi.countDifferences(blockId, newContent.viewer) combinedViewer.updateBlockContent(block, newContent) request.onAssigned(true) } } } combinedViewer.contentChanged() if (blockIdToSelect != null) { combinedViewer.diffBlocks[blockIdToSelect]?.let { block -> combinedViewer.selectDiffBlock(block, ScrollPolicy.DIFF_BLOCK, false) } } } @RequiresEdt override fun onRequestsPreloaded(requests: List<Pair<CombinedBlockId, DiffRequest>>) { invokeAndWaitIfNeeded { for ((index, blockIdAndRequest) in requests.withIndex()) { val (blockId, request) = blockIdAndRequest buildBlockContent(mainUi, model.context, request, blockId)?.let { combinedViewer.addChildBlock(it, index > 0) mainUi.countDifferences(blockId, it.viewer) request.onAssigned(true) } } combinedViewer.contentChanged() } } @RequiresEdt override fun onRequestContentsUnloaded(requests: Map<CombinedBlockId, DiffRequest>) { for ((blockId, request) in requests) { buildLoadingBlockContent(blockId, combinedViewer.diffViewers[blockId]?.component?.size).let { newContent -> combinedViewer.diffBlocks[blockId]?.let { block -> combinedViewer.updateBlockContent(block, newContent) request.onAssigned(false) } } } } @RequiresEdt override fun onRequestAdded(requestData: NewRequestData, request: DiffRequest, onAdded: (CombinedBlockId) -> Unit) { addNewBlock(mainUi, combinedViewer, model.context, requestData, request)?.run { onAdded(id) } } } private inner class MyBlockListener : BlockListener { override fun blocksHidden(blocks: Collection<CombinedDiffBlock<*>>) { val blockIds = blocks.asSequence().map(CombinedDiffBlock<*>::id).toSet() model.unloadRequestContents(blockIds) } override fun blocksVisible(blocks: Collection<CombinedDiffBlock<*>>, blockToSelect: CombinedBlockId?) { val blockIds = blocks.asSequence().map(CombinedDiffBlock<*>::id).toSet() model.loadRequestContents(blockIds, blockToSelect) } } private fun buildCombinedDiffChildBlocks() { Alarm(combinedViewer.component, combinedViewer).addComponentRequest( Runnable { val childCount = model.requests.size val visibleBlockCount = min(combinedViewer.scrollPane.visibleRect.height / CombinedLazyDiffViewer.HEIGHT.get(), childCount) val blockToSelect = model.context.getUserData(COMBINED_DIFF_SCROLL_TO_BLOCK) BackgroundTaskUtil.executeOnPooledThread(ourDisposable) { val indicator = EmptyProgressIndicator() BackgroundTaskUtil.runUnderDisposeAwareIndicator(ourDisposable, { runInEdt { mainUi.startProgress() } try { val allRequests = model.requests .asSequence() .map { CombinedDiffModel.RequestData(it.key, it.value) } model.preloadRequests(indicator, allRequests.take(visibleBlockCount).toList()) allRequests.drop(visibleBlockCount).forEachIndexed { index, childRequest -> invokeAndWaitIfNeeded { combinedViewer.addChildBlock(buildLoadingBlockContent(childRequest.blockId), index > 0 || visibleBlockCount > 0) } } } finally { runInEdt { mainUi.stopProgress() if (blockToSelect != null) { combinedViewer.selectDiffBlock(blockToSelect, ScrollPolicy.DIFF_BLOCK, true) } } } }, indicator) } }, 100 ) } companion object { private fun addNewBlock(mainUi: CombinedDiffMainUI, viewer: CombinedDiffViewer, context: DiffContext, requestData: NewRequestData, request: DiffRequest, needTakeTool: (FrameDiffTool) -> Boolean = { true }): CombinedDiffBlock<*>? { val content = buildBlockContent(mainUi, context, request, requestData.blockId, needTakeTool) ?: return null return viewer.insertChildBlock(content, requestData.position) } private fun buildBlockContent(mainUi: CombinedDiffMainUI, context: DiffContext, request: DiffRequest, blockId: CombinedBlockId, needTakeTool: (FrameDiffTool) -> Boolean = { true }): CombinedDiffBlockContent? { val diffSettings = DiffSettingsHolder.DiffSettings.getSettings(context.getUserData(DiffUserDataKeys.PLACE)) val diffTools = DiffManagerEx.getInstance().diffTools request.putUserData(DiffUserDataKeys.ALIGNED_TWO_SIDED_DIFF, true) context.getUserData(DiffUserDataKeysEx.SCROLL_TO_CHANGE)?.let { request.putUserData(DiffUserDataKeysEx.SCROLL_TO_CHANGE, it) } val frameDiffTool = if (mainUi.isUnified() && UnifiedDiffTool.INSTANCE.canShow(context, request)) { UnifiedDiffTool.INSTANCE } else { getDiffToolsExceptUnified(context, diffSettings, diffTools, request, needTakeTool) } val childViewer = frameDiffTool ?.let { findSubstitutor(it, context, request) } ?.createComponent(context, request) ?: return null notifyDiffViewerCreated(childViewer, context, request) return CombinedDiffBlockContent(childViewer, blockId) } private fun buildLoadingBlockContent(blockId: CombinedBlockId, size: Dimension? = null): CombinedDiffBlockContent { return CombinedDiffBlockContent(CombinedLazyDiffViewer(size), blockId) } private fun findSubstitutor(tool: FrameDiffTool, context: DiffContext, request: DiffRequest): FrameDiffTool { return DiffUtil.findToolSubstitutor(tool, context, request) as? FrameDiffTool ?: tool } private fun getDiffToolsExceptUnified(context: DiffContext, diffSettings: DiffSettingsHolder.DiffSettings, diffTools: List<DiffTool>, request: DiffRequest, needTakeTool: (FrameDiffTool) -> Boolean): FrameDiffTool? { return DiffRequestProcessor.getToolOrderFromSettings(diffSettings, diffTools) .asSequence().filterIsInstance<FrameDiffTool>() .filter { needTakeTool(it) && it !is UnifiedDiffTool && it.canShow(context, request) } .toList().let(DiffUtil::filterSuppressedTools).firstOrNull() } private fun notifyDiffViewerCreated(viewer: FrameDiffTool.DiffViewer, context: DiffContext, request: DiffRequest) { DiffExtension.EP_NAME.forEachExtensionSafe { extension -> try { extension.onViewerCreated(viewer, context, request) } catch (e: Throwable) { LOG.error(e) } } } } }
apache-2.0
449b6b0facff7835987c9dd8208bd28e
38.825926
132
0.679624
4.973636
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/gradle/importAndCheckHighlighting/hmppStdlibUsageInAllBackends/p1/src/linuxMain/kotlin/KTIJ2447LinuxMain.kt
10
277
object KTIJ2447LinuxMain { val a = hashMapOf<String, String>() val b = arrayListOf("").associateBy { } val c = buildString { append(342) } fun commonA() = KTIJ2447CommonMain.a fun commonB() = KTIJ2447CommonMain.b fun commonC() = KTIJ2447CommonMain.c }
apache-2.0
a5fc78c6a81a5102130376b04561426f
29.777778
43
0.66787
3.506329
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsOptionsTopHitProvider.kt
4
6572
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.configurable import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsApplicationSettings import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictTracker import com.intellij.openapi.vcs.contentAnnotation.VcsContentAnnotationSettings import com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl import com.intellij.openapi.vfs.ReadonlyStatusHandler import com.intellij.ui.layout.* import com.intellij.vcs.commit.CommitModeManager.Companion.setCommitFromLocalChanges import com.intellij.vcs.commit.message.CommitMessageInspectionProfile import com.intellij.vcsUtil.VcsUtil private val vcsOptionGroupName get() = VcsBundle.message("settings.version.control.option.group") private val commitMessageOptionGroupName get() = VcsBundle.message("settings.commit.message.option.group") private val commitOptionGroupName get() = VcsBundle.message("settings.commit.option.group") private val confirmationOptionGroupName get() = VcsBundle.message("settings.confirmation.option.group") private val changelistsOptionGroupName get() = VcsBundle.message("settings.changelists.option.group") private fun vcsConfiguration(project: Project) = VcsConfiguration.getInstance(project) private fun changelistsOptions(project: Project) = ChangelistConflictTracker.getInstance(project).options private fun cdLimitMaximumHistory(project: Project): CheckboxDescriptor { val vcs = vcsConfiguration(project) val name = VcsBundle.message("settings.limit.history.to.n.rows.label", vcs.MAXIMUM_HISTORY_ROWS) return CheckboxDescriptor(name, vcs::LIMIT_HISTORY, groupName = vcsOptionGroupName) } private fun cdShowChangesLastNDays(project: Project): CheckboxDescriptor { val vcsCA = VcsContentAnnotationSettings.getInstance(project) val name = VcsBundle.message("settings.show.changed.in.last.n.days.label", vcsCA.limitDays) return CheckboxDescriptor(name, PropertyBinding(vcsCA::isShow, vcsCA::setShow), groupName = vcsOptionGroupName) } fun cdShowReadOnlyStatusDialog(project: Project): CheckboxDescriptor { val state = (ReadonlyStatusHandler.getInstance(project) as ReadonlyStatusHandlerImpl).state val name = VcsBundle.message("checkbox.show.clear.read.only.status.dialog") val vcses = ProjectLevelVcsManager.getInstance(project).allSupportedVcss .filter { it.editFileProvider != null } .map { it.displayName } val comment = when { vcses.isNotEmpty() -> VcsBundle.message("description.text.option.applicable.to.vcses", VcsUtil.joinWithAnd(vcses, 0)) else -> null } return CheckboxDescriptor(name, state::SHOW_DIALOG, groupName = vcsOptionGroupName, comment = comment) } private fun cdShowRightMargin(project: Project): CheckboxDescriptor { val margin = CommitMessageInspectionProfile.getBodyRightMargin(project) val name = VcsBundle.message("settings.commit.message.show.right.margin.n.columns.label", margin) return CheckboxDescriptor(name, vcsConfiguration(project)::USE_COMMIT_MESSAGE_MARGIN, groupName = commitMessageOptionGroupName) } // @formatter:off fun cdShowDirtyRecursively(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("checkbox.show.dirty.recursively"), vcsConfiguration(project)::SHOW_DIRTY_RECURSIVELY, groupName = vcsOptionGroupName) private fun cdWrapTypingOnRightMargin(project: Project): CheckboxDescriptor = CheckboxDescriptor(ApplicationBundle.message("checkbox.wrap.typing.on.right.margin"), vcsConfiguration(project)::WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN, groupName = commitMessageOptionGroupName) private fun cdClearInitialCommitMessage(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("checkbox.clear.initial.commit.message"), vcsConfiguration(project)::CLEAR_INITIAL_COMMIT_MESSAGE, groupName = commitMessageOptionGroupName) private fun cdIncludeShelfBaseContent(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("vcs.shelf.store.base.content"), vcsConfiguration(project)::INCLUDE_TEXT_INTO_SHELF, groupName = confirmationOptionGroupName) private fun cdChangelistConflictDialog(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("settings.show.conflict.resolve.dialog.checkbox"), changelistsOptions(project)::SHOW_DIALOG, groupName = changelistsOptionGroupName) private fun cdChangelistShowConflicts(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("settings.highlight.files.with.conflicts.checkbox"), changelistsOptions(project)::HIGHLIGHT_CONFLICTS, groupName = changelistsOptionGroupName) private fun cdChangelistShowNonCurrent(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("settings.highlight.files.from.non.active.changelist.checkbox"), changelistsOptions(project)::HIGHLIGHT_NON_ACTIVE_CHANGELIST, groupName = changelistsOptionGroupName) private fun cdNonModalCommit(project: Project): CheckboxDescriptor = CheckboxDescriptor(VcsBundle.message("settings.commit.without.dialog"), PropertyBinding({ VcsApplicationSettings.getInstance().COMMIT_FROM_LOCAL_CHANGES }, { setCommitFromLocalChanges(project, it) }), groupName = commitOptionGroupName) // @formatter:on class VcsOptionsTopHitProvider : VcsOptionsTopHitProviderBase() { override fun getId(): String { return "vcs" } override fun getOptions(project: Project): Collection<OptionDescription> { if (!project.isDefault && !ProjectLevelVcsManager.getInstance(project).hasActiveVcss()) { return emptyList() } return listOf( cdLimitMaximumHistory(project), cdShowChangesLastNDays(project), cdShowReadOnlyStatusDialog(project), cdShowRightMargin(project), cdShowDirtyRecursively(project), cdWrapTypingOnRightMargin(project), cdClearInitialCommitMessage(project), cdIncludeShelfBaseContent(project), cdChangelistConflictDialog(project), cdChangelistShowConflicts(project), cdChangelistShowNonCurrent(project), cdNonModalCommit(project) ).map(CheckboxDescriptor::asOptionDescriptor) } }
apache-2.0
de18808fad8939e8cf8d7e9e5819d6b5
67.46875
319
0.812538
4.83947
false
true
false
false
jk1/intellij-community
java/execution/impl/src/com/intellij/execution/ui/DefaultJreSelector.kt
2
5110
/* * 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.execution.ui import com.intellij.application.options.ModuleDescriptionsComboBox import com.intellij.application.options.ModulesComboBox import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.util.JavaParametersUtil import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.util.Pair import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.ui.EditorTextFieldWithBrowseButton /** * @author nik */ abstract class DefaultJreSelector { companion object { @JvmStatic fun projectSdk(project: Project): DefaultJreSelector = ProjectSdkSelector(project) @JvmStatic fun fromModuleDependencies(moduleComboBox: ModulesComboBox, productionOnly: Boolean): DefaultJreSelector = SdkFromModuleDependencies(moduleComboBox, ModulesComboBox::getSelectedModule, {productionOnly}) @JvmStatic fun fromModuleDependencies(moduleComboBox: ModuleDescriptionsComboBox, productionOnly: Boolean): DefaultJreSelector = SdkFromModuleDependencies(moduleComboBox, ModuleDescriptionsComboBox::getSelectedModule, {productionOnly}) @JvmStatic fun fromSourceRootsDependencies(moduleComboBox: ModulesComboBox, classSelector: EditorTextFieldWithBrowseButton): DefaultJreSelector = SdkFromSourceRootDependencies(moduleComboBox, ModulesComboBox::getSelectedModule, classSelector) @JvmStatic fun fromSourceRootsDependencies(moduleComboBox: ModuleDescriptionsComboBox, classSelector: EditorTextFieldWithBrowseButton): DefaultJreSelector = SdkFromSourceRootDependencies(moduleComboBox, ModuleDescriptionsComboBox::getSelectedModule, classSelector) } abstract fun getNameAndDescription(): Pair<String?, String> open fun addChangeListener(listener: Runnable) { } fun getDescriptionString(): String { val (name, description) = getNameAndDescription() return " (${name ?: "<no JRE>"} - $description)" } class ProjectSdkSelector(val project: Project): DefaultJreSelector() { override fun getNameAndDescription(): Pair<String?, String> = Pair.create(ProjectRootManager.getInstance(project).projectSdkName, "project SDK") } open class SdkFromModuleDependencies<T: ComboBox<*>>(val moduleComboBox: T, val getSelectedModule: (T) -> Module?, val productionOnly: () -> Boolean): DefaultJreSelector() { override fun getNameAndDescription(): Pair<String?, String> { val module = getSelectedModule(moduleComboBox) ?: return Pair.create(null, "module not specified") val productionOnly = productionOnly() val jdkToRun = JavaParameters.getJdkToRunModule(module, productionOnly) val moduleJdk = ModuleRootManager.getInstance(module).sdk if (moduleJdk == null || jdkToRun == null) { return Pair.create(null, "module not specified") } if (moduleJdk.homeDirectory == jdkToRun.homeDirectory) { return Pair.create(moduleJdk.name, "SDK of '${module.name}' module") } return Pair.create(jdkToRun.name, "newest SDK from '${module.name}' module${if (productionOnly) "" else " test"} dependencies") } override fun addChangeListener(listener: Runnable) { moduleComboBox.addActionListener { listener.run() } } } class SdkFromSourceRootDependencies<T: ComboBox<*>>(moduleComboBox: T, getSelectedModule: (T) -> Module?, val classSelector: EditorTextFieldWithBrowseButton) : SdkFromModuleDependencies<T>(moduleComboBox, getSelectedModule, { isClassInProductionSources(moduleComboBox, getSelectedModule, classSelector) }) { override fun addChangeListener(listener: Runnable) { super.addChangeListener(listener) classSelector.childComponent.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent?) { listener.run() } }) } } } private fun <T: ComboBox<*>> isClassInProductionSources(moduleSelector: T, getSelectedModule: (T) -> Module?, classSelector: EditorTextFieldWithBrowseButton): Boolean { val module = getSelectedModule(moduleSelector) ?: return false return JavaParametersUtil.isClassInProductionSources(classSelector.text, module) ?: false }
apache-2.0
acdd36bd8cbed47c4179c1983ea65bb1
45.036036
175
0.771233
4.766791
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/HttpHeaders.kt
1
8806
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http @Suppress("unused", "KDocMissingDocumentation", "PublicApiImplicitType", "MayBeConstant") public object HttpHeaders { // Permanently registered standard HTTP headers // The list is taken from http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers public val Accept: String = "Accept" public val AcceptCharset: String = "Accept-Charset" public val AcceptEncoding: String = "Accept-Encoding" public val AcceptLanguage: String = "Accept-Language" public val AcceptRanges: String = "Accept-Ranges" public val Age: String = "Age" public val Allow: String = "Allow" // Application-Layer Protocol Negotiation, HTTP/2 public val ALPN: String = "ALPN" public val AuthenticationInfo: String = "Authentication-Info" public val Authorization: String = "Authorization" public val CacheControl: String = "Cache-Control" public val Connection: String = "Connection" public val ContentDisposition: String = "Content-Disposition" public val ContentEncoding: String = "Content-Encoding" public val ContentLanguage: String = "Content-Language" public val ContentLength: String = "Content-Length" public val ContentLocation: String = "Content-Location" public val ContentRange: String = "Content-Range" public val ContentType: String = "Content-Type" public val Cookie: String = "Cookie" // WebDAV Search public val DASL: String = "DASL" public val Date: String = "Date" // WebDAV public val DAV: String = "DAV" public val Depth: String = "Depth" public val Destination: String = "Destination" public val ETag: String = "ETag" public val Expect: String = "Expect" public val Expires: String = "Expires" public val From: String = "From" public val Forwarded: String = "Forwarded" public val Host: String = "Host" public val HTTP2Settings: String = "HTTP2-Settings" public val If: String = "If" public val IfMatch: String = "If-Match" public val IfModifiedSince: String = "If-Modified-Since" public val IfNoneMatch: String = "If-None-Match" public val IfRange: String = "If-Range" public val IfScheduleTagMatch: String = "If-Schedule-Tag-Match" public val IfUnmodifiedSince: String = "If-Unmodified-Since" public val LastModified: String = "Last-Modified" public val Location: String = "Location" public val LockToken: String = "Lock-Token" public val Link: String = "Link" public val MaxForwards: String = "Max-Forwards" public val MIMEVersion: String = "MIME-Version" public val OrderingType: String = "Ordering-Type" public val Origin: String = "Origin" public val Overwrite: String = "Overwrite" public val Position: String = "Position" public val Pragma: String = "Pragma" public val Prefer: String = "Prefer" public val PreferenceApplied: String = "Preference-Applied" public val ProxyAuthenticate: String = "Proxy-Authenticate" public val ProxyAuthenticationInfo: String = "Proxy-Authentication-Info" public val ProxyAuthorization: String = "Proxy-Authorization" public val PublicKeyPins: String = "Public-Key-Pins" public val PublicKeyPinsReportOnly: String = "Public-Key-Pins-Report-Only" public val Range: String = "Range" public val Referrer: String = "Referer" public val RetryAfter: String = "Retry-After" public val ScheduleReply: String = "Schedule-Reply" public val ScheduleTag: String = "Schedule-Tag" public val SecWebSocketAccept: String = "Sec-WebSocket-Accept" public val SecWebSocketExtensions: String = "Sec-WebSocket-Extensions" public val SecWebSocketKey: String = "Sec-WebSocket-Key" public val SecWebSocketProtocol: String = "Sec-WebSocket-Protocol" public val SecWebSocketVersion: String = "Sec-WebSocket-Version" public val Server: String = "Server" public val SetCookie: String = "Set-Cookie" // Atom Publishing public val SLUG: String = "SLUG" public val StrictTransportSecurity: String = "Strict-Transport-Security" public val TE: String = "TE" public val Timeout: String = "Timeout" public val Trailer: String = "Trailer" public val TransferEncoding: String = "Transfer-Encoding" public val Upgrade: String = "Upgrade" public val UserAgent: String = "User-Agent" public val Vary: String = "Vary" public val Via: String = "Via" public val Warning: String = "Warning" public val WWWAuthenticate: String = "WWW-Authenticate" // CORS public val AccessControlAllowOrigin: String = "Access-Control-Allow-Origin" public val AccessControlAllowMethods: String = "Access-Control-Allow-Methods" public val AccessControlAllowCredentials: String = "Access-Control-Allow-Credentials" public val AccessControlAllowHeaders: String = "Access-Control-Allow-Headers" public val AccessControlRequestMethod: String = "Access-Control-Request-Method" public val AccessControlRequestHeaders: String = "Access-Control-Request-Headers" public val AccessControlExposeHeaders: String = "Access-Control-Expose-Headers" public val AccessControlMaxAge: String = "Access-Control-Max-Age" // Unofficial de-facto headers public val XHttpMethodOverride: String = "X-Http-Method-Override" public val XForwardedHost: String = "X-Forwarded-Host" public val XForwardedServer: String = "X-Forwarded-Server" public val XForwardedProto: String = "X-Forwarded-Proto" public val XForwardedFor: String = "X-Forwarded-For" public val XForwardedPort: String = "X-Forwarded-Port" public val XRequestId: String = "X-Request-ID" public val XCorrelationId: String = "X-Correlation-ID" public val XTotalCount: String = "X-Total-Count" /** * Check if [header] is unsafe. Header is unsafe if listed in [UnsafeHeadersList] */ public fun isUnsafe(header: String): Boolean = UnsafeHeadersArray.any { it.equals(header, ignoreCase = true) } private val UnsafeHeadersArray: Array<String> = arrayOf(TransferEncoding, Upgrade) @Deprecated("Use UnsafeHeadersList instead.", replaceWith = ReplaceWith("HttpHeaders.UnsafeHeadersList")) public val UnsafeHeaders: Array<String> get() = UnsafeHeadersArray.copyOf() /** * A list of header names that are not safe to use unless it is low-level engine implementation. */ public val UnsafeHeadersList: List<String> = UnsafeHeadersArray.asList() /** * Validates header [name] throwing [IllegalHeaderNameException] when the name is not valid. */ public fun checkHeaderName(name: String) { name.forEachIndexed { index, ch -> if (ch <= ' ' || isDelimiter(ch)) { throw IllegalHeaderNameException(name, index) } } } /** * Validates header [value] throwing [IllegalHeaderValueException] when the value is not valid. */ public fun checkHeaderValue(value: String) { value.forEachIndexed { index, ch -> if (ch < ' ' && ch != '\u0009') { throw IllegalHeaderValueException(value, index) } } } } /** * Thrown when an attempt to set unsafe header detected. A header is unsafe if listed in [HttpHeaders.UnsafeHeadersList]. */ public class UnsafeHeaderException(header: String) : IllegalArgumentException( "Header(s) $header are controlled by the engine and " + "cannot be set explicitly" ) /** * Thrown when an illegal header name was used. * A header name should only consist from visible characters * without delimiters "double quote" and the following characters: `(),/:;<=>?@[\]{}`. * @property headerName that was tried to use * @property position at which validation failed */ public class IllegalHeaderNameException(public val headerName: String, public val position: Int) : IllegalArgumentException( "Header name '$headerName' contains illegal character '${headerName[position]}'" + " (code ${(headerName[position].code and 0xff)})" ) /** * Thrown when an illegal header value was used. * A header value should only consist from visible characters, spaces and/or HTAB (0x09). * @property headerValue that was tried to use * @property position at which validation failed */ public class IllegalHeaderValueException(public val headerValue: String, public val position: Int) : IllegalArgumentException( "Header value '$headerValue' contains illegal character '${headerValue[position]}'" + " (code ${(headerValue[position].code and 0xff)})" ) private fun isDelimiter(ch: Char): Boolean = ch in "\"(),/:;<=>?@[\\]{}"
apache-2.0
444c8bb22d998ac1587d404102079a3e
43.251256
121
0.70452
4.245902
false
false
false
false
ktorio/ktor
ktor-utils/jvm/src/io/ktor/util/reflect/TypeInfoJvm.kt
1
903
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.reflect import kotlin.reflect.* public actual typealias Type = java.lang.reflect.Type @PublishedApi @Deprecated("Will be removed") internal open class TypeBase<T> @OptIn(ExperimentalStdlibApi::class) public actual inline fun <reified T> typeInfo(): TypeInfo { val kType = typeOf<T>() val reifiedType = kType.javaType return typeInfoImpl(reifiedType, T::class, kType) } public fun typeInfoImpl(reifiedType: Type, kClass: KClass<*>, kType: KType?): TypeInfo = TypeInfo(kClass, reifiedType, kType) /** * Check [this] is instance of [type]. */ public actual fun Any.instanceOf(type: KClass<*>): Boolean = type.java.isInstance(this) @OptIn(ExperimentalStdlibApi::class) public actual val KType.platformType: Type get() = javaType
apache-2.0
a36d0a628b4293cba0829147bbe68731
27.21875
119
0.736434
3.842553
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-caching-headers/jvmAndNix/src/io/ktor/server/plugins/cachingheaders/CacheControlMerge.kt
1
2833
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.cachingheaders import io.ktor.http.* /** * Merge a list of cache control directives. * * Currently, visibility is pinned to the expiration directive, * then to the first no-cache, * then to the no-store directive. * The RFC doesn't state, where a visibility modifier should be so we can place it at any place * so there is nothing behind the rule beyond, therefore could be changed. * * Only one visibility specifier is kept. * * If there are different visibility modifiers specified, then the private wins. * All max ages directives are reduced to a single with all minimal max age values. * * A no-cache directive is always placed first. * A no-store directive is always placed after no-cache, otherwise it's placed first. * A max-age directive is always the last. * * Revalidation directives are collected as well. * Currently, revalidation directives are tied to max age by-design. * This is not fair according to RFC so will be changed in the future. */ internal fun List<CacheControl>.mergeCacheControlDirectives(): List<CacheControl> { if (size < 2) return this val visibility = when { any { it.visibility == CacheControl.Visibility.Private } -> CacheControl.Visibility.Private any { it.visibility == CacheControl.Visibility.Public } -> CacheControl.Visibility.Public else -> null } val noCacheDirective = firstOrNull { it is CacheControl.NoCache } as CacheControl.NoCache? val noStoreDirective = firstOrNull { it is CacheControl.NoStore } as CacheControl.NoStore? val maxAgeDirectives = filterIsInstance<CacheControl.MaxAge>() val minMaxAge = maxAgeDirectives.minByOrNull { it.maxAgeSeconds }?.maxAgeSeconds val minProxyMaxAge = maxAgeDirectives.minByOrNull { it.proxyMaxAgeSeconds ?: Int.MAX_VALUE }?.proxyMaxAgeSeconds val mustRevalidate = maxAgeDirectives.any { it.mustRevalidate } val proxyRevalidate = maxAgeDirectives.any { it.proxyRevalidate } return mutableListOf<CacheControl>().apply { noCacheDirective?.let { add(CacheControl.NoCache(null)) } noStoreDirective?.let { add(CacheControl.NoStore(null)) } if (maxAgeDirectives.isNotEmpty()) { add( CacheControl.MaxAge( minMaxAge!!, minProxyMaxAge, mustRevalidate, proxyRevalidate, visibility ) ) } else { when { noCacheDirective != null -> set(0, CacheControl.NoCache(visibility)) noStoreDirective != null -> set(0, CacheControl.NoStore(visibility)) } } } }
apache-2.0
cc07970ba54aaa06ff2cc7c82472f350
39.471429
119
0.680198
4.76936
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionPresenter.kt
1
7359
package eu.kanade.tachiyomi.ui.browse.extension import android.app.Application import android.os.Bundle import android.view.View import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferenceValues import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.extension.ExtensionManager import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.util.system.LocaleHelper import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.util.concurrent.TimeUnit private typealias ExtensionTuple = Triple<List<Extension.Installed>, List<Extension.Untrusted>, List<Extension.Available>> /** * Presenter of [ExtensionController]. */ open class ExtensionPresenter( private val extensionManager: ExtensionManager = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get() ) : BasePresenter<ExtensionController>() { private var extensions = emptyList<ExtensionItem>() private var currentDownloads = hashMapOf<String, InstallStep>() override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) extensionManager.findAvailableExtensions() bindToExtensionsObservable() } private fun bindToExtensionsObservable(): Subscription { val installedObservable = extensionManager.getInstalledExtensionsObservable() val untrustedObservable = extensionManager.getUntrustedExtensionsObservable() val availableObservable = extensionManager.getAvailableExtensionsObservable() .startWith(emptyList<Extension.Available>()) return Observable.combineLatest(installedObservable, untrustedObservable, availableObservable) { installed, untrusted, available -> Triple(installed, untrusted, available) } .debounce(500, TimeUnit.MILLISECONDS) .map(::toItems) .observeOn(AndroidSchedulers.mainThread()) .subscribeLatestCache({ view, _ -> view.setExtensions(extensions) }) } @Synchronized private fun toItems(tuple: ExtensionTuple): List<ExtensionItem> { val context = Injekt.get<Application>() val activeLangs = preferences.enabledLanguages().get() val showNsfwSources = preferences.showNsfwSource().get() val (installed, untrusted, available) = tuple val items = mutableListOf<ExtensionItem>() val updatesSorted = installed.filter { it.hasUpdate && (showNsfwSources || !it.isNsfw) } .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.name })) val installedSorted = installed.filter { !it.hasUpdate && (showNsfwSources || !it.isNsfw) } .sortedWith( compareBy<Extension.Installed> { !it.isObsolete } .thenBy(String.CASE_INSENSITIVE_ORDER) { it.name } ) val untrustedSorted = untrusted.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.name })) val availableSorted = available // Filter out already installed extensions and disabled languages .filter { avail -> installed.none { it.pkgName == avail.pkgName } && untrusted.none { it.pkgName == avail.pkgName } && avail.lang in activeLangs && (showNsfwSources || !avail.isNsfw) } .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.name })) if (updatesSorted.isNotEmpty()) { val header = ExtensionGroupItem(context.getString(R.string.ext_updates_pending), updatesSorted.size, true) if (preferences.extensionInstaller().get() != PreferenceValues.ExtensionInstaller.LEGACY) { header.actionLabel = context.getString(R.string.ext_update_all) header.actionOnClick = View.OnClickListener { _ -> extensions .filter { it.extension is Extension.Installed && it.extension.hasUpdate } .forEach { updateExtension(it.extension as Extension.Installed) } } } items += updatesSorted.map { extension -> ExtensionItem(extension, header, currentDownloads[extension.pkgName] ?: InstallStep.Idle) } } if (installedSorted.isNotEmpty() || untrustedSorted.isNotEmpty()) { val header = ExtensionGroupItem(context.getString(R.string.ext_installed), installedSorted.size + untrustedSorted.size) items += installedSorted.map { extension -> ExtensionItem(extension, header, currentDownloads[extension.pkgName] ?: InstallStep.Idle) } items += untrustedSorted.map { extension -> ExtensionItem(extension, header) } } if (availableSorted.isNotEmpty()) { val availableGroupedByLang = availableSorted .groupBy { LocaleHelper.getSourceDisplayName(it.lang, context) } .toSortedMap() availableGroupedByLang .forEach { val header = ExtensionGroupItem(it.key, it.value.size) items += it.value.map { extension -> ExtensionItem(extension, header, currentDownloads[extension.pkgName] ?: InstallStep.Idle) } } } this.extensions = items return items } @Synchronized private fun updateInstallStep(extension: Extension, state: InstallStep): ExtensionItem? { val extensions = extensions.toMutableList() val position = extensions.indexOfFirst { it.extension.pkgName == extension.pkgName } return if (position != -1) { val item = extensions[position].copy(installStep = state) extensions[position] = item this.extensions = extensions item } else { null } } fun installExtension(extension: Extension.Available) { extensionManager.installExtension(extension).subscribeToInstallUpdate(extension) } fun updateExtension(extension: Extension.Installed) { extensionManager.updateExtension(extension).subscribeToInstallUpdate(extension) } fun cancelInstallUpdateExtension(extension: Extension) { extensionManager.cancelInstallUpdateExtension(extension) } private fun Observable<InstallStep>.subscribeToInstallUpdate(extension: Extension) { this.doOnNext { currentDownloads[extension.pkgName] = it } .doOnUnsubscribe { currentDownloads.remove(extension.pkgName) } .map { state -> updateInstallStep(extension, state) } .subscribeWithView({ view, item -> if (item != null) { view.downloadUpdate(item) } }) } fun uninstallExtension(pkgName: String) { extensionManager.uninstallExtension(pkgName) } fun findAvailableExtensions() { extensionManager.findAvailableExtensions() } fun trustSignature(signatureHash: String) { extensionManager.trustSignature(signatureHash) } }
apache-2.0
a115e43d68749372f6c0e49394f6fe33
39.883333
181
0.661911
5.117524
false
false
false
false
actions-on-google/actions-shortcut-convert
src/main/kotlin/com/google/assistant/actions/converters/ShortcutConverter.kt
1
5177
// 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.assistant.actions.converters import com.google.assistant.actions.* import com.google.assistant.actions.model.actions.Action import com.google.assistant.actions.model.actions.ActionsRoot import com.google.assistant.actions.model.actions.Entity import com.google.assistant.actions.model.actions.EntitySet import com.google.assistant.actions.model.shortcuts.* private var shortcutIdCount = 0 fun convertActionsToShortcuts(actionsRoot: ActionsRoot): List<Shortcut> { // Creates a map of entity set IDs to actions for use when creating the <shortcut> tags val entitySetIdToAction = mutableMapOf<String, MutableList<Action>>() actionsRoot.actions.forEach { action -> val entitySetIds = getEntitySetIdsForAction(action) entitySetIds.forEach { entitySetId -> val actions = entitySetIdToAction[entitySetId] ?: mutableListOf() actions.add(action) entitySetIdToAction[entitySetId] = actions } } val shortcuts = mutableListOf<Shortcut>() actionsRoot.entitySets.forEach { entitySet -> addShortcutsFromEntitySets(entitySet, entitySetIdToAction, shortcuts) } actionsRoot.actions.forEach { action -> action.entitySets.forEach { entitySet -> addShortcutsFromEntitySets(entitySet, entitySetIdToAction, shortcuts) } } return shortcuts } private fun addShortcutsFromEntitySets( entitySet: EntitySet, entitySetIdToActions: Map<String, List<Action>>, shortcuts: MutableList<Shortcut> ) { val matchingActions = entitySetIdToActions[entitySet.entitySetId] ?: return val shortcutIdToShortcutMap = mutableMapOf<String, Shortcut>() entitySet.entities.forEach { entity -> val capabilityBindings = createCapabilityBindingsFromEntity(matchingActions, entity) val intent: ShortcutIntent = createIntentFromEntity(entity) val id = entity.identifier ?: "" val extra = createExtraFromEntity(entity) val extras = if (extra != null) mutableListOf(extra) else mutableListOf() if (shortcutIdToShortcutMap.containsKey(id)) { if (extra != null) { shortcutIdToShortcutMap[id]!!.extras += extra //TODO: clean up !! usage } } else { // No shortcut created for this identifier, proceed with adding new shortcut. val shortcut = Shortcut( shortcutId = id.ifEmpty { "YOUR_SHORTCUT_ID_" + shortcutIdCount++ }, shortcutShortLabel = DEFAULT_SHORTCUT_SHORT_LABEL, enabled = "false", intents = mutableListOf(intent), capabilityBindings = capabilityBindings, extras = extras ) shortcuts.add(shortcut) shortcutIdToShortcutMap[id] = shortcut } } } private fun createCapabilityBindingsFromEntity( matchingActions: List<Action>, entity: Entity ): List<CapabilityBinding> { return matchingActions.mapNotNull { matchingAction -> createCapabilityBinding(matchingAction, entity).takeIf { val intentName = matchingAction.intentName intentName != null && intentName.startsWith( ACTIONS_BUILT_IN_INTENT_RESERVED_NAMESPACE ) } } } private fun createIntentFromEntity(entity: Entity?): ShortcutIntent { return ShortcutIntent( // Defaulting to android.intent.action.VIEW and allowing user to override action = ANDROID_ACTION_VIEW_DEFAULT_INTENT, data = entity?.url ) } private fun createExtraFromEntity(entity: Entity): Extra? { if (entity.sameAs.isNullOrEmpty()) { return null } return Extra( key = SAME_AS_KEY, value = entity.sameAs ) } private fun createCapabilityBinding( action: Action, entity: Entity? ): CapabilityBinding { return CapabilityBinding( key = action.intentName, parameterBinding = mutableListOf(createParameterBinding(action, entity)) ) } private fun createParameterBinding( action: Action, matchingEntity: Entity? ): ParameterBinding { action.parameters.forEach { parameter -> return ParameterBinding(key = parameter.name, value = matchingEntity?.name) } return ParameterBinding( key = DEFAULT_PARAMETER_BINDING_KEY, value = DEFAULT_PARAMETER_BINDING_VALUE ) } private fun getEntitySetIdsForAction(action: Action): List<String> { return action.parameters.mapNotNull { parameter -> parameter.entitySetReference?.entitySetId } }
apache-2.0
934ce666ec5b8d9f1b75e11376550c5d
34.703448
92
0.688816
4.693563
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/reader/view/rss/ArticleCardAdapter.kt
1
2622
package org.secfirst.umbrella.feature.reader.view.rss import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.card_article_view.view.* import org.jsoup.Jsoup import org.secfirst.umbrella.R import org.secfirst.umbrella.data.database.reader.Article import org.secfirst.umbrella.data.database.reader.RSS import org.secfirst.umbrella.misc.convertDateToString import org.secfirst.umbrella.misc.shareLink class ArticleCardAdapter(private val onClickLearnMore: (Article) -> Unit) : RecyclerView.Adapter<ArticleCardAdapter.CardHolder>() { private lateinit var items: MutableList<Article> override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.card_article_view, parent, false) return CardHolder(view) } override fun getItemCount() = items.size override fun onBindViewHolder(holder: CardHolder, position: Int) { holder.bind(items[position], clickListener = { onClickLearnMore(items[position]) }) } fun addAll(rss: RSS) { items = rss.items_.toMutableList() } class CardHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(articleItem: Article, clickListener: (CardHolder) -> Unit) { with(articleItem) { itemView.cardTitle.text = title itemView.cardDescription.text = Jsoup.parse(description_).text() itemView.cardLastUpdate.text = convertDateToString(publicationDate) itemView.cardOpenLink.setOnClickListener { clickListener(this@CardHolder) } itemView.cardShare.setOnClickListener { itemView.context.shareLink(link) } if (imageLink_ != "") Picasso.get() .load(imageLink_) .placeholder(ContextCompat.getDrawable(itemView.context, R.drawable.default_image) ?: ColorDrawable(Color.TRANSPARENT)) .into(itemView.cardImage) else Picasso.get() .load("nothing") .placeholder(ContextCompat.getDrawable(itemView.context, R.drawable.default_image) ?: ColorDrawable(Color.TRANSPARENT)) .into(itemView.cardImage) } } } }
gpl-3.0
c66815a418c9ee1f69bac6172544a14f
42.716667
147
0.678108
4.758621
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/account/presenter/AccountPresenterImp.kt
1
5802
package org.secfirst.umbrella.feature.account.presenter import com.raizlabs.android.dbflow.config.FlowManager import org.secfirst.umbrella.data.database.AppDatabase.EXTENSION import org.secfirst.umbrella.data.database.AppDatabase.NAME import org.secfirst.umbrella.data.database.reader.FeedLocation import org.secfirst.umbrella.data.database.reader.FeedSource import org.secfirst.umbrella.data.disk.validateRepository import org.secfirst.umbrella.feature.account.interactor.AccountBaseInteractor import org.secfirst.umbrella.feature.account.view.AccountView import org.secfirst.umbrella.feature.base.presenter.BasePresenterImp import org.secfirst.umbrella.misc.AppExecutors.Companion.uiContext import org.secfirst.umbrella.misc.launchSilent import java.io.File import javax.inject.Inject class AccountPresenterImp<V : AccountView, I : AccountBaseInteractor> @Inject constructor( interactor: I) : BasePresenterImp<V, I>( interactor = interactor), AccountBasePresenter<V, I> { override fun changeContentLanguage(path: String) { launchSilent (uiContext) { interactor?.let { if (it.serializeNewContent(path)) { getView()?.onChangedLanguageSuccess() } else { getView()?.onChangedLanguageFail() } } } } override fun submitIsMaskApp() { interactor?.let { getView()?.getMaskApp(it.isMaskApp()) } } override fun setDefaultLanguage(isoCountry: String) { interactor?.setDefaultLanguage(isoCountry) } override fun submitDefaultLanguage() { interactor?.let { getView()?.getDefaultLanguage(it.getDefaultLanguage()) } } override fun submitFakeView(isShowFakeView: Boolean) { interactor?.setFakeView(isShowFakeView) } override fun switchServerProcess(repoUrl: String) { launchSilent(uiContext) { var isReset = false if (validateRepository(repoUrl)) isReset = interactor?.resetContent() ?: false getView()?.onSwitchServer(isReset) } } override fun submitExportDatabase(destinationDir: String, fileName: String, isWipeData: Boolean) { if (destinationDir.isNotBlank()) { val dstDatabase = File("$destinationDir/$fileName.$EXTENSION") val databaseFile = FlowManager.getContext().getDatabasePath("$NAME.$EXTENSION") databaseFile.copyTo(dstDatabase, true) if (isWipeData) launchSilent(uiContext) { interactor?.resetContent() } getView()?.exportDatabaseSuccessfully() } } override fun prepareShareContent(fileName: String) { val databaseFile = FlowManager.getContext().getDatabasePath("$NAME.$EXTENSION") val backupFile = File("${FlowManager.getContext().cacheDir}/$fileName.$EXTENSION") databaseFile.copyTo(backupFile, true) getView()?.onShareContent(backupFile) } override fun validateBackupPath(backupPath: String) { val backupDatabase = File(backupPath) val databaseFile = FlowManager.getContext().getDatabasePath("$NAME.$EXTENSION") backupDatabase.copyTo(databaseFile, true) if (backupDatabase.extension == EXTENSION) { getView()?.onImportBackupSuccess() } else getView()?.onImportBackupFail() } override fun prepareView() { launchSilent(uiContext) { interactor?.let { val feedLocation = it.fetchFeedLocation() val refreshFeedInterval = it.fetchRefreshInterval() val feedSource = it.fetchFeedSources() getView()?.loadDefaultValue(feedLocation, refreshFeedInterval, feedSource) } } } override fun submitCleanDatabase() { launchSilent(uiContext) { interactor?.let { getView()?.onResetContent(it.resetContent()) } } } override fun submitIsLogged() { val res = interactor?.isUserLoggedIn() ?: false getView()?.isUserLogged(res) } override fun setMaskApp(value: Boolean) { interactor?.setMaskApp(value) } override fun submitSkippPassword() { val res = interactor?.isSkippPassword() ?: false getView()?.getSkipPassword(res) } override fun submitInsertFeedSource(feedSources: List<FeedSource>) { launchSilent(uiContext) { interactor?.insertAllFeedSources(feedSources) } } override fun submitFeedLocation(feedLocation: FeedLocation) { launchSilent(uiContext) { interactor?.insertFeedLocation(feedLocation) } } override fun setUserLogIn() { interactor?.setLoggedIn(true) } override fun submitPutRefreshInterval(position: Int) { launchSilent(uiContext) { interactor?.putRefreshInterval(position) } } override fun setSkipPassword(value: Boolean) { launchSilent(uiContext) { interactor?.let { it.setSkipPassword(value) if (value) { it.enablePasswordBanner(false) } else { it.enablePasswordBanner(true) } } getView()?.getSkipPassword(value) } } override fun submitChangeDatabaseAccess(userToken: String) { launchSilent(uiContext) { interactor?.let { val res = it.changeDatabaseAccess(userToken) if (res) { it.setLoggedIn(true) it.setSkipPassword(true) it.enablePasswordBanner(false) } getView()?.isTokenChanged(res) } } } }
gpl-3.0
a5f7ac3d718635f1c97470c6dd32207f
33.135294
102
0.633919
4.958974
false
false
false
false
CesarValiente/KUnidirectional
persistence/src/androidTest/kotlin/com/cesarvaliente/kunidirectional/persistence/handler/DeleteHandlerTest.kt
1
2726
/** * Copyright (C) 2017 Cesar Valiente & Corey Shaw * * https://github.com/CesarValiente * https://github.com/coshaw * * 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.cesarvaliente.kunidirectional.persistence.handler import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.cesarvaliente.kunidirectional.persistence.createPersistenceItem import com.cesarvaliente.kunidirectional.persistence.delete import com.cesarvaliente.kunidirectional.persistence.insertOrUpdate import com.cesarvaliente.kunidirectional.persistence.queryAllItemsSortedByPosition import io.realm.Realm import io.realm.RealmConfiguration import org.hamcrest.CoreMatchers.not import org.junit.After import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import com.cesarvaliente.kunidirectional.persistence.Color as PersistenceColor import com.cesarvaliente.kunidirectional.persistence.Item as PersistenceItem import com.cesarvaliente.kunidirectional.store.Color as StoreColor import com.cesarvaliente.kunidirectional.store.Item as StoreItem import org.hamcrest.core.Is.`is` as iz @RunWith(AndroidJUnit4::class) class DeleteHandlerTest { lateinit var config: RealmConfiguration lateinit var db: Realm @Before fun setup() { Realm.init(InstrumentationRegistry.getTargetContext()) config = RealmConfiguration.Builder() .name("test.realm") .inMemory() .build() Realm.setDefaultConfiguration(config) db = Realm.getInstance(config) } @After fun clean() { db.close() Realm.deleteRealm(config) } @Test fun should_delete_Item() { val item = createPersistenceItem(1) val managedItem = item.insertOrUpdate(db) var itemsCollection = db.queryAllItemsSortedByPosition() assertThat(itemsCollection, iz(not(emptyList<PersistenceItem>()))) assertThat(itemsCollection.size, iz(1)) managedItem.delete(db) itemsCollection = db.queryAllItemsSortedByPosition() assertThat(itemsCollection, iz(emptyList<PersistenceItem>())) } }
apache-2.0
27304f36bc9c89a1c56e3e3c9e7ce5e7
34.415584
82
0.74945
4.490939
false
true
false
false