path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
library/src/main/java/net/vrgsoft/library/ParseContent.kt | VRGsoftUA | 94,071,050 | false | null | package net.vrgsoft.library
data class ParseContent(
var success: Boolean = false,
var htmlCode: String = "",
var raw: String = "",
var title: String = "",
var description: String = "",
var url: String = "",
var finalUrl: String = "",
var canonicalUrl: String = "",
var metaTags: Map<String, String> = mapOf(),
var images: MutableList<String> = mutableListOf(),
var urlData: List<Int> = listOf()
) | 3 | Kotlin | 3 | 49 | 6eb49be161d83cdc17986d10f85a3f2fb8cdc50b | 420 | Kotlin-Link-Parser | Apache License 2.0 |
validator-web/src/commonMain/kotlin/com.chrynan.validator/UrlValidator.kt | chRyNaN | 283,900,572 | false | null | package com.chrynan.validator
class UrlValidator : Validator<String?, String> {
companion object {
private val URL_REGEX = Regex(WebRegexConstants.WEB_URL)
private val AUTO_URL_REGEX = Regex(WebRegexConstants.AUTOLINK_WEB_URL)
}
override fun validate(input: String?): ValidationResult<String> {
if (input == null) return Invalid(UrlValidationError.InputIsNull)
if (!input.matches(URL_REGEX) && !input.matches(AUTO_URL_REGEX)) return Invalid(UrlValidationError.InvalidFormat)
return Valid(input)
}
} | 0 | Kotlin | 3 | 9 | 435169c7560f522c6319d19796919ce7a53fe8a1 | 560 | validator | Apache License 2.0 |
keel-bakery-plugin/src/main/kotlin/com/netflix/spinnaker/keel/bakery/api/ImageSpec.kt | nimakaviani | 267,638,742 | true | {"Kotlin": 1720771, "Java": 15301, "Shell": 1691} | package com.netflix.spinnaker.keel.bakery.api
import com.fasterxml.jackson.annotation.JsonIgnore
import com.netflix.spinnaker.keel.api.ResourceSpec
import com.netflix.spinnaker.keel.api.UnhappyControl
import com.netflix.spinnaker.keel.api.artifacts.ArtifactStatus
import com.netflix.spinnaker.keel.api.artifacts.BaseLabel
import com.netflix.spinnaker.keel.api.artifacts.StoreType
import java.time.Duration
data class ImageSpec(
val artifactName: String,
val baseLabel: BaseLabel,
val baseOs: String,
val regions: Set<String>,
val storeType: StoreType,
val artifactStatuses: Set<ArtifactStatus> = enumValues<ArtifactStatus>().toSet(),
override val application: String // the application an image is baked in
) : ResourceSpec, UnhappyControl {
@JsonIgnore
override val id: String = artifactName
@JsonIgnore
override val maxDiffCount = 2
@JsonIgnore
override val unhappyWaitTime = Duration.ZERO
}
| 0 | null | 0 | 0 | c6667679423ab3c1e063d3f95eab4e12ba8e80a4 | 924 | keel | Apache License 2.0 |
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/tasks/UnsafeOutputsTask.kt | RivanParmar | 526,653,590 | false | null | /*
* Copyright (C) 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 com.android.build.gradle.internal.tasks
import com.android.buildanalyzer.common.TaskCategory
import org.gradle.api.tasks.TaskAction
import org.gradle.work.DisableCachingByDefault
/**
* Base class for tasks that don't use gradle's up-to-date checks.
*
* Be careful using this class, strongly prefer extending [NonIncrementalTask].
*
* Such tasks always run when in the task graph, and rely on the task implementation to handle
* up-to-date checks e.g. the external native build tasks, where the underlying external build
* system handles those checks. Lint does not use this class, as while it is never up-to-date
* currently as it doesn't model its inputs, it should clean its outputs before running.
*
* Unlike [NonIncrementalTask], this task does **not** clean up its outputs before the task is run.
* This means that the task implementation is responsible for ensuring that the outputs are correct
* in that case.
*/
@DisableCachingByDefault
@BuildAnalyzer(primaryTaskCategory = TaskCategory.HELP)
abstract class UnsafeOutputsTask(reasonToLog: String) : AndroidVariantTask() {
init {
outputs.upToDateWhen { task ->
task.logger.debug(reasonToLog)
return@upToDateWhen false
}
}
@Throws(Exception::class)
protected abstract fun doTaskAction()
@TaskAction
fun taskAction() {
// recordTaskAction(analyticsService.get()) {
doTaskAction()
// }
}
}
| 1 | null | 2 | 17 | a497291d77bba1aa34271808088fe1e8aab5efe2 | 2,086 | androlabs | Apache License 2.0 |
android/src/main/kotlin/com/shekarmudaliyar/social_share/SocialSharePlugin.kt | mpvirani | 458,516,349 | false | {"Kotlin": 33351, "Dart": 24597, "Objective-C": 22545, "Ruby": 2278, "Swift": 404} | package com.shekarmudaliyar.social_share
import android.app.Activity
import android.content.*
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.SystemClock
import android.provider.ContactsContract
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.NonNull
import androidx.core.content.FileProvider
import com.facebook.AccessToken
import com.facebook.GraphRequest
import com.facebook.GraphResponse
import com.facebook.HttpMethod
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import com.facebook.share.widget.ShareDialog
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import org.json.JSONArray
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
class SocialSharePlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel
private var activity: Activity? = null
private var activeContext: Context? = null
private var context: Context? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
context = flutterPluginBinding.applicationContext
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "social_share")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
activeContext = if (activity != null) activity!!.applicationContext else context!!
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else if (call.method == "shareInstagramStory") {
//share on instagram story
val stickerImage: String? = call.argument("stickerImage")
val backgroundImage: String? = call.argument("backgroundImage")
val backgroundTopColor: String? = call.argument("backgroundTopColor")
val backgroundBottomColor: String? = call.argument("backgroundBottomColor")
val attributionURL: String? = call.argument("attributionURL")
val file = File(activeContext!!.cacheDir, stickerImage!!)
val stickerImageFile = FileProvider.getUriForFile(
activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share",
file
)
val intent = Intent("com.instagram.share.ADD_TO_STORY")
intent.type = "image/*"
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("interactive_asset_uri", stickerImageFile)
if (backgroundImage != null) {
//check if background image is also provided
val backfile = File(activeContext!!.cacheDir, backgroundImage)
val backgroundImageFile = FileProvider.getUriForFile(
activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share",
backfile
)
intent.setDataAndType(backgroundImageFile, "image/*")
}
intent.putExtra("content_url", attributionURL)
intent.putExtra("top_background_color", backgroundTopColor)
intent.putExtra("bottom_background_color", backgroundBottomColor)
Log.d("", activity!!.toString())
// Instantiate activity and verify it will resolve implicit intent
activity!!.grantUriPermission(
"com.instagram.android",
stickerImageFile,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
if (activity!!.packageManager.resolveActivity(intent, 0) != null) {
activeContext!!.startActivity(intent)
result.success("success")
} else {
result.success("error")
}
} else if (call.method == "shareFacebookStory") {
//share on facebook story
val stickerImage: String? = call.argument("stickerImage")
val backgroundTopColor: String? = call.argument("backgroundTopColor")
val backgroundBottomColor: String? = call.argument("backgroundBottomColor")
val attributionURL: String? = call.argument("attributionURL")
val appId: String? = call.argument("appId")
val file = File(activeContext!!.cacheDir, stickerImage)
val stickerImageFile = FileProvider.getUriForFile(
activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share",
file
)
val intent = Intent("com.facebook.stories.ADD_TO_STORY")
intent.type = "image/*"
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("com.facebook.platform.extra.APPLICATION_ID", appId)
intent.putExtra("interactive_asset_uri", stickerImageFile)
intent.putExtra("content_url", attributionURL)
intent.putExtra("top_background_color", backgroundTopColor)
intent.putExtra("bottom_background_color", backgroundBottomColor)
Log.d("", activity!!.toString())
// Instantiate activity and verify it will resolve implicit intent
activity!!.grantUriPermission(
"com.facebook.katana",
stickerImageFile,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
if (activity!!.packageManager.resolveActivity(intent, 0) != null) {
activeContext!!.startActivity(intent)
result.success("success")
} else {
result.success("error")
}
} else if (call.method == "shareOptions") {
//native share options
val content: String? = call.argument("content")
val image: String? = call.argument("image")
val intent = Intent()
intent.action = Intent.ACTION_SEND
if (image != null) {
//check if image is also provided
val imagefile = File(activeContext!!.cacheDir, image)
val imageFileUri = FileProvider.getUriForFile(
activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share",
imagefile
)
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_STREAM, imageFileUri)
} else {
intent.type = "text/plain";
}
intent.putExtra(Intent.EXTRA_TEXT, content)
//create chooser intent to launch intent
//source: "share" package by flutter (https://github.com/flutter/plugins/blob/master/packages/share/)
val chooserIntent: Intent =
Intent.createChooser(intent, null /* dialog title optional */)
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activeContext!!.startActivity(chooserIntent)
result.success(true)
} else if (call.method == "copyToClipboard") {
//copies content onto the clipboard
val content: String? = call.argument("content")
val clipboard =
context!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("", content)
clipboard.setPrimaryClip(clip)
result.success(true)
} else if (call.method == "shareWhatsapp") {
//shares content on WhatsApp
val content: String? = call.argument("content")
val whatsappIntent = Intent(Intent.ACTION_SEND)
whatsappIntent.type = "text/plain"
whatsappIntent.setPackage("com.whatsapp")
whatsappIntent.putExtra(Intent.EXTRA_TEXT, content)
try {
activity!!.startActivity(whatsappIntent)
result.success("true")
} catch (ex: ActivityNotFoundException) {
result.success("false")
}
} else if (call.method == "shareSms") {
//shares content on sms
val content: String? = call.argument("message")
val intent = Intent(Intent.ACTION_SENDTO)
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.type = "vnd.android-dir/mms-sms"
intent.data = Uri.parse("sms:")
intent.putExtra("sms_body", content)
try {
activity!!.startActivity(intent)
result.success("true")
} catch (ex: ActivityNotFoundException) {
result.success("false")
}
} else if (call.method == "shareTwitter") {
//shares content on twitter
val text: String? = call.argument("captionText")
val url: String? = call.argument("url")
val trailingText: String? = call.argument("trailingText")
val urlScheme = "http://www.twitter.com/intent/tweet?text=$text$url$trailingText"
Log.d("log", urlScheme)
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(urlScheme)
try {
activity!!.startActivity(intent)
result.success("true")
} catch (ex: ActivityNotFoundException) {
result.success("false")
}
} else if (call.method == "shareTelegram") {
//shares content on Telegram
val content: String? = call.argument("content")
val telegramIntent = Intent(Intent.ACTION_SEND)
telegramIntent.type = "text/plain"
telegramIntent.setPackage("org.telegram.messenger")
telegramIntent.putExtra(Intent.EXTRA_TEXT, content)
try {
activity!!.startActivity(telegramIntent)
result.success("true")
} catch (ex: ActivityNotFoundException) {
result.success("false")
}
} else if (call.method == "checkInstalledApps") {
//check if the apps exists
//creating a mutable map of apps
val apps: MutableMap<String, Boolean> = mutableMapOf()
//assigning package manager
val pm: PackageManager = context!!.packageManager
//get a list of installed apps.
val packages = pm.getInstalledApplications(PackageManager.GET_META_DATA)
//intent to check sms app exists
val intent = Intent(Intent.ACTION_SENDTO).addCategory(Intent.CATEGORY_DEFAULT)
intent.type = "vnd.android-dir/mms-sms"
intent.data = Uri.parse("sms:")
val resolvedActivities: List<ResolveInfo> = pm.queryIntentActivities(intent, 0)
//if sms app exists
apps["sms"] = resolvedActivities.isNotEmpty()
//if other app exists
apps["instagram"] =
packages.any { it.packageName.toString().contentEquals("com.instagram.android") }
apps["facebook"] =
packages.any { it.packageName.toString().contentEquals("com.facebook.katana") }
apps["twitter"] =
packages.any { it.packageName.toString().contentEquals("com.twitter.android") }
apps["whatsapp"] =
packages.any { it.packageName.toString().contentEquals("com.whatsapp") }
apps["telegram"] =
packages.any { it.packageName.toString().contentEquals("org.telegram.messenger") }
result.success(apps)
} else if (call.method == "getFacebookUser") {
getFacebookUser(result)
} else if (call.method == "shareOnFeedFacebook") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
val message: String? = args["message"] as? String?
shareOnFeedFacebook(url, message, result)
} else if (call.method == "shareStoryOnInstagram") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
shareStoryOnInstagram(url, result)
} else if (call.method == "shareStoryOnFacebook") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
val facebookId = args["facebookId"] as String
shareStoryOnFacebook(url, facebookId, result)
} else if (call.method == "shareOnFeedInstagram") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
val message: String? = args["message"] as? String?
shareOnFeedInstagram(url, message, result)
} else if (call.method == "shareOnWhatsApp") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
val message: String? = args["message"] as? String?
shareOnWhatsApp(url, message, result, false)
} else if (call.method == "shareOnWhatsAppBusiness") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
val message: String? = args["message"] as? String?
shareOnWhatsApp(url, message, result, true)
} else if (call.method == "openAppOnStore") {
val args = call.arguments as Map<*, *>
val appUrl: String? = args["appUrl"] as? String?
openAppOnStore(appUrl)
} else if (call.method == "shareOnNative") {
val args = call.arguments as Map<*, *>
val url: String? = args["url"] as? String?
val message: String? = args["message"] as? String?
shareOnNative(url, message, result)
} else if (call.method == "shareLinkOnWhatsApp") {
val args = call.arguments as Map<*, *>
val link: String? = args["link"] as? String?
shareLinkOnWhatsApp(link, result, false)
} else if (call.method == "shareLinkOnWhatsAppBusiness") {
val args = call.arguments as Map<*, *>
val link: String? = args["link"] as? String?
shareLinkOnWhatsApp(link, result, true)
} else if (call.method == "shareOnGallery") {
val image = call.argument<ByteArray>("imageBytes") ?: return
shareOnGallery(BitmapFactory.decodeByteArray(image, 0, image.size))
} else if (call.method == "checkPermissionToPublish") {
checkPermissionToPublish(result)
} else {
result.notImplemented()
}
}
private fun getFacebookUser(result: Result) {
if (AccessToken.getCurrentAccessToken() != null) {
val parameters = Bundle()
parameters.putString("fields", "id,name")
GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me",
parameters,
HttpMethod.GET,
GraphRequest.Callback() {
fun onCompleted(response: GraphResponse) {
if (response.jsonObject != null) {
val obj = response.jsonObject
val map = HashMap<String, String>()
if (obj != null) {
map["id"] = obj.optString("id")
}
if (obj != null) {
map["name"] = obj.optString("name")
}
result.success(map)
} else {
result.error("FAIL_TO_GET_FB_USER", "Response is null", "FACEBOOK_APP")
}
}
}
) .executeAsync()
}
}
private fun shareOnFeedFacebook(url: String?, message: String?, result: Result) {
try {
val imgFile = File(url!!)
if (imgFile.exists()) {
// val activity = activity.get()!!
val bitmapUri =
FileProvider.getUriForFile(activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share", imgFile)
val content = if (bitmapUri != null) {
val photo = SharePhoto.Builder().setCaption("$message #Postou").setImageUrl(bitmapUri).build()
SharePhotoContent.Builder().addPhoto(photo).build()
} else {
ShareLinkContent.Builder().setQuote(message).build()
}
val shareDialog = ShareDialog(activity)
if (ShareDialog.canShow(SharePhotoContent::class.java)) {
shareDialog.show(content)
result.success("POST_SENT")
} else result.error("APP_NOT_FOUND", "Facebook app not found", "FACEBOOK_APP")
} else {
result.error("FAIL_TO_POST", "$url not found", "FACEBOOK_APP")
}
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), "FACEBOOK_APP")
}
}
private fun shareStoryOnInstagram(url: String?, result: Result) {
try {
if (isInstalled("com.instagram.android")) {
val imgFile = File(url!!)
if (imgFile.exists()) {
// val activity = activity.get()!!
val bitmapUri =
FileProvider.getUriForFile(activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share", imgFile)
val storiesIntent = Intent("com.instagram.share.ADD_TO_STORY")
storiesIntent.setDataAndType(bitmapUri,
activity?.contentResolver?.getType(bitmapUri))
storiesIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
activity?.startActivity(storiesIntent)
result.success("POST_SENT")
} else {
result.error("FAIL_TO_POST", "$url not found", "INSTAGRAM_STORY_APP")
}
} else {
result.error("APP_NOT_FOUND", "Instagram app not found", "INSTAGRAM_STORY_APP")
}
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), "INSTAGRAM_STORY_APP")
}
}
private fun shareStoryOnFacebook(url: String?, facebookId: String, result: Result){
try {
if (isInstalled("com.facebook.katana")) {
val imgFile = File(url!!)
if (imgFile.exists()) {
val bitmapUri =
FileProvider.getUriForFile(activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share", imgFile)
val intent = Intent("com.facebook.stories.ADD_TO_STORY")
intent.type = "image/*"
intent.putExtra("com.facebook.platform.extra.APPLICATION_ID", facebookId)
intent.putExtra("interactive_asset_uri", bitmapUri)
intent.putExtra("top_background_color", "#26242e")
intent.putExtra("bottom_background_color", "#26242e")
activeContext!!.grantUriPermission(
"com.facebook.katana", bitmapUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (activeContext!!.packageManager.resolveActivity(intent, 0) != null) {
activity?.startActivityForResult(intent, 0)
}
result.success("POST_SENT")
} else {
result.error("FAIL_TO_POST", "$url not found", "FACEBOOK_POST_APP")
}
} else {
result.error("APP_NOT_FOUND", "App do Facebook não encontrado", "FACEBOOK_POST_APP")
}
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), "FACEBOOK_POST_APP")
}
}
private fun shareOnFeedInstagram(url: String?, msg: String?, result: Result) {
try {
if (isInstalled("com.instagram.android")) {
val imgFile = File(url!!)
if (imgFile.exists()) {
val bitmapUri =
FileProvider.getUriForFile(activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share", imgFile)
val feedIntent = Intent(Intent.ACTION_SEND)
feedIntent.type = "image/*"
feedIntent.putExtra(Intent.EXTRA_TEXT, msg)
feedIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
feedIntent.putExtra(Intent.EXTRA_STREAM, bitmapUri)
feedIntent.setPackage("com.instagram.android")
activity?.startActivity(feedIntent)
result.success("POST_SENT")
} else {
result.error("FAIL_TO_POST", "$url not found", "INSTAGRAM_POST_APP")
}
} else {
result.error("APP_NOT_FOUND", "App do Instagram não encontrado", "INSTAGRAM_POST_APP")
}
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), "INSTAGRAM_POST_APP")
}
}
private fun shareOnWhatsApp(url: String?, msg: String?, result: Result,
shareToWhatsAppBiz: Boolean) {
val app = if (shareToWhatsAppBiz) "com.whatsapp.w4b" else "com.whatsapp"
try {
if (isInstalled(app)) {
val whatsappIntent = Intent(Intent.ACTION_SEND)
whatsappIntent.setPackage(app)
whatsappIntent.putExtra(Intent.EXTRA_TEXT, msg)
val imgFile = File(url!!)
if (imgFile.exists()) {
val bitmapUri =
FileProvider.getUriForFile(activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share", imgFile)
whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
whatsappIntent.putExtra(Intent.EXTRA_STREAM, bitmapUri)
val cr = activity?.contentResolver
whatsappIntent.type = cr?.getType(bitmapUri)
activity?.startActivity(whatsappIntent)
result.success("POST_SENT")
} else {
result.error("FAIL_TO_POST", "$url not found", app)
}
} else {
result.error("APP_NOT_FOUND", "App do WhatsApp não foi encontrado", app)
}
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), app)
}
}
private fun shareLinkOnWhatsApp(link: String?, result: Result, shareToWhatsAppBiz: Boolean) {
val app = if (shareToWhatsAppBiz) "com.whatsapp.w4b" else "com.whatsapp"
if (isInstalled(app)) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.setPackage(app)
intent.putExtra(Intent.EXTRA_TEXT, link)
activeContext!!.startActivity(intent)
} else {
result.error("APP_NOT_FOUND", "App do WhatsApp não foi encontrado", app)
}
}
private fun shareOnNative(url: String?, msg: String?, result: Result) {
try {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_TEXT, msg)
if (url != null) {
val imgFile = File(url)
if (imgFile.exists()) {
val bitmapUri =
FileProvider.getUriForFile(activeContext!!,
activeContext!!.applicationContext.packageName + ".com.shekarmudaliyar.social_share", imgFile)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, bitmapUri)
val cr = activity?.contentResolver
intent.type = cr?.getType(bitmapUri)
} else {
result.error("FAIL_TO_POST", "$url not found", "NATIVE")
}
activity?.startActivity(Intent.createChooser(intent, "Enviar post..."))
} else {
intent.type = "text/plain"
activity?.startActivity(Intent.createChooser(intent, "Enviar mensagem..."))
}
result.success("POST_SENT")
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), "NATIVE")
}
}
private fun checkPermissionToPublish(result: Result) {
result.success(AccessToken.getCurrentAccessToken() != null)
}
private fun shareLinkOnFacebook(link: String?, result: Result) {
try {
val content = ShareLinkContent.Builder()
.setContentUrl(Uri.parse(link))
.build()
val shareDialog = ShareDialog(activity!!)
if (ShareDialog.canShow(ShareLinkContent::class.java)) {
shareDialog.show(content)
result.success("POST_SENT")
} else result.error("APP_NOT_FOUND", "App do Facebook não foi encontrado", "FACEBOOK_APP")
} catch (e: Exception) {
result.error("FAIL_TO_POST", e.toString(), "FACEBOOK_APP")
}
}
private fun openAppOnStore(packageName: String?) {
try {
val playStoreUri = Uri.parse("market://details?id=$packageName")
val intent = Intent(Intent.ACTION_VIEW, playStoreUri)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activeContext!!.startActivity(intent)
} catch (e: ActivityNotFoundException) {
val playStoreUri = Uri.parse("https://play.google.com/store/apps/details?id=$packageName")
val intent = Intent(Intent.ACTION_VIEW, playStoreUri)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activeContext!!.startActivity(intent)
}
}
private fun isInstalled(packageName: String): Boolean {
val packageManager = activeContext!!.packageManager
return try {
packageManager.getApplicationInfo(packageName, 0).enabled
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
fun shareOnGallery(bmp: Bitmap): Uri? {
if (android.os.Build.VERSION.SDK_INT >= 29) {
val values = ContentValues()
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/test_pictures")
values.put(MediaStore.Images.Media.IS_PENDING, true)
values.put(MediaStore.Images.Media.DISPLAY_NAME, "img_${SystemClock.uptimeMillis()}")
val uri: Uri? =
activeContext!!.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
if (uri != null) {
saveImageToStream(bmp, activeContext!!.contentResolver.openOutputStream(uri))
values.put(MediaStore.Images.Media.IS_PENDING, false)
activeContext!!.contentResolver.update(uri, values, null, null)
return uri
}
} else {
val directory =
File(activeContext!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + File.separator + "MediaSocialShare")
if (!directory.exists()) {
directory.mkdirs()
}
val fileName = "img_${SystemClock.uptimeMillis()}"+ ".jpeg"
val file = File(directory, fileName)
saveImageToStream(bmp, FileOutputStream(file))
val values = ContentValues()
values.put(MediaStore.Images.Media._ID, file.absolutePath)
// .DATA is deprecated in API 29
activeContext!!.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
return Uri.fromFile(file)
}
return null
}
fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) {
if (outputStream != null) {
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
outputStream.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
// activity = WeakReference(binding.activity)
activity = binding.getActivity()
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivity() {
activity = null
}
} | 0 | Kotlin | 1 | 0 | b714d8c27c2f37fe7afc98167e83aa1e81d4b614 | 30,345 | social_share | MIT License |
kotlinx-coroutines-debug/test/junit5/CoroutinesTimeoutInheritanceTest.kt | hltj | 151,721,407 | true | null | /*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.debug.junit5
import kotlinx.coroutines.*
import org.junit.jupiter.api.*
/**
* Tests that [CoroutinesTimeout] is inherited.
*
* This test class is not intended to be run manually. Instead, use [CoroutinesTimeoutTest] as the entry point.
*/
class CoroutinesTimeoutInheritanceTest {
@CoroutinesTimeout(100)
open class Base
@TestMethodOrder(MethodOrderer.OrderAnnotation::class)
class InheritedWithNoTimeout: Base() {
@Test
@Order(1)
fun usesBaseClassTimeout() = runBlocking {
delay(1000)
}
@CoroutinesTimeout(300)
@Test
@Order(2)
fun methodOverridesBaseClassTimeoutWithGreaterTimeout() = runBlocking {
delay(200)
}
@CoroutinesTimeout(10)
@Test
@Order(3)
fun methodOverridesBaseClassTimeoutWithLesserTimeout() = runBlocking {
delay(50)
}
}
@CoroutinesTimeout(300)
class InheritedWithGreaterTimeout : TestBase() {
@Test
fun classOverridesBaseClassTimeout1() = runBlocking {
delay(200)
}
@Test
fun classOverridesBaseClassTimeout2() = runBlocking {
delay(400)
}
}
} | 1 | Kotlin | 106 | 255 | 9565dc2d1bc33056dd4321f9f74da085e6c0f39e | 1,365 | kotlinx.coroutines-cn | Apache License 2.0 |
kwhen/src/commonMain/kotlin/ap/panini/kwhen/common/Merger.kt | Pahina0 | 804,021,638 | false | {"Kotlin": 80508} | package common
import DateTime
abstract class Merger(open val config: Config) {
/**
* regex that should be applied to every pattern for matching prefix (text before first time)
* */
open val prefixPattern: Regex by lazy { prefixMatchPattern }
/**
* regex that should be applied to every pattern between two times
* */
open val betweenPattern: Regex by lazy { betweenMatchPattern }
/**
* the pattern that is overwritten for matching prefix
* */
protected open val prefixMatchPattern: Regex = "[\\s\\S]*".toRegex()
/**
* the pattern that is overwritten for matching between two times
* */
protected open val betweenMatchPattern: Regex = "[\\s\\S]*".toRegex()
open val mergePrefixWithLeft = false
open val mergeRightWithLeft = false
/**
* The amount of points rewarded per successful merge
* */
open val reward = 1
/**
* what is called when there is a match with all the patterns
*
* usual parsing will be prefix left between right
*
* @return DateTime: null if cannot merge, else a merged version of the date times besides text and range
* */
abstract fun onMatch(
left: DateTime?,
right: DateTime?,
prefix: MatchResult?,
between: MatchResult?,
): DateTime?
} | 0 | Kotlin | 0 | 1 | 445c9bcffacbc8bebd6743094f07a8e6a3050a5c | 1,339 | KWhen | Apache License 2.0 |
src/main/kotlin/br/com/zup/edu/keymanager/chavepix/client/bcb/PixDetailResponse.kt | jaacksonalves | 399,572,593 | true | {"Kotlin": 108088} | package br.com.zup.edu.keymanager.chavepix.client.bcb
import br.com.zup.edu.keymanager.chavepix.*
import br.com.zup.edu.keymanager.chavepix.carrega.ChavePixInfo
import br.com.zup.edu.keymanager.chavepix.carrega.ContaAssociadaInfo
import br.com.zup.edu.keymanager.chavepix.carrega.TitularInfo
import java.time.LocalDateTime
data class PixDetailResponse(
val keyType: KeyType,
val key: String,
val bankAccount: BankAccountResponse,
val owner: OwnerResponse,
val createdAt: LocalDateTime
) {
fun toInfo(): ChavePixInfo {
return ChavePixInfo(
tipoChave = KeyType.toTipoChave(keyType),
chave = key,
tipoConta = AccountType.toTipoConta(bankAccount.accountType),
contaInfo = ContaAssociadaInfo(
instituicao = Instituicao(
nomeInstituicao = Instituicoes.nome(bankAccount.participant),
ispb = bankAccount.participant
),
agencia = bankAccount.branch,
numeroConta = bankAccount.accountNumber,
titularInfo = TitularInfo(
nomeTitular = owner.name,
cpf = owner.taxIdNumber
)
)
)
}
fun toModel(): ChavePix {
return ChavePix(
tipoChave = KeyType.toTipoChave(keyType),
chave = key,
contaAssociada = ContaAssociada(
tipoConta = AccountType.toTipoConta(bankAccount.accountType),
instituicao = Instituicao(
nomeInstituicao = Instituicoes.nome(bankAccount.participant),
ispb = bankAccount.participant
),
agencia = bankAccount.branch,
numeroConta = bankAccount.accountNumber,
titular = Titular(
titularId = null,
nomeTitular = owner.name,
cpf = owner.taxIdNumber
)
)
)
}
}
| 0 | Kotlin | 0 | 0 | e11f987f10675ce553549f6a1c24e404a7f29a3c | 2,023 | orange-talents-06-template-pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/knf/kuma/search/GenresDialog.kt | xxspokiixx | 163,215,061 | true | {"Kotlin": 988561, "PHP": 267654, "Java": 121069, "CSS": 55991, "JavaScript": 50577, "HTML": 25952, "Ruby": 815} | package knf.kuma.search
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import java.util.*
class GenresDialog : DialogFragment() {
private var genres: MutableList<String> = ArrayList()
private var selected: MutableList<String> = ArrayList()
private var listener: MultiChoiceListener? = null
private val states: BooleanArray
get() {
val states = BooleanArray(genres.size)
var index = 0
for (genre in genres) {
states[index++] = selected.contains(genre)
}
return states
}
fun init(genres: MutableList<String>, selected: MutableList<String>, listener: MultiChoiceListener) {
this.genres = genres
this.selected = selected
this.listener = listener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(activity!!)
.setTitle("Generos")
.setMultiChoiceItems(genres.toTypedArray(), states) { _, index, isSelected ->
if (isSelected)
selected.add(genres[index])
else
selected.remove(genres[index])
}.setPositiveButton("BUSCAR") { _, _ ->
selected.sort()
listener?.onOkay(selected)
}.setNegativeButton("CERRAR") { dialogInterface, _ -> dialogInterface.dismiss() }
.create()
}
override fun show(manager: FragmentManager, tag: String?) {
try {
super.show(manager, tag)
} catch (e: Exception) {
//
}
}
override fun dismiss() {
try {
super.dismiss()
} catch (e: Exception) {
//
}
}
interface MultiChoiceListener {
fun onOkay(selected: MutableList<String>)
}
}
| 0 | Kotlin | 0 | 0 | c8afbc6b80cba8551f305f49b3d43170deafcb60 | 2,022 | UKIKU | MIT License |
tachikoma-it/src/test/kotlin/com/sourceforgery/tachikoma/unsubscribe/UnsubscribeDecoderTest.kt | SourceForgery | 112,076,342 | false | null | package com.sourceforgery.tachikoma.unsubscribe
import com.sourceforgery.tachikoma.grpc.frontend.EmailId
import com.sourceforgery.tachikoma.grpc.frontend.unsubscribe.UnsubscribeData
import com.sourceforgery.tachikoma.testModule
import org.junit.Test
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.instance
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class UnsubscribeDecoderTest : DIAware {
override val di =
DI {
importOnce(testModule(), allowOverride = true)
}
val unsubscribeDecoder: UnsubscribeDecoder by instance()
@Test
fun `should create an unsubscribe url`() {
val emailId =
EmailId
.newBuilder()
.setId(999)
.build()
val unsubscribeData =
UnsubscribeData
.newBuilder()
.setEmailId(emailId)
.build()
val url = unsubscribeDecoder.createUrl(unsubscribeData)
assertEquals("qgYGqgYDCM4PsgYUlGa_Cd7_XRqsoeZRMZPkrcANRy8", url)
}
@Test
fun `should decode an unsubscribe url`() {
val unsubscribeDataString = "qgYGqgYDCM4PsgYUlGa_Cd7_XRqsoeZRMZPkrcANRy8"
val unsubscribeData = unsubscribeDecoder.decodeUnsubscribeData(unsubscribeDataString)
assertEquals(999, unsubscribeData.emailId.id)
}
@Test
fun `should throw if trying to decode an invalid url`() {
val unsubscribeDataString = "qgYGqgYDCM5PsgYUlGa_Cd7_XRqsoeZRMZPkrcANRy8"
assertFailsWith<RuntimeException> {
unsubscribeDecoder.decodeUnsubscribeData(unsubscribeDataString)
}
}
}
| 7 | null | 3 | 5 | 12d8d0e0ccafaa8506b98d6269cae4f1bb228bf4 | 1,677 | tachikoma | Apache License 2.0 |
android/app/src/main/java/com/eathemeat/easytimer/screen/SettingScreen.kt | peter12757 | 616,378,789 | false | {"Kotlin": 42866} | package com.eathemeat.easytimer.screen
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun SettingScreen() {
Text(text = "SettingPage")
}
@Preview
@Composable
fun SettingScreenPreview() {
SettingScreen()
} | 0 | Kotlin | 0 | 0 | 1aa19f82612ec4563c240c6a23dddbf786ac7754 | 314 | EasyTimer | Apache License 2.0 |
app/src/main/java/com/sandeep/womenincloudrvce/models/Task.kt | mssandeepkamath | 600,313,527 | false | {"Kotlin": 205073, "Java": 11104} | package earth.devgalileo.assimilator.models
import android.os.Parcel
import android.os.Parcelable
data class Task (
var title: String = "",
val createdBy: String = "",
var cards: ArrayList<Card> = ArrayList()
): Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString()!!,
parcel.readString()!!,
parcel.createTypedArrayList(Card.CREATOR)!!
)
override fun writeToParcel(parcel: Parcel, flags: Int) = with(parcel) {
writeString(title)
writeString(createdBy)
writeTypedList(cards)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Task> {
override fun createFromParcel(parcel: Parcel): Task {
return Task(parcel)
}
override fun newArray(size: Int): Array<Task?> {
return arrayOfNulls(size)
}
}
} | 0 | Kotlin | 1 | 1 | fc0bfc3b717a681f504c7a438460798d4c7620d5 | 913 | women-in-cloud-rvce-android | MIT License |
scripts/ChatColorGenerator.kts | Spikot | 129,165,327 | false | null | fun transform(text: String): String {
val lower = text.toLowerCase()
var upper = false
val builder = StringBuilder()
lower.forEach {
if (it == '_') {
upper = true
} else {
if (upper) {
upper = false
builder.append(it.toUpperCase())
} else {
builder.append(it.toLowerCase())
}
}
}
return builder.toString()
}
val builder = StringBuilder()
val colors = listOf(
"BLACK",
"DARK_BLUE",
"DARK_GREEN",
"DARK_AQUA",
"DARK_RED",
"DARK_PURPLE",
"GOLD", "GRAY",
"DARK_GRAY",
"BLUE",
"GREEN",
"AQUA",
"RED",
"LIGHT_PURPLE",
"YELLOW",
"WHITE",
"MAGIC",
"BOLD",
"STRIKETHROUGH",
"UNDERLINE",
"ITALIC",
"RESET"
)
colors.forEach { raw ->
val mini = transform(raw)
builder.append(
"fun $mini(builder: Builder): ChatBuilder = chat{$mini(builder)}\n" +
"fun $mini(text: String): ChatBuilder = chat{$mini(text)}\n" +
"fun ChatBuilder.$mini(builder: Builder) = color($raw,builder)\n" +
"fun ChatBuilder.$mini(text: String) = color($raw,text)\n"
)
}
println(builder.toString())
| 0 | Kotlin | 3 | 11 | a44e2c9ad3203f3ea1bbf65ae9ef53f6f6283d77 | 1,244 | SpikotLegacy | Apache License 2.0 |
app/src/main/java/com/raul/macias/wikiheroes/view/ui/search/SearchActivity.kt | xR4ULx | 313,670,556 | false | null | package com.raul.macias.wikiheroes.view.ui.search
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.util.Pair
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.raul.macias.wikiheroes.R
import com.raul.macias.wikiheroes.databinding.ActivitySearchBinding
import com.raul.macias.wikiheroes.factory.AppViewModelFactory
import com.raul.macias.wikiheroes.models.Character
import com.raul.macias.wikiheroes.models.Detail
import com.raul.macias.wikiheroes.models.Item
import com.raul.macias.wikiheroes.models.SearchObjectItem
import com.raul.macias.wikiheroes.utils.Utils
import com.raul.macias.wikiheroes.view.adapter.SearchAdapter
import com.raul.macias.wikiheroes.view.ui.detail.DetailActivity
import com.raul.macias.wikiheroes.view.ui.detail_items.detail_comic.DetailItemActivity
import com.raul.macias.wikiheroes.view.ui.person.PersonDetailActivity
import com.raul.macias.wikiheroes.view.viewholder.*
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.item_character.view.*
import kotlinx.android.synthetic.main.item_creator.view.*
import javax.inject.Inject
class SearchActivity : AppCompatActivity(), SearchObjectCharacterViewHolder.Delegate, SearchObjectComicViewHolder.Delegate, SearchObjectSeriesViewHolder.Delegate, SearchObjectCreatorViewHolder.Delegate {
@Inject
lateinit var viewModelFactory: AppViewModelFactory
private val viewModel by lazy { ViewModelProvider(this, viewModelFactory).get(SearchActivityViewModel::class.java) }
private val binding by lazy { DataBindingUtil.setContentView<ActivitySearchBinding>(this, R.layout.activity_search) }
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this) //This line initialise our dependencies
super.onCreate(savedInstanceState)
initUI()
}
private fun initUI() {
binding.backArrow.setOnClickListener {
onBackPressed()
}
val linearLayout = androidx.recyclerview.widget.LinearLayoutManager(this)
binding.listResults.layoutManager = linearLayout
viewModel.adapter = SearchAdapter(this, this, this, this)
binding.listResults.adapter = viewModel.adapter
binding.optionCharacterTextview.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
viewModel.searchOption = "Character"
if (viewModel.searchOption != null && viewModel.adapter.items.size > 0) {
viewModel.switchTab = true
search()
}
}
}
binding.optionComicTextview.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
viewModel.searchOption = "Comic"
if (viewModel.searchOption != null && viewModel.adapter.items.size > 0) {
viewModel.switchTab = true
search()
}
}
}
binding.optionSeriesTextview.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
viewModel.searchOption = "Series"
if (viewModel.searchOption != null && viewModel.adapter.items.size > 0) {
viewModel.switchTab = true
search()
}
}
}
binding.optionPersonTextview.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
viewModel.searchOption = "Person"
if (viewModel.searchOption != null && viewModel.adapter.items.size > 0) {
viewModel.switchTab = true
search()
}
}
}
//INFINITE SCROLL LISTENER
binding.listResults.addOnScrollListener(Utils.InfiniteScrollListener({
viewModel.increasePage()
search()
}, linearLayout))
binding.searchEdit.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
viewModel.resetLists()
closeKeyboard(binding.searchEdit)
search()
true
} else {
false
}
}
}
private fun search() {
viewModel.searchText = binding.searchEdit.text.toString()
if (viewModel.searchOption != null) {
binding.progressBar.visibility = View.VISIBLE
when (viewModel.searchOption) {
"Character" -> {
searchCharacter(viewModel.searchText)
}
"Comic" -> {
searchComic(viewModel.searchText)
}
"Series" -> {
searchSeries(viewModel.searchText)
}
"Person" -> {
searchCreator(viewModel.searchText)
}
}
} else {
Utils.showAlert(this, "Select what you want to search")
}
}
private fun searchComic(searchText: String) {
if(viewModel.comics == null || (viewModel.comicsPageCounter != 0 && !viewModel.switchTab)) {
viewModel.searchComics(searchText)
.observe(this, Observer { response ->
if (response != null && response.isSuccessful) {
if (!response.body!!.data.results.isNullOrEmpty()) {
val items: MutableList<Detail> = mutableListOf()
response.body.data.results.forEach {
it.week = Utils.WEEK.none
items.add(it)
}
binding.progressBar.visibility = View.GONE
if(viewModel.comics == null) {
viewModel.comics = mutableListOf()
viewModel.comics!!.addAll(items)
viewModel.adapter.createList(items)
} else {
viewModel.comics!!.addAll(items)
viewModel.adapter.addNewItems(items)
}
viewModel.switchTab = false
viewModel.increaseOffset()
} else {
// no results
binding.progressBar.visibility = View.GONE
Utils.showAlert(this, "No results found.")
}
} else {
renderErrorState(response.error)
}
})
} else {
binding.progressBar.visibility = View.GONE
viewModel.adapter.createList(viewModel.comics!!)
viewModel.switchTab = false
}
}
private fun searchCharacter(searchText: String) {
if(viewModel.characters == null || (viewModel.charactersPageCounter != 0 && !viewModel.switchTab)) {
viewModel.searchCharacter(searchText)
.observe(this, Observer { response ->
if (response != null && response.isSuccessful) {
if (!response.body!!.data.results.isNullOrEmpty()) {
binding.progressBar.visibility = View.GONE
val items: MutableList<SearchObjectItem> = mutableListOf()
response.body.data.results.forEach {
items.add(it)
}
if(viewModel.characters == null) {
viewModel.characters = mutableListOf()
viewModel.characters!!.addAll(items)
viewModel.adapter.createList(items)
} else {
viewModel.characters!!.addAll(items)
viewModel.adapter.addNewItems(items)
}
viewModel.switchTab = false
viewModel.increaseOffset()
//viewModel.adapter.createList(response.body!!.data.results)
} else {
// no results
binding.progressBar.visibility = View.GONE
if(viewModel.charactersPageCounter == 0) {
Utils.showAlert(this, "No results found.")
}
}
} else {
renderErrorState(response.error)
}
})
} else {
// i'm switching tab so i load the current list of items without any webcall
binding.progressBar.visibility = View.GONE
viewModel.adapter.createList(viewModel.characters!!)
viewModel.switchTab = false
}
}
private fun searchCreator( searchText: String ) {
if(viewModel.persons == null || (viewModel.personPageCounter != 0 && !viewModel.switchTab)) {
viewModel.searchCreator(searchText).observe( this , Observer { response ->
if (response != null && response.isSuccessful) {
if (!response.body!!.data.results.isNullOrEmpty()) {
binding.progressBar.visibility = View.GONE
val items: MutableList<SearchObjectItem> = mutableListOf()
response.body.data.results.forEach {
it.week = Utils.WEEK.none
items.add(it)
}
if(viewModel.persons == null) {
viewModel.persons = mutableListOf()
viewModel.persons!!.addAll(items)
viewModel.adapter.createList(items)
} else {
viewModel.persons!!.addAll(items)
viewModel.adapter.addNewItems(items)
}
viewModel.switchTab = false
viewModel.increaseOffset()
} else {
// no results
binding.progressBar.visibility = View.GONE
if(viewModel.personPageCounter == 0) {
Utils.showAlert(this, "No results found.")
}
}
} else {
renderErrorState(response.error)
}
})
} else {
binding.progressBar.visibility = View.GONE
viewModel.adapter.createList(viewModel.persons!!)
viewModel.switchTab = false
}
}
private fun searchSeries( searchText: String ) {
if(viewModel.series == null || (viewModel.seriesPageCounter != 0 && !viewModel.switchTab)) {
viewModel.searchSeries(searchText).observe( this , Observer { response ->
if (response != null && response.isSuccessful) {
if (!response.body!!.data.results.isNullOrEmpty()) {
binding.progressBar.visibility = View.GONE
viewModel.increaseOffset()
val items: MutableList<Detail> = mutableListOf()
response.body!!.data.results.forEach {
it.week = Utils.WEEK.none
items.add(it)
}
if(viewModel.series == null) {
viewModel.series = mutableListOf()
viewModel.series!!.addAll(items)
viewModel.adapter.createList(items)
} else {
viewModel.series!!.addAll(items)
viewModel.adapter.addNewItems(items)
}
viewModel.switchTab = false
} else {
// no results
binding.progressBar.visibility = View.GONE
if(viewModel.seriesPageCounter == 0) {
Utils.showAlert(this, "No results found.")
}
}
} else {
renderErrorState(response.error)
}
})
} else {
binding.progressBar.visibility = View.GONE
viewModel.adapter.createList(viewModel.series!!)
viewModel.switchTab = false
}
}
private fun renderErrorState(throwable: Throwable?) {
binding.progressBar.visibility = View.GONE
throwable?.message?.let { Utils.showAlert(this, it) }
}
override fun onCharacterClicked(character: Character, view: View) {
val img = Pair.create(view.image as View, resources.getString(R.string.transition_character_image))
val name = Pair.create(view.name as View, resources.getString(R.string.transition_character_name))
val options = ActivityOptions.makeSceneTransitionAnimation(this, img, name)
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(DetailActivity.INTENT_CHARACTER, character as Parcelable)
startActivity(intent, options.toBundle())
}
override fun onSeriesClicked(item: Detail, view: View) {
val intent = Intent(this, DetailItemActivity::class.java)
intent.putExtra(DetailItemActivity.INTENT_ITEM, item as Parcelable)
intent.putExtra(DetailItemActivity.INTENT_SECTION, "Series")
startActivity(intent)
}
override fun onComicClicked(item: Detail, view: View) {
val intent = Intent(this, DetailItemActivity::class.java)
intent.putExtra(DetailItemActivity.INTENT_ITEM, item as Parcelable)
intent.putExtra(DetailItemActivity.INTENT_SECTION, "Comics")
startActivity(intent)
}
override fun onCreatorClicked(item : Detail, view: View) {
val txt = Pair.create(view.creator_name as View, resources.getString(R.string.transition_creator_name))
val options = ActivityOptions.makeSceneTransitionAnimation(this, txt)
val intent = Intent(this, PersonDetailActivity::class.java)
//val intent = Intent(this, CreatorDetailActivity::class.java)
val creator = Item(item.resourceURI , item.fullName!!, null , null, null)
intent.putExtra(PersonDetailActivity.CREATOR , creator as Parcelable)
intent.putExtra(PersonDetailActivity.IMAGE , item.thumbnail?.path + "." +item.thumbnail?.extension)
//intent.putExtra(CreatorDetailActivity.TITLE_SECTION, "Comics")
//startActivity(intent, options.toBundle())
startActivity(intent)
}
private fun closeKeyboard(view : View) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken , 0)
}
} | 1 | null | 1 | 1 | d76d4736780b156d2b8133e794cca2de6b408f28 | 15,741 | kotlin_api_marvel | MIT License |
box/src/main/kotlin/com/mrt/box/core/BoxOutput.kt | myrealtrip | 237,138,426 | false | null | package com.mrt.box.core
/**
* Created by jaehochoe on 2020-01-01.
*/
sealed class BoxOutput<out S : BoxState, out E : BoxEvent, out SE : BoxSideEffect> {
abstract val from: S
abstract val event: E
data class Valid<out S : BoxState, out E : BoxEvent, out SE : BoxSideEffect>(
override val from: S,
override val event: E,
val to: S,
val sideEffect: SE
) : BoxOutput<S, E, SE>()
data class Void<out S : BoxState, out E : BoxEvent, out SE : BoxSideEffect>(
override val from: S,
override val event: E
) : BoxOutput<S, E, SE>()
} | 1 | Kotlin | 3 | 40 | 516c142a4234a8b9b5b468b23bb9cbfd65eaf8d6 | 602 | box | The Unlicense |
core/src/commonMain/kotlin/com/lehaine/littlekt/graphics/g2d/font/internal/GpuGlyphWriter.kt | littlektframework | 442,309,478 | false | {"Kotlin": 2285392} | package com.lehaine.littlekt.graphics.g2d.font.internal
import com.lehaine.littlekt.file.ByteBuffer
/**
* @author <NAME>
* @date 1/5/2022
*/
internal object GpuGlyphWriter {
fun writeGlyphToBuffer(
buffer: ByteBuffer,
curves: List<Bezier>,
glyphWidth: Int,
glyphHeight: Int,
gridX: Short,
gridY: Short,
gridWidth: Short,
gridHeight: Short
) {
buffer.putUShort(gridX).putUShort(gridY).putUShort(gridWidth).putUShort(gridHeight)
curves.forEach {
writeBezierToBuffer(buffer, it, glyphWidth, glyphHeight)
}
}
/**
* A [Bezier] is written as 6 16-bit integers (12 bytes). Increments buffer by the number of bytes written (always 12).
* Coords are scaled from [0, glyphSize] to [o, UShort.MAX_VALUE]
*/
private fun writeBezierToBuffer(buffer: ByteBuffer, bezier: Bezier, glyphWidth: Int, glyphHeight: Int) {
buffer.apply {
putUShort((bezier.p0.x * UShort.MAX_VALUE.toInt() / glyphWidth).toInt().toShort())
putUShort((bezier.p0.y * UShort.MAX_VALUE.toInt() / glyphHeight).toInt().toShort())
putUShort((bezier.control.x * UShort.MAX_VALUE.toInt() / glyphWidth).toInt().toShort())
putUShort((bezier.control.y * UShort.MAX_VALUE.toInt() / glyphHeight).toInt().toShort())
putUShort((bezier.p1.x * UShort.MAX_VALUE.toInt() / glyphWidth).toInt().toShort())
putUShort((bezier.p1.y * UShort.MAX_VALUE.toInt() / glyphHeight).toInt().toShort())
}
}
} | 14 | Kotlin | 9 | 291 | 89f372fd18e47998d9b1d3add93ba92e4dcaca6e | 1,566 | littlekt | Apache License 2.0 |
app/src/main/java/com/duckduckgo/app/feedback/ui/negative/brokensite/BrokenSiteNegativeFeedbackFragment.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2019 DuckDuckGo
*
* 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.duckduckgo.app.feedback.ui.negative.brokensite
import androidx.core.view.doOnNextLayout
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.app.browser.R
import com.duckduckgo.app.browser.databinding.ContentFeedbackNegativeBrokenSiteFeedbackBinding
import com.duckduckgo.app.feedback.ui.common.FeedbackFragment
import com.duckduckgo.app.feedback.ui.common.LayoutScrollingTouchListener
import com.duckduckgo.di.scopes.FragmentScope
import com.duckduckgo.mobile.android.ui.viewbinding.viewBinding
@InjectWith(FragmentScope::class)
class BrokenSiteNegativeFeedbackFragment : FeedbackFragment(R.layout.content_feedback_negative_broken_site_feedback) {
interface BrokenSiteFeedbackListener {
fun onProvidedBrokenSiteFeedback(
feedback: String,
url: String?
)
fun userCancelled()
}
private val binding: ContentFeedbackNegativeBrokenSiteFeedbackBinding by viewBinding()
private val viewModel by bindViewModel<BrokenSiteNegativeFeedbackViewModel>()
private val listener: BrokenSiteFeedbackListener?
get() = activity as BrokenSiteFeedbackListener
override fun configureViewModelObservers() {
viewModel.command.observe(this) { command ->
when (command) {
is BrokenSiteNegativeFeedbackViewModel.Command.Exit -> {
listener?.userCancelled()
}
is BrokenSiteNegativeFeedbackViewModel.Command.ExitAndSubmitFeedback -> {
listener?.onProvidedBrokenSiteFeedback(command.feedback, command.brokenSite)
}
}
}
}
override fun configureListeners() {
with(binding) {
submitFeedbackButton.doOnNextLayout {
brokenSiteInput.setOnTouchListener(LayoutScrollingTouchListener(rootScrollView, brokenSiteInputContainer.y.toInt()))
openEndedFeedback.setOnTouchListener(LayoutScrollingTouchListener(rootScrollView, openEndedFeedbackContainer.y.toInt()))
}
submitFeedbackButton.setOnClickListener {
val feedback = openEndedFeedback.text.toString()
val brokenSite = brokenSiteInput.text.toString()
viewModel.userSubmittingFeedback(feedback, brokenSite)
}
}
}
companion object {
fun instance(): BrokenSiteNegativeFeedbackFragment {
return BrokenSiteNegativeFeedbackFragment()
}
}
}
| 67 | null | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 3,102 | Android | Apache License 2.0 |
app/src/main/java/com/moataz/afternoonhadeeth/ui/videos/adapter/VideosTopListAdapter.kt | ahmed-tasaly | 533,010,125 | false | null | package com.moataz.afternoonhadeeth.ui.videos.adapter
import android.annotation.SuppressLint
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.moataz.afternoonhadeeth.R
import com.moataz.afternoonhadeeth.data.model.videos.top.TopVideosList
import com.moataz.afternoonhadeeth.data.model.videos.top.TopVideosResponse
import com.moataz.afternoonhadeeth.databinding.ItemVideosTopListVideosBinding
import com.moataz.afternoonhadeeth.ui.home.view.activity.YoutubePlayerActivity
import java.util.*
class VideosTopListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: TopVideosResponse? = null
@SuppressLint("NotifyDataSetChanged")
fun setTopVideosList(items: TopVideosResponse) {
this.items = items
Collections.shuffle(items.topVideosList)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return TopVideosViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.item_videos_top_list_videos,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val topVideosList = items!!.topVideosList[position]
(holder as TopVideosViewHolder).itemVideosTopListVideosBinding.listTopVideosModel =
topVideosList
holder.setOnClick(topVideosList)
}
override fun getItemCount(): Int {
return if (items == null) 0 else items!!.topVideosList.size
}
internal class TopVideosViewHolder(var itemVideosTopListVideosBinding: ItemVideosTopListVideosBinding) :
RecyclerView.ViewHolder(
itemVideosTopListVideosBinding.root
) {
fun setOnClick(topVideosList: TopVideosList) {
itemView.setOnClickListener { v: View? ->
val intent = Intent(itemView.context, YoutubePlayerActivity::class.java)
intent.putExtra("url", topVideosList.url)
itemView.context.startActivity(intent)
}
}
}
} | 0 | Kotlin | 0 | 1 | ec70b362b5966475693e7f7a406a397ee08099d4 | 2,327 | Sunset-Hadith-Market | Apache License 2.0 |
src/main/kotlin/io/github/pursuewind/intellij/plugin/generate/CodeGenerator.kt | pursue-wind | 634,922,477 | false | {"Kotlin": 78430, "HTML": 1115, "FreeMarker": 500} | package io.github.pursuewind.intellij.plugin.generate
import io.github.pursuewind.intellij.plugin.generate.getset.PostfixData
interface CodeGenerator {
fun generate(postfixData: PostfixData): String =""
} | 0 | Kotlin | 0 | 1 | 818c0e23147c129d8ad45095482c8dbd2f7451d4 | 210 | intellij-plugin-bobobox | Apache License 2.0 |
app/src/main/java/net/xblacky/animexstream/utils/model/EpisodeInfo.kt | justdvnsh | 270,673,285 | false | null | package net.xblacky.animexstream.utils.model
data class EpisodeInfo(
var vidcdnUrl: String? =null,
var nextEpisodeUrl: String? = null,
var previousEpisodeUrl: String? = null
) | 0 | null | 1 | 3 | 667434d34e3f66767c1e317db3c4eeab0d365dee | 188 | AnimeXStream | MIT License |
miniplate-app/src/main/java/com/sample/miniplate/android/ui/splash/MiniplateSplashActivity.kt | droidpl | 153,784,171 | false | null | package com.sample.miniplate.android.ui.splash
import com.sample.miniplate.android.base.MiniplatePresenterActivity
/**
* Created by <EMAIL> on 8/21/17.
*/
class MiniplateSplashActivity: MiniplatePresenterActivity<MiniplateSplashPresenter>(), MiniplateSplashView {
override fun createPresenter(): MiniplateSplashPresenter = MiniplateSplashPresenter(this)
} | 0 | Kotlin | 0 | 0 | a535fedfff57c1eeba75fce133494fd0605555b7 | 364 | miniplate-android | MIT License |
app/src/main/java/com/alexbezhan/instagram/screens/login/LoginActivity.kt | alexbezhan | 129,704,036 | false | null | package ru.clearline.instagram.screens.login
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import ru.clearline.instagram.R
import ru.clearline.instagram.screens.common.BaseActivity
import ru.clearline.instagram.screens.common.coordinateBtnAndInputs
import ru.clearline.instagram.screens.home.HomeActivity
import ru.clearline.instagram.screens.register.RegisterActivity
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_login.*
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEventListener
class LoginActivity : BaseActivity(), KeyboardVisibilityEventListener, View.OnClickListener {
private lateinit var mAuth: FirebaseAuth
private lateinit var mViewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
Log.d(TAG, "onCreate")
KeyboardVisibilityEvent.setEventListener(this, this)
coordinateBtnAndInputs(login_btn, email_input, password_input)
login_btn.setOnClickListener(this)
create_account_text.setOnClickListener(this)
mViewModel = initViewModel()
mViewModel.goToHomeScreen.observe(this, Observer {
startActivity(Intent(this, HomeActivity::class.java))
finish()
})
mViewModel.goToRegisterScreen.observe(this, Observer {
startActivity(Intent(this, RegisterActivity::class.java))
})
mAuth = FirebaseAuth.getInstance()
}
override fun onClick(view: View) {
when (view.id) {
R.id.login_btn ->
mViewModel.onLoginClick(
email = email_input.text.toString(),
password = password_input.text.toString()
)
R.id.create_account_text -> mViewModel.onRegisterClick()
}
}
override fun onVisibilityChanged(isKeyboardOpen: Boolean) {
if (isKeyboardOpen) {
create_account_text.visibility = View.GONE
} else {
create_account_text.visibility = View.VISIBLE
}
}
companion object {
const val TAG = "LoginActivity"
}
}
| 4 | null | 58 | 177 | a55df4aa21d4c728fc415483796a98cf2c288be2 | 2,398 | Instagram-Clone-Kotlin | MIT License |
buttons.kt | mohi0 | 858,659,707 | false | {"Kotlin": 3697} | // code for buttons, switches, toggle widgets
@Composable
fun MToggleSwitch(value: Boolean, onToggle: (value: Boolean)->Unit){
Row(modifier = Modifier
.height(20.dp)
.width(40.dp)
.clip(CircleShape)
.background(Color.LightGray)
.border(1.dp, Color.Gray)){
if (value){
Spacer(modifier=Modifier.width(20.dp))
}
Button(onClick = { onToggle(!value) }, modifier= Modifier
.width(20.dp)
.height(20.dp)
.clip(CircleShape)){
}
}
}
@Composable
fun MIconButton(onClick: () -> Unit, text: String, icon: Painter, iconDescription: String?, textColor: Color, bgColor: Color, iconHeight: Dp, iconWidth: Dp, textSize: TextUnit){
Box(Modifier.clickable(
interactionSource = MutableInteractionSource(),
indication = null, onClick = onClick
)){
Row(
Modifier
.background(bgColor)
.padding(horizontal = (iconWidth / 2), vertical = (iconHeight / 2)), verticalAlignment = Alignment.CenterVertically){
Text(text = text, color = textColor, fontSize = textSize)
Spacer(Modifier.width(iconWidth.div(2)))
Image(icon, "icon", modifier = Modifier
.height(iconHeight)
.width(iconWidth))
}
}
}
| 0 | Kotlin | 0 | 0 | fa7de45793d751c2c6378e1998eaa59cc552066f | 1,353 | SummerCampUI | Apache License 2.0 |
app/src/main/java/com/rarilabs/rarime/modules/profile/ExportKeysScreen.kt | rarimo | 775,551,013 | false | {"Kotlin": 1036626, "Java": 86126, "C++": 17305, "C": 5321, "CMake": 1262} | package com.rarilabs.rarime.modules.profile
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.rarilabs.rarime.R
import com.rarilabs.rarime.ui.components.CardContainer
import com.rarilabs.rarime.ui.components.HorizontalDivider
import com.rarilabs.rarime.ui.components.InfoAlert
import com.rarilabs.rarime.ui.components.PrimaryTextButton
import com.rarilabs.rarime.ui.theme.RarimeTheme
import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.seconds
@Composable
fun ExportKeysScreen(
onBack: () -> Unit, viewModel: ExportKeysViewModel = hiltViewModel()
) {
val privateKey = viewModel.privateKey.collectAsState()
val clipboardManager = LocalClipboardManager.current
var isCopied by remember { mutableStateOf(false) }
if (isCopied) {
LaunchedEffect(Unit) {
delay(3.seconds)
isCopied = false
}
}
ProfileRouteLayout(
title = stringResource(R.string.export_keys), onBack = onBack
) {
CardContainer {
Column(verticalArrangement = Arrangement.spacedBy(20.dp)) {
privateKey.value?.let {
Text(
text = it,
style = RarimeTheme.typography.body3,
color = RarimeTheme.colors.textPrimary,
modifier = Modifier
.background(
RarimeTheme.colors.componentPrimary, RoundedCornerShape(8.dp)
)
.padding(vertical = 14.dp, horizontal = 16.dp)
)
Row(
horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()
) {
PrimaryTextButton(leftIcon = if (isCopied) R.drawable.ic_check else R.drawable.ic_copy_simple,
text = if (isCopied) {
stringResource(R.string.copied_text)
} else {
stringResource(R.string.copy_to_clipboard_btn)
},
onClick = {
clipboardManager.setText(AnnotatedString(it))
isCopied = true
})
}
HorizontalDivider()
InfoAlert(text = stringResource(R.string.new_identity_warning))
}
}
}
}
}
@Preview
@Composable
private fun ExportKeysScreenPreview() {
ExportKeysScreen({})
}
| 1 | Kotlin | 0 | 5 | c92dd78d59c40a09370acaded9ea5b01e80dc10d | 3,620 | rarime-android-app | MIT License |
libs/docker-client/src/integrationTest/kotlin/batect/integrationtests/ImageClientIntegrationTest.kt | viniciussalmeida | 330,515,605 | true | {"Kotlin": 3777014, "Python": 32167, "Groovy": 27495, "Shell": 22487, "PowerShell": 6949, "Dockerfile": 5467, "Batchfile": 3234, "Java": 1421, "HTML": 745} | /*
Copyright 2017-2021 <NAME>.
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 batect.integrationtests
import batect.docker.DockerImage
import batect.docker.api.BuilderVersion
import batect.os.ProcessOutput
import batect.os.ProcessRunner
import batect.testutils.createForGroup
import batect.testutils.runBeforeGroup
import com.natpryce.hamkrest.anyElement
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.containsSubstring
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.has
import com.natpryce.hamkrest.hasElement
import com.natpryce.hamkrest.matches
import com.natpryce.hamkrest.or
import com.nhaarman.mockitokotlin2.mock
import okio.sink
import org.spekframework.spek2.Spek
import org.spekframework.spek2.dsl.Skip
import org.spekframework.spek2.style.specification.describe
import java.io.ByteArrayOutputStream
object ImageClientIntegrationTest : Spek({
describe("a Docker images client") {
val client by createForGroup { createClient() }
describe("pulling an image that has not been cached locally already") {
beforeGroup { removeImage("hello-world:latest") }
val image by runBeforeGroup { client.pull("hello-world:latest") }
it("pulls the image successfully") {
assertThat(image, equalTo(DockerImage("hello-world:latest")))
}
}
describe("building an image with BuildKit", skip = if (runBuildKitTests) Skip.No else Skip.Yes("not supported on this version of Docker")) {
val imageDirectory = testImagesDirectory.resolve("basic-image")
val output by createForGroup { ByteArrayOutputStream() }
runBeforeGroup { client.build(imageDirectory, "batect-integration-tests-image-buildkit", BuilderVersion.BuildKit, output.sink()) }
it("includes all expected output in the response") {
val lines = output.toString().lines()
assertThat(lines, hasElement("#1 [internal] load remote build context"))
assertThat(lines, hasElement("#1 CACHED") or hasElement("#1 DONE"))
assertThat(lines, hasElement("#2 copy /context /"))
assertThat(lines, hasElement("#2 CACHED") or hasElement("#2 DONE"))
assertThat(lines, anyElement(matches("""^#3 \[internal] load metadata for docker.io/library/alpine:.*""".toRegex())))
assertThat(lines, hasElement("#3 CACHED") or hasElement("#3 DONE"))
assertThat(lines, anyElement(matches("""^#4 \[1/1] FROM docker.io/library/alpine:.*""".toRegex())))
assertThat(lines, hasElement("#4 CACHED") or hasElement("#4 DONE"))
assertThat(lines, hasElement("#5 exporting to image"))
assertThat(lines, hasElement("#5 CACHED") or hasElement("#5 DONE"))
}
}
}
})
private fun removeImage(imageName: String) {
val processRunner = ProcessRunner(mock())
val result = processRunner.runAndCaptureOutput(listOf("docker", "rmi", "-f", imageName))
assertThat(result, has(ProcessOutput::output, containsSubstring("No such image: $imageName")) or has(ProcessOutput::exitCode, equalTo(0)))
}
| 0 | null | 0 | 0 | 1013e57de23f9b493606fb246264a44d4a13b048 | 3,721 | batect | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/EditLocationOutlined.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/EditLocationOutlined")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val EditLocationOutlined: SvgIconComponent
| 10 | null | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 222 | kotlin-wrappers | Apache License 2.0 |
s4-repository-layer/final-project/app/src/main/java/com/droidcon/easyinvoice/ui/utils/Symbols.kt | droidcon-academy | 557,290,152 | false | null | package com.droidcon.easyinvoice.ui.utils
const val INR = "₹" | 0 | Kotlin | 0 | 0 | df32960315a4a501893a478daf4f61ae4149cfb3 | 62 | android-room-database-course-materials | Apache License 2.0 |
educational-core/testSrc/com/jetbrains/edu/learning/marketplace/MarketplaceUpdateCheckerTest.kt | JetBrains | 43,696,115 | false | null | package com.jetbrains.edu.learning.marketplace
import com.jetbrains.edu.learning.course
import com.jetbrains.edu.learning.courseFormat.EduCourse
import com.jetbrains.edu.learning.marketplace.api.MarketplaceConnector
import com.jetbrains.edu.learning.marketplace.api.MockMarketplaceConnector
import com.jetbrains.edu.learning.marketplace.update.MarketplaceUpdateChecker
import com.jetbrains.edu.learning.newproject.CourseProjectGenerator
import com.jetbrains.edu.learning.update.CourseUpdateCheckerTestBase
class MarketplaceUpdateCheckerTest : CourseUpdateCheckerTestBase() {
private val mockConnector: MockMarketplaceConnector get() = MarketplaceConnector.getInstance() as MockMarketplaceConnector
override fun setUp() {
super.setUp()
configureResponse()
}
private fun configureResponse() {
mockConnector.withResponseHandler(testRootDisposable) { request ->
UPDATE_INFO_REQUEST_RE.matchEntire(request.path) ?: return@withResponseHandler null
mockResponse("updateInfo.json")
}
}
fun `test check scheduled for not upToDate course`() {
doTestCheckScheduled(expectedInvocationNumber = 2, isCourseUpToDate = false, courseVersion = 1)
}
fun `test check scheduled for upToDate course`() {
doTestCheckScheduled(expectedInvocationNumber = 2, isCourseUpToDate = true)
}
fun `test check scheduled for newly created course`() {
doTestCheckScheduled(expectedInvocationNumber = 2, isCourseUpToDate = true, isNewlyCreated = true)
}
fun `test no isUpToDate check for newly created course at project opening`() {
createCourse(isNewlyCreated = true, courseVersion = 3)
testNoCheck(MarketplaceUpdateChecker.getInstance(project))
}
fun `test no check scheduled for stepik course`() {
createCourse(isNewlyCreated = false, courseVersion = 0, isMarketplaceCourse = false)
testNoCheck(MarketplaceUpdateChecker.getInstance(project))
}
private fun doTestCheckScheduled(expectedInvocationNumber: Int,
isCourseUpToDate: Boolean,
courseVersion: Int = 3,
isNewlyCreated: Boolean = false) {
val course = createCourse(isNewlyCreated, courseVersion)
doTest(MarketplaceUpdateChecker.getInstance(project), isCourseUpToDate, 0, expectedInvocationNumber, checkInterval = 1) {
assertEquals(isCourseUpToDate, course.isUpToDate)
}
}
private fun createCourse(isNewlyCreated: Boolean, courseVersion: Int, isMarketplaceCourse: Boolean = true): EduCourse {
val course = course { } as EduCourse
with(course) {
name = "Test Course"
id = 1
marketplaceCourseVersion = courseVersion
isMarketplace = isMarketplaceCourse
}
createCourseStructure(course)
project.putUserData(CourseProjectGenerator.EDU_PROJECT_CREATED, isNewlyCreated)
return course
}
override fun getTestDataPath(): String = super.getTestDataPath() + "marketplace/updateInfo/"
companion object {
private val UPDATE_INFO_REQUEST_RE = """/api/search/graphql?.*""".toRegex()
}
} | 7 | null | 49 | 99 | cfc24fe13318de446b8adf6e05d1a7c15d9511b5 | 3,079 | educational-plugin | Apache License 2.0 |
java-to-kotlin/src/main/kotlin/lec12/Person.kt | JinseongHwang | 629,867,831 | false | {"Kotlin": 29011, "Java": 14569} | package lec12
class Person private constructor(
private val name: String,
private val age: Int,
) {
companion object {
private const val MIN_AGE: Int = 1
@JvmStatic
fun newBaby(name: String): Person {
return Person(name, MIN_AGE)
}
}
}
fun main() {
val person = Person.Companion.newBaby("js")
} | 0 | Kotlin | 0 | 2 | 445aec00ceb19bca3cc96494edd849bfebcc91b2 | 361 | kotlin-playground | MIT License |
app/src/main/java/com/megatest/myapplication/framework/presentation/list/state/TransactionListSateEvent.kt | jizhe7550 | 389,287,987 | false | null | package com.megatest.myapplication.framework.presentation.list.state
import com.megatest.myapplication.business.domain.state.StateEvent
sealed class TransactionListSateEvent: StateEvent {
object GetAllTransactionsInCacheEvent: TransactionListSateEvent() {
override fun errorInfo(): String {
return "Error get all transactions in cache."
}
override fun eventName(): String {
return "GetAllTransactionsInCacheEvent"
}
override fun shouldDisplayProgressBar() = true
}
} | 0 | Kotlin | 2 | 0 | 7db69c94205810d6a9569c517dc644b4bfbb9c05 | 544 | BudgetExpenseApp | MIT License |
android/app/src/main/java/com/algorand/android/utils/CurrencyUtils.kt | AllanMangeni | 412,352,101 | true | {"Kotlin": 1709104} | /*
* Copyright 2019 Algorand, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.algorand.android.utils
import com.algorand.android.models.CurrencyValue
import java.math.BigDecimal
import java.math.BigInteger
fun getAlgoBalanceAsCurrencyValue(balance: BigInteger?, currencyValue: CurrencyValue): BigDecimal? {
val algoValue = balance?.toBigDecimal()?.movePointLeft(ALGO_DECIMALS) ?: return null
return currencyValue.getAlgorandCurrencyValue()?.multiply(algoValue)
}
| 1 | Kotlin | 0 | 1 | d47f08026fa797ea6474622ce5d1990666a241e9 | 989 | algorand-wallet | Apache License 2.0 |
lib/src/main/kotlin/com/lemonappdev/konsist/api/provider/KoDeclarationProvider.kt | LemonAppDev | 621,181,534 | false | {"Kotlin": 2114775, "Python": 13962} | package com.lemonappdev.konsist.api.provider
import com.lemonappdev.konsist.api.declaration.KoBaseDeclaration
/**
* An interface representing a Kotlin declaration that provides information about declarations.
*/
interface KoDeclarationProvider : KoBaseProvider {
/**
* The declarations present in the declaration.
*
* @param includeNested specifies whether to include nested declarations.
* @param includeLocal specifies whether to include local declarations.
* @return a list of [KoBaseDeclaration] representing the declarations in the declaration.
*/
fun declarations(
includeNested: Boolean = true,
includeLocal: Boolean = true,
): List<KoBaseDeclaration>
/**
* Checks whether the declaration contains a declaration that satisfies the specified predicate.
*
* @param includeNested Specifies whether to include nested declarations in the check (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the check (optional, default is `true`).
* @param predicate The predicate function to determine if a declaration satisfies a condition.
* @return `true` if the declaration contains a declaration that satisfies the specified predicate, `true` otherwise.
*/
fun containsDeclaration(
includeNested: Boolean = true,
includeLocal: Boolean = true,
predicate: (KoBaseDeclaration) -> Boolean,
): Boolean
/**
* Gets the number of declarations present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @return The number of declarations in the declaration.
*/
fun numDeclarations(includeNested: Boolean = true, includeLocal: Boolean = true): Int
/**
* Gets the number of declarations that satisfies the specified predicate present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @param predicate The predicate function to determine if a declaration satisfies a condition.
* @return The number of declarations that satisfies the specified predicate in the declaration.
*/
fun countDeclarations(
includeNested: Boolean = true,
includeLocal: Boolean = true,
predicate: (KoBaseDeclaration) -> Boolean,
): Int
/**
* Gets the number of declarations with public visibility modifier present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @return The number of declarations in the declaration.
*/
fun numPublicDeclarations(includeNested: Boolean = true, includeLocal: Boolean = true): Int
/**
* Gets the number of declarations with public or default visibility modifier present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @return The number of declarations in the declaration.
*/
fun numPublicOrDefaultDeclarations(includeNested: Boolean = true, includeLocal: Boolean = true): Int
/**
* Gets the number of declarations with private visibility modifier present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @return The number of declarations in the declaration.
*/
fun numPrivateDeclarations(includeNested: Boolean = true, includeLocal: Boolean = true): Int
/**
* Gets the number of declarations with protected visibility modifier present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @return The number of declarations in the declaration.
*/
fun numProtectedDeclarations(includeNested: Boolean = true, includeLocal: Boolean = true): Int
/**
* Gets the number of declarations with internal visibility modifier present in the declaration.
*
* @param includeNested Specifies whether to include nested declarations in the count (optional, default is `true`).
* @param includeLocal Specifies whether to include local declarations in the count (optional, default is `true`).
* @return The number of declarations in the declaration.
*/
fun numInternalDeclarations(includeNested: Boolean = true, includeLocal: Boolean = true): Int
}
| 8 | Kotlin | 11 | 595 | 2e33b6f26741d709ad63fa8c637c57208330aea9 | 5,339 | konsist | Apache License 2.0 |
seskar/seskar-compiler-plugin/src/main/kotlin/seskar/compiler/workers/backend/WorkerFactoryTransformer.kt | turansky | 279,976,108 | false | {"Kotlin": 148063, "JavaScript": 1520, "Shell": 459, "HTML": 302} | package seskar.compiler.workers.backend
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.name
import org.jetbrains.kotlin.ir.util.file
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import seskar.compiler.common.backend.JsFileName
import seskar.compiler.common.backend.JsName
internal class WorkerFactoryTransformer(
private val context: IrPluginContext,
) : IrElementTransformerVoid() {
override fun visitProperty(declaration: IrProperty): IrStatement {
if (!declaration.isWorkerFactory())
return declaration
val fileName = declaration.file.name.removeSuffix(".kt")
declaration.file.annotations += JsFileName(context, "${fileName}__worker__factory")
val jsName = sequenceOf(
fileName,
declaration.name.identifier,
).joinToString(
separator = WORKER_DELIMITER,
prefix = WORKER_DELIMITER,
postfix = WORKER_DELIMITER,
)
declaration.annotations += JsName(context, jsName)
return super.visitProperty(declaration)
}
}
| 0 | Kotlin | 7 | 53 | fd8be63786b9c427ac718772655a9d1f86da57f7 | 1,248 | seskar | Apache License 2.0 |
mui-kotlin/src/jsMain/kotlin/mui/base/OptionUnstyled.types.kt | karakum-team | 387,062,541 | false | null | // Automatically generated - do not modify!
package mui.base
import web.cssom.ClassName
external interface OptionUnstyledProps<TValue> :
OptionUnstyledOwnProps<TValue> {
var component: react.ElementType<*>?
}
external interface OptionUnstyledOwnProps<TValue> :
react.PropsWithChildren,
react.PropsWithClassName {
/**
* The value of the option.
*/
var value: TValue
override var children: react.ReactNode?
/**
* If `true`, the option will be disabled.
* @default false
*/
var disabled: Boolean?
override var className: ClassName?
/**
* The props used for each slot inside the OptionUnstyled.
* @default {}
*/
var slotProps: SlotProps?
interface SlotProps {
var root: react.Props? /* SlotComponentProps<'li', OptionUnstyledComponentsPropsOverrides, OptionUnstyledOwnerState<TValue>> */
}
/**
* The components used for each slot inside the OptionUnstyled.
* Either a string to use a HTML element or a component.
* @default {}
*/
var slots: Slots?
interface Slots {
var root: react.ElementType<*>?
}
/**
* A text representation of the option's content.
* Used for keyboard text navigation matching.
*/
var label: String?
}
| 0 | Kotlin | 3 | 31 | d1ea32754f43e696f6b3e946692c2e81f25ad6ae | 1,302 | mui-kotlin | Apache License 2.0 |
test/src/commonMain/kotlin/test/Sample.kt | siloni-hub | 369,211,487 | true | {"Kotlin": 288455, "SWIG": 5989, "CMake": 2692, "Java": 974} | /*
* Copyright 2020 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test
import io.realm.RealmObject
class Sample : RealmObject {
var stringField: String = "Realm"
var byteField: Byte = 0xA
var charField: Char = 'a'
var shortField: Short = 17
var intField: Int = 42
var longField: Long = 256
var booleanField: Boolean = true
var floatField: Float = 3.14f
var doubleField: Double = 1.19840122
var child: Sample? = null
}
| 0 | null | 0 | 0 | ac907a06d8166f2bc33a9e3f3c158b5e47df31d0 | 996 | realm-kotlin | DOC License |
misk-metrics/src/testFixtures/kotlin/misk/metrics/v2/CollectorRegistryModule.kt | cashapp | 113,107,217 | false | {"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58} | package misk.metrics.v2
import io.prometheus.client.Collector
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.Predicate
import io.prometheus.client.SimpleCollector
import misk.inject.KAbstractModule
import misk.testing.TestFixture
import java.util.Enumeration
internal class CollectorRegistryModule : KAbstractModule() {
override fun configure() {
val registry = CollectorRegistryFixture(CollectorRegistry(true))
bind<CollectorRegistry>().toInstance(registry)
multibind<TestFixture>().toInstance(registry)
}
}
internal class CollectorRegistryFixture(val registry: CollectorRegistry) : CollectorRegistry(true), TestFixture {
private val registeredCollectors = mutableSetOf<Collector>()
override fun reset() {
registeredCollectors.forEach {
if (it is SimpleCollector<*>) {
it.clear()
}
}
}
override fun register(collector: Collector) {
registeredCollectors.add(collector)
registry.register(collector)
}
override fun unregister(collector: Collector) {
registeredCollectors.remove(collector)
registry.unregister(collector)
}
override fun metricFamilySamples(): Enumeration<Collector.MetricFamilySamples> {
return registry.metricFamilySamples()
}
override fun filteredMetricFamilySamples(includedNames: Set<String?>?): Enumeration<Collector.MetricFamilySamples> {
return registry.filteredMetricFamilySamples(includedNames)
}
override fun filteredMetricFamilySamples(sampleNameFilter: Predicate<String?>?): Enumeration<Collector.MetricFamilySamples> {
return registry.filteredMetricFamilySamples(sampleNameFilter)
}
override fun getSampleValue(name: String): Double? {
return registry.getSampleValue(name)
}
override fun getSampleValue(
name: String,
labelNames: Array<String?>?,
labelValues: Array<String?>?
): Double? {
return registry.getSampleValue(name, labelNames, labelValues)
}
override fun clear() {
registry.clear()
}
}
| 169 | Kotlin | 169 | 400 | 13dcba0c4e69cc2856021270c99857e7e91af27d | 2,000 | misk | Apache License 2.0 |
test.kt | jwerle | 174,743,481 | false | null | import datkt.tape.test
import kargv.parse
fun main(argv: Array<String>) {
test("""
fun <T : Any> parse(
argv: Array<String>,
model: T,
handler: (T, Node) -> Any?
): T? """.trimMargin().trimIndent().replace("\n", "")) { t ->
class Model(
var a: String = "",
var b: String = "",
var c: Boolean = false,
var d: Int = 0,
var option: String = "",
var number: Int = 0,
var key: String = "",
var list: Array<String> = emptyArray(),
var args: Array<String> = emptyArray()
)
var rest = arrayOf("the", "rest", "of", "the", "arguments")
val values = Model(
a = "hello",
b = "world",
c = true,
d = 2,
option = "value",
number = 1234,
key = "value",
list = arrayOf("x", "y", "z"),
args = rest
)
val args = arrayOf(
"-a", "hello",
"-b", "world",
"-c",
"-d",
"-d",
"--option", "value",
"--number", "1234",
"--key=value",
"--list", "x",
"--list", "y",
"--list", "z",
*rest,
"--",
"fefe"
)
val model = Model()
parse(args, model) { m, node ->
val value = node.value
when (node.name) {
// strings
"a" -> m.a = if (null != value) value else m.a
"b" -> m.b = if (null != value) value else m.b
"key" -> m.key = if (null != value) value else m.key
"option" -> m.option = if (null != value) value else m.option
// boolean
"c" -> m.c = true
// numbers
"d" -> {
m.d = if (null != value) value.toInt() else ++m.d
}
"number" -> {
m.number = if (null != value) value.toInt() else ++m.number
}
// array
"list" -> {
m.list = if (null != value) m.list + value else m.list
}
// otherwise/fallback
else -> {
m.args = if (null != value) m.args + value else m.args
}
}
}
t.equal(model.a, values.a, "model.a == values.a")
t.equal(model.b, values.b, "model.b == values.b")
t.equal(model.c, values.c, "model.c == values.c")
t.equal(model.d, values.d, "model.d == values.d")
t.equal(model.number, values.number, "model.number == values.number")
t.equal(model.option, values.option, "model.option == values.option")
t.equal(model.key, values.key, "model.key == values.key")
rest += "fefe"
model.args.forEachIndexed { i, arg -> t.equal(arg, rest[i]) }
model.list.forEachIndexed { i, arg -> t.equal(arg, values.list[i]) }
t.end()
}
}
| 0 | Kotlin | 0 | 1 | 7e239bdb1f9a61db18b366e63d234d49ecaabaf6 | 2,613 | kargv | MIT License |
ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt | LloydFinch | 166,520,021 | false | null | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.cio
import io.ktor.http.cio.internals.*
import io.ktor.network.util.*
import io.ktor.util.*
import kotlinx.coroutines.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import java.io.*
import java.io.EOFException
import java.nio.*
import kotlin.coroutines.*
/**
* Represents a multipart content starting event. Every part need to be completely consumed or released via [release]
*/
public sealed class MultipartEvent {
/**
* Release underlying data/packet.
*/
public abstract fun release()
/**
* Represents a multipart content preamble. A multipart stream could have at most one preamble.
* @property body contains preamble's content
*/
public class Preamble(public val body: ByteReadPacket) : MultipartEvent() {
override fun release() {
body.release()
}
}
/**
* Represents a multipart part. There could be any number of parts in a multipart stream. Please note that
* it is important to consume [body] otherwise multipart parser could get stuck (suspend)
* so you will not receive more events.
*
* @property headers deferred that will be completed once will be parsed
* @property body a channel of part content
*/
public class MultipartPart(
public val headers: Deferred<HttpHeadersMap>,
public val body: ByteReadChannel
) : MultipartEvent() {
@OptIn(ExperimentalCoroutinesApi::class)
override fun release() {
headers.invokeOnCompletion { t ->
if (t != null) {
headers.getCompleted().release()
}
}
runBlocking {
body.discard()
}
}
}
/**
* Represents a multipart content epilogue. A multipart stream could have at most one epilogue.
* @property body contains epilogue's content
*/
public class Epilogue(public val body: ByteReadPacket) : MultipartEvent() {
override fun release() {
body.release()
}
}
}
@Suppress("KDocMissingDocumentation", "unused")
@Deprecated(
"Simply copy required number of bytes from input to output instead",
level = DeprecationLevel.HIDDEN
)
public suspend fun copyMultipart(headers: HttpHeadersMap, input: ByteReadChannel, out: ByteWriteChannel) {
val length = headers["Content-Length"]?.parseDecLong() ?: Long.MAX_VALUE
input.copyTo(out, length)
}
/**
* Parse a multipart preamble
* @return number of bytes copied
*/
@Deprecated("This is going to be removed. Use parseMultipart instead.")
public suspend fun parsePreamble(
boundaryPrefixed: ByteBuffer,
input: ByteReadChannel,
output: BytePacketBuilder,
limit: Long = Long.MAX_VALUE
): Long {
return parsePreambleImpl(boundaryPrefixed, input, output, limit)
}
/**
* Parse a multipart preamble
* @return number of bytes copied
*/
private suspend fun parsePreambleImpl(
boundaryPrefixed: ByteBuffer,
input: ByteReadChannel,
output: BytePacketBuilder,
limit: Long = Long.MAX_VALUE
): Long {
return copyUntilBoundary(
"preamble/prologue",
boundaryPrefixed,
input,
{ output.writeFully(it) },
limit
)
}
/**
* Parse multipart part headers and body. Body bytes will be copied to [output] but up to [limit] bytes
*/
@Deprecated("This is going to be removed. Use parseMultipart instead.")
public suspend fun parsePart(
boundaryPrefixed: ByteBuffer, input: ByteReadChannel, output: ByteWriteChannel,
limit: Long = Long.MAX_VALUE
): Pair<HttpHeadersMap, Long> {
val headers = parsePartHeadersImpl(input)
try {
val size = parsePartBodyImpl(boundaryPrefixed, input, output, headers, limit)
return Pair(headers, size)
} catch (t: Throwable) {
headers.release()
throw t
}
}
/**
* Parse multipart part headers
*/
@Deprecated("This is going to be removed. Use parseMultipart instead.")
public suspend fun parsePartHeaders(input: ByteReadChannel): HttpHeadersMap {
return parsePartHeadersImpl(input)
}
/**
* Parse multipart part headers
*/
private suspend fun parsePartHeadersImpl(input: ByteReadChannel): HttpHeadersMap {
val builder = CharArrayBuilder()
try {
return parseHeaders(input, builder)
?: throw EOFException("Failed to parse multipart headers: unexpected end of stream")
} catch (t: Throwable) {
builder.release()
throw t
}
}
/**
* Parse multipart part body copying them to [output] channel but up to [limit] bytes
*/
@Deprecated("This is going to be removed. Use parseMultipart instead.")
public suspend fun parsePartBody(
boundaryPrefixed: ByteBuffer,
input: ByteReadChannel, output: ByteWriteChannel,
headers: HttpHeadersMap, limit: Long = Long.MAX_VALUE
): Long {
return parsePartBodyImpl(boundaryPrefixed, input, output, headers, limit)
}
/**
* Parse multipart part body copying them to [output] channel but up to [limit] bytes
*/
private suspend fun parsePartBodyImpl(
boundaryPrefixed: ByteBuffer,
input: ByteReadChannel, output: ByteWriteChannel,
headers: HttpHeadersMap, limit: Long = Long.MAX_VALUE
): Long {
val cl = headers["Content-Length"]?.parseDecLong()
val size = if (cl != null) {
if (cl > limit) throw IOException("Multipart part content length limit of $limit exceeded (actual size is $cl)")
input.copyTo(output, cl)
} else {
copyUntilBoundary("part", boundaryPrefixed, input, { output.writeFully(it) }, limit)
}
output.flush()
return size
}
/**
* Skip multipart boundary
*/
@OptIn(ExperimentalIoApi::class)
@Deprecated("This is going to be removed. Use parseMultipart instead.")
public suspend fun boundary(boundaryPrefixed: ByteBuffer, input: ByteReadChannel): Boolean {
return skipBoundary(boundaryPrefixed, input)
}
/**
* Skip multipart boundary
*/
private suspend fun skipBoundary(boundaryPrefixed: ByteBuffer, input: ByteReadChannel): Boolean {
input.skipDelimiter(boundaryPrefixed)
var result = false
@Suppress("DEPRECATION")
input.lookAheadSuspend {
awaitAtLeast(1)
val buffer = request(0, 1)
?: throw IOException("Failed to pass multipart boundary: unexpected end of stream")
if (buffer[buffer.position()] != PrefixChar) return@lookAheadSuspend
if (buffer.remaining() > 1 && buffer[buffer.position() + 1] == PrefixChar) {
result = true
consumed(2)
return@lookAheadSuspend
}
awaitAtLeast(2)
val attempt2buffer = request(1, 1)
?: throw IOException("Failed to pass multipart boundary: unexpected end of stream")
if (attempt2buffer[attempt2buffer.position()] == PrefixChar) {
result = true
consumed(2)
return@lookAheadSuspend
}
}
return result
}
/**
* Check if we have multipart content
*/
@Deprecated("This is going to be removed.")
public fun expectMultipart(headers: HttpHeadersMap): Boolean {
return headers["Content-Type"]?.startsWith("multipart/") ?: false
}
@Suppress("KDocMissingDocumentation", "unused", "DeprecatedCallableAddReplaceWith")
@Deprecated("Specify CoroutineScope explicitly", level = DeprecationLevel.HIDDEN)
public fun parseMultipart(
coroutineContext: CoroutineContext,
input: ByteReadChannel,
headers: HttpHeadersMap
): ReceiveChannel<MultipartEvent> {
return CoroutineScope(coroutineContext).parseMultipart(input, headers)
}
/**
* Starts a multipart parser coroutine producing multipart events
*/
@KtorExperimentalAPI
public fun CoroutineScope.parseMultipart(input: ByteReadChannel, headers: HttpHeadersMap): ReceiveChannel<MultipartEvent> {
val contentType = headers["Content-Type"] ?: throw IOException("Failed to parse multipart: no Content-Type header")
val contentLength = headers["Content-Length"]?.parseDecLong()
return parseMultipart(input, contentType, contentLength)
}
@Suppress("KDocMissingDocumentation", "unused", "DeprecatedCallableAddReplaceWith")
@Deprecated("Specify coroutine scope explicitly", level = DeprecationLevel.HIDDEN)
public fun parseMultipart(
coroutineContext: CoroutineContext,
input: ByteReadChannel,
contentType: CharSequence,
contentLength: Long?
): ReceiveChannel<MultipartEvent> {
return CoroutineScope(coroutineContext).parseMultipart(input, contentType, contentLength)
}
/**
* Starts a multipart parser coroutine producing multipart events
*/
@KtorExperimentalAPI
public fun CoroutineScope.parseMultipart(
input: ByteReadChannel,
contentType: CharSequence,
contentLength: Long?
): ReceiveChannel<MultipartEvent> {
if (!contentType.startsWith("multipart/")) throw IOException("Failed to parse multipart: Content-Type should be multipart/* but it is $contentType")
val boundaryBytes = parseBoundary(contentType)
// TODO fail if contentLength = 0 and content subtype is wrong
@Suppress("DEPRECATION")
return parseMultipart(boundaryBytes, input, contentLength)
}
private val CrLf = ByteBuffer.wrap("\r\n".toByteArray())!!
private val BoundaryTrailingBuffer = ByteBuffer.allocate(8192)!!
@Suppress("KDocMissingDocumentation", "unused", "DeprecatedCallableAddReplaceWith")
@Deprecated("Use parseMultipart with coroutine scope specified", level = DeprecationLevel.HIDDEN)
public fun parseMultipart(
coroutineContext: CoroutineContext,
boundaryPrefixed: ByteBuffer,
input: ByteReadChannel,
totalLength: Long?
): ReceiveChannel<MultipartEvent> {
@Suppress("DEPRECATION")
return CoroutineScope(coroutineContext).parseMultipart(boundaryPrefixed, input, totalLength)
}
/**
* Starts a multipart parser coroutine producing multipart events
*/
@Deprecated("This is going to be removed. Use parseMultipart(contentType) instead.")
public fun CoroutineScope.parseMultipart(
boundaryPrefixed: ByteBuffer, input: ByteReadChannel, totalLength: Long?
): ReceiveChannel<MultipartEvent> = produce {
@Suppress("DEPRECATION")
val readBeforeParse = input.totalBytesRead
val firstBoundary = boundaryPrefixed.duplicate()!!.apply {
position(2)
}
val preamble = BytePacketBuilder()
parsePreambleImpl(firstBoundary, input, preamble, 8192)
if (preamble.size > 0) {
send(MultipartEvent.Preamble(preamble.build()))
}
if (skipBoundary(firstBoundary, input)) {
return@produce
}
val trailingBuffer = BoundaryTrailingBuffer.duplicate()
do {
input.readUntilDelimiter(CrLf, trailingBuffer)
if (input.readUntilDelimiter(
CrLf,
trailingBuffer
) != 0
) throw IOException("Failed to parse multipart: boundary line is too long")
input.skipDelimiter(CrLf)
val body = ByteChannel()
val headers = CompletableDeferred<HttpHeadersMap>()
val part = MultipartEvent.MultipartPart(headers, body)
send(part)
var hh: HttpHeadersMap? = null
try {
hh = parsePartHeadersImpl(input)
if (!headers.complete(hh)) {
hh.release()
throw CancellationException("Multipart processing has been cancelled")
}
parsePartBodyImpl(boundaryPrefixed, input, body, hh)
} catch (t: Throwable) {
if (headers.completeExceptionally(t)) {
hh?.release()
}
body.close(t)
throw t
}
body.close()
} while (!skipBoundary(boundaryPrefixed, input))
if (totalLength != null) {
@Suppress("DEPRECATION")
val consumedExceptEpilogue = input.totalBytesRead - readBeforeParse
val size = totalLength - consumedExceptEpilogue
if (size > Int.MAX_VALUE) throw IOException("Failed to parse multipart: prologue is too long")
if (size > 0) {
send(MultipartEvent.Epilogue(input.readPacket(size.toInt())))
}
} else {
val epilogueContent = input.readRemaining()
if (epilogueContent.isNotEmpty) {
send(MultipartEvent.Epilogue(epilogueContent))
}
}
}
/**
* @return number of copied bytes or 0 if a boundary of EOF encountered
*/
private suspend fun copyUntilBoundary(
name: String,
boundaryPrefixed: ByteBuffer,
input: ByteReadChannel,
writeFully: suspend (ByteBuffer) -> Unit,
limit: Long = Long.MAX_VALUE
): Long {
val buffer = DefaultByteBufferPool.borrow()
var copied = 0L
try {
while (true) {
buffer.clear()
val rc = input.readUntilDelimiter(boundaryPrefixed, buffer)
if (rc <= 0) break // got boundary or eof
buffer.flip()
writeFully(buffer)
copied += rc
if (copied > limit) {
throw IOException("Multipart $name limit of $limit bytes exceeded")
}
}
return copied
} finally {
DefaultByteBufferPool.recycle(buffer)
}
}
private const val PrefixChar = '-'.toByte()
private fun findBoundary(contentType: CharSequence): Int {
var state = 0 // 0 header value, 1 param name, 2 param value unquoted, 3 param value quoted, 4 escaped
var paramNameCount = 0
for (i in contentType.indices) {
val ch = contentType[i]
when (state) {
0 -> {
if (ch == ';') {
state = 1
paramNameCount = 0
}
}
1 -> {
if (ch == '=') {
state = 2
} else if (ch == ';') {
// do nothing
paramNameCount = 0
} else if (ch == ',') {
state = 0
} else if (ch == ' ') {
// do nothing
} else if (paramNameCount == 0 && contentType.startsWith("boundary=", i, ignoreCase = true)) {
return i
} else {
paramNameCount++
}
}
2 -> {
when (ch) {
'"' -> state = 3
',' -> state = 0
';' -> {
state = 1
paramNameCount = 0
}
}
}
3 -> {
if (ch == '"') {
state = 1
paramNameCount = 0
} else if (ch == '\\') {
state = 4
}
}
4 -> {
state = 3
}
}
}
return -1
}
/**
* Parse multipart boundary encoded in [contentType] header value
* @return a buffer containing CRLF, prefix '--' and boundary bytes
*/
@KtorExperimentalAPI
public fun parseBoundary(contentType: CharSequence): ByteBuffer {
val boundaryParameter = findBoundary(contentType)
if (boundaryParameter == -1) throw IOException("Failed to parse multipart: Content-Type's boundary parameter is missing")
val boundaryStart = boundaryParameter + 9
val boundaryBytes: ByteBuffer = ByteBuffer.allocate(74)
boundaryBytes.put(0x0d)
boundaryBytes.put(0x0a)
boundaryBytes.put(PrefixChar)
boundaryBytes.put(PrefixChar)
var state = 0 // 0 - skipping spaces, 1 - unquoted characters, 2 - quoted no escape, 3 - quoted after escape
loop@ for (i in boundaryStart until contentType.length) {
val ch = contentType[i]
val v = ch.toInt() and 0xffff
if (v and 0xffff > 0x7f) throw IOException("Failed to parse multipart: wrong boundary byte 0x${v.toString(16)} - should be 7bit character")
when (state) {
0 -> {
when (ch) {
' ' -> {
// skip space
}
'"' -> {
state = 2 // start quoted string parsing
}
';', ',' -> {
break@loop
}
else -> {
state = 1
boundaryBytes.put(v.toByte())
}
}
}
1 -> { // non-quoted string
if (ch == ' ' || ch == ',' || ch == ';') { // space, comma or semicolon (;)
break@loop
} else if (boundaryBytes.hasRemaining()) {
boundaryBytes.put(v.toByte())
} else {
// RFC 2046, sec 5.1.1
throw IOException("Failed to parse multipart: boundary shouldn't be longer than 70 characters")
}
}
2 -> {
if (ch == '\\') {
state = 3
} else if (ch == '"') {
break@loop
} else if (boundaryBytes.hasRemaining()) {
boundaryBytes.put(v.toByte())
} else {
// RFC 2046, sec 5.1.1
throw IOException("Failed to parse multipart: boundary shouldn't be longer than 70 characters")
}
}
3 -> {
if (boundaryBytes.hasRemaining()) {
boundaryBytes.put(v.toByte())
state = 2
} else {
// RFC 2046, sec 5.1.1
throw IOException("Failed to parse multipart: boundary shouldn't be longer than 70 characters")
}
}
}
}
boundaryBytes.flip()
if (boundaryBytes.remaining() == 4) {
throw IOException("Empty multipart boundary is not allowed")
}
return boundaryBytes
}
| 0 | null | 1 | 2 | 9b9fc6c3b853c929a806c65cf6bf7c104b4c07fc | 18,040 | ktor | Apache License 2.0 |
jetpackmvvm/src/main/java/com/simplation/mvvm/app/ext/AppExt.kt | Simplation | 324,966,218 | false | null | package com.simplation.mvvm.app.ext
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.getActionButton
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.ToastUtils
import com.simplation.mvvm.R
import com.simplation.mvvm.app.util.CacheUtil
import com.simplation.mvvm.app.util.SettingUtil
import com.simplation.mvvmlib.ext.navigateAction
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
/**
* @param message 显示对话框的内容 必填项
* @param title 显示对话框的标题 默认 温馨提示
* @param positiveButtonText 确定按钮文字 默认确定
* @param positiveAction 点击确定按钮触发的方法 默认空方法
* @param negativeButtonText 取消按钮文字 默认空 不为空时显示该按钮
* @param negativeAction 点击取消按钮触发的方法 默认空方法
*/
fun AppCompatActivity.showMessage(
message: String,
title: String = "温馨提示",
positiveButtonText: String = "确定",
positiveAction: () -> Unit = {},
negativeButtonText: String = "",
negativeAction: () -> Unit = {}
) {
MaterialDialog(this)
.cancelable(true)
.lifecycleOwner(this)
.show {
title(text = title)
message(text = message)
positiveButton(text = positiveButtonText) {
positiveAction.invoke()
}
if (negativeButtonText.isNotEmpty()) {
negativeButton(text = negativeButtonText) {
negativeAction.invoke()
}
}
getActionButton(WhichButton.POSITIVE).updateTextColor(SettingUtil.getColor(this@showMessage))
getActionButton(WhichButton.NEGATIVE).updateTextColor(SettingUtil.getColor(this@showMessage))
}
}
/**
* @param message 显示对话框的内容 必填项
* @param title 显示对话框的标题 默认 温馨提示
* @param positiveButtonText 确定按钮文字 默认确定
* @param positiveAction 点击确定按钮触发的方法 默认空方法
* @param negativeButtonText 取消按钮文字 默认空 不为空时显示该按钮
* @param negativeAction 点击取消按钮触发的方法 默认空方法
*/
fun Fragment.showMessage(
message: String,
title: String = "温馨提示",
positiveButtonText: String = "确定",
positiveAction: () -> Unit = {},
negativeButtonText: String = "",
negativeAction: () -> Unit = {}
) {
activity?.let {
MaterialDialog(it)
.cancelable(true)
.lifecycleOwner(viewLifecycleOwner)
.show {
title(text = title)
message(text = message)
positiveButton(text = positiveButtonText) {
positiveAction.invoke()
}
if (negativeButtonText.isNotEmpty()) {
negativeButton(text = negativeButtonText) {
negativeAction.invoke()
}
}
getActionButton(WhichButton.POSITIVE).updateTextColor(SettingUtil.getColor(it))
getActionButton(WhichButton.NEGATIVE).updateTextColor(SettingUtil.getColor(it))
}
}
}
/**
* 获取进程号对应的进程名
*
* @param pid 进程号
* @return 进程名
*/
fun getProcessName(pid: Int): String? {
var reader: BufferedReader? = null
try {
reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
var processName = reader.readLine()
if (!TextUtils.isEmpty(processName)) {
processName = processName.trim { it <= ' ' }
}
return processName
} catch (throwable: Throwable) {
throwable.printStackTrace()
} finally {
try {
reader?.close()
} catch (exception: IOException) {
exception.printStackTrace()
}
}
return null
}
/**
* 加入 qq 聊天群
*/
fun Fragment.joinQQGroup(key: String): Boolean {
val intent = Intent()
intent.data =
Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key")
// 此 Flag 可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手 Q 主界面,不设置,按返回会返回到呼起产品界面 //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return try {
startActivity(intent)
true
} catch (e: Exception) {
// 未安装手 Q 或安装的版本不支持
ToastUtils.showShort("未安装手机 QQ 或安装的版本不支持")
false
}
}
/**
* 拦截登录操作,如果没有登录跳转登录,登录过了则执行你的方法
*/
fun NavController.jumpByLogin(action: (NavController) -> Unit) {
if (CacheUtil.isLogin()) {
action(this)
} else {
this.navigateAction(R.id.action_to_loginFragment)
}
}
/**
* 拦截登录操作,如果没有登录执行方法 actionLogin 登录过了执行 action
*/
fun NavController.jumpByLogin(
actionLogin: (NavController) -> Unit,
action: (NavController) -> Unit
) {
if (CacheUtil.isLogin()) {
action(this)
} else {
actionLogin(this)
}
}
fun List<*>?.isNull(): Boolean {
return this?.isEmpty() ?: true
}
fun List<*>?.isNotNull(): Boolean {
return this != null && this.isNotEmpty()
}
/**
* 根据索引获取集合的 child 值
* @receiver List<T>?
* @param position Int
* @return T?
*/
inline fun <reified T> List<T>?.getChild(position: Int): T? {
// 如果 List 为 null 返回 null
return if (this == null) {
null
} else {
// 如果 position 大于集合的 size 返回 null
if (position + 1 > this.size) {
null
} else {
// 返回正常数据
this[position]
}
}
} | 0 | Kotlin | 0 | 2 | 9116550267238e6f8dba8ee3e88f51daecd67a38 | 5,482 | LearnJetpack | Apache License 2.0 |
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitMalformedDeclarationInspection.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.junit.codeInspection
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInsight.AnnotationUtil.CHECK_HIERARCHY
import com.intellij.codeInsight.MetaAnnotationUtil
import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.options.JavaClassValidator
import com.intellij.codeInspection.*
import com.intellij.codeInspection.options.OptPane
import com.intellij.codeInspection.options.OptPane.pane
import com.intellij.codeInspection.options.OptPane.stringList
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.execution.JUnitBundle
import com.intellij.execution.junit.*
import com.intellij.execution.junit.references.MethodSourceReference
import com.intellij.jvm.analysis.quickFix.CompositeModCommandQuickFix
import com.intellij.jvm.analysis.quickFix.createModifierQuickfixes
import com.intellij.lang.Language
import com.intellij.lang.jvm.JvmMethod
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmPrimitiveTypeKind
import com.intellij.lang.jvm.types.JvmType
import com.intellij.modcommand.ModPsiUpdater
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.*
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference
import com.intellij.psi.impl.source.tree.java.PsiNameValuePairImpl
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.util.*
import com.intellij.uast.UastHintedVisitorAdapter
import com.intellij.util.asSafely
import com.siyeh.ig.junit.JUnitCommonClassNames.*
import com.siyeh.ig.psiutils.TestUtils
import com.siyeh.ig.psiutils.TypeUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
import kotlin.streams.asSequence
class JUnitMalformedDeclarationInspection : AbstractBaseUastLocalInspectionTool() {
@JvmField
val ignorableAnnotations = mutableListOf("mockit.Mocked", "org.junit.jupiter.api.io.TempDir")
override fun getOptionsPane(): OptPane = pane(
stringList(
"ignorableAnnotations",
JUnitBundle.message("jvm.inspections.junit.malformed.option.ignore.test.parameter.if.annotated.by"),
JavaClassValidator().annotationsOnly()
)
)
private fun shouldInspect(file: PsiFile) = isJUnit3InScope(file) || isJUnit4InScope(file) || isJUnit5InScope(file)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
if (!shouldInspect(holder.file)) return PsiElementVisitor.EMPTY_VISITOR
return UastHintedVisitorAdapter.create(
holder.file.language,
JUnitMalformedSignatureVisitor(holder, isOnTheFly, ignorableAnnotations),
arrayOf(UClass::class.java, UField::class.java, UMethod::class.java),
directOnly = true
)
}
}
private class JUnitMalformedSignatureVisitor(
private val holder: ProblemsHolder,
private val isOnTheFly: Boolean,
private val ignorableAnnotations: List<String>
) : AbstractUastNonRecursiveVisitor() {
override fun visitClass(node: UClass): Boolean {
checkUnconstructableClass(node)
checkMalformedNestedClass(node)
return true
}
override fun visitField(node: UField): Boolean {
checkMalformedCallbackExtension(node)
dataPoint.check(holder, node)
ruleSignatureProblem.check(holder, node)
classRuleSignatureProblem.check(holder, node)
registeredExtensionProblem.check(holder, node)
return true
}
override fun visitMethod(node: UMethod): Boolean {
checkMalformedParameterized(node)
checkRepeatedTestNonPositive(node)
checkIllegalCombinedAnnotations(node)
dataPoint.check(holder, node)
checkSuite(node)
checkedMalformedSetupTeardown(node)
beforeAfterProblem.check(holder, node)
beforeAfterEachProblem.check(holder, node)
beforeAfterClassProblem.check(holder, node)
beforeAfterAllProblem.check(holder, node)
ruleSignatureProblem.check(holder, node)
classRuleSignatureProblem.check(holder, node)
checkJUnit3Test(node)
junit4TestProblem.check(holder, node)
junit5TestProblem.check(holder, node)
return true
}
private val dataPoint = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINT, ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINTS),
shouldBeStatic = true,
validVisibility = { UastVisibility.PUBLIC },
)
private val ruleSignatureProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_RULE),
shouldBeStatic = false,
shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE, ORG_JUNIT_RULES_METHOD_RULE),
validVisibility = { UastVisibility.PUBLIC }
)
private val registeredExtensionProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION),
shouldBeSubTypeOf = listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTENSION),
validVisibility = { decl ->
val junitVersion = getUJUnitVersion(decl) ?: return@AnnotatedSignatureProblem null
if (junitVersion < JUnitVersion.V_5_8_0) notPrivate(decl) else null
}
)
private val classRuleSignatureProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_CLASS_RULE),
shouldBeStatic = true,
shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE),
validVisibility = { UastVisibility.PUBLIC }
)
private val beforeAfterProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_BEFORE, ORG_JUNIT_AFTER),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = { UastVisibility.PUBLIC },
validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } }
)
private val beforeAfterEachProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_EACH, ORG_JUNIT_JUPITER_API_AFTER_EACH),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = ::notPrivate,
validParameters = { method ->
if (method.uastParameters.isEmpty()) emptyList()
else if (method.inParameterResolverContext()) method.uastParameters
else method.uastParameters.filter { param ->
param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO
|| param.type.canonicalText == ORG_JUNIT_JUPITER_API_REPETITION_INFO
|| param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER
|| MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
|| param.inParameterResolverContext()
}
}
)
private val beforeAfterClassProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_BEFORE_CLASS, ORG_JUNIT_AFTER_CLASS),
shouldBeStatic = true,
shouldBeVoidType = true,
validVisibility = { UastVisibility.PUBLIC },
validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } }
)
private val beforeAfterAllProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_ALL, ORG_JUNIT_JUPITER_API_AFTER_ALL),
shouldBeInTestInstancePerClass = true,
shouldBeStatic = true,
shouldBeVoidType = true,
validVisibility = ::notPrivate,
validParameters = { method ->
if (method.uastParameters.isEmpty()) emptyList()
else if (method.inParameterResolverContext()) method.uastParameters
else method.uastParameters.filter { param ->
param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO
|| MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
|| param.inParameterResolverContext()
}
}
)
private val junit4TestProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_TEST),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = { UastVisibility.PUBLIC },
validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } }
)
private val junit5TestProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_TEST),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = ::notPrivate,
validParameters = { method ->
if (method.uastParameters.isEmpty()) emptyList()
else if (MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE))) null // handled in parameterized test check
else if (method.inParameterResolverContext()) method.uastParameters
else method.uastParameters.filter { param ->
param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO
|| param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER
|| MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
|| param.inParameterResolverContext()
}
}
)
private val PsiAnnotation.shortName get() = qualifiedName?.substringAfterLast(".")
private fun notPrivate(method: UDeclaration): UastVisibility? =
if (method.visibility == UastVisibility.PRIVATE) UastVisibility.PUBLIC else null
private fun UParameter.inParameterResolverContext(): Boolean = uAnnotations.any { ann -> ann.resolve()?.inParameterResolverContext() == true }
private fun UMethod.inParameterResolverContext(): Boolean {
val sourcePsi = this.sourcePsi ?: return false
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
return alternatives.any { it.javaPsi.inParameterResolverContext() }
}
private fun PsiModifierListOwner.inParameterResolverContext(): Boolean {
val hasAnnotation = MetaAnnotationUtil.findMetaAnnotationsInHierarchy(this, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH))
.asSequence()
.any { annotation ->
annotation?.flattenedAttributeValues(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)?.any {
val uClassLiteral = it.toUElementOfType<UClassLiteralExpression>()
uClassLiteral != null && InheritanceUtil.isInheritor(uClassLiteral.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
} == true
}
if (hasAnnotation) return true
val hasRegisteredExtension = if (this is PsiClass) {
fields.any { field ->
field.hasAnnotation(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION)
&& InheritanceUtil.isInheritor(field.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
}
} else false
if (hasRegisteredExtension) return true
if (parentOfType<PsiModifierListOwner>(withSelf = false)?.inParameterResolverContext() == true) return true
return hasPotentialAutomaticParameterResolver(this)
}
private fun hasPotentialAutomaticParameterResolver(element: PsiElement): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return false
val resourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(TestUtils.isInTestCode(element))
for (resourceRoot in resourceRoots) {
val directory = PsiManager.getInstance(module.project).findDirectory(resourceRoot)
val serviceFile = directory
?.findSubdirectory("META-INF")
?.findSubdirectory("services")
?.findFile(ORG_JUNIT_JUPITER_API_EXTENSION_EXTENSION)
val serviceFqns = serviceFile?.text?.lines() ?: continue
return serviceFqns.any { serviceFqn ->
val service = JavaPsiFacade.getInstance(module.project).findClass(serviceFqn, module.moduleContentScope)
InheritanceUtil.isInheritor(service, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
}
}
return false
}
private fun checkUnconstructableClass(aClass: UClass) {
val javaClass = aClass.javaPsi
if (javaClass.isInterface || javaClass.isEnum || javaClass.isAnnotationType) return
if (javaClass.hasModifier(JvmModifier.ABSTRACT)) return
val constructors = javaClass.constructors.toList()
if (TestUtils.isJUnitTestClass(javaClass)) {
checkMalformedClass(aClass)
if (constructors.isNotEmpty()) {
val compatibleConstr = constructors.firstOrNull {
val parameters = it.parameterList.parameters
it.hasModifier(JvmModifier.PUBLIC)
&& (it.parameterList.isEmpty || parameters.size == 1 && TypeUtils.isJavaLangString(parameters.first().type))
}
if (compatibleConstr == null) {
val message = JUnitBundle.message("jvm.inspections.unconstructable.test.case.junit3.descriptor")
holder.registerUProblem(aClass, message)
return
}
}
} else if (TestUtils.isJUnit4TestClass(javaClass, false)) {
checkMalformedClass(aClass)
if (constructors.isNotEmpty()) {
val publicConstructors = constructors.filter { it.hasModifier(JvmModifier.PUBLIC) }
if (publicConstructors.size != 1 || !publicConstructors.first().parameterList.isEmpty) {
val message = JUnitBundle.message("jvm.inspections.unconstructable.test.case.junit4.descriptor")
holder.registerUProblem(aClass, message)
return
}
}
}
return
}
private fun checkMalformedClass(aClass: UClass) {
val javaClass = aClass.javaPsi
if (!javaClass.hasModifier(JvmModifier.PUBLIC) && !aClass.isAnonymousOrLocal()) {
val message = JUnitBundle.message("jvm.inspections.unconstructable.test.case.not.public.descriptor")
val fixes = createModifierQuickfixes(aClass, modifierRequest(JvmModifier.PUBLIC, true))
holder.registerUProblem(aClass, message, *fixes)
}
}
private fun checkMalformedNestedClass(aClass: UClass) {
val classHierarchy = aClass.nestedClassHierarchy()
if (classHierarchy.isEmpty()) return
if (classHierarchy.all { it.javaPsi.hasModifier(JvmModifier.ABSTRACT) }) return
val outer = classHierarchy.last()
checkMalformedJUnit4NestedClass(aClass, outer)
checkMalformedJUnit5NestedClass(aClass)
}
private fun UClass.nestedClassHierarchy(current: List<UClass> = emptyList()): List<UClass> {
val containingClass = getContainingUClass()
if (containingClass == null) return current
return listOf(containingClass) + containingClass.nestedClassHierarchy(current)
}
private fun checkMalformedJUnit4NestedClass(aClass: UClass, outerClass: UClass) {
if (aClass.isInterface || aClass.javaPsi.hasModifier(JvmModifier.ABSTRACT)) return
if (aClass.methods.none { it.javaPsi.hasAnnotation(ORG_JUNIT_TEST) }) return
if (outerClass.uAnnotations.firstOrNull { it.qualifiedName == ORG_JUNIT_RUNNER_RUN_WITH } != null) return
val message = JUnitBundle.message("jvm.inspections.junit.malformed.missing.nested.annotation.descriptor")
holder.registerUProblem(aClass, message, MakeJUnit4InnerClassRunnableFix(aClass))
}
private inner class MakeJUnit4InnerClassRunnableFix(aClass: UClass) : ClassSignatureQuickFix(
aClass.javaPsi.name, true, aClass.visibility != UastVisibility.PRIVATE, null
) {
override fun getName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.class.signature.multi")
override fun getActions(project: Project): List<(JvmModifiersOwner) -> List<IntentionAction>> {
val list = super.getActions(project).toMutableList()
list.add { owner ->
val outerClass = owner.sourceElement?.toUElementOfType<UClass>()?.nestedClassHierarchy()?.last()!!
val request = annotationRequest(ORG_JUNIT_RUNNER_RUN_WITH, classAttribute(
PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME,
ORG_JUNIT_EXPERIMENTAL_RUNNERS_ENCLOSED
))
createAddAnnotationActions(outerClass.javaPsi, request)
}
return list
}
override fun getFamilyName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.class.signature.multi")
override fun applyFix(project: Project, element: PsiElement, updater: ModPsiUpdater) {
val uClass = getUParentForIdentifier(element)?.asSafely<UClass>() ?: return
applyFixes(project, uClass.javaPsi.asSafely<PsiClass>() ?: return,
element.containingFile ?: return)
}
}
private fun checkMalformedJUnit5NestedClass(aClass: UClass) {
val javaClass = aClass.javaPsi
if (aClass.isInterface || aClass.javaPsi.hasModifier(JvmModifier.ABSTRACT)) return
if (!javaClass.hasAnnotation(ORG_JUNIT_JUPITER_API_NESTED) && !aClass.methods.any { it.javaPsi.hasAnnotation(ORG_JUNIT_JUPITER_API_TEST) }) return
if (javaClass.hasAnnotation(ORG_JUNIT_JUPITER_API_NESTED) && !aClass.isStatic && aClass.visibility != UastVisibility.PRIVATE) return
val message = JUnitBundle.message("jvm.inspections.junit.malformed.missing.nested.annotation.descriptor")
val fix = ClassSignatureQuickFix(
aClass.javaPsi.name ?: return,
false,
aClass.visibility == UastVisibility.PRIVATE,
if (javaClass.hasAnnotation(ORG_JUNIT_JUPITER_API_NESTED)) null else ORG_JUNIT_JUPITER_API_NESTED
)
holder.registerUProblem(aClass, message, fix)
}
private fun checkMalformedCallbackExtension(field: UField) {
val javaField = field.javaPsi?.asSafely<PsiField>() ?: return
val type = field.javaPsi?.asSafely<PsiField>()?.type ?: return
if (!field.isStatic
&& javaField.hasAnnotation(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION)
&& type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_BEFORE_ALL_CALLBACK, ORG_JUNIT_JUPITER_API_EXTENSION_AFTER_ALL_CALLBACK)
) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.extension.class.level.descriptor", type.presentableText)
val fixes = createModifierQuickfixes(field, modifierRequest(JvmModifier.STATIC, shouldBePresent = true))
holder.registerUProblem(field, message, *fixes)
}
}
private fun UMethod.isNoArg(): Boolean = uastParameters.isEmpty() || uastParameters.all { param ->
param.javaPsi?.asSafely<PsiParameter>()?.let { AnnotationUtil.isAnnotated(it, ignorableAnnotations, 0) } == true
}
private fun checkSuspendFunction(method: UMethod): Boolean {
return if (method.lang == Language.findLanguageByID("kotlin") && method.javaPsi.modifierList.text.contains("suspend")) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.suspend.function.descriptor")
holder.registerUProblem(method, message)
true
} else false
}
private fun checkJUnit3Test(method: UMethod) {
val sourcePsi = method.sourcePsi ?: return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return
if (method.isConstructor) return
if (!TestUtils.isJUnit3TestMethod(javaMethod.javaPsi)) return
val containingClass = method.javaPsi.containingClass ?: return
if (AnnotationUtil.isAnnotated(containingClass, TestUtils.RUN_WITH, CHECK_HIERARCHY)) return
if (checkSuspendFunction(method)) return
if (PsiTypes.voidType() != method.returnType || method.visibility != UastVisibility.PUBLIC || javaMethod.isStatic
|| (!method.isNoArg() && !method.isParameterizedTest())) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.no.arg.descriptor", "public", "non-static", DOUBLE)
return holder.registerUProblem(method, message, MethodSignatureQuickfix(method.name, false, newVisibility = JvmModifier.PUBLIC))
}
}
private fun UMethod.isParameterizedTest(): Boolean =
uAnnotations.firstOrNull { it.qualifiedName == ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST } != null
private fun checkedMalformedSetupTeardown(method: UMethod) {
if ("setUp" != method.name && "tearDown" != method.name) return
if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return
val sourcePsi = method.sourcePsi ?: return
if (checkSuspendFunction(method)) return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return
if (PsiTypes.voidType() != method.returnType || method.visibility == UastVisibility.PRIVATE || javaMethod.isStatic || !method.isNoArg()) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.no.arg.descriptor", "non-private", "non-static", DOUBLE)
val quickFix = MethodSignatureQuickfix(
method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = false, shouldBeVoidType = true, inCorrectParams = emptyMap()
)
return holder.registerUProblem(method, message, quickFix)
}
}
private fun checkSuite(method: UMethod) {
if ("suite" != method.name) return
if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return
val sourcePsi = method.sourcePsi ?: return
if (checkSuspendFunction(method)) return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return
if (method.visibility == UastVisibility.PRIVATE || !javaMethod.isStatic || !method.isNoArg()) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.no.arg.descriptor", "non-private", "static", SINGLE)
val quickFix = MethodSignatureQuickfix(
method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = true, shouldBeVoidType = false, inCorrectParams = emptyMap()
)
return holder.registerUProblem(method, message, quickFix)
}
}
private fun checkIllegalCombinedAnnotations(decl: UDeclaration) {
val javaPsi = decl.javaPsi.asSafely<PsiModifierListOwner>() ?: return
val annotatedTest = nonCombinedTests.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) }
if (annotatedTest.size > 1) {
val last = annotatedTest.last().substringAfterLast('.')
val annText = annotatedTest.dropLast(1).joinToString { "'@${it.substringAfterLast('.')}'" }
val message = JUnitBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", annText, last)
return holder.registerUProblem(decl, message)
}
else if (annotatedTest.size == 1 && annotatedTest.first() != ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST) {
val annotatedArgSource = parameterizedSources.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) }
if (annotatedArgSource.isNotEmpty()) {
val testAnnText = annotatedTest.first().substringAfterLast('.')
val argAnnText = annotatedArgSource.joinToString { "'@${it.substringAfterLast('.')}'" }
val message = JUnitBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", argAnnText, testAnnText)
return holder.registerUProblem(decl, message)
}
}
}
private fun checkRepeatedTestNonPositive(method: UMethod) {
val repeatedAnno = method.findAnnotation(ORG_JUNIT_JUPITER_API_REPEATED_TEST) ?: return
val repeatedNumber = repeatedAnno.findDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) ?: return
val repeatedSrcPsi = repeatedNumber.sourcePsi ?: return
val constant = repeatedNumber.evaluate()
if (constant is Int && constant <= 0) {
holder.registerProblem(repeatedSrcPsi, JUnitBundle.message("jvm.inspections.junit.malformed.repetition.number.descriptor"))
}
}
private fun checkMalformedParameterized(method: UMethod) {
if (!MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf(ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST))) return
val usedSourceAnnotations = MetaAnnotationUtil.findMetaAnnotations(method.javaPsi, SOURCE_ANNOTATIONS).toList()
checkConflictingSourceAnnotations(usedSourceAnnotations, method)
usedSourceAnnotations.forEach { annotation ->
when (annotation.qualifiedName) {
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE -> checkMethodSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE -> checkValuesSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE -> checkEnumSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE -> checkCsvSource(annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE -> checkNullSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE -> checkEmptySource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE -> {
checkNullSource(method, annotation)
checkEmptySource(method, annotation)
}
}
}
}
private fun checkConflictingSourceAnnotations(annotations: List<PsiAnnotation>, method: UMethod) {
val isSingleParameterProvider = annotations.firstOrNull { ann ->
singleParamProviders.contains(ann.qualifiedName)
} != null
val isMultipleParameterProvider = annotations.firstOrNull { ann ->
multipleParameterProviders.contains(ann.qualifiedName)
} != null
if (!isMultipleParameterProvider && !isSingleParameterProvider && hasCustomProvider(annotations)) return
if (!isMultipleParameterProvider) {
val message = if (!isSingleParameterProvider) {
JUnitBundle.message("jvm.inspections.junit.malformed.param.no.sources.are.provided.descriptor")
}
else if (hasMultipleParameters(method.javaPsi)) {
JUnitBundle.message("jvm.inspections.junit.malformed.param.multiple.parameters.descriptor")
}
else return
holder.registerUProblem(method, message)
}
}
private fun hasCustomProvider(annotations: List<PsiAnnotation>): Boolean {
for (ann in annotations) {
when (ann.qualifiedName) {
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE -> return true
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCES -> {
val attributes = ann.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
if ((attributes as? PsiArrayInitializerMemberValue)?.initializers?.isNotEmpty() == true) return true
}
}
}
return false
}
private fun checkMethodSource(method: UMethod, methodSource: PsiAnnotation) {
val psiMethod = method.javaPsi
val containingClass = psiMethod.containingClass ?: return
val annotationMemberValue = methodSource.flattenedAttributeValues(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
if (annotationMemberValue.isEmpty()) {
if (methodSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) == null) return
val foundMethod = containingClass.findMethodsByName(method.name, true).singleOrNull { it.parameters.isEmpty() }
val uFoundMethod = foundMethod.toUElementOfType<UMethod>()
return if (uFoundMethod != null) {
checkSourceProvider(uFoundMethod, containingClass, methodSource, method)
}
else {
checkAbsentSourceProvider(containingClass, methodSource, method.name, method)
}
}
else {
annotationMemberValue.forEach { attributeValue ->
for (reference in attributeValue.references) {
if (reference is MethodSourceReference) {
val resolve = reference.resolve()
if (resolve !is PsiMethod) {
return checkAbsentSourceProvider(containingClass, attributeValue, reference.value, method)
}
else {
val sourceProvider: PsiMethod = resolve
val uSourceProvider = sourceProvider.toUElementOfType<UMethod>() ?: return
return checkSourceProvider(uSourceProvider, containingClass, attributeValue, method)
}
}
}
}
}
}
private fun checkAbsentSourceProvider(
containingClass: PsiClass, attributeValue: PsiElement, sourceProviderName: String, method: UMethod
) {
val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.param.method.source.unresolved.descriptor",
sourceProviderName
)
return if (isOnTheFly) {
val modifiers = mutableListOf(JvmModifier.PUBLIC)
if (!TestUtils.testInstancePerClass(containingClass)) modifiers.add(JvmModifier.STATIC)
val typeFromText = JavaPsiFacade.getElementFactory(containingClass.project).createTypeFromText(
METHOD_SOURCE_RETURN_TYPE, containingClass
)
val request = methodRequest(containingClass.project, sourceProviderName, modifiers, typeFromText)
val actions = createMethodActions(containingClass, request)
val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, containingClass.containingFile).toTypedArray()
holder.registerProblem(place, message, *quickFixes)
} else {
holder.registerProblem(place, message)
}
}
private fun checkSourceProvider(sourceProvider: UMethod, containingClass: PsiClass?, attributeValue: PsiElement, method: UMethod) {
val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return
val providerName = sourceProvider.name
if (!sourceProvider.isStatic &&
containingClass != null && !TestUtils.testInstancePerClass(containingClass) &&
!implementationsTestInstanceAnnotated(containingClass)
) {
val annotation = JavaPsiFacade.getElementFactory(containingClass.project).createAnnotationFromText(
TEST_INSTANCE_PER_CLASS, containingClass
)
val actions = mutableListOf<IntentionAction>()
val value = (annotation.attributes.first() as PsiNameValuePairImpl).value
if (value != null) {
actions.addAll(createAddAnnotationActions(
containingClass,
annotationRequest(
ORG_JUNIT_JUPITER_API_TEST_INSTANCE,
constantAttribute(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME, value.text)
)
))
}
actions.addAll(createModifierActions(sourceProvider, modifierRequest(JvmModifier.STATIC, true)))
val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, sourceProvider.javaPsi.containingFile).toTypedArray()
val message = JUnitBundle.message("jvm.inspections.junit.malformed.param.method.source.static.descriptor",
providerName)
holder.registerProblem(place, message, *quickFixes)
}
else if (sourceProvider.uastParameters.isNotEmpty() && !classHasParameterResolverField(containingClass)) {
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.param.method.source.no.params.descriptor", providerName)
holder.registerProblem(place, message)
}
else {
val componentType = getComponentType(sourceProvider.returnType, method.javaPsi)
if (componentType == null) {
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.param.method.source.return.type.descriptor", providerName
)
holder.registerProblem(place, message)
}
else if (hasMultipleParameters(method.javaPsi)
&& !InheritanceUtil.isInheritor(componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS)
&& !componentType.equalsToText(JAVA_LANG_OBJECT)
&& !componentType.deepComponentType.equalsToText(JAVA_LANG_OBJECT)
) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.param.wrapped.in.arguments.descriptor")
holder.registerProblem(place, message)
}
}
}
private fun classHasParameterResolverField(aClass: PsiClass?): Boolean {
if (aClass == null) return false
if (aClass.isInterface) return false
return aClass.fields.any { field ->
AnnotationUtil.isAnnotated(field, ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION, 0) &&
field.type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
}
}
private fun implementationsTestInstanceAnnotated(containingClass: PsiClass): Boolean =
ClassInheritorsSearch.search(containingClass, containingClass.resolveScope, true).any { TestUtils.testInstancePerClass(it) }
private fun getComponentType(returnType: PsiType?, method: PsiMethod): PsiType? {
val collectionItemType = JavaGenericsUtil.getCollectionItemType(returnType, method.resolveScope)
if (collectionItemType != null) return collectionItemType
if (InheritanceUtil.isInheritor(returnType, JAVA_UTIL_STREAM_INT_STREAM)) return PsiTypes.intType()
if (InheritanceUtil.isInheritor(returnType, JAVA_UTIL_STREAM_LONG_STREAM)) return PsiTypes.longType()
if (InheritanceUtil.isInheritor(returnType, JAVA_UTIL_STREAM_DOUBLE_STREAM)) return PsiTypes.doubleType()
val streamItemType = PsiUtil.substituteTypeParameter(returnType, JAVA_UTIL_STREAM_STREAM, 0, true)
if (streamItemType != null) return streamItemType
return PsiUtil.substituteTypeParameter(returnType, JAVA_UTIL_ITERATOR, 0, true)
}
private fun hasMultipleParameters(method: PsiMethod): Boolean {
val containingClass = method.containingClass
return containingClass != null && method.parameterList.parameters.count { param ->
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_INFO) &&
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_REPORTER) &&
!MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
} > 1 && !containingClass.inParameterResolverContext()
}
private fun getPassedParameter(method: PsiMethod): PsiParameter? {
return method.parameterList.parameters.firstOrNull { param ->
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_INFO) &&
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_REPORTER) &&
!MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
}
}
private fun checkNullSource(method: UMethod, annotation: PsiAnnotation) {
if (hasMultipleParameters(method.javaPsi)) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.param.multiple.parameters.descriptor")
holder.registerProblem(annotation, message)
}
if (getPassedParameter(method.javaPsi) == null) {
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.source.without.params.descriptor",
annotation.shortName
)
holder.registerProblem(annotation.navigationElement, message)
}
}
private fun checkEmptySource(method: UMethod, annotation: PsiAnnotation) {
if (hasMultipleParameters(method.javaPsi)) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.param.multiple.parameters.descriptor")
return holder.registerProblem(annotation.navigationElement, message)
}
val passedParameter = getPassedParameter(method.javaPsi)
if(passedParameter == null) {
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.source.without.params.descriptor",
annotation.shortName
)
holder.registerProblem(annotation.navigationElement, message)
} else {
val type = passedParameter.type
if (type is PsiClassType) {
val psiClass = type.resolve() ?: return
val version = getUJUnitVersion(method) ?: return
if (version < JUnitVersion.V_5_10_0) {
if (validEmptySourceTypeBefore510.any { it == psiClass.qualifiedName }) return
} else {
if (validEmptySourceTypeAfter510.any { it == psiClass.qualifiedName }) return
val constructors = psiClass.constructors.mapNotNull { it.toUElementOfType<UMethod>() }
val isCollectionOrMap = InheritanceUtil.isInheritor(psiClass, JAVA_UTIL_COLLECTION)
|| InheritanceUtil.isInheritor(psiClass, JAVA_UTIL_MAP)
if (isCollectionOrMap && constructors.any { it.visibility == UastVisibility.PUBLIC && it.isNoArg() }) return
}
}
if (type is PsiArrayType) return
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.param.empty.source.unsupported.descriptor",
annotation.shortName, type.presentableText
)
holder.registerProblem(annotation.navigationElement, message)
}
}
private fun checkEnumSource(method: UMethod, enumSource: PsiAnnotation) {
val value = enumSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
if (value !is PsiClassObjectAccessExpression) return // @EnumSource#value type is Class<?>, not an array
val enumType = value.operand.type
checkSourceTypeAndParameterTypeAgree(method, value, enumType)
checkEnumConstants(enumSource, enumType, method)
}
private fun checkSourceTypeAndParameterTypeAgree(method: UMethod, attributeValue: PsiAnnotationMemberValue, componentType: PsiType) {
val parameters = method.uastParameters
if (parameters.size == 1) {
val paramType = parameters.first().type
if (!paramType.isAssignableFrom(componentType) && !InheritanceUtil.isInheritor(
componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS)
) {
if (componentType.equalsToText(JAVA_LANG_STRING)) {
//implicit conversion to primitive/wrapper
if (TypeConversionUtil.isPrimitiveAndNotNullOrWrapper(paramType)) return
val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType)
//implicit conversion to enum
if (psiClass != null) {
if (psiClass.isEnum && psiClass.findFieldByName((attributeValue as PsiLiteral).value as String?, false) != null) return
//implicit java time conversion
val qualifiedName = psiClass.qualifiedName
if (qualifiedName != null) {
if (qualifiedName.startsWith("java.time.")) return
if (qualifiedName == "java.nio.file.Path") return
}
val factoryMethod: (PsiMethod) -> Boolean = {
!it.hasModifier(JvmModifier.PRIVATE) &&
it.parameterList.parametersCount == 1 &&
it.parameterList.parameters.first().type.equalsToText(JAVA_LANG_STRING)
}
if (!psiClass.hasModifier(JvmModifier.ABSTRACT) && psiClass.constructors.find(factoryMethod) != null) return
if (psiClass.methods.find { it.hasModifier(JvmModifier.STATIC) && factoryMethod(it) } != null) return
}
}
else if (componentType.equalsToText(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM)) {
val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType)
if (psiClass != null && psiClass.isEnum) return
}
val param = parameters.first()
val default = param.sourcePsi as PsiNameIdentifierOwner
val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue
else default.nameIdentifier ?: default).toUElement()?.sourcePsi ?: return
if (param.findAnnotation(ORG_JUNIT_JUPITER_PARAMS_CONVERTER_CONVERT_WITH) != null) return
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.param.method.source.assignable.descriptor",
componentType.presentableText, paramType.presentableText
)
holder.registerProblem(place, message)
}
}
}
private fun checkValuesSource(method: UMethod, valuesSource: PsiAnnotation) {
val psiMethod = method.javaPsi
val possibleValues = mapOf(
"strings" to PsiType.getJavaLangString(psiMethod.manager, psiMethod.resolveScope),
"ints" to PsiTypes.intType(),
"longs" to PsiTypes.longType(),
"doubles" to PsiTypes.doubleType(),
"shorts" to PsiTypes.shortType(),
"bytes" to PsiTypes.byteType(),
"floats" to PsiTypes.floatType(),
"chars" to PsiTypes.charType(),
"booleans" to PsiTypes.booleanType(),
"classes" to PsiType.getJavaLangClass(psiMethod.manager, psiMethod.resolveScope)
)
possibleValues.keys.forEach { valueKey ->
valuesSource.flattenedAttributeValues(valueKey).forEach { value ->
possibleValues[valueKey]?.let { checkSourceTypeAndParameterTypeAgree(method, value, it) }
}
}
val attributesNumber = valuesSource.parameterList.attributes.size
val annotation = (if (method.javaPsi.isAncestor(valuesSource, true)) valuesSource
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElementOfType<UAnnotation>() ?: return
val message = if (attributesNumber == 0) {
JUnitBundle.message("jvm.inspections.junit.malformed.param.no.value.source.is.defined.descriptor")
}
else if (attributesNumber > 1) {
JUnitBundle.message(
"jvm.inspections.junit.malformed.param.exactly.one.type.of.input.must.be.provided.descriptor")
}
else return
return holder.registerUProblem(annotation, message)
}
private fun checkEnumConstants(enumSource: PsiAnnotation, enumType: PsiType, method: UMethod) {
val mode = enumSource.findAttributeValue("mode")
val uMode = mode.toUElement()
if (uMode is UReferenceExpression && ("INCLUDE" == uMode.resolvedName || "EXCLUDE" == uMode.resolvedName)) {
var validType = enumType
if (enumType.canonicalText == ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM) {
val parameters = method.uastParameters
if (parameters.isNotEmpty()) validType = parameters.first().type
}
val allEnumConstants = (PsiUtil.resolveClassInClassTypeOnly(validType) ?: return).fields
.filterIsInstance<PsiEnumConstant>()
.map { it.name }
.toSet()
val definedConstants = mutableSetOf<String>()
enumSource.flattenedAttributeValues("names").forEach { name ->
if (name is PsiLiteralExpression) {
val value = name.value
if (value is String) {
val sourcePsi = (if (method.javaPsi.isAncestor(name, true)) name
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return@forEach
val message = if (!allEnumConstants.contains(value)) {
JUnitBundle.message("jvm.inspections.junit.malformed.param.unresolved.enum.descriptor")
}
else if (!definedConstants.add(value)) {
JUnitBundle.message("jvm.inspections.junit.malformed.param.duplicated.enum.descriptor")
}
else return@forEach
holder.registerProblem(sourcePsi, message)
}
}
}
}
}
private fun checkCsvSource(methodSource: PsiAnnotation) {
methodSource.flattenedAttributeValues("resources").forEach { attributeValue ->
for (ref in attributeValue.references) {
if (ref.isSoft) continue
if (ref is FileReference && ref.multiResolve(false).isEmpty()) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.param.file.source.descriptor", attributeValue.text)
holder.registerProblem(ref.element, message, *ref.quickFixes)
}
}
}
}
class AnnotatedSignatureProblem(
private val annotations: List<String>,
private val shouldBeStatic: Boolean? = null,
private val ignoreOnRunWith: Boolean = false,
private val shouldBeInTestInstancePerClass: Boolean = false,
private val shouldBeVoidType: Boolean? = null,
private val shouldBeSubTypeOf: List<String>? = null,
private val validVisibility: ((UDeclaration) -> UastVisibility?)? = null,
private val validParameters: ((UMethod) -> List<UParameter>?)? = null,
) {
private fun modifierProblems(
validVisibility: UastVisibility?, decVisibility: UastVisibility, isStatic: Boolean, isInstancePerClass: Boolean
): List<@NlsSafe String> {
val problems = mutableListOf<String>()
if (shouldBeInTestInstancePerClass) { if (!isStatic && !isInstancePerClass) problems.add("static") }
else if (shouldBeStatic == true && !isStatic) problems.add("static")
else if (shouldBeStatic == false && isStatic) problems.add("non-static")
if (validVisibility != null && validVisibility != decVisibility) problems.add(validVisibility.text)
return problems
}
private fun isApplicable(element: UElement): Boolean {
if (!ignoreOnRunWith) {
val containingClass = element.getContainingUClass()?.javaPsi ?: return false
val annotation = AnnotationUtil.findAnnotationInHierarchy(containingClass, setOf(ORG_JUNIT_RUNNER_RUN_WITH))
if (annotation != null) {
val runnerType = annotation.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
.toUElement()?.asSafely<UClassLiteralExpression>()
?.type ?: return false
return checkableRunners.any(runnerType::equalsToText)
}
}
return true
}
fun check(holder: ProblemsHolder, element: UField) {
if (!isApplicable(element)) return
val javaPsi = element.javaPsi.asSafely<PsiField>() ?: return
val annotation = annotations
.firstOrNull { MetaAnnotationUtil.isMetaAnnotated(javaPsi, annotations) }
?.substringAfterLast(".") ?: return
val visibility = validVisibility?.invoke(element)
val problems = modifierProblems(visibility, element.visibility, element.isStatic, false)
if (shouldBeVoidType == true && element.type != PsiTypes.voidType()) {
return holder.fieldTypeProblem(element, visibility, annotation, problems, PsiTypes.voidType().name)
}
if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.type, it) } == false) {
return holder.fieldTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first())
}
if (problems.isNotEmpty()) return holder.fieldModifierProblem(element, visibility, annotation, problems)
}
private fun ProblemsHolder.fieldModifierProblem(
element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>
) {
val message = if (problems.size == 1) {
JUnitBundle.message("jvm.inspections.junit.malformed.annotated.single.descriptor", FIELD, annotation, problems.first())
} else {
JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.double.descriptor", FIELD, annotation, problems.first(), problems.last()
)
}
reportFieldProblem(message, element, visibility)
}
private fun ProblemsHolder.fieldTypeProblem(
element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String
) {
if (problems.isEmpty()) {
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.typed.descriptor", FIELD, annotation, type)
registerUProblem(element, message)
}
else if (problems.size == 1) {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.annotated.single.typed.descriptor", FIELD,
annotation, problems.first(), type
)
reportFieldProblem(message, element, visibility)
} else {
val message = JUnitBundle.message("jvm.inspections.junit.malformed.annotated.double.typed.descriptor", FIELD,
annotation, problems.first(), problems.last(), type
)
reportFieldProblem(message, element, visibility)
}
}
private fun ProblemsHolder.reportFieldProblem(message: @InspectionMessage String, element: UField, visibility: UastVisibility?) {
val quickFix = FieldSignatureQuickfix(element.name, shouldBeStatic, visibilityToModifier[visibility])
return registerUProblem(element, message, quickFix)
}
fun check(holder: ProblemsHolder, element: UMethod) {
if (!isApplicable(element)) return
val javaPsi = element.javaPsi.asSafely<PsiMethod>() ?: return
val sourcePsi = element.sourcePsi ?: return
val annotation = annotations
.firstOrNull { AnnotationUtil.isAnnotated(javaPsi, it, CHECK_HIERARCHY) }
?.substringAfterLast('.') ?: return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val elementIsStatic = alternatives.any { it.isStatic }
val visibility = validVisibility?.invoke(element)
val params = validParameters?.invoke(element)
val problems = modifierProblems(
visibility, element.visibility, elementIsStatic, javaPsi.containingClass?.let { cls -> TestUtils.testInstancePerClass(cls) } == true
)
if (element.lang == Language.findLanguageByID("kotlin") && element.javaPsi.modifierList.text.contains("suspend")) {
val message = JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.suspend.function.descriptor", annotation
)
return holder.registerUProblem(element, message)
}
if (params != null && params.size != element.uastParameters.size) {
if (shouldBeVoidType == true && element.returnType != PsiTypes.voidType()) {
return holder.methodParameterTypeProblem(element, visibility, annotation, problems, PsiTypes.voidType().name, params)
}
if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) {
return holder.methodParameterTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first(), params)
}
return holder.methodParameterProblem(element, visibility, annotation, problems, params)
}
if (shouldBeVoidType == true && element.returnType != PsiTypes.voidType()) {
return holder.methodTypeProblem(element, visibility, annotation, problems, PsiTypes.voidType().name)
}
if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) {
return holder.methodTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first())
}
if (problems.isNotEmpty()) return holder.methodModifierProblem(element, visibility, annotation, problems)
}
private fun ProblemsHolder.methodParameterProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, parameters: List<UParameter>
) {
val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) }
val message = when {
problems.isEmpty() && invalidParams.size == 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.param.single.descriptor", annotation, invalidParams.first().name
)
problems.isEmpty() && invalidParams.size > 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.param.double.descriptor",
annotation, invalidParams.joinToString { "'${it.name}'" }, invalidParams.last().name
)
problems.size == 1 && invalidParams.size == 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.param.single.descriptor",
annotation, problems.first(), invalidParams.first().name
)
problems.size == 1 && invalidParams.size > 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.param.double.descriptor",
annotation, problems.first(), invalidParams.joinToString { "'${it.name}'" },
invalidParams.last().name
)
problems.size == 2 && invalidParams.size == 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.param.single.descriptor",
annotation, problems.first(), problems.last(), invalidParams.first().name
)
problems.size == 2 && invalidParams.size > 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.param.double.descriptor",
annotation, problems.first(), problems.last(), invalidParams.joinToString { "'${it.name}'" },
invalidParams.last().name
)
else -> error("Non valid problem.")
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.methodParameterTypeProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String,
parameters: List<UParameter>
) {
val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) }
val message = when {
problems.isEmpty() && invalidParams.size == 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.typed.param.single.descriptor",
annotation, type, invalidParams.first().name
)
problems.isEmpty() && invalidParams.size > 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.typed.param.double.descriptor",
annotation, type, invalidParams.joinToString { "'${it.name}'" }, invalidParams.last().name
)
problems.size == 1 && invalidParams.size == 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.typed.param.single.descriptor",
annotation, problems.first(), type, invalidParams.first().name
)
problems.size == 1 && invalidParams.size > 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.typed.param.double.descriptor",
annotation, problems.first(), type, invalidParams.joinToString { "'${it.name}'" },
invalidParams.last().name
)
problems.size == 2 && invalidParams.size == 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.typed.param.single.descriptor",
annotation, problems.first(), problems.last(), type, invalidParams.first().name
)
problems.size == 2 && invalidParams.size > 1 -> JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.typed.param.double.descriptor",
annotation, problems.first(), problems.last(), type, invalidParams.joinToString { "'${it.name}'" },
invalidParams.last().name
)
else -> error("Non valid problem.")
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.methodTypeProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String
) {
val message = if (problems.isEmpty()) {
JUnitBundle.message("jvm.inspections.junit.malformed.annotated.typed.descriptor", METHOD, annotation, type)
} else if (problems.size == 1) {
JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.single.typed.descriptor", METHOD, annotation, problems.first(), type
)
} else {
JUnitBundle.message(
"jvm.inspections.junit.malformed.annotated.double.typed.descriptor", METHOD, annotation, problems.first(), problems.last(), type
)
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.methodModifierProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>
) {
val message = if (problems.size == 1) {
JUnitBundle.message("jvm.inspections.junit.malformed.annotated.single.descriptor", METHOD, annotation, problems.first())
} else {
JUnitBundle.message("jvm.inspections.junit.malformed.annotated.double.descriptor", METHOD,
annotation, problems.first(), problems.last()
)
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.reportMethodProblem(message: @InspectionMessage String,
element: UMethod,
visibility: UastVisibility? = null,
params: List<UParameter>? = null) {
val quickFix = MethodSignatureQuickfix(
element.name, shouldBeStatic, shouldBeVoidType, visibilityToModifier[visibility],
params?.associate { it.name to it.type } ?: emptyMap()
)
return registerUProblem(element, message, quickFix)
}
}
private open class ClassSignatureQuickFix(
private val name: @NlsSafe String?,
private val makeStatic: Boolean? = null,
private val makePublic: Boolean? = null,
private val annotation: String? = null
) : CompositeModCommandQuickFix() {
override fun getFamilyName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.class.signature")
override fun getName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.class.signature.descriptor", name)
override fun applyFix(project: Project, element: PsiElement, updater: ModPsiUpdater) {
val javaDeclaration = getUParentForIdentifier(element)?.asSafely<UClass>() ?: return
applyFixes(project, javaDeclaration.javaPsi.asSafely<PsiClass>() ?: return,
element.containingFile ?: return)
}
override fun getActions(project: Project): List<(JvmModifiersOwner) -> List<IntentionAction>> {
val actions = mutableListOf<(JvmModifiersOwner) -> List<IntentionAction>>()
if (makeStatic != null) {
actions.add { jvmClass -> createModifierActions(jvmClass, modifierRequest(JvmModifier.STATIC, makeStatic)) }
}
if (makePublic != null) {
actions.add { jvmClass -> createModifierActions(jvmClass, modifierRequest(JvmModifier.PUBLIC, makePublic))}
}
if (annotation != null) {
actions.add { jvmClass -> createAddAnnotationActions(jvmClass, annotationRequest(annotation)) }
}
return actions
}
}
private class FieldSignatureQuickfix(
private val name: @NlsSafe String,
private val makeStatic: Boolean?,
private val newVisibility: JvmModifier? = null
) : CompositeModCommandQuickFix() {
override fun getFamilyName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.field.signature")
override fun getName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.field.signature.descriptor", name)
override fun applyFix(project: Project, element: PsiElement, updater: ModPsiUpdater) {
val javaDeclaration = getUParentForIdentifier(element)?.asSafely<UField>() ?: return
applyFixes(project, javaDeclaration.javaPsi ?: return, element.containingFile ?: return)
}
override fun getActions(project: Project): List<(JvmModifiersOwner) -> List<IntentionAction>> {
val actions = mutableListOf<(JvmModifiersOwner) -> List<IntentionAction>>()
if (newVisibility != null) {
actions.add { jvmField -> createModifierActions(jvmField, modifierRequest(newVisibility, true)) }
}
if (makeStatic != null) {
actions.add { jvmField -> createModifierActions(jvmField, modifierRequest(JvmModifier.STATIC, makeStatic)) }
}
return actions
}
}
private class MethodSignatureQuickfix(
private val name: @NlsSafe String,
private val makeStatic: Boolean?,
private val shouldBeVoidType: Boolean? = null,
private val newVisibility: JvmModifier? = null,
@SafeFieldForPreview private val inCorrectParams: Map<String, JvmType>? = null
) : CompositeModCommandQuickFix() {
override fun getFamilyName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.method.signature")
override fun getName(): String = JUnitBundle.message("jvm.inspections.junit.malformed.fix.method.signature.descriptor", name)
override fun applyFix(project: Project, element: PsiElement, updater: ModPsiUpdater) {
val javaDeclaration = getUParentForIdentifier(element)?.asSafely<UMethod>() ?: return
applyFixes(project, javaDeclaration.javaPsi, element.containingFile ?: return)
}
override fun getActions(project: Project): List<(JvmModifiersOwner) -> List<IntentionAction>> {
val actions = mutableListOf<(JvmModifiersOwner) -> List<IntentionAction>>()
if (shouldBeVoidType == true) {
actions.add { jvmMethod -> createChangeTypeActions(
jvmMethod.asSafely<JvmMethod>()!!,
typeRequest(JvmPrimitiveTypeKind.VOID.name, emptyList())
) }
}
if (newVisibility != null) {
actions.add { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(newVisibility, true, false)) }
}
if (inCorrectParams != null) {
actions.add { jvmMethod -> createChangeParametersActions(
jvmMethod.asSafely<JvmMethod>()!!,
setMethodParametersRequest(inCorrectParams.entries)
) }
}
if (makeStatic != null) {
actions.add { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic, false)) }
}
return actions
}
}
private companion object {
// message choices
const val FIELD = 0
const val METHOD = 1
const val SINGLE = 0
const val DOUBLE = 1
const val TEST_INSTANCE_PER_CLASS = "@org.junit.jupiter.api.TestInstance(TestInstance.Lifecycle.PER_CLASS)"
const val METHOD_SOURCE_RETURN_TYPE = "java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>"
val checkableRunners = listOf(
"org.junit.runners.AllTests",
"org.junit.runners.Parameterized",
"org.junit.runners.BlockJUnit4ClassRunner",
"org.junit.runners.JUnit4",
"org.junit.runners.Suite",
"org.junit.internal.runners.JUnit38ClassRunner",
"org.junit.internal.runners.JUnit4ClassRunner",
"org.junit.experimental.categories.Categories",
"org.junit.experimental.categories.Enclosed"
)
private val validEmptySourceTypeBefore510 = listOf(
JAVA_LANG_STRING,
JAVA_UTIL_LIST,
JAVA_UTIL_SET,
JAVA_UTIL_MAP
)
private val validEmptySourceTypeAfter510 = listOf(
JAVA_LANG_STRING,
JAVA_UTIL_LIST,
JAVA_UTIL_SET,
JAVA_UTIL_SORTED_SET,
JAVA_UTIL_NAVIGABLE_SET,
JAVA_UTIL_SORTED_MAP,
JAVA_UTIL_NAVIGABLE_MAP,
JAVA_UTIL_MAP,
JAVA_UTIL_COLLECTION
)
val visibilityToModifier = mapOf(
UastVisibility.PUBLIC to JvmModifier.PUBLIC,
UastVisibility.PROTECTED to JvmModifier.PROTECTED,
UastVisibility.PRIVATE to JvmModifier.PRIVATE,
UastVisibility.PACKAGE_LOCAL to JvmModifier.PACKAGE_LOCAL
)
val singleParamProviders = listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE
)
val multipleParameterProviders = listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_SOURCE
)
val nonCombinedTests = listOf(
ORG_JUNIT_JUPITER_API_TEST,
ORG_JUNIT_JUPITER_API_TEST_FACTORY,
ORG_JUNIT_JUPITER_API_REPEATED_TEST,
ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST
)
val parameterizedSources = listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE
)
}
}
| 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 64,136 | intellij-community | Apache License 2.0 |
app/src/main/kotlin/com/example/app/HelloApp.kt | jensbarthel | 713,360,193 | false | {"Kotlin": 9283, "Dockerfile": 408} | package com.example.app
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
import org.springframework.context.annotation.ComponentScan
@SpringBootApplication
@ComponentScan("com.example")
@ConfigurationPropertiesScan("com.example")
class HelloApp
fun main(args: Array<String>) {
runApplication<HelloApp>(*args) {
val maybeWorkerPort = System.getenv("FUNCTIONS_HTTPWORKER_PORT")
val workerPort = maybeWorkerPort ?: 43475
println("Setting worker port to $workerPort")
setDefaultProperties(mapOf("server.port" to workerPort))
}
}
| 0 | Kotlin | 0 | 0 | 099e86235c2dc018789215961e9c3f6d5c32f671 | 714 | azure-kotlin-function-graal-spring | Apache License 2.0 |
app/src/main/java/com/neuralbit/letsnote/room/relationships/LabelWIthNotes.kt | NormanGadenya | 421,601,972 | false | {"Kotlin": 373046, "Java": 20226} | package com.neuralbit.letsnote.room.relationships
import androidx.room.Embedded
import androidx.room.Relation
import com.neuralbit.letsnote.room.entities.Label
import com.neuralbit.letsnote.room.entities.Note
data class LabelWIthNotes(
@Embedded val label : Label,
@Relation(
parentColumn = "labelColor",
entityColumn = "labelColor"
)
val notes : List<Note>
)
| 0 | Kotlin | 0 | 4 | 7e7295e5a35d5413ee660c2af8022ee991706af1 | 394 | Lets-Note-App | Apache License 2.0 |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/ClockLock.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.ClockLock: ImageVector
get() {
if (_clockLock != null) {
return _clockLock!!
}
_clockLock = fluentIcon(name = "Regular.ClockLock") {
fluentPath {
moveTo(11.0f, 21.5f)
verticalLineToRelative(-1.06f)
arcToRelative(8.5f, 8.5f, 0.0f, true, false, -7.45f, -9.35f)
arcToRelative(3.5f, 3.5f, 0.0f, false, false, -1.47f, 2.17f)
arcToRelative(10.0f, 10.0f, 0.0f, true, true, 8.88f, 8.69f)
curveToRelative(0.03f, -0.15f, 0.04f, -0.3f, 0.04f, -0.45f)
close()
moveTo(12.0f, 6.65f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.5f, 0.1f)
verticalLineToRelative(6.1f)
curveToRelative(0.06f, 0.37f, 0.37f, 0.65f, 0.75f, 0.65f)
horizontalLineToRelative(4.1f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.1f, -1.5f)
lineTo(12.0f, 12.0f)
lineTo(12.0f, 6.65f)
close()
moveTo(3.0f, 15.0f)
verticalLineToRelative(-1.0f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, 5.0f, 0.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(0.5f)
curveToRelative(0.83f, 0.0f, 1.5f, 0.67f, 1.5f, 1.5f)
verticalLineToRelative(5.0f)
curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-6.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 1.0f, 21.5f)
verticalLineToRelative(-5.0f)
curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f)
lineTo(3.0f, 15.0f)
close()
moveTo(4.5f, 14.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f)
close()
moveTo(6.5f, 19.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 2.0f, 0.0f)
close()
}
}
return _clockLock!!
}
private var _clockLock: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 2,627 | compose-fluent-ui | Apache License 2.0 |
app/src/main/java/com/creativedrewy/nativ/ui/AddressListScreen.kt | Rvjain | 393,466,003 | true | {"Kotlin": 68327} | package com.creativedrewy.nativ.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.creativedrewy.nativ.ui.theme.LightPurple
import com.creativedrewy.nativ.ui.theme.Turquoise
import com.creativedrewy.nativ.viewmodel.AddressListViewModel
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AddressListScreen(
viewModel: AddressListViewModel = viewModel()
) {
val viewState = viewModel.viewState.collectAsState().value
Box(
modifier = Modifier
.fillMaxSize()
.padding(bottom = 64.dp)
) {
Column(
modifier = Modifier.padding(16.dp, 0.dp, 0.dp, 0.dp)
) {
Text(
modifier = Modifier.padding(bottom = 8.dp),
text = "Your Addresses",
style = MaterialTheme.typography.h5,
)
LazyColumn() {
items(viewState.userAddresses) { addr ->
Row(
verticalAlignment = Alignment.CenterVertically,
) {
OutlinedCircleImage(
imageRes = addr.chainLogoRes,
size = 36.dp,
outlineWidth = 2.dp,
outlineColor = Turquoise,
backgroundColor = LightPurple
)
Text(
modifier = Modifier.weight(1f)
.padding(start = 8.dp),
style = MaterialTheme.typography.h6,
text = formatAddress(addr.address)
)
IconButton(
onClick = { viewModel.deleteAddress(addr.address, addr.chainTicker) }
) {
Icon(
imageVector = Icons.Filled.DeleteOutline,
contentDescription = "Delete",
modifier = Modifier.size(24.dp),
tint = Turquoise
)
}
}
}
}
}
}
}
fun formatAddress(srcAddr: String): String {
return if (srcAddr.length >= 20) {
srcAddr.take(10) + "..." + srcAddr.takeLast(10)
} else {
srcAddr
}
}
| 0 | null | 0 | 0 | 5335765b90819427e96f1876ca3d7868eafbad5d | 3,340 | NATIV | Apache License 2.0 |
reaktive/src/commonTest/kotlin/com/badoo/reaktive/observable/ObservableByEmitterTest.kt | badoo | 174,194,386 | false | {"Kotlin": 1507792, "Swift": 2268, "HTML": 956} | package com.badoo.reaktive.observable
import com.badoo.reaktive.disposable.Disposable
import com.badoo.reaktive.test.base.assertDisposed
import com.badoo.reaktive.test.base.assertError
import com.badoo.reaktive.test.base.assertNotError
import com.badoo.reaktive.test.base.assertSubscribed
import com.badoo.reaktive.test.observable.assertComplete
import com.badoo.reaktive.test.observable.assertNoValues
import com.badoo.reaktive.test.observable.assertNotComplete
import com.badoo.reaktive.test.observable.assertValues
import com.badoo.reaktive.test.observable.test
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ObservableByEmitterTest {
private lateinit var emitter: ObservableEmitter<Int?>
private val observable = observable { emitter = it }
private val observer = observable.test()
@Test
fun onSubscribe_called_WHEN_subscribe() {
observer.assertSubscribed()
}
@Test
fun emitted_same_values_and_completed_in_the_same_order() {
emitter.onNext(null)
emitter.onNext(1)
emitter.onNext(2)
emitter.onComplete()
observer.assertValues(null, 1, 2)
observer.assertComplete()
}
@Test
fun emitted_same_values_and_completed_with_error_in_the_same_order() {
val error = Throwable()
emitter.onNext(null)
emitter.onNext(1)
emitter.onNext(2)
emitter.onError(error)
observer.assertValues(null, 1, 2)
observer.assertError(error)
}
@Test
fun emitted_same_values_in_the_same_order_WHEN_disposed_after_producing_values() {
emitter.onNext(null)
emitter.onNext(1)
emitter.onNext(2)
observer.dispose()
observer.assertValues(null, 1, 2)
}
@Test
fun completed_WHEN_onComplete_signalled() {
emitter.onComplete()
observer.assertComplete()
}
@Test
fun completed_with_error_WHEN_onError_signalled() {
val error = Throwable()
emitter.onError(error)
observer.assertError(error)
}
@Test
fun onNext_ignored_AFTER_onCompleted_signalled() {
emitter.onComplete()
observer.reset()
emitter.onNext(2)
observer.assertNoValues()
}
@Test
fun onNext_ignored_AFTER_onError_signalled() {
emitter.onError(Throwable())
observer.reset()
emitter.onNext(2)
observer.assertNoValues()
}
@Test
fun onComplete_ignored_AFTER_onError_signalled() {
emitter.onError(Throwable())
observer.reset()
emitter.onComplete()
observer.assertNotComplete()
}
@Test
fun onError_ignored_AFTER_onCompleted_signalled() {
emitter.onComplete()
observer.reset()
emitter.onError(Throwable())
observer.assertNotError()
}
@Test
fun second_onComplete_ignored_AFTER_first_onComplete_signalled() {
emitter.onComplete()
observer.reset()
emitter.onComplete()
observer.assertNotComplete()
}
@Test
fun second_onError_ignored_AFTER_first_onError_signalled() {
emitter.onError(Throwable())
observer.reset()
emitter.onError(Throwable())
observer.assertNotError()
}
@Test
fun onNext_ignored_AFTER_dispose() {
observer.dispose()
emitter.onNext(1)
observer.assertNoValues()
}
@Test
fun disposable_disposed_WHEN_onComplete_signalled() {
emitter.onComplete()
observer.assertDisposed()
}
@Test
fun disposable_disposed_WHEN_onError_signalled() {
emitter.onError(Throwable())
observer.assertDisposed()
}
@Test
fun completed_with_error_WHEN_exception_during_subscribe() {
val error = RuntimeException()
val observer = observable<Int> { throw error }.test()
observer.assertError(error)
}
@Test
fun disposable_is_not_disposed_WHEN_assigned() {
val disposable = Disposable()
emitter.setDisposable(disposable)
assertFalse(disposable.isDisposed)
}
@Test
fun assigned_disposable_is_disposed_WHEN_disposed() {
val disposable = Disposable()
emitter.setDisposable(disposable)
observer.dispose()
assertTrue(disposable.isDisposed)
}
@Test
fun reassigned_disposable_is_disposed_WHEN_disposed() {
emitter.setDisposable(Disposable())
observer.dispose()
val disposable = Disposable()
emitter.setDisposable(disposable)
assertTrue(disposable.isDisposed)
}
@Test
fun assigned_disposable_is_disposed_AFTER_onComplete_is_signalled() {
val events = ArrayList<String>()
observable.subscribe(observer(onComplete = { events += "onComplete" }))
emitter.setDisposable(Disposable { events += "dispose" })
emitter.onComplete()
assertEquals(listOf("onComplete", "dispose"), events)
}
@Test
fun assigned_disposable_is_disposed_AFTER_onError_is_signalled() {
val events = ArrayList<String>()
observable.subscribe(observer(onError = { events += "onError" }))
emitter.setDisposable(Disposable { events += "dispose" })
emitter.onError(Throwable())
assertEquals(listOf("onError", "dispose"), events)
}
@Test
fun isDisposed_is_false_WHEN_created() {
assertFalse(emitter.isDisposed)
}
@Test
fun isDisposed_is_false_WHEN_onNext_is_signalled() {
observer.onNext(0)
assertFalse(emitter.isDisposed)
}
@Test
fun isDisposed_is_true_WHEN_disposed() {
observer.dispose()
assertTrue(emitter.isDisposed)
}
@Test
fun isDisposed_is_true_WHEN_onComplete_is_signalled() {
emitter.onComplete()
assertTrue(emitter.isDisposed)
}
@Test
fun isDisposed_is_disposed_WHEN_onError_is_signalled() {
emitter.onError(Throwable())
assertTrue(emitter.isDisposed)
}
@Test
fun does_not_emit_values_recursively_WHEN_completing() {
var isEmittedRecursively = false
observable.subscribe(
observer(
onNext = { isEmittedRecursively = true },
onComplete = { emitter.onNext(0) }
)
)
emitter.onComplete()
assertFalse(isEmittedRecursively)
}
@Test
fun does_not_emit_values_recursively_WHEN_producing_error() {
var isEmittedRecursively = false
observable.subscribe(
observer(
onNext = { isEmittedRecursively = true },
onError = { emitter.onNext(0) }
)
)
emitter.onError(Exception())
assertFalse(isEmittedRecursively)
}
@Test
fun does_not_complete_recursively_WHEN_completing() {
var isCompletedRecursively = false
var isCompleted = false
observable.subscribe(
observer(
onComplete = {
if (!isCompleted) {
isCompleted = true
emitter.onComplete()
} else {
isCompletedRecursively = true
}
}
)
)
emitter.onComplete()
assertFalse(isCompletedRecursively)
}
@Test
fun does_not_complete_recursively_WHEN_producing_error() {
var isCompletedRecursively = false
observable.subscribe(
observer(
onComplete = { isCompletedRecursively = true },
onError = { emitter.onComplete() }
)
)
emitter.onError(Exception())
assertFalse(isCompletedRecursively)
}
@Test
fun does_not_produce_error_recursively_WHEN_completing() {
var isErrorRecursively = false
observable.subscribe(
observer(
onComplete = { emitter.onError(Exception()) },
onError = { isErrorRecursively = true }
)
)
emitter.onComplete()
assertFalse(isErrorRecursively)
}
@Test
fun does_not_produce_error_recursively_WHEN_producing_error() {
var isErrorRecursively = false
var hasError = false
observable.subscribe(
observer(
onError = {
if (!hasError) {
hasError = true
emitter.onError(Exception())
} else {
isErrorRecursively = true
}
}
)
)
emitter.onError(Exception())
assertFalse(isErrorRecursively)
}
private fun observer(
onNext: (Int?) -> Unit = {},
onComplete: () -> Unit = {},
onError: (Throwable) -> Unit = {}
): ObservableObserver<Int?> =
object : ObservableObserver<Int?> {
override fun onSubscribe(disposable: Disposable) {
}
override fun onNext(value: Int?) {
onNext.invoke(value)
}
override fun onComplete() {
onComplete.invoke()
}
override fun onError(error: Throwable) {
onError.invoke(error)
}
}
}
| 2 | Kotlin | 57 | 1,171 | 26788ab67ef85e2e3971e5bc79cce4ed9e3b5636 | 9,403 | Reaktive | Apache License 2.0 |
analysis/symbol-light-classes/tests/org/jetbrains/kotlin/light/classes/symbol/base/service/symbolLightClassTestUtils.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.light.classes.symbol.base.service
import org.jetbrains.kotlin.asJava.PsiClassRenderer
import java.nio.file.Path
internal inline fun <R> withExtendedTypeRenderer(testDataFile: Path, action: () -> R): R {
val extendedTypeRendererOld = PsiClassRenderer.extendedTypeRenderer
return try {
PsiClassRenderer.extendedTypeRenderer = testDataFile.toString().endsWith("typeAnnotations.kt")
action()
} finally {
PsiClassRenderer.extendedTypeRenderer = extendedTypeRendererOld
}
} | 157 | Kotlin | 5411 | 43,797 | a8f547d080724fae3a45d675a16c5b3fc2f13b17 | 748 | kotlin | Apache License 2.0 |
tensorflow-lite-examples-common/src/main/java/com/dailystudio/tflite/example/common/image/AbsImageAnalyzer.kt | dailystudio | 267,263,865 | false | null | package com.dailystudio.tflite.example.common.image
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Environment
import android.util.Size
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.dailystudio.devbricksx.GlobalContextWrapper
import com.dailystudio.devbricksx.development.Logger
import com.dailystudio.devbricksx.preference.AbsPrefs
import com.dailystudio.devbricksx.utils.ImageUtils
import com.dailystudio.devbricksx.utils.ImageUtils.toBitmap
import com.dailystudio.tflite.example.common.InferenceAgent
import com.dailystudio.tflite.example.common.ui.InferenceSettingsPrefs
import java.io.File
class AvgTime(private val capacity: Int = 10) {
private val timeValues = Array<Long>(capacity) { 0 }
private var wIndex = 0
val value: Long
get() {
val len = timeValues.size
var sum = 0L
for (i in 0 until len) {
sum += timeValues[i]
}
return sum / len
}
fun record(newValue: Long) {
timeValues[wIndex] = newValue
wIndex = (wIndex + 1) % capacity
}
}
abstract class AbsImageAnalyzer<Info: ImageInferenceInfo, Results> (private val rotation: Int,
private val lensFacing: Int,
var useAverageTime: Boolean = true,
var preprocessEnabled: Boolean = true,
): ImageAnalysis.Analyzer {
private var inferenceAgent: InferenceAgent<Info, Results> =
InferenceAgent()
private val avgInferenceTime = AvgTime(20)
private val avgAnalyzeTime = AvgTime(20)
init {
inferenceAgent.deliverInferenceInfo(createInferenceInfo())
}
override fun analyze(image: ImageProxy) {
var results: Results? = null
val info: Info = createInferenceInfo().apply {
imageSize = Size(image.width, image.height)
imageRotation = image.imageInfo.rotationDegrees
cameraLensFacing = lensFacing
screenRotation = rotation
}
val start = System.currentTimeMillis()
image.image?.let {
val frameBitmap: Bitmap? = it.toBitmap()
val inferenceBitmap: Bitmap? = if (preprocessEnabled) {
preProcessImage(frameBitmap, info)
} else {
frameBitmap
}
inferenceBitmap?.let { bitmap ->
info.inferenceImageSize = Size(bitmap.width, bitmap.height)
results = analyzeFrame(bitmap, info)
}
}
val end = System.currentTimeMillis()
info.analysisTime = (end - start)
if (info.inferenceTime == 0L) {
info.inferenceTime = info.analysisTime
}
Logger.debug("analysis [in ${info.analysisTime} ms (inference: ${info.inferenceTime} ms)]: result = ${results.toString().replace("%", "%%")}")
Logger.debug("useAverageTime = $useAverageTime")
if (useAverageTime) {
avgInferenceTime.record(info.inferenceTime)
avgAnalyzeTime.record(info.analysisTime)
info.inferenceTime = avgInferenceTime.value
info.analysisTime = avgAnalyzeTime.value
}
inferenceAgent.deliverInferenceInfo(info)
image.close()
results?.let {
inferenceAgent.deliverResults(it)
}
}
protected open fun preProcessImage(frameBitmap: Bitmap?,
info: Info): Bitmap? {
return frameBitmap
}
protected open fun setResultsUpdateInterval(interval: Long) {
inferenceAgent.resultsUpdateInterval = interval
}
protected fun dumpIntermediateBitmap(bitmap: Bitmap,
filename: String) {
if (!isDumpIntermediatesEnabled()) {
return
}
saveIntermediateBitmap(bitmap, filename)
}
protected fun saveIntermediateBitmap(bitmap: Bitmap,
filename: String) {
val dir = GlobalContextWrapper.context?.getExternalFilesDir(
Environment.DIRECTORY_PICTURES
)
ImageUtils.saveBitmap(bitmap, File(dir, filename))
}
protected open fun isDumpIntermediatesEnabled(): Boolean {
return false
}
@Synchronized
open fun onInferenceSettingsChange(changePrefName: String, inferenceSettings: AbsPrefs) {
Logger.debug("[SETTINGS UPDATE]: changed preference: $changePrefName")
if (inferenceSettings !is InferenceSettingsPrefs) {
return
}
when (changePrefName) {
InferenceSettingsPrefs.PREF_ENABLE_IMAGE_PREPROCESS -> {
preprocessEnabled = inferenceSettings.enableImagePreprocess
}
InferenceSettingsPrefs.PREF_USER_AVERAGE_TIME -> {
useAverageTime = inferenceSettings.userAverageTime
}
}
}
abstract fun createInferenceInfo(): Info
abstract fun analyzeFrame(inferenceBitmap: Bitmap,
info: Info): Results?
} | 1 | Kotlin | 6 | 17 | 62910b05ff88b6817d75082a5b93d26c2289c43e | 5,265 | tensorflow-lite-examples-android | Apache License 2.0 |
adaptive-core/src/commonMain/kotlin/fun/adaptive/adat/metadata/AdatPropertyMetadata.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 2318583, "Java": 24560, "HTML": 7875, "JavaScript": 3880, "Shell": 687} | /*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package `fun`.adaptive.adat.metadata
import `fun`.adaptive.adat.Adat
import `fun`.adaptive.adat.AdatClass
import `fun`.adaptive.adat.AdatCompanion
import `fun`.adaptive.adat.descriptor.AdatDescriptor
import `fun`.adaptive.adat.descriptor.AdatDescriptorSet
import `fun`.adaptive.adat.descriptor.ConstraintFail
import `fun`.adaptive.adat.descriptor.InstanceValidationResult
import `fun`.adaptive.adat.descriptor.kotlin.string.StringSecret
import `fun`.adaptive.adat.wireformat.AdatClassWireFormat
@Adat
class AdatPropertyMetadata(
val name: String,
val index: Int,
val flags: Int,
val signature: String,
val descriptors: List<AdatDescriptorMetadata> = emptyList(),
) : AdatClass<AdatPropertyMetadata> {
/**
* True when the property is mutable:
*
* - it is read-write **AND** has a backing field
* - **OR** the value of the property is mutable
*/
val isMutableProperty
inline get() = ! isImmutableProperty
/**
* True when the property is immutable:
*
* - it is read-only (declared as `val`)
* - **AND**
* - the value of the property is immutable
* - **OR** it does not have a backing field
*/
val isImmutableProperty
get() = isVal && hasImmutableValue
/**
* True when the property is read-only (declared as `val`, no getter).
*
* Note that this **DOES NOT** mean immutability, the internal properties of
* the value can change even if the property itself is read-only.
*
* Use [hasImmutableValue] to check if the value itself is immutable.
*/
val isVal
get() = (flags and VAL) != 0
/**
* True when the value of the property is mutable.
*/
val hasMutableValue
get() = ! hasImmutableValue
/**
* True when the value of the property is immutable.
*
* Note that this **DOES NOT** mean immutability, the property value can change.
* Use [isMutableProperty] or [isImmutableProperty] to check for actual mutability.
*/
val hasImmutableValue
get() = (flags and IMMUTABLE_VALUE) != 0
/**
* True when the property value is an adat class.
*/
val isAdatClass
get() = (flags and ADAT_CLASS) != 0
fun isSecret(descriptors : Array<AdatDescriptorSet>) =
descriptors.first { it.property.name == name }.descriptors.filterIsInstance<StringSecret>().firstOrNull()?.isSecret == true
fun fail(result : InstanceValidationResult, descriptor : AdatDescriptor) {
result.failedConstraints += ConstraintFail(this, descriptor.metadata)
}
// --------------------------------------------------------------------------------
// AdatClass overrides
// --------------------------------------------------------------------------------
override val adatCompanion: AdatCompanion<AdatPropertyMetadata>
get() = AdatPropertyMetadata
override fun equals(other: Any?): Boolean = adatEquals(other)
override fun hashCode(): Int = adatHashCode()
override fun toString(): String = adatToString()
override fun genGetValue(index: Int): Any? =
when (index) {
0 -> name
1 -> this.index
2 -> flags
3 -> signature
4 -> descriptors
else -> throw IndexOutOfBoundsException()
}
companion object : AdatCompanion<AdatPropertyMetadata> {
const val VAL = 1
const val IMMUTABLE_VALUE = 2
const val ADAT_CLASS = 4
override val wireFormatName: String
get() = "fun.adaptive.adat.metadata.AdatPropertyMetadata"
override val adatMetadata = AdatClassMetadata(
version = 1,
name = wireFormatName,
flags = 0,
properties = listOf(
AdatPropertyMetadata("name", 0, 0, "T"),
AdatPropertyMetadata("index", 1, 0, "I"),
AdatPropertyMetadata("flags", 2, 0, "I"),
AdatPropertyMetadata("signature", 3, 0, "T"),
AdatPropertyMetadata("properties", 4, 0, "Lkotlin.collections.List<Lfun.adaptive.adat.metadata.AdatDescriptorMetadata;>;")
)
)
override val adatWireFormat: AdatClassWireFormat<AdatPropertyMetadata>
get() = AdatClassWireFormat(this, adatMetadata)
override fun newInstance(): AdatPropertyMetadata {
throw UnsupportedOperationException()
}
override fun newInstance(values: Array<Any?>): AdatPropertyMetadata {
@Suppress("UNCHECKED_CAST")
return AdatPropertyMetadata(
name = values[0] as String,
index = values[1] as Int,
flags = values[2] as Int,
signature = values[3] as String,
descriptors = values[4] as List<AdatDescriptorMetadata>
)
}
}
} | 35 | Kotlin | 0 | 3 | e7d8bb8682a6399675bc75d2976b862268d20fb5 | 5,029 | adaptive | Apache License 2.0 |
privacysandbox/activity/activity-provider/src/main/java/androidx/privacysandbox/activity/provider/SdkActivityLauncherFactory.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 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.privacysandbox.activity.provider
import android.os.Bundle
import android.os.IBinder
import androidx.privacysandbox.activity.core.ISdkActivityLauncher
import androidx.privacysandbox.activity.core.ISdkActivityLauncherCallback
import androidx.privacysandbox.activity.core.ProtocolConstants.SDK_ACTIVITY_LAUNCHER_BINDER_KEY
import androidx.privacysandbox.activity.core.SdkActivityLauncher
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.suspendCancellableCoroutine
object SdkActivityLauncherFactory {
/**
* Creates a [SdkActivityLauncher] using the given [launcherInfo] Bundle.
*
* You can create such a Bundle by calling [toLauncherInfo][androidx.privacysandbox.activity.client.toLauncherInfo].
* A [launcherInfo] is expected to have a valid SdkActivityLauncher Binder with
* `"sdkActivityLauncherBinderKey"` for a key, [IllegalArgumentException] is thrown otherwise.
*/
@JvmStatic
fun fromLauncherInfo(launcherInfo: Bundle): SdkActivityLauncher {
val remote: ISdkActivityLauncher? = ISdkActivityLauncher.Stub.asInterface(
launcherInfo.getBinder(SDK_ACTIVITY_LAUNCHER_BINDER_KEY)
)
requireNotNull(remote) { "Invalid SdkActivityLauncher info bundle." }
return SdkActivityLauncherProxy(remote)
}
private class SdkActivityLauncherProxy(
private val remote: ISdkActivityLauncher
) : SdkActivityLauncher {
override suspend fun launchSdkActivity(sdkActivityHandlerToken: IBinder): Boolean =
suspendCancellableCoroutine {
remote.launchSdkActivity(
sdkActivityHandlerToken,
object : ISdkActivityLauncherCallback.Stub() {
override fun onLaunchAccepted(sdkActivityHandlerToken: IBinder?) {
it.resume(true)
}
override fun onLaunchRejected(sdkActivityHandlerToken: IBinder?) {
it.resume(false)
}
override fun onLaunchError(message: String?) {
it.resumeWithException(RuntimeException(message))
}
})
}
}
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,930 | androidx | Apache License 2.0 |
quickDoctor/app/src/main/java/com/example/quickdoctor/repository/HospitalRepository.kt | margi24 | 248,317,241 | false | {"Kotlin": 71499} | package com.example.quickdoctor.repository
import com.example.quickdoctor.data.Hospital
import com.example.quickdoctor.data.request.HospitalRequest
class HospitalRepository {
suspend fun getHospitals(): List<Hospital> {
var result = emptyList<Hospital>()
try {
result = HospitalRemote.service.findAll()
} catch (e: Exception) {
print(e.message)
} finally {
return result
}
}
suspend fun addHospital(name: String, country: String, city: String, street: String, idUser: String, speciality: String) {
val hospital = HospitalRequest(
name,
country,
city,
street,
idUser,
speciality
)
try {
HospitalRemote.service.add(hospital)
} catch (e: java.lang.Exception) {
print(e.message)
}
}
} | 0 | Kotlin | 0 | 0 | b0e6c48dfcef0ee1340028abe04382d9bc51784d | 912 | chat-appointment-notDONE | Apache License 2.0 |
libnavigation-core/src/main/java/com/mapbox/navigation/module/NavigationModuleProvider.kt | niilante | 239,169,427 | false | null | package com.mapbox.navigation.core.module
import com.mapbox.annotation.MODULE_CONFIGURATION_CLASS_NAME_FORMAT
import com.mapbox.annotation.MODULE_CONFIGURATION_PROVIDER_METHOD_FORMAT
import com.mapbox.annotation.MODULE_CONFIGURATION_PROVIDER_VARIABLE_NAME
import com.mapbox.annotation.MODULE_CONFIGURATION_SKIPPED_CLASS
import com.mapbox.annotation.MODULE_CONFIGURATION_SKIPPED_PACKAGE
import com.mapbox.annotation.MODULE_CONFIGURATION_SKIP_VARIABLE
import com.mapbox.annotation.MODULE_PROVIDER_PACKAGE_NAVIGATION
import com.mapbox.annotation.navigation.module.MapboxNavigationModuleType
internal object NavigationModuleProvider {
fun <T> createModule(
type: MapboxNavigationModuleType,
// finding a constructor requires exact params types, not subclass/implementations,
// that's why we need to pass the expected interface class as well
paramsProvider: (MapboxNavigationModuleType) -> Array<Pair<Class<*>?, Any?>>
): T {
try {
val configurationClass = Class.forName(
"$MODULE_PROVIDER_PACKAGE_NAVIGATION.${String.format(
MODULE_CONFIGURATION_CLASS_NAME_FORMAT,
type.name
)}"
)
val skipConfiguration =
configurationClass.getMethod(MODULE_CONFIGURATION_SKIP_VARIABLE.asGetter())
.invoke(null) as Boolean
val instance: Any
if (skipConfiguration) {
val implPackage =
configurationClass.getMethod(MODULE_CONFIGURATION_SKIPPED_PACKAGE.asGetter())
.invoke(null) as String
val implClassName =
configurationClass.getMethod(MODULE_CONFIGURATION_SKIPPED_CLASS.asGetter())
.invoke(null) as String
val implClass = Class.forName("$implPackage.$implClassName")
instance = try {
// try to invoke a no-arg, public constructor
val constructor = implClass.getConstructor()
constructor.newInstance()
} catch (ex: NoSuchMethodException) {
// try find default arguments for Mapbox default module
val params = paramsProvider.invoke(type)
try {
val constructor =
implClass.getConstructor(*params.map { it.first }.toTypedArray())
constructor.newInstance(*params.map { it.second }.toTypedArray())
} catch (ex: NoSuchMethodException) {
// try to create instance of Kotlin object
try {
implClass.getField("INSTANCE").get(null)
} catch (ex: NoSuchMethodException) {
// try to get instance of singleton
try {
implClass.getMethod("getInstance").invoke(null)
} catch (ex: NoSuchMethodException) {
throw MapboxInvalidModuleException(type)
}
}
}
}
} else {
val providerField =
configurationClass.getDeclaredField(MODULE_CONFIGURATION_PROVIDER_VARIABLE_NAME)
providerField.isAccessible = true
val provider = providerField.get(null)
if (provider != null) {
// get module instance from the provider
val providerClass = providerField.type
val providerMethod = providerClass.getDeclaredMethod(
String.format(
MODULE_CONFIGURATION_PROVIDER_METHOD_FORMAT,
type.name
)
)
instance = providerMethod.invoke(provider)
} else {
throw MapboxInvalidModuleException(type)
}
}
return instance as T
} catch (ex: Exception) {
throw if (ex is MapboxInvalidModuleException) {
ex
} else {
ex.printStackTrace()
MapboxInvalidModuleException(type)
}
}
}
private fun String.asGetter() = "get${this[0].toUpperCase()}${this.substring(1)}"
}
| 1 | null | 1 | 1 | f1e5d047665617c4ef32a3b4b5c9ab29d0ecaa93 | 4,509 | mapbox-navigation-android | Apache License 2.0 |
example/src/main/java/com/uploadcare/android/example/viewmodels/CdnViewModel.kt | uploadcare | 45,728,119 | false | {"Kotlin": 394871, "Java": 1370} | package com.uploadcare.android.example.viewmodels
import android.app.Application
import android.content.Context
import androidx.annotation.StringRes
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.uploadcare.android.example.R
import com.uploadcare.android.library.addon.AWSRekognitionAddOn
import com.uploadcare.android.library.addon.AWSRekognitionModerationAddOn
import com.uploadcare.android.library.addon.AddOnExecutor
import com.uploadcare.android.library.addon.ClamAVAddOn
import com.uploadcare.android.library.addon.RemoveBgAddOn
import com.uploadcare.android.library.api.UploadcareFile
import com.uploadcare.android.library.callbacks.ConversionFilesCallback
import com.uploadcare.android.library.callbacks.UploadcareFileCallback
import com.uploadcare.android.library.conversion.*
import com.uploadcare.android.library.exceptions.UploadcareApiException
import com.uploadcare.android.widget.controller.UploadcareWidget
class CdnViewModel(application: Application) : AndroidViewModel(application) {
val uploadcareFile = MutableLiveData<UploadcareFile>()
val loading = MutableLiveData<Boolean>().apply { value = false }
val status = MutableLiveData<String>()
private val client = UploadcareWidget.getInstance().uploadcareClient
private var converter: Converter? = null
private var executor: AddOnExecutor? = null
private val executorCallback = object : UploadcareFileCallback {
override fun onFailure(e: UploadcareApiException) {
showProgressOrResult(false, e.message)
}
override fun onSuccess(result: UploadcareFile) {
showProgressOrResult(false, getContext().getString(R.string.cdn_status_execute_sucess))
setFile(result)
}
}
fun setFile(uploadcareFile: UploadcareFile?) {
this.uploadcareFile.value = uploadcareFile
}
fun convertDocument() {
showProgressOrResult(true, getContext().getString(R.string.cdn_status_conversion_doc))
uploadcareFile.value?.let {
val conversionJob = DocumentConversionJob(it.uuid).apply {
setFormat(DocumentFormat.JPG)
}
converter = DocumentConverter(client, listOf(conversionJob))
converter?.convertAsync(object : ConversionFilesCallback {
override fun onFailure(e: UploadcareApiException) {
showProgressOrResult(false, e.message)
}
override fun onSuccess(result: List<UploadcareFile>) {
showProgressOrResult(false, getContext().getString(R.string.cdn_status_sucess))
setFile(result.getOrNull(0))
}
})
}
}
fun convertVideo() {
showProgressOrResult(true, getContext().getString(R.string.cdn_status_conversion_vid))
uploadcareFile.value?.let {
val conversionJob = VideoConversionJob(it.uuid).apply {
setFormat(VideoFormat.MP4)
quality(VideoQuality.NORMAL)
thumbnails(2)
}
converter = VideoConverter(client, listOf(conversionJob))
converter?.convertAsync(object : ConversionFilesCallback {
override fun onFailure(e: UploadcareApiException) {
showProgressOrResult(false, e.message)
}
override fun onSuccess(result: List<UploadcareFile>) {
showProgressOrResult(false, getContext().getString(R.string.cdn_status_sucess))
setFile(result.getOrNull(0))
}
})
}
}
fun cancel() {
converter?.cancel()
converter = null
executor?.cancel()
executor = null
showProgressOrResult(false, "Canceled")
}
fun executeAWSRekognitionAddOn() {
executeAddOn(R.string.cdn_status_execute_aws_rekognition, AWSRekognitionAddOn(client))
}
fun executeAWSRekognitionModerationAddOn() {
executeAddOn(
R.string.cdn_status_execute_aws_rekognition_moderation,
AWSRekognitionModerationAddOn(client)
)
}
fun executeClamAVAddOn() {
executeAddOn(R.string.cdn_status_execute_clam_av, ClamAVAddOn(client))
}
fun executeRemoveBgAddOn() {
executeAddOn(R.string.cdn_status_execute_remove_bg, RemoveBgAddOn(client))
}
private fun executeAddOn(@StringRes progressMessageResId: Int, addOnExecutor: AddOnExecutor) {
cancel()
showProgressOrResult(true, getContext().getString(progressMessageResId))
uploadcareFile.value?.let { file ->
executor = addOnExecutor.apply {
executeAsync(file.uuid, executorCallback)
}
}
}
/**
* Shows current status message.
*
* @param progress `true` if request is in progress.
* @param message message to show.
*/
private fun showProgressOrResult(progress: Boolean, message: String? = null) {
if (!progress) {
converter = null
}
loading.value = progress
status.value = message
}
private fun getContext(): Context {
return getApplication()
}
}
| 2 | Kotlin | 12 | 13 | 9409572d2b617cc622c11c19b7dff7f0f11ac5b2 | 5,258 | uploadcare-android | Apache License 2.0 |
domain/src/test/kotlin/no/nav/su/se/bakover/domain/brev/PdfInnholdTest.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.domain.brev
import no.nav.su.se.bakover.common.februar
import no.nav.su.se.bakover.common.januar
import no.nav.su.se.bakover.common.objectMapper
import no.nav.su.se.bakover.domain.Beløp
import no.nav.su.se.bakover.domain.Fnr
import no.nav.su.se.bakover.domain.MånedBeløp
import no.nav.su.se.bakover.domain.behandling.Satsgrunn
import no.nav.su.se.bakover.domain.behandling.avslag.Opphørsgrunn
import no.nav.su.se.bakover.domain.beregning.Sats
import no.nav.su.se.bakover.domain.brev.beregning.Beregningsperiode
import no.nav.su.se.bakover.domain.brev.beregning.BrevPeriode
import no.nav.su.se.bakover.domain.brev.beregning.Fradrag
import no.nav.su.se.bakover.domain.brev.beregning.Tilbakekreving
import no.nav.su.se.bakover.domain.brev.søknad.lukk.TrukketSøknadBrevInnhold
import no.nav.su.se.bakover.test.fixedClock
import no.nav.su.se.bakover.test.fnr
import no.nav.su.se.bakover.test.periodeJanuar2021
import no.nav.su.se.bakover.test.person
import no.nav.su.se.bakover.test.saksnummer
import org.junit.jupiter.api.Test
import org.skyscreamer.jsonassert.JSONAssert
import java.time.LocalDate
import kotlin.text.Typography.nbsp
internal class BrevInnholdTest {
private val personalia = BrevInnhold.Personalia(
dato = "01.01.2020",
fødselsnummer = Fnr("12345678901"),
fornavn = "Tore",
etternavn = "Strømøy",
saksnummer = 2021,
)
private val trukketSøknad = TrukketSøknadBrevInnhold(
personalia, 1.januar(2020), 1.februar(2020), "saksbehandler",
)
@Test
fun `jsonformat for personalia stemmer overens med det som forventes av pdfgenerator`() {
val actualJson = objectMapper.writeValueAsString(personalia)
//language=json
val expectedJson = """
{
"dato":"01.01.2020",
"fødselsnummer": "12345678901",
"fornavn": "Tore",
"etternavn": "Strømøy",
"saksnummer": 2021
}
""".trimIndent()
JSONAssert.assertEquals(expectedJson, actualJson, true)
}
@Test
fun `jsonformat for innvilget vedtak stemmer overens med det som forventes av pdfgenerator`() {
val innvilgetVedtak = BrevInnhold.InnvilgetVedtak(
personalia = personalia,
fradato = "01.01.2020",
tildato = "01.01.2020",
sats = Sats.HØY.toString(),
satsGrunn = Satsgrunn.DELER_BOLIG_MED_VOKSNE_BARN_ELLER_ANNEN_VOKSEN,
satsBeløp = 100,
forventetInntektStørreEnn0 = true,
harEktefelle = true,
beregningsperioder = listOf(
Beregningsperiode(
periode = BrevPeriode("januar 2021", "desember 2021"),
ytelsePerMåned = 100,
satsbeløpPerMåned = 100,
epsFribeløp = 100,
fradrag = Fradrag(emptyList(), Fradrag.Eps(emptyList(), false)),
),
),
saksbehandlerNavn = "Hei",
attestantNavn = "Hopp",
fritekst = "",
satsGjeldendeFraDato = "01.01.2020",
)
val actualJson = objectMapper.writeValueAsString(innvilgetVedtak)
//language=json
val expectedJson =
"""
{
"personalia": {
"dato": "01.01.2020",
"fødselsnummer": "12345678901",
"fornavn": "Tore",
"etternavn": "Strømøy",
"saksnummer": 2021
},
"fradato": "01.01.2020",
"tildato": "01.01.2020",
"sats": "HØY",
"satsGrunn": "DELER_BOLIG_MED_VOKSNE_BARN_ELLER_ANNEN_VOKSEN",
"satsBeløp": 100,
"satsGjeldendeFraDato": "01.01.2020",
"forventetInntektStørreEnn0": true,
"harEktefelle": true,
"harFradrag": false,
"beregningsperioder": [{
"periode": {
"fraOgMed": "januar 2021",
"tilOgMed": "desember 2021"
},
"ytelsePerMåned": 100,
"satsbeløpPerMåned": 100,
"epsFribeløp": 100.0,
"fradrag": {
"bruker" : [],
"eps": {
"fradrag": [],
"harFradragMedSumSomErLavereEnnFribeløp": false
}
}
}],
"saksbehandlerNavn": "Hei",
"attestantNavn": "Hopp",
"fritekst": "",
"harAvkorting": false
}
""".trimIndent()
JSONAssert.assertEquals(expectedJson, actualJson, true)
}
@Test
fun `jsonformat for trukket søknad stemmer overens med det som forventes av pdfgenerator`() {
val actualJson = objectMapper.writeValueAsString(trukketSøknad)
//language=json
val expectedJson = """
{
"personalia": {
"dato":"01.01.2020",
"fødselsnummer": "12345678901",
"fornavn": "Tore",
"etternavn": "Strømøy",
"saksnummer": 2021
},
"datoSøknadOpprettet": "01.01.2020",
"trukketDato": "01.02.2020",
"saksbehandlerNavn": "saksbehandler"
}
""".trimIndent()
JSONAssert.assertEquals(expectedJson, actualJson, true)
}
@Test
fun `jsonformat for opphørsvedtak stemmer overens med det som forventes av pdfgenerator`() {
val opphørsvedtak = BrevInnhold.Opphørsvedtak(
personalia = personalia,
sats = Sats.HØY.toString(),
satsBeløp = 100,
harEktefelle = true,
beregningsperioder = listOf(
Beregningsperiode(
periode = BrevPeriode("januar 2021", "desember 2021"),
ytelsePerMåned = 100,
satsbeløpPerMåned = 100,
epsFribeløp = 100,
fradrag = Fradrag(emptyList(), Fradrag.Eps(emptyList(), false)),
),
),
saksbehandlerNavn = "Hei",
attestantNavn = "Hopp",
fritekst = "",
opphørsgrunner = listOf(Opphørsgrunn.FOR_HØY_INNTEKT),
avslagsparagrafer = listOf(1),
satsGjeldendeFraDato = "01.01.2020",
forventetInntektStørreEnn0 = false,
halvGrunnbeløp = 50000,
opphørsdato = "01.01.2020",
avkortingsBeløp = null,
)
//language=JSON
val expectedJson = """
{
"personalia": {
"dato": "01.01.2020",
"fødselsnummer": "12345678901",
"fornavn": "Tore",
"etternavn": "Strømøy",
"saksnummer": 2021
},
"sats": "HØY",
"satsBeløp": 100,
"satsGjeldendeFraDato": "01.01.2020",
"harEktefelle": true,
"harFradrag": false,
"beregningsperioder": [{
"periode": {
"fraOgMed": "januar 2021",
"tilOgMed": "desember 2021"
},
"ytelsePerMåned": 100,
"satsbeløpPerMåned": 100,
"epsFribeløp": 100.0,
"fradrag": {
"bruker" : [],
"eps": {
"fradrag": [],
"harFradragMedSumSomErLavereEnnFribeløp": false
}
}
}],
"saksbehandlerNavn": "Hei",
"attestantNavn": "Hopp",
"fritekst": "",
"opphørsgrunner" : ["FOR_HØY_INNTEKT"],
"avslagsparagrafer" : [1],
"forventetInntektStørreEnn0" : false,
"halvGrunnbeløp": 50000,
"opphørsdato": "01.01.2020",
"avkortingsBeløp": null,
"harAvkorting": false
}
""".trimIndent()
JSONAssert.assertEquals(expectedJson, objectMapper.writeValueAsString(opphørsvedtak), true)
}
@Test
fun `brev for forhåndsvarsel ingen tilbakekreving`() {
val forhåndsvarsel = LagBrevRequest.Forhåndsvarsel(
person = person(),
saksbehandlerNavn = "saks",
fritekst = "fri",
dagensDato = LocalDate.now(fixedClock),
saksnummer = saksnummer,
)
val expected = """
{
"personalia": {
"dato": "01.01.2021",
"fødselsnummer": "$fnr",
"fornavn": "Tore",
"etternavn": "Strømøy",
"saksnummer": 12345676
},
"saksbehandlerNavn": "saks",
"fritekst": "fri",
}
""".trimIndent()
JSONAssert.assertEquals(expected, objectMapper.writeValueAsString(forhåndsvarsel.brevInnhold), true)
}
@Test
fun `brev for forhåndsvarsel med tilbakekreving`() {
val forhåndsvarsel = LagBrevRequest.ForhåndsvarselTilbakekreving(
person = person(),
saksbehandlerNavn = "saks",
fritekst = "fri",
dagensDato = LocalDate.now(fixedClock),
saksnummer = saksnummer,
bruttoTilbakekreving = 5000000,
tilbakekreving = Tilbakekreving(listOf(MånedBeløp(periodeJanuar2021, Beløp.invoke(1000))))
)
val expected = """
{
"personalia": {
"dato": "01.01.2021",
"fødselsnummer": "$fnr",
"fornavn": "Tore",
"etternavn": "Strømøy",
"saksnummer": 12345676
},
"saksbehandlerNavn": "saks",
"fritekst": "fri",
"bruttoTilbakekreving":"5${nbsp}000${nbsp}000",
"tilbakekreving": [{"periode": "1. januar 2021 - 31. januar 2021", "beløp":"1${nbsp}000", "tilbakekrevingsgrad": "100%"}],
"periodeStart": "1. januar 2021",
"periodeSlutt": "31. januar 2021",
"dato": "1. januar 2021",
}
""".trimIndent()
JSONAssert.assertEquals(expected, objectMapper.writeValueAsString(forhåndsvarsel.brevInnhold), true)
}
}
| 6 | Kotlin | 0 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 10,707 | su-se-bakover | MIT License |
http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/server/GenerateAccessTokenTest.kt | http4k | 86,003,479 | false | null | package org.http4k.security.oauth.server
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.*
import org.http4k.core.Status.Companion.BAD_REQUEST
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Status.Companion.UNAUTHORIZED
import org.http4k.core.body.form
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasStatus
import org.http4k.security.AccessTokenResponse
import org.http4k.security.ResponseType.CodeIdToken
import org.http4k.security.accessTokenResponseBody
import org.http4k.util.FixedClock
import org.junit.jupiter.api.Test
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.time.temporal.ChronoUnit.SECONDS
import java.time.temporal.TemporalUnit
class GenerateAccessTokenTest {
private val handlerClock = SettableClock()
private val codes = InMemoryAuthorizationCodes(FixedClock)
private val authRequest = AuthRequest(ClientId("a-clientId"), listOf(), Uri.of("redirect"), "state")
private val request = Request(Method.GET, "http://some-thing")
private val code = codes.create(request, authRequest, Response(OK))
private val handler = GenerateAccessToken(HardcodedClientValidator(authRequest.client, authRequest.redirectUri, "a-secret"), codes, DummyAccessTokens(), handlerClock, DummyIdtokens())
@Test
fun `generates a dummy token`() {
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(OK) and hasBody("dummy-access-token"))
assertThat(codes.available(code), equalTo(false))
}
@Test
fun `generates dummy access_token and id_token`() {
val codeForIdTokenRequest = codes.create(request, authRequest.copy(responseType = CodeIdToken), Response(OK))
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", codeForIdTokenRequest.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(OK))
assertThat(accessTokenResponseBody(response), equalTo(AccessTokenResponse("dummy-access-token", "dummy-id-token-for-access-token")))
}
@Test
fun `handles invalid grant_type`() {
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "something_else")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody("Invalid grant type"))
}
@Test
fun `handles invalid client credentials`() {
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", code.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "wrong-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(UNAUTHORIZED) and hasBody("Invalid client credentials"))
}
@Test
fun `handles expired code`() {
handlerClock.advance(1, SECONDS)
val expiredCode = codes.create(request, authRequest, Response(OK))
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", expiredCode.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody("Authorization code has expired"))
}
@Test
fun `handles client id different from one in authorization code`(){
val storedCode = codes.create(request, authRequest.copy(client = ClientId("different client")), Response(OK))
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", storedCode.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody("Invalid client_id"))
}
@Test
fun `handles redirectUri different from one in authorization code`(){
val storedCode = codes.create(request, authRequest.copy(redirectUri = Uri.of("somethingelse")), Response(OK))
val response = handler(Request(Method.POST, "/token")
.header("content-type", ContentType.APPLICATION_FORM_URLENCODED.value)
.form("grant_type", "authorization_code")
.form("code", storedCode.value)
.form("client_id", authRequest.client.value)
.form("client_secret", "a-secret")
.form("redirect_uri", authRequest.redirectUri.toString())
)
assertThat(response, hasStatus(BAD_REQUEST) and hasBody("Invalid redirect_uri"))
}
}
class SettableClock : Clock() {
private var currentTime = Instant.EPOCH
fun advance(amount: Long, unit: TemporalUnit) {
currentTime = currentTime.plus(amount, unit)
}
override fun withZone(zone: ZoneId?): Clock = this
override fun getZone(): ZoneId = ZoneId.systemDefault()
override fun instant(): Instant = currentTime
} | 34 | null | 249 | 2,615 | 7ad276aa9c48552a115a59178839477f34d486b1 | 6,478 | http4k | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/LinkAlt.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.LinkAlt: ImageVector
get() {
if (_linkAlt != null) {
return _linkAlt!!
}
_linkAlt = Builder(name = "LinkAlt", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.834f, 16.169f)
curveToRelative(-0.557f, -0.557f, -0.975f, -1.207f, -1.281f, -1.901f)
lineToRelative(1.57f, -1.57f)
curveToRelative(0.175f, 0.761f, 0.548f, 1.48f, 1.125f, 2.057f)
curveToRelative(0.803f, 0.803f, 1.87f, 1.245f, 3.005f, 1.245f)
reflectiveCurveToRelative(2.203f, -0.442f, 3.005f, -1.245f)
lineToRelative(5.5f, -5.5f)
curveToRelative(0.803f, -0.803f, 1.245f, -1.87f, 1.245f, -3.005f)
reflectiveCurveToRelative(-0.442f, -2.203f, -1.245f, -3.005f)
curveToRelative(-1.655f, -1.655f, -4.346f, -1.657f, -6.004f, -0.007f)
lineToRelative(-1.012f, 1.012f)
curveToRelative(-0.644f, -0.159f, -1.309f, -0.25f, -1.99f, -0.25f)
curveToRelative(-0.208f, 0.0f, -0.413f, 0.015f, -0.618f, 0.03f)
lineToRelative(2.199f, -2.199f)
horizontalLineToRelative(0.0f)
curveToRelative(2.437f, -2.438f, 6.402f, -2.438f, 8.839f, 0.0f)
curveToRelative(2.437f, 2.437f, 2.437f, 6.402f, 0.0f, 8.839f)
lineToRelative(-5.5f, 5.5f)
curveToRelative(-1.18f, 1.181f, -2.75f, 1.831f, -4.419f, 1.831f)
reflectiveCurveToRelative(-3.239f, -0.65f, -4.419f, -1.831f)
close()
moveTo(0.003f, 17.75f)
curveToRelative(0.0f, 1.669f, 0.65f, 3.239f, 1.831f, 4.419f)
curveToRelative(1.18f, 1.181f, 2.749f, 1.831f, 4.419f, 1.831f)
reflectiveCurveToRelative(3.239f, -0.65f, 4.419f, -1.831f)
lineToRelative(2.2f, -2.2f)
curveToRelative(-0.205f, 0.015f, -0.411f, 0.03f, -0.618f, 0.03f)
curveToRelative(-0.681f, 0.0f, -1.346f, -0.091f, -1.99f, -0.25f)
lineToRelative(-1.006f, 1.006f)
curveToRelative(-0.803f, 0.803f, -1.87f, 1.245f, -3.005f, 1.245f)
reflectiveCurveToRelative(-2.202f, -0.442f, -3.005f, -1.245f)
reflectiveCurveToRelative(-1.245f, -1.87f, -1.245f, -3.005f)
reflectiveCurveToRelative(0.442f, -2.203f, 1.245f, -3.005f)
lineToRelative(5.5f, -5.5f)
curveToRelative(0.803f, -0.803f, 1.87f, -1.245f, 3.005f, -1.245f)
reflectiveCurveToRelative(2.197f, 0.44f, 2.999f, 1.238f)
lineToRelative(0.006f, 0.007f)
curveToRelative(0.577f, 0.577f, 0.95f, 1.296f, 1.125f, 2.057f)
lineToRelative(1.57f, -1.57f)
curveToRelative(-0.306f, -0.694f, -0.724f, -1.344f, -1.281f, -1.901f)
horizontalLineToRelative(0.0f)
curveToRelative(-1.18f, -1.181f, -2.75f, -1.831f, -4.419f, -1.831f)
reflectiveCurveToRelative(-3.239f, 0.65f, -4.419f, 1.831f)
lineTo(1.834f, 13.331f)
curveTo(0.653f, 14.511f, 0.003f, 16.081f, 0.003f, 17.75f)
close()
}
}
.build()
return _linkAlt!!
}
private var _linkAlt: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,229 | icons | MIT License |
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/database/WorkoutObject.kt | sonnytron | 98,830,747 | false | null | package com.sonnyrodriguez.fittrainer.fittrainerbasic.database
import android.arch.persistence.room.*
import android.os.Parcel
import android.os.Parcelable
import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.LocalExerciseObject
@Entity(tableName = "workouts")
data class WorkoutObject(@ColumnInfo(name = "workout_title") var title: String,
@ColumnInfo(name = "exercise_meta_list") var exerciseMetaList: List<LocalExerciseObject>) : Parcelable {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true) var id: Long = 0
constructor(source: Parcel) : this(
source.readString(),
source.createTypedArrayList(LocalExerciseObject.CREATOR)
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(title)
writeTypedList(exerciseMetaList)
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<WorkoutObject> = object : Parcelable.Creator<WorkoutObject> {
override fun createFromParcel(source: Parcel): WorkoutObject = WorkoutObject(source)
override fun newArray(size: Int): Array<WorkoutObject?> = arrayOfNulls(size)
}
}
}
| 0 | Kotlin | 0 | 1 | def9c5e05a1c03efd3f815c4145b446f6a170692 | 1,240 | FitTrainerBasic | Apache License 2.0 |
app/src/main/java/com/cornellappdev/coffee_chats_android/models/Interest.kt | cuappdev | 237,100,389 | false | null | package com.cornellappdev.coffee_chats_android.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Interest(
val id: Int,
val name: String,
val subtitle: String,
@Json(name = "img_url")
val imageUrl: String = ""
)
| 2 | Kotlin | 0 | 1 | f6376012b1f03530f89fed11c83bce1bbd12bbfc | 304 | pear-android | MIT License |
client/android/div-storage/src/test/java/com/yandex/div/storage/StubCursor.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.storage
import android.content.ContentResolver
import android.database.CharArrayBuffer
import android.database.ContentObserver
import android.database.Cursor
import android.database.DataSetObserver
import android.net.Uri
import android.os.Bundle
abstract class StubCursor: Cursor {
override fun close() {}
override fun getCount(): Int = 1
override fun isClosed(): Boolean = false
override fun move(offset: Int): Boolean = true
override fun moveToFirst(): Boolean = true
override fun getPosition(): Int = throw NotImplementedError()
override fun moveToPosition(position: Int): Boolean = throw NotImplementedError()
override fun moveToLast(): Boolean = throw NotImplementedError()
override fun moveToPrevious(): Boolean = throw NotImplementedError()
override fun isFirst(): Boolean = throw NotImplementedError()
override fun isLast(): Boolean = throw NotImplementedError()
override fun isBeforeFirst(): Boolean = throw NotImplementedError()
override fun isAfterLast(): Boolean = throw NotImplementedError()
override fun getColumnIndexOrThrow(columnName: String?): Int = throw NotImplementedError()
override fun getColumnName(columnIndex: Int): String = throw NotImplementedError()
override fun getColumnNames(): Array<String> = throw NotImplementedError()
override fun getColumnCount(): Int = throw NotImplementedError()
override fun copyStringToBuffer(columnIndex: Int, buffer: CharArrayBuffer?) =
throw NotImplementedError()
override fun getShort(columnIndex: Int): Short = throw NotImplementedError()
override fun getInt(columnIndex: Int): Int = throw NotImplementedError()
override fun getLong(columnIndex: Int): Long = throw NotImplementedError()
override fun getFloat(columnIndex: Int): Float = throw NotImplementedError()
override fun getDouble(columnIndex: Int): Double = throw NotImplementedError()
override fun getType(columnIndex: Int): Int = throw NotImplementedError()
override fun deactivate() = throw NotImplementedError()
override fun requery(): Boolean = throw NotImplementedError()
override fun registerContentObserver(observer: ContentObserver?) = throw NotImplementedError()
override fun unregisterContentObserver(observer: ContentObserver?) = throw NotImplementedError()
override fun registerDataSetObserver(observer: DataSetObserver?) = throw NotImplementedError()
override fun unregisterDataSetObserver(observer: DataSetObserver?) = throw NotImplementedError()
override fun setNotificationUri(cr: ContentResolver?, uri: Uri?) = throw NotImplementedError()
override fun getNotificationUri(): Uri = throw NotImplementedError()
override fun getWantsAllOnMoveCalls(): Boolean = throw NotImplementedError()
override fun setExtras(extras: Bundle?) = throw NotImplementedError()
override fun getExtras(): Bundle = throw NotImplementedError()
override fun respond(extras: Bundle?): Bundle = throw NotImplementedError()
}
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 3,020 | divkit | Apache License 2.0 |
rssparser/src/main/java/com/prof/rssparser/caching/CachedFeed.kt | prof18 | 61,429,036 | false | null | package com.prof.rssparser.caching
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = CacheConstants.CACHED_FEEDS_TABLE_NAME)
internal class CachedFeed(
@PrimaryKey
@ColumnInfo(name = "url_hash")
var urlHash: Int,
@ColumnInfo(name = "byte_data", typeAffinity = ColumnInfo.BLOB)
var byteArray: ByteArray,
@ColumnInfo(name = "cached_date")
var cachedDate: Long,
@ColumnInfo(name = "library_version")
var libraryVersion: Int
)
| 5 | null | 118 | 403 | 686eb4194dd5496bedca002a8194378b84e6115b | 559 | RSS-Parser | Apache License 2.0 |
src/main/java/io/fobo66/crypto/Lab3.kt | fobo66 | 152,875,715 | false | null | package io.fobo66.crypto
import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.Options
import org.apache.commons.cli.ParseException
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import javax.xml.bind.DatatypeConverter
fun main(args: Array<String>) {
var message = "Hello World!"
val options = Options()
options.addOption("f", "file", true, "Input file")
options.addOption("a", "algorithm", true, "Hashing algorithm, either MD5 or SHA1. Defaults to MD5")
val parser = DefaultParser()
try {
val cmd = parser.parse(options, args)
if (cmd.hasOption('f')) {
val filePath = cmd.getOptionValue("file")
System.out.format("Reading cleartext from file %s...%n", filePath)
message = loadClearTextFromFile(filePath)
}
val hash = resolveHashFunction(cmd)
printResults(message, hash.compute(message.toByteArray()))
} catch (e: ParseException) {
}
}
fun resolveHashFunction(cmd: CommandLine): Hash {
if (cmd.hasOption('a')) {
return when (cmd.getOptionValue('a').toUpperCase()) {
"MD5" -> MD5()
"SHA1", "SHA-1" -> SHA1()
else -> throw IllegalArgumentException("Wrong algorithm. Must be either SHA1 or MD5")
}
}
return MD5()
}
fun printResults(clearText: String, encryptedText: ByteArray) {
println("Message: \"$clearText\"")
println("Hashed message: " + DatatypeConverter.printHexBinary(encryptedText))
}
@Throws(IOException::class)
private fun loadClearTextFromFile(filePath: String): String {
return String(Files.readAllBytes(Paths.get(filePath)))
} | 1 | Kotlin | 0 | 0 | 745ad29a7afcb36399b988ce12d4fa9c4b5bc8e0 | 1,730 | BSUIRCryptoLab3 | The Unlicense |
src/main/kotlin/com/skeleton/common/utils/FileUtils.kt | freelife1191 | 398,951,098 | false | null | package com.skeleton.common.utils
import java.io.File
/**
* 파일처리 유틸
* Created by KMS on 2021/08/03.
*/
class FileUtils {
companion object {
/**
* delete
* @param files
*/
fun deleteFile(vararg files: File) {
for (file in files) {
if (file.exists()) {
file.delete()
}
}
}
}
} | 0 | Kotlin | 2 | 1 | 3beee9aed1414a764965490153b6ae0320208eb6 | 415 | kotlin-springboot-skeleton-apis | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/SignalCellularOff.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/SignalCellularOff")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val SignalCellularOff: SvgIconComponent
| 10 | null | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 216 | kotlin-wrappers | Apache License 2.0 |
redwood-protocol-guest/src/commonMain/kotlin/app/cash/redwood/protocol/guest/ProtocolRedwoodComposition.kt | cashapp | 305,409,146 | false | null | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.redwood.protocol.guest
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.MonotonicFrameClock
import androidx.compose.runtime.saveable.SaveableStateRegistry
import app.cash.redwood.compose.LocalWidgetVersion
import app.cash.redwood.compose.RedwoodComposition
import app.cash.redwood.protocol.ChangesSink
import app.cash.redwood.ui.OnBackPressedDispatcher
import app.cash.redwood.ui.UiConfiguration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow
/**
* @param scope A [CoroutineScope] whose [coroutineContext][kotlin.coroutines.CoroutineContext]
* must have a [MonotonicFrameClock] key which is being ticked.
*/
public fun ProtocolRedwoodComposition(
scope: CoroutineScope,
bridge: ProtocolBridge,
changesSink: ChangesSink,
widgetVersion: UInt,
onBackPressedDispatcher: OnBackPressedDispatcher,
saveableStateRegistry: SaveableStateRegistry?,
uiConfigurations: StateFlow<UiConfiguration>,
): RedwoodComposition {
val composition = RedwoodComposition(
scope = scope,
container = bridge.root,
onBackPressedDispatcher = onBackPressedDispatcher,
saveableStateRegistry = saveableStateRegistry,
uiConfigurations = uiConfigurations,
provider = bridge.provider,
) {
bridge.getChangesOrNull()?.let(changesSink::sendChanges)
}
return ProtocolRedwoodComposition(composition, widgetVersion)
}
private class ProtocolRedwoodComposition(
private val composition: RedwoodComposition,
private val widgetVersion: UInt,
) : RedwoodComposition by composition {
override fun setContent(content: @Composable () -> Unit) {
composition.setContent {
CompositionLocalProvider(LocalWidgetVersion provides widgetVersion) {
content()
}
}
}
}
| 98 | null | 73 | 1,648 | 3f14e622c2900ec7e0dfaff5bd850c95a7f29937 | 2,436 | redwood | Apache License 2.0 |
fontawesome/src/de/msrd0/fontawesome/icons/FA_FLAG_CHECKERED.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** flag-checkered */
object FA_FLAG_CHECKERED: Icon {
override val name get() = "flag-checkered"
override val unicode get() = "f11e"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M509.5 .0234c-6.145 0-12.53 1.344-18.64 4.227c-44.11 20.86-76.81 27.94-104.1 27.94c-57.89 0-91.53-31.86-158.2-31.87C195 .3203 153.3 8.324 96 32.38V32c0-17.75-14.25-32-32-32S32 14.25 32 32L31.96 496c0 8.75 7.25 16 16 16H80C88.75 512 96 504.8 96 496V384c51.74-23.86 92.71-31.82 128.3-31.82c71.09 0 120.6 31.78 191.7 31.78c30.81 0 65.67-5.969 108.1-23.09C536.3 355.9 544 344.4 544 332.1V30.74C544 12.01 527.8 .0234 509.5 .0234zM480 141.8c-31.99 14.04-57.81 20.59-80 22.49v80.21c25.44-1.477 51.59-6.953 80-17.34V308.9c-22.83 7.441-43.93 11.08-64.03 11.08c-5.447 0-10.71-.4258-15.97-.8906V244.5c-4.436 .2578-8.893 .6523-13.29 .6523c-25.82 0-47.35-4.547-66.71-10.08v66.91c-23.81-6.055-50.17-11.41-80-12.98V213.1C236.2 213.7 232.5 213.3 228.5 213.3C208.8 213.3 185.1 217.7 160 225.1v69.1C139.2 299.4 117.9 305.8 96 314.4V250.7l24.77-10.39C134.8 234.5 147.6 229.9 160 225.1V143.4C140.9 148.5 120.1 155.2 96 165.3V101.8l24.77-10.39C134.8 85.52 147.6 80.97 160 77.02v66.41c26.39-6.953 49.09-10.17 68.48-10.16c4.072 0 7.676 .4453 11.52 .668V65.03C258.6 66.6 274.4 71.55 293.2 77.83C301.7 80.63 310.7 83.45 320 86.12v66.07c20.79 6.84 41.45 12.96 66.71 12.96c4.207 0 8.781-.4766 13.29-.8594V95.54c25.44-1.477 51.59-6.953 80-17.34V141.8zM240 133.9v80.04c18.61 1.57 34.37 6.523 53.23 12.8C301.7 229.6 310.7 232.4 320 235.1V152.2C296.1 144.3 271.6 135.8 240 133.9z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | 1358935395f9254cab27852457e2aa6c58902e16 | 2,581 | fontawesome-kt | Apache License 2.0 |
compiler/testData/loadJava/compiledKotlin/annotations/classes/EnumArgument.kt | JakeWharton | 99,388,807 | true | null | // TARGET_BACKEND: JVM
// ALLOW_AST_ACCESS
package test
import java.lang.annotation.ElementType
annotation class Anno(val t: ElementType)
@Anno(ElementType.METHOD) class Class {
@Anno(ElementType.PARAMETER) inner class Inner
@Anno(ElementType.TYPE) class Nested
@Anno(ElementType.ANNOTATION_TYPE) companion object
}
| 181 | Kotlin | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 337 | kotlin | Apache License 2.0 |
app/src/main/java/com/copper/debt/presentation/implementation/AddDebtPresenterImpl.kt | glebxhleb | 281,331,933 | false | null | package com.copper.debt.presentation.implementation
import com.copper.debt.App
import com.copper.debt.R
import com.copper.debt.common.*
import com.copper.debt.firebase.authentication.FirebaseAuthenticationInterface
import com.copper.debt.firebase.database.FirebaseDatabaseInterface
import com.copper.debt.model.*
import com.copper.debt.presentation.AddDebtPresenter
import com.copper.debt.ui.addDebt.AddDebtView
import kotlinx.coroutines.*
import java.util.*
import javax.inject.Inject
class AddDebtPresenterImpl @Inject constructor(
private val authenticationInterface: FirebaseAuthenticationInterface,
private val databaseInterface: FirebaseDatabaseInterface
) : AddDebtPresenter {
private lateinit var view: AddDebtView
private lateinit var currentUser: User
private var userGroups = listOf<Group>()
private var groupUsers = mapOf<String, User>()
private var debtors = mutableListOf<Debtor>()
private var groupId = NO_GROUP_ID
private var debtText = ""
private var creditorId = NO_USER_ID
private var debtDate = Calendar.getInstance().timeInMillis
private var currency = Currency.getInstance(Locale("ru", "RU"))
private var fixedSum = 0.0
private var debtId = UUID.randomUUID().toString()
private var status = Status.ADDED
private var oldDebt: Debt? = null
private val presenterJob = Job()
private val coroutineScope = CoroutineScope(Dispatchers.Main + presenterJob)
override fun fetchData(debt: Debt?) = runBlocking {
oldDebt = debt
if (debt != null) {
groupId = debt.groupId
debtText = debt.text
creditorId = debt.creditorId
debtDate = debt.debtDate
currency = debt.currency
fixedSum = debt.debtorsIds.map { entry -> entry.value }.sum()
debtId = debt.id
status = Status.CHANGED
view.setTitle(App.instance.getString(R.string.edit_debt))
} else {
view.setTitle(App.instance.getString(R.string.new_debt))
}
coroutineScope.launch {
currentUser =
databaseInterface.getProfile(authenticationInterface.getUserId()) ?: return@launch
val groups = withContext(Dispatchers.IO) { fetchGroups() }
val users = withContext(Dispatchers.IO) { fetchGroupUsers(groups) }
fillFields(groups, users, debt?.debtorsIds)
view.showContent()
}
}
private fun fillFields(
groups: List<Group>,
users: Map<String, User>,
debtorsIds: Map<String, Double>?
) {
userGroups = groups
groupUsers = users
view.showDescription(debtText)
view.showSum(fixedSum)
view.showDate(debtDate.getDate())
view.showGroupOptions(userGroups, groupId) { group ->
onGroupSelected(group)
}
view.showCreditorOptions(groupUsers.values.toList(), creditorId) { creditor ->
onCreditorChanged(creditor)
}
view.showCurrencyOptions(
listOf("RUB", "EUR", "USD"),
currency.currencyCode
) { currency -> onCurrencyChanged(currency) }
debtorsIds?.forEach { (userId: String, sum: Double) ->
groupUsers[userId]?.let {
val debtor = Debtor(it)
debtor.sum = sum
view.addDebtor(debtor)
debtors.add(debtor)
}
}
}
private fun onGroupSelected(group: Group) = runBlocking {
coroutineScope.launch {
val users = mutableMapOf<String, User>()
users[currentUser.id] = currentUser
withContext(Dispatchers.IO) {
databaseInterface.getProfiles(group.users).forEach {
users[it.id] = it
}
}
groupId = group.id
groupUsers = users
view.showCreditorOptions(groupUsers.values.toList(), creditorId) { creditor ->
onCreditorChanged(creditor)
}
}
}
private suspend fun fetchGroups(): List<Group> {
val mutGroups = mutableListOf<Group>()
mutGroups.add(Group(App.instance.getString(NO_GROUP), currentUser.contactsIds, NO_GROUP_ID))
mutGroups.addAll(databaseInterface.getUserGroups(currentUser.id))
return mutGroups
}
private suspend fun fetchGroupUsers(groups: List<Group>): Map<String, User> {
val users = mutableMapOf<String, User>()
users[currentUser.id] = currentUser
val currentGroup = groups.findLast { it.id == groupId } ?: Group(
App.instance.getString(NO_GROUP),
currentUser.contactsIds,
NO_GROUP_ID
)
databaseInterface.getProfiles(currentGroup.users).forEach {
users[it.id] = it
}
return users
}
override fun saveDebtTapped() {
if (isValidDebt(debtText,fixedSum, debtors.map { it.sum })) {
view.removeDebtError()
val creditorName = groupUsers[creditorId]?.username ?: ""
val debtorsIds = debtors.map { it.user.id to it.sum }.toMap()
val debt = Debt(
groupId,
creditorId,
creditorName,
debtText,
debtorsIds,
debtDate,
authenticationInterface.getUserId(),
Calendar.getInstance().timeInMillis,
status,
currency,
debtId
)
databaseInterface.addNewDebt(debt) { onAddDebtResult(it) }
} else {
view.showDebtError()
}
}
override fun onDebtTextChanged(debtText: String) {
this.debtText = debtText
}
override fun dateChangeTapped() {
val calendar = Calendar.getInstance()
calendar.timeInMillis = debtDate
val year = calendar[Calendar.YEAR]
val month = calendar[Calendar.MONTH]
val day = calendar[Calendar.DAY_OF_MONTH]
view.showDatePickerDialog(year, month, day) { y, m, d -> onDateSet(y, m, d) }
}
override fun onSumChanged(sum: Double) {
fixedSum = sum
}
override fun equalCalcTapped() {
if (fixedSum > 0 && debtors.isNotEmpty()) {
val num = fixedSum / debtors.size
debtors.forEach {
view.removeDebtor(it)
it.sum = num
view.addDebtor(it)
}
}
}
override fun sumCalcTapped() {
fixedSum = debtors.map { it.sum }.sum()
view.showSum(fixedSum)
}
override fun addDebtorsTapped() {
val involvedUsers: List<User> = debtors.map { it.user }
val availableUsers: List<User> = groupUsers.values.toList()
view.showAddDebtorsDialog(availableUsers, involvedUsers)
}
override fun onDebtorChecked(debtor: User, isChecked: Boolean) {
if (isChecked) {
val newDebtor = Debtor(debtor)
debtors.add(newDebtor)
view.addDebtor(newDebtor)
} else {
debtors.removeAll { it.user == debtor }
view.removeDebtor(Debtor(debtor))
}
}
override fun onBackPressed(ifChanged: (Boolean) -> Unit) {
val creditorName = groupUsers[creditorId]?.username ?: ""
val debtorsIds = debtors.map { it.user.id to it.sum }.toMap()
val debt = Debt(
groupId,
creditorId,
creditorName,
debtText,
debtorsIds,
debtDate,
oldDebt?.lastChangerId?:"",
oldDebt?.lastChangeDate?:0L,
oldDebt?.status?:status,
currency,
debtId
)
ifChanged(debt != oldDebt)
}
override fun setView(view: AddDebtView) {
this.view = view
}
private fun onCreditorChanged(creditor: User) {
creditorId = creditor.id
}
private fun onCurrencyChanged(currencyCode: String) {
this.currency = Currency.getInstance(currencyCode)
}
private fun onDateSet(year: Int, month: Int, day: Int) {
val calendar = Calendar.getInstance()
calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, month)
calendar.set(Calendar.DAY_OF_MONTH, day)
debtDate = calendar.timeInMillis
view.showDate(debtDate.getDate())
}
private fun onAddDebtResult(isSuccessful: Boolean) {
if (isSuccessful) {
view.onDebtAdded()
presenterJob.cancel()
} else {
view.showAddDebtError()
}
}
} | 0 | Kotlin | 0 | 0 | 3681f3b71d87c92234aec1da8a9a3493d6490ea9 | 8,632 | Debt | Apache License 2.0 |
jetbrains-core/tst/software/aws/toolkits/jetbrains/services/codewhisperer/CodeWhispererRecommendationManagerTest.kt | aws | 91,485,909 | false | {"Kotlin": 5578345, "C#": 96334, "Java": 20992, "Shell": 2920, "Dockerfile": 2209, "Batchfile": 77} | // Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.codewhisperer
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.project.Project
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import com.intellij.testFramework.runInEdtAndGet
import com.intellij.testFramework.runInEdtAndWait
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import software.amazon.awssdk.services.codewhisperer.model.Reference
import software.aws.toolkits.jetbrains.services.codewhisperer.service.CodeWhispererRecommendationManager
import software.aws.toolkits.jetbrains.utils.rules.PythonCodeInsightTestFixtureRule
class CodeWhispererRecommendationManagerTest {
@Rule
@JvmField
var projectRule = PythonCodeInsightTestFixtureRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
private val documentContentContent = "012345678"
private lateinit var fixture: CodeInsightTestFixture
private lateinit var project: Project
private val originalReference = Reference.builder()
.licenseName("test_license")
.repository("test_repo")
.build()
@Before
fun setup() {
fixture = projectRule.fixture
project = projectRule.project
fixture.configureByText("test.py", documentContentContent)
runInEdtAndWait {
fixture.editor.caretModel.moveToOffset(documentContentContent.length)
}
}
@Test
fun `test reformatReference() should generate a new reference with span based on rangeMarker and no surfix newline char`() {
// invocationOffset and markerStartOffset is of our choice as long as invocationOffset <= markerStartOffset
val recommendationManager = CodeWhispererRecommendationManager()
testReformatReferenceUtil(recommendationManager, documentContentSurfix = "", invocationOffset = 2, markerStartOffset = 5)
testReformatReferenceUtil(recommendationManager, documentContentSurfix = "\n", invocationOffset = 2, markerStartOffset = 5)
testReformatReferenceUtil(recommendationManager, documentContentSurfix = "\n\n", invocationOffset = 1, markerStartOffset = 4)
}
private fun testReformatReferenceUtil(
recommendationManager: CodeWhispererRecommendationManager,
documentContentSurfix: String,
invocationOffset: Int,
markerStartOffset: Int
) {
// insert newline characters
WriteCommandAction.runWriteCommandAction(project) {
fixture.editor.document.insertString(fixture.editor.caretModel.offset, documentContentSurfix)
}
val rangeMarker =
runInEdtAndGet { fixture.editor.document.createRangeMarker(markerStartOffset, documentContentContent.length + documentContentSurfix.length) }
val reformattedReference = runInEdtAndGet { recommendationManager.reformatReference(originalReference, rangeMarker, invocationOffset) }
assertThat(reformattedReference.licenseName()).isEqualTo("test_license")
assertThat(reformattedReference.repository()).isEqualTo("test_repo")
assertThat(reformattedReference.recommendationContentSpan().start()).isEqualTo(rangeMarker.startOffset - invocationOffset)
assertThat(reformattedReference.recommendationContentSpan().end()).isEqualTo(rangeMarker.endOffset - invocationOffset - documentContentSurfix.length)
val span = runInEdtAndGet {
fixture.editor.document.charsSequence.subSequence(
reformattedReference.recommendationContentSpan().start(),
reformattedReference.recommendationContentSpan().end()
)
}
// span should not include newline char
assertThat(span.last()).isNotEqualTo('\n')
}
}
| 389 | Kotlin | 168 | 705 | 1f5e7365cd13ece32e682ecd46a058dd587edd11 | 3,971 | aws-toolkit-jetbrains | Apache License 2.0 |
app/src/main/java/com/domatix/yevbes/nucleus/sga/view/ui/DashboardInventoryFragment.kt | sm2x | 234,568,179 | true | {"Kotlin": 782306} | package com.domatix.yevbes.nucleus.sga.view.ui
import android.content.res.Configuration
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.SearchView
import android.view.*
import com.domatix.yevbes.nucleus.*
import com.domatix.yevbes.nucleus.core.Odoo
import com.domatix.yevbes.nucleus.databinding.FragmentDashboardInventoryBinding
import com.domatix.yevbes.nucleus.sga.service.model.StockPickingType
import com.domatix.yevbes.nucleus.sga.view.adapter.DashboardAdapter
import com.domatix.yevbes.nucleus.sga.view.callbacks.OnItemClickListener
import com.google.gson.reflect.TypeToken
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.fragment_dashboard_inventory.*
class DashboardInventoryFragment : Fragment(), SearchView.OnQueryTextListener {
lateinit var binding: FragmentDashboardInventoryBinding private set
lateinit var activity: MainActivity private set
lateinit var compositeDisposable: CompositeDisposable private set
private lateinit var drawerToggle: ActionBarDrawerToggle
private val dashboardItemListType = object : TypeToken<ArrayList<StockPickingType>>() {}.type
private lateinit var stockPickingType: StockPickingType
private val mAdapter: DashboardAdapter by lazy {
DashboardAdapter(this, arrayListOf(), object : OnItemClickListener {
override fun onItemClick(item: Any) {
stockPickingType = item as StockPickingType
val query = "${jsonElementToString(stockPickingType.warehouseId)}: ${stockPickingType.name}"
val transfersFragment = TransfersFragment.newInstance(stockPickingType.id, query)
activity.replaceFragment(transfersFragment, MainActivity.ACTION_TRANSFERS_INVENTORY)
}
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
compositeDisposable = CompositeDisposable()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = FragmentDashboardInventoryBinding.inflate(inflater, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity = getActivity() as MainActivity
activity.binding.abl.visibility = View.GONE
activity.binding.nsv.visibility = View.GONE
activity.setTitle(R.string.action_dashboard_inventory)
activity.setSupportActionBar(binding.tb)
val actionBar = activity.supportActionBar
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true)
actionBar.setDisplayHomeAsUpEnabled(true)
}
drawerToggle = ActionBarDrawerToggle(activity, activity.binding.dl,
binding.tb, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
activity.binding.dl.addDrawerListener(drawerToggle)
drawerToggle.syncState()
val mLayoutManager = LinearLayoutManager(context)
binding.rv.layoutManager = mLayoutManager
binding.rv.itemAnimator = DefaultItemAnimator()
rv.addItemDecoration(DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL))
mAdapter.setupScrollListener(binding.rv)
if (!mAdapter.hasRetryListener()) {
mAdapter.retryListener {
fetchDashboardInventory()
}
}
binding.srl.setOnRefreshListener {
mAdapter.clear()
if (!mAdapter.hasMoreListener()) {
mAdapter.showMore()
fetchDashboardInventory()
}
binding.srl.post {
binding.srl.isRefreshing = false
}
}
if (mAdapter.rowItemCount == 0) {
mAdapter.showMore()
fetchDashboardInventory()
}
binding.rv.adapter = mAdapter
}
private fun fetchDashboardInventory() {
Odoo.searchRead("stock.picking.type", StockPickingType.fields,
listOf(), mAdapter.rowItemCount, RECORD_LIMIT) {
onSubscribe { disposable ->
compositeDisposable.add(disposable)
}
onNext { response ->
if (response.isSuccessful) {
val searchRead = response.body()!!
if (searchRead.isSuccessful) {
mAdapter.hideEmpty()
mAdapter.hideError()
mAdapter.hideMore()
val items: ArrayList<StockPickingType> = gson.fromJson(searchRead.result.records, dashboardItemListType)
if (items.size < RECORD_LIMIT) {
mAdapter.removeMoreListener()
if (items.size == 0 && mAdapter.rowItemCount == 0) {
mAdapter.showEmpty()
}
} else {
if (!mAdapter.hasMoreListener()) {
mAdapter.moreListener {
fetchDashboardInventory()
}
}
}
mAdapter.addRowItems(items)
} else {
mAdapter.showError(searchRead.errorMessage)
}
} else {
mAdapter.showError(response.errorBodySpanned)
}
mAdapter.finishedMoreLoading()
}
onError { error ->
error.printStackTrace()
mAdapter.showError(error.message ?: getString(R.string.generic_error))
mAdapter.finishedMoreLoading()
}
}
}
override fun onStart() {
super.onStart()
activity.binding.nv.menu.findItem(R.id.nav_dashboard_inventory).isChecked = true
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
if (::drawerToggle.isInitialized) {
drawerToggle.onConfigurationChanged(newConfig)
}
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
inflater?.inflate(R.menu.menu_dashboard_inventory, menu)
val searchItem = menu?.findItem(R.id.action_search_dashboard_inventory)
val searchView = searchItem?.actionView as SearchView
searchView.setOnQueryTextListener(this)
}
override fun onDestroyView() {
super.onDestroyView()
compositeDisposable.dispose()
activity.binding.nv.menu.findItem(R.id.nav_dashboard_inventory).isChecked = false
}
override fun onDestroy() {
super.onDestroy()
}
override fun onQueryTextSubmit(query: String?): Boolean {
if (query != null) {
mAdapter.filter(query)
}
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
if (newText != null) {
mAdapter.filter(newText)
}
return true
}
}
| 0 | null | 0 | 0 | 237e9496b5fb608f543e98111269da9b91a06ed3 | 7,567 | nucleus | MIT License |
personklient/personklient-infrastruktur/main/no/nav/tiltakspenger/libs/personklient/pdl/adressebeskyttelse/FellesAdressebeskyttelseKlient.kt | navikt | 585,932,206 | false | {"Kotlin": 214197, "Shell": 1193} | package no.nav.tiltakspenger.libs.personklient.pdl.adressebeskyttelse
import arrow.core.Either
import mu.KLogger
import no.nav.tiltakspenger.libs.common.AccessToken
import no.nav.tiltakspenger.libs.common.Fnr
import no.nav.tiltakspenger.libs.person.AdressebeskyttelseGradering
import no.nav.tiltakspenger.libs.personklient.pdl.FellesAdressebeskyttelseError
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/**
* Klient for å hente adressebeskyttelse fra PDL
*/
interface FellesAdressebeskyttelseKlient {
/**
* @return null dersom identen ikke finnes. Tom liste dersom identen ikke har adressebeskyttelse.
*/
suspend fun enkel(fnr: Fnr): Either<FellesAdressebeskyttelseError, List<AdressebeskyttelseGradering>?>
/**
* @return garanterer at alle identer i inputlisten er med i outputlisten. Null betyr at identen ikke finnes. Tom liste dersom identen ikke har adressebeskyttelse.
*/
suspend fun bolk(
fnrListe: List<Fnr>,
): Either<FellesAdressebeskyttelseError, Map<Fnr, List<AdressebeskyttelseGradering>?>>
companion object {
fun create(
baseUrl: String,
getToken: suspend () -> AccessToken,
connectTimeout: Duration = 1.seconds,
timeout: Duration = 1.seconds,
sikkerlogg: KLogger?,
): FellesAdressebeskyttelseKlient = FellesHttpAdressebeskyttelseKlient(
baseUrl = baseUrl,
getToken = getToken,
connectTimeout = connectTimeout,
timeout = timeout,
sikkerlogg = sikkerlogg,
)
}
}
| 0 | Kotlin | 0 | 0 | f092b8c522d380d892ed1e5dde3a961cb5694175 | 1,609 | tiltakspenger-libs | MIT License |
backend/data/src/main/kotlin/io/tolgee/development/testDataBuilder/data/OrganizationTestData.kt | tolgee | 303,766,501 | false | null | package io.tolgee.development.testDataBuilder.data
import io.tolgee.model.Organization
import io.tolgee.model.UserAccount
import io.tolgee.model.enums.OrganizationRoleType
class OrganizationTestData : BaseTestData() {
lateinit var franta: UserAccount
lateinit var pepa: UserAccount
lateinit var jirina: UserAccount
lateinit var kvetoslav: UserAccount
lateinit var milan: UserAccount
lateinit var pepaOrg: Organization
lateinit var jirinaOrg: Organization
init {
root.apply {
addUserAccountWithoutOrganization {
name = "<NAME>"
username = "<EMAIL>"
franta = this
}
projectBuilder.addPermission {
user = franta
}
val pepaBuilder = addUserAccountWithoutOrganization {
username = "pepa"
name = "<NAME>"
pepa = this
}
projectBuilder.addPermission {
user = pepa
project = projectBuilder.self
}
addOrganization {
name = "Organizacion"
pepaOrg = this
}.build {
addRole {
user = pepa
type = OrganizationRoleType.OWNER
}
}
pepaBuilder.build {
setUserPreferences {
language = "de"
preferredOrganization = pepaOrg
}
}
val jirinaBuilder = addUserAccountWithoutOrganization {
username = "jirina"
name = "<NAME>"
jirina = this
}
val kvetoslavBuilder = addUserAccountWithoutOrganization {
username = "kvetoslav"
name = "<NAME>"
kvetoslav = this
}
projectBuilder.build {
addPermission {
user = kvetoslav
}
}
kvetoslavBuilder.build {
setUserPreferences {
preferredOrganization = this@OrganizationTestData.userAccountBuilder.defaultOrganizationBuilder.self
}
}
addOrganization {
name = "Jirinina Org 2"
jirinaOrg = this
}.build {
addRole {
user = jirina
type = OrganizationRoleType.OWNER
}
// to make it possible for jirina to leave
addRole {
user = kvetoslavBuilder.self
type = OrganizationRoleType.OWNER
}
}
jirinaBuilder.apply {
setUserPreferences {
language = "ft"
preferredOrganization = jirinaOrg
}
}
addUserAccountWithoutOrganization {
name = "Milan"
username = "milan"
milan = this
}
}
}
}
| 170 | null | 40 | 666 | 38c1064783f3ec5d60d0502ec0420698395af539 | 2,503 | tolgee-platform | Apache License 2.0 |
Hermes/Logger/src/main/java/com/spartancookie/hermeslogger/filters/ui/viewholders/BaseViewHolder.kt | RafaelsRamos | 352,183,568 | false | null | package com.spartancookie.hermeslogger.filters.ui.viewholders
import android.view.View
import androidx.recyclerview.widget.RecyclerView
/**
* ViewHolder class to be used by items present in [com.spartancookie.hermeslogger.ui.fragments.FiltersFragment]
*/
abstract class BaseViewHolder<T>(rootView: View): RecyclerView.ViewHolder(rootView) {
/**
* Set the data from [item] into the item View
*/
abstract fun bind(item: T)
} | 6 | null | 0 | 3 | 12007ddb2110f8585e50a86ede897366f4df3dff | 446 | HermesLogger | Apache License 2.0 |
app/src/main/java/com/shevelev/my_footprints_remastered/ui/activity_first_loading/fragment_loading_progress/model/LoadingProgressFragmentModel.kt | AlShevelev | 283,178,554 | false | null | package com.shevelev.my_footprints_remastered.ui.activity_first_loading.fragment_loading_progress.model
import com.shevelev.my_footprints_remastered.ui.activity_first_loading.fragment_loading_progress.dto.Event
import com.shevelev.my_footprints_remastered.ui.shared.mvvm.model.ModelBase
interface LoadingProgressFragmentModel : ModelBase {
fun setEventsListener(listener: ((Event) -> Unit)?)
suspend fun tryToStartService()
} | 0 | Kotlin | 0 | 1 | 6894f98fb439f30ef7a9988043ace059b844c81b | 436 | MyFootprints_remastered | Apache License 2.0 |
app/src/main/java/com/sky/android/news/data/source/NewsDataSource.kt | qianniaoge | 199,862,302 | true | {"Kotlin": 154968, "Java": 71026, "JavaScript": 2916} | /*
* Copyright (c) 2017 The sky Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sky.android.news.data.source
import com.sky.android.news.data.model.CategoryModel
import com.sky.android.news.data.model.DetailsModel
import com.sky.android.news.data.model.HeadLineModel
import io.reactivex.Observable
/**
* Created by sky on 17-9-21.
*/
interface NewsDataSource {
/**
* 获取分类列表
*/
fun getCategory(): Observable<CategoryModel>
/**
* 获取新闻列表
*/
fun getHeadLine(tid: String,
start: Int, end: Int): Observable<HeadLineModel>
/**
* 获取详情信息
*/
fun getDetails(docId: String): Observable<DetailsModel>
}
| 0 | Kotlin | 0 | 0 | f159b9dae4b628820c2ae177d162d6dbddc18f76 | 1,209 | android-news | Apache License 2.0 |
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/MethodParameterAugmenter.kt | jmuchch | 304,496,677 | true | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.intentions.style.inference
import com.intellij.openapi.util.RecursionManager
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.intentions.style.inference.driver.closure.getBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeAugmenter
class MethodParameterAugmenter : TypeAugmenter() {
companion object {
const val GROOVY_COLLECT_METHOD_CALLS_FOR_INFERENCE = "groovy.collect.method.calls.for.inference"
internal fun createInferenceResult(method: GrMethod): InferenceResult? {
if (!Registry.`is`(GROOVY_COLLECT_METHOD_CALLS_FOR_INFERENCE, false)) {
return null
}
val (scope, originalFile) = getFileScope(method) ?: return null
return computeInferredMethod(method, scope, originalFile)
}
private fun computeInferredMethod(method: GrMethod, scope: SearchScope, originalFile: VirtualFile?): InferenceResult? =
CachedValuesManager.getCachedValue(method) {
RecursionManager.doPreventingRecursion(method, true) {
val options = SignatureInferenceOptions(scope, true, ClosureIgnoringInferenceContext(method.manager), lazy { unreachable() })
val typedMethod = runInferenceProcess(method, options)
val typeParameterSubstitutor = createVirtualToActualSubstitutor(typedMethod, method)
val dependencies = if (originalFile != null) arrayOf(method, originalFile) else arrayOf(method)
CachedValueProvider.Result(InferenceResult(typedMethod, typeParameterSubstitutor), *dependencies)
}
}
private fun getFileScope(method: GrMethod): Pair<SearchScope, VirtualFile?>? {
val originalMethod = getOriginalMethod(method)
return originalMethod.containingFile?.run { GlobalSearchScope.fileScope(this) to this.virtualFile }
}
}
data class InferenceResult(val virtualMethod: GrMethod?, val typeParameterSubstitutor: PsiSubstitutor)
override fun inferType(variable: GrVariable): PsiType? {
if (variable !is GrParameter || variable.typeElement != null || getBlock(variable) != null) {
return null
}
val method = variable.parentOfType<GrMethod>()?.takeIf { it.parameters.contains(variable) } ?: return null
val inferenceResult = createInferenceResult(method)
val parameterIndex = method.parameterList.getParameterNumber(variable)
return inferenceResult?.virtualMethod?.parameters?.getOrNull(parameterIndex)
?.takeIf { it.typeElementGroovy != null }?.type
?.let { inferenceResult.typeParameterSubstitutor.substitute(it) }
}
} | 0 | null | 0 | 0 | 59c2156cebc47ad05ecde54a2c415b23a18b758a | 3,315 | intellij-community | Apache License 2.0 |
common/common-tests/src/main/kotlin/ru/itbasis/gradle/common/tests/helpers.kt | itbasis | 303,078,207 | false | null | package ru.itbasis.gradle.common.tests
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
import org.gradle.kotlin.dsl.apply
import org.gradle.testfixtures.ProjectBuilder
import ru.itbasis.gradle.rootmodule.RootModulePlugin
fun initTestProject(projectBuilderConfig: ProjectBuilder.() -> Unit = {}): Project {
val projectBuilder = ProjectBuilder.builder()
projectBuilder.apply(projectBuilderConfig)
val project = projectBuilder.build()
project.pluginManager.apply(RootModulePlugin::class)
return project
}
fun Project.getAllDependenciesAsRows(filterPrefix: String = "") = getAllDependencies(filterPrefix = filterPrefix).map {
"${it.group}:${it.module}:${it.version}"
}
fun Project.getAllDependencies(filterPrefix: String = "") = configurations.asSequence().filter {
it.name.startsWith(prefix = filterPrefix, ignoreCase = true)
&& it.isCanBeResolved
&& !it.name.endsWith("Metadata")
}.getAllDependencies()
fun Sequence<Configuration>.getAllDependencies() = map {
it.resolvedConfiguration.resolvedArtifacts
}.flatten().distinct().map {
it.id.componentIdentifier
}.filterIsInstance(ModuleComponentIdentifier::class.java).toList()
| 1 | Kotlin | 0 | 1 | c059c3407aceb0823c9645841899ae19cd05a107 | 1,238 | fullstack-plugins | MIT License |
core/oauth2/impl/src/jvmMain/kotlin/ru/kyamshanov/mission/oauth2/generateCodeVerifier.kt | KYamshanov | 656,042,097 | false | {"Kotlin": 456764, "Batchfile": 2703, "HTML": 199, "Dockerfile": 195} | package ru.kyamshanov.mission.oauth2
import io.ktor.utils.io.core.toByteArray
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
internal actual fun generateCodeVerifier(): String {
val secureRandom = SecureRandom()
val codeVerifier = ByteArray(32)
secureRandom.nextBytes(codeVerifier)
return Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifier)
}
internal actual fun generateCodeChallange(codeVerifier: String): String {
val bytes: ByteArray = codeVerifier.toByteArray(Charsets.US_ASCII)
val messageDigest = MessageDigest.getInstance("SHA-256")
messageDigest.update(bytes, 0, bytes.size)
val digest = messageDigest.digest()
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest)
} | 7 | Kotlin | 0 | 1 | 1367b1afd0b66d726fa3cc70362846bd01ab9951 | 794 | Mission-app | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/waf/regional/CfnIPSetProps.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.waf.regional
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
/**
* Properties for defining a `CfnIPSet`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.waf.regional.*;
* CfnIPSetProps cfnIPSetProps = CfnIPSetProps.builder()
* .name("name")
* // the properties below are optional
* .ipSetDescriptors(List.of(Map.of(
* "type", "type",
* "value", "value")))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html)
*/
public interface CfnIPSetProps {
/**
* The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in CIDR notation) that web
* requests originate from.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html#cfn-wafregional-ipset-ipsetdescriptors)
*/
public fun ipSetDescriptors(): Any? = unwrap(this).getIpSetDescriptors()
/**
* A friendly name or description of the `IPSet` .
*
* You can't change the name of an `IPSet` after you create it.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html#cfn-wafregional-ipset-name)
*/
public fun name(): String
/**
* A builder for [CfnIPSetProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param ipSetDescriptors The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in
* CIDR notation) that web requests originate from.
*/
public fun ipSetDescriptors(ipSetDescriptors: IResolvable)
/**
* @param ipSetDescriptors The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in
* CIDR notation) that web requests originate from.
*/
public fun ipSetDescriptors(ipSetDescriptors: List<Any>)
/**
* @param ipSetDescriptors The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in
* CIDR notation) that web requests originate from.
*/
public fun ipSetDescriptors(vararg ipSetDescriptors: Any)
/**
* @param name A friendly name or description of the `IPSet` .
* You can't change the name of an `IPSet` after you create it.
*/
public fun name(name: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.waf.regional.CfnIPSetProps.Builder =
software.amazon.awscdk.services.waf.regional.CfnIPSetProps.builder()
/**
* @param ipSetDescriptors The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in
* CIDR notation) that web requests originate from.
*/
override fun ipSetDescriptors(ipSetDescriptors: IResolvable) {
cdkBuilder.ipSetDescriptors(ipSetDescriptors.let(IResolvable::unwrap))
}
/**
* @param ipSetDescriptors The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in
* CIDR notation) that web requests originate from.
*/
override fun ipSetDescriptors(ipSetDescriptors: List<Any>) {
cdkBuilder.ipSetDescriptors(ipSetDescriptors)
}
/**
* @param ipSetDescriptors The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in
* CIDR notation) that web requests originate from.
*/
override fun ipSetDescriptors(vararg ipSetDescriptors: Any): Unit =
ipSetDescriptors(ipSetDescriptors.toList())
/**
* @param name A friendly name or description of the `IPSet` .
* You can't change the name of an `IPSet` after you create it.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
public fun build(): software.amazon.awscdk.services.waf.regional.CfnIPSetProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.waf.regional.CfnIPSetProps,
) : CdkObject(cdkObject), CfnIPSetProps {
/**
* The IP address type ( `IPV4` or `IPV6` ) and the IP address range (in CIDR notation) that web
* requests originate from.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html#cfn-wafregional-ipset-ipsetdescriptors)
*/
override fun ipSetDescriptors(): Any? = unwrap(this).getIpSetDescriptors()
/**
* A friendly name or description of the `IPSet` .
*
* You can't change the name of an `IPSet` after you create it.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html#cfn-wafregional-ipset-name)
*/
override fun name(): String = unwrap(this).getName()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnIPSetProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.waf.regional.CfnIPSetProps):
CfnIPSetProps = CdkObjectWrappers.wrap(cdkObject) as? CfnIPSetProps ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnIPSetProps):
software.amazon.awscdk.services.waf.regional.CfnIPSetProps = (wrapped as
CdkObject).cdkObject as software.amazon.awscdk.services.waf.regional.CfnIPSetProps
}
}
| 3 | null | 0 | 4 | ddf2bfd2275b50bb86a667c4298dd92f59d7e342 | 5,842 | kotlin-cdk-wrapper | Apache License 2.0 |
app/src/main/java/com/axel_stein/glucose_tracker/ui/glucose_report/GlucoseReportFactory.kt | AxelStein | 320,277,698 | false | null | package com.axel_stein.glucose_tracker.ui.edit.edit_weight
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.savedstate.SavedStateRegistryOwner
@Suppress("UNCHECKED_CAST")
class EditWeightFactory(
owner: SavedStateRegistryOwner,
private val id: Long
): AbstractSavedStateViewModelFactory(owner, null) {
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T = EditWeightViewModel(id, handle) as T
} | 4 | Kotlin | 0 | 1 | d6f6877c33b960c8bcc1cfd2ff355071908891ec | 595 | GlucoseTracker | Apache License 2.0 |
vector/src/main/java/im/vector/app/core/pushers/FcmHelper.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright (c) 2022 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app.core.pushers
import android.app.Activity
import im.vector.app.core.di.ActiveSessionHolder
interface FcmHelper {
fun isFirebaseAvailable(): Boolean
/**
* Retrieves the FCM registration token.
*
* @return the FCM token or null if not received from FCM.
*/
fun getFcmToken(): String?
/**
* Store FCM token to the SharedPrefs.
*
* @param token the token to store.
*/
fun storeFcmToken(token: String?)
/**
* onNewToken may not be called on application upgrade, so ensure my shared pref is set.
*
* @param activity the first launch Activity.
* @param pushersManager the instance to register the pusher on.
* @param registerPusher whether the pusher should be registered.
*/
fun ensureFcmTokenIsRetrieved(activity: Activity, pushersManager: PushersManager, registerPusher: Boolean)
fun onEnterForeground(activeSessionHolder: ActiveSessionHolder)
fun onEnterBackground(activeSessionHolder: ActiveSessionHolder)
}
| 4 | null | 4 | 9 | 9bd50a49e0a5a2a17195507ef3fe96594ddd739e | 1,643 | tchap-android | Apache License 2.0 |
app/src/main/java/br/com/wellingtoncosta/amdk/util/schedulers/TestSchedulerProvider.kt | wellingtoncosta | 115,824,145 | false | null | package br.com.wellingtoncosta.amdk.util.schedulers
import io.reactivex.Scheduler
import io.reactivex.schedulers.TestScheduler
/**
* @author wellingtoncosta on 05/02/18.
*/
class TestSchedulerProvider(private val testScheduler: TestScheduler) : BaseScheduler {
override fun io(): Scheduler {
return testScheduler
}
override fun ui(): Scheduler {
return testScheduler
}
} | 0 | null | 4 | 24 | e3b081346404e32852b1c4b402c77e58802148ac | 409 | android-mvvm-databinding-kotlin | MIT License |
src/main/kotlin/com/github/kerubistan/kerub/model/errors/HardwareError.kt | soloturn | 164,455,794 | true | {"Kotlin": 1728202, "Gherkin": 74051, "HTML": 73962, "JavaScript": 53966, "CSS": 754} | package com.github.kerubistan.kerub.model.errors
import com.github.kerubistan.kerub.model.Entity
import java.util.UUID
data class HardwareError(
override val id: UUID = UUID.randomUUID()
) : Entity<UUID> | 0 | Kotlin | 0 | 1 | 42b70cb9a182af4923a7f960c6df98284e03bab2 | 207 | kerub | Apache License 2.0 |
core/core-ktx/src/androidTest/java/androidx/core/util/PairTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.util
import android.util.Pair as AndroidPair
import androidx.test.filters.SmallTest
import kotlin.Pair as KotlinPair
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
@SmallTest
class PairTest {
@Test fun androidDestructuringNonNull() {
val pair = AndroidPair("one", "two")
val (first: String, second: String) = pair
assertSame(pair.first, first)
assertSame(pair.second, second)
}
@Test fun androidDestructuringNullable() {
val pair = AndroidPair("one", "two")
val (first: String?, second: String?) = pair
assertSame(pair.first, first)
assertSame(pair.second, second)
}
@Test fun androidToKotlin() {
val android = AndroidPair("one", "two")
val kotlin = android.toKotlinPair()
assertEquals(android.first to android.second, kotlin)
}
@Test fun kotlinToAndroid() {
val kotlin = KotlinPair("one", "two")
val android = kotlin.toAndroidPair()
assertEquals(AndroidPair(kotlin.first, kotlin.second), android)
}
@Test fun androidXDestructuringNonNull() {
val pair = Pair("one", "two")
val (first: String, second: String) = pair
assertSame(pair.first, first)
assertSame(pair.second, second)
}
@Test fun androidXDestructuringNullable() {
val pair = Pair("one", "two")
val (first: String?, second: String?) = pair
assertSame(pair.first, first)
assertSame(pair.second, second)
}
@Test fun androidXToKotlin() {
val pair = Pair("one", "two")
val kotlin = pair.toKotlinPair()
assertEquals(pair.first to pair.second, kotlin)
}
@Test fun kotlinToAndroidX() {
val kotlin = KotlinPair("one", "two")
val pair = kotlin.toAndroidXPair()
assertEquals(Pair(kotlin.first, kotlin.second), pair)
}
}
| 29 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 2,557 | androidx | Apache License 2.0 |
app/src/main/java/com/moon/beautygirlkotlin/data/service/youmei/TaoService.kt | shichonghuotian | 130,451,148 | false | null | package com.moon.beautygirlkotlin.data.service.youmei
import com.moon.beautygirlkotlin.data.entity.GirlData
import com.moon.beautygirlkotlin.data.entity.Result
import com.moon.beautygirlkotlin.data.service.DataService
import com.moon.beautygirlkotlin.utils.DataUtil
import java.util.*
/**
* Created by Arthur on 2019-12-29.
*/
class TaoService: DataService {
override suspend fun getData(page: Int, pageSize: Int, type: String?): Result<List<GirlData>> {
val url = "http://www.umei.cc/bizhitupian/meinvbizhi/"
val result =
if (page == 1) {
DataUtil.parserMeiTuLuHtml(url)
} else {
DataUtil.parserMeiTuLuHtml(url + page + ".htm")
}
return Result.Success(result.map {
GirlData(UUID.randomUUID().toString(),it.url,it.title)
})
}
} | 1 | null | 1 | 1 | 6da51446c6ec62e250dc955aba3a043aaabc3808 | 856 | BeautyGirlKotlin | Apache License 2.0 |
app/src/main/java/dev/vengateshm/android_kotlin_compose_practice/multiple_screen_size/WindowInfo.kt | vengateshm | 670,054,614 | false | null | package dev.vengateshm.android_kotlin_compose_practice.multiple_screen_size
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun rememberWindowInfo(): WindowInfo {
val configuration = LocalConfiguration.current
return WindowInfo(
screenWidth = configuration.screenWidthDp.dp,
screenHeight = configuration.screenHeightDp.dp,
screenWidthType =
when {
configuration.screenWidthDp < 600 -> WindowInfo.WindowType.Compact
configuration.screenWidthDp < 840 -> WindowInfo.WindowType.Medium
else -> WindowInfo.WindowType.Expanded
},
screenHeightType =
when {
configuration.screenHeightDp < 480 -> WindowInfo.WindowType.Compact
configuration.screenHeightDp < 900 -> WindowInfo.WindowType.Medium
else -> WindowInfo.WindowType.Expanded
},
)
}
data class WindowInfo(
val screenWidth: Dp,
val screenHeight: Dp,
val screenWidthType: WindowType,
val screenHeightType: WindowType,
) {
sealed class WindowType {
object Compact : WindowType()
object Medium : WindowType()
object Expanded : WindowType()
}
}
| 0 | null | 0 | 1 | 382c1b29f62f521b252e9b973de085496e51fdc1 | 1,360 | Android-Kotlin-Jetpack-Compose-Practice | Apache License 2.0 |
openrndr-draw/src/jsMain/kotlin/org/openrndr/draw/ColorBuffer.kt | openrndr | 122,222,767 | false | null | package org.openrndr.draw
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.khronos.webgl.ArrayBufferView
import org.khronos.webgl.TexImageSource
import org.openrndr.color.ColorRGBa
import org.openrndr.internal.Driver
import org.openrndr.shape.IntRectangle
import org.openrndr.shape.Rectangle
import org.openrndr.utils.buffer.MPPBuffer
import org.w3c.dom.CanvasRenderingContext2D
actual abstract class ColorBuffer {
/**
* write the contents from [sourceBuffer] to the [ColorBuffer], potentially with format and type conversions
*
* The [sourceBuffer] should be allocated using [ByteBuffer.allocateDirect] and have an amount of remaining bytes
* that matches with the dimensions, [sourceFormat] and [sourceType].
* @param sourceBuffer a [ByteBuffer] holding raw image data
* @param sourceFormat the [ColorFormat] that is used for the image data stored in [sourceBuffer], default is [ColorBuffer.format]
* @param sourceType the [ColorType] that is used for the image data stored in [sourceBuffer], default is [ColorBuffer.type]
* @param level the mipmap-level of [ColorBuffer] to write to
*/
actual abstract val session: Session?
/** the width of the [ColorBuffer] in device units */
actual abstract val width: Int
/** the height of the [ColorBuffer] in device units */
actual abstract val height: Int
/** the content scale of the [ColorBuffer] */
actual abstract val contentScale: Double
/**
* the [ColorFormat] of the image stored in the [ColorBuffer]
*/
actual abstract val format: ColorFormat
/**
* the [ColorType] of the image stored in the [ColorBuffer]
*/
actual abstract val type: ColorType
/** the number of mipmap levels */
actual abstract val levels: Int
/** the multisampling method used for this [ColorBuffer] */
actual abstract val multisample: BufferMultisample
/** the width of the [ColorBuffer] in pixels */
actual val effectiveWidth: Int
get() = (width * contentScale).toInt()
/** the height of the [ColorBuffer] in pixels */
actual val effectiveHeight: Int
get() = (height * contentScale).toInt()
actual val bounds: Rectangle
get() = Rectangle(0.0, 0.0, width.toDouble(), height.toDouble())
/** permanently destroy the underlying [ColorBuffer] resources, [ColorBuffer] can not be used after it is destroyed */
actual abstract fun destroy()
/** bind the colorbuffer to a texture unit, internal API */
actual abstract fun bind(unit: Int)
/** generates mipmaps from the top-level mipmap */
actual abstract fun generateMipmaps()
/** the (unitless?) degree of anisotropy to be used in filtering */
actual abstract var anisotropy: Double
/**
* should the v coordinate be flipped because the [ColorBuffer] contents are stored upside-down?
*/
actual abstract var flipV: Boolean
actual abstract fun copyTo(
target: ColorBuffer,
fromLevel: Int,
toLevel: Int,
sourceRectangle: IntRectangle,
targetRectangle: IntRectangle,
filter: MagnifyingFilter
)
actual abstract fun copyTo(
target: ColorBuffer,
fromLevel: Int,
toLevel: Int,
filter: MagnifyingFilter
)
/**
* copies contents to a target array texture
* @param target the color buffer to which contents will be copied
* @param layer the array layer from which will be copied
* @param fromLevel the mip-map level from which will be copied
* @param toLevel the mip-map level of [target] to which will be copied
*/
actual abstract fun copyTo(
target: ArrayTexture,
layer: Int,
fromLevel: Int,
toLevel: Int
)
abstract fun write(
source: TexImageSource,
x: Int = 0,
y: Int = 0,
width: Int = this.effectiveWidth,
height: Int = this.effectiveHeight,
level: Int = 0
)
abstract fun write(
source: ArrayBufferView,
sourceFormat: ColorFormat,
sourceType: ColorType,
x: Int = 0,
y: Int = 0,
width: Int = this.effectiveWidth,
height: Int = this.effectiveHeight,
level: Int = 0
)
abstract fun read(
target: ArrayBufferView,
x: Int,
y: Int,
width: Int = this.effectiveWidth,
height: Int = this.effectiveHeight,
level: Int = 0
)
actual abstract fun write(
sourceBuffer: MPPBuffer,
sourceFormat: ColorFormat,
sourceType: ColorType,
x: Int,
y: Int,
width: Int,
height: Int,
level: Int
)
actual abstract fun filter(
filterMin: MinifyingFilter,
filterMag: MagnifyingFilter
)
/** the wrapping mode to use in the horizontal direction */
actual abstract var wrapU: WrapMode
/** the wrapping mode to use in the vertical direction */
actual abstract var wrapV: WrapMode
/**
* sets all pixels in the color buffer to [color]
* @param color the color used for filling
*/
actual abstract fun fill(color: ColorRGBa)
}
/**
* load an image from a file or url encoded as [String], also accepts base64 encoded data urls
*/
actual fun loadImage(
fileOrUrl: String,
formatHint: ImageFileFormat?,
session: Session?
): ColorBuffer {
return Driver.instance.createColorBufferFromUrl(fileOrUrl, null, session)
}
actual suspend fun loadImageSuspend(
fileOrUrl: String,
formatHint: ImageFileFormat?,
session: Session?
): ColorBuffer {
return Driver.instance.createColorBufferFromUrl(fileOrUrl, null, session)
} | 33 | null | 73 | 880 | 2ef3c463ecb66701771dc0cf8fb3364e960a5e3c | 5,735 | openrndr | BSD 2-Clause FreeBSD License |
app/src/main/java/com/mytests/testExam/domain/repository/IAnimalFactsRepository.kt | FredNekrasov | 766,574,196 | false | {"Kotlin": 49690} | package com.mytests.testExam.domain.repository
import com.mytests.testExam.domain.model.AnimalFacts
import com.mytests.testExam.domain.util.ConnectionStatus
import kotlinx.coroutines.flow.StateFlow
interface IAnimalFactsRepository {
suspend fun getList(animalType: String, amount: Int): StateFlow<Pair<ConnectionStatus,List<AnimalFacts>>>
suspend fun updateEntity(animalFacts: AnimalFacts)
} | 0 | Kotlin | 0 | 1 | 7d7603c85380db9db2c5688367d7be76101640fb | 401 | my-tests | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/MessageDollar.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.MessageDollar: ImageVector
get() {
if (_messageDollar != null) {
return _messageDollar!!
}
_messageDollar = Builder(name = "MessageDollar", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.5f, 0.0f)
lineTo(4.5f, 0.0f)
curveTo(2.02f, 0.0f, 0.0f, 2.02f, 0.0f, 4.5f)
lineTo(0.0f, 15.51f)
curveToRelative(0.0f, 2.48f, 2.02f, 4.5f, 4.5f, 4.5f)
horizontalLineToRelative(2.46f)
lineToRelative(3.41f, 2.88f)
curveToRelative(0.47f, 0.42f, 1.06f, 0.62f, 1.64f, 0.62f)
reflectiveCurveToRelative(1.14f, -0.2f, 1.58f, -0.59f)
lineToRelative(3.52f, -2.91f)
horizontalLineToRelative(2.39f)
curveToRelative(2.48f, 0.0f, 4.5f, -2.02f, 4.5f, -4.5f)
lineTo(24.0f, 4.5f)
curveToRelative(0.0f, -2.48f, -2.02f, -4.5f, -4.5f, -4.5f)
close()
moveTo(21.0f, 15.51f)
curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-2.93f)
curveToRelative(-0.35f, 0.0f, -0.69f, 0.12f, -0.96f, 0.34f)
lineToRelative(-3.61f, 2.99f)
lineToRelative(-3.53f, -2.98f)
curveToRelative(-0.27f, -0.23f, -0.61f, -0.35f, -0.97f, -0.35f)
horizontalLineToRelative(-3.0f)
curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f)
lineTo(3.0f, 4.5f)
curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(15.0f)
curveToRelative(0.83f, 0.0f, 1.5f, 0.67f, 1.5f, 1.5f)
lineTo(21.0f, 15.51f)
close()
moveTo(16.0f, 12.39f)
curveToRelative(0.0f, 1.45f, -1.18f, 2.62f, -2.62f, 2.62f)
horizontalLineToRelative(-0.38f)
curveToRelative(0.0f, 0.55f, -0.45f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.45f, -1.0f, -1.0f)
horizontalLineToRelative(-0.27f)
curveToRelative(-1.07f, 0.0f, -2.06f, -0.57f, -2.6f, -1.5f)
curveToRelative(-0.28f, -0.48f, -0.11f, -1.09f, 0.36f, -1.37f)
curveToRelative(0.48f, -0.28f, 1.09f, -0.11f, 1.37f, 0.36f)
curveToRelative(0.18f, 0.31f, 0.51f, 0.5f, 0.87f, 0.5f)
horizontalLineToRelative(2.64f)
curveToRelative(0.34f, 0.0f, 0.62f, -0.28f, 0.62f, -0.62f)
curveToRelative(0.0f, -0.31f, -0.22f, -0.57f, -0.52f, -0.62f)
lineToRelative(-3.29f, -0.55f)
curveToRelative(-1.27f, -0.21f, -2.19f, -1.3f, -2.19f, -2.59f)
curveToRelative(0.0f, -1.45f, 1.18f, -2.62f, 2.62f, -2.62f)
horizontalLineToRelative(0.38f)
curveToRelative(0.0f, -0.55f, 0.45f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.45f, 1.0f, 1.0f)
horizontalLineToRelative(0.27f)
curveToRelative(1.07f, 0.0f, 2.06f, 0.57f, 2.6f, 1.5f)
curveToRelative(0.28f, 0.48f, 0.11f, 1.09f, -0.36f, 1.37f)
curveToRelative(-0.48f, 0.28f, -1.09f, 0.11f, -1.37f, -0.36f)
curveToRelative(-0.18f, -0.31f, -0.51f, -0.5f, -0.87f, -0.5f)
horizontalLineToRelative(-2.64f)
curveToRelative(-0.34f, 0.0f, -0.62f, 0.28f, -0.62f, 0.62f)
curveToRelative(0.0f, 0.31f, 0.22f, 0.57f, 0.52f, 0.62f)
lineToRelative(3.29f, 0.55f)
curveToRelative(1.27f, 0.21f, 2.19f, 1.3f, 2.19f, 2.59f)
close()
}
}
.build()
return _messageDollar!!
}
private var _messageDollar: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,775 | icons | MIT License |
rubik/rubik_plugins/src/main/java/ByVersion.kt | baidu | 504,447,693 | false | {"Kotlin": 607049, "Java": 37304} | const val BY_VERSION = "1.10.0.0-AGBT4_2-K1_5-LOCAL"
// KTNail plugin update.
// by [sync].
// at timestamp : 2024-05-22 12:51:23.
| 1 | Kotlin | 7 | 153 | 065ba8f4652b39ff558a5e3f18b9893e2cf9bd25 | 135 | Rubik | Apache License 2.0 |
sherlock-plugin/src/main/kotlin/com/quadible/sherlockplugin/GetOSNameTask.kt | St4B | 257,113,166 | false | null | package com.quadible.sherlockplugin
import org.gradle.api.Project
import org.gradle.api.tasks.Exec
import org.gradle.api.tasks.Internal
import java.io.ByteArrayOutputStream
open class GetOSNameTask : Exec() {
companion object {
internal const val TASK_NAME_GET_OPERATING_SYSTEM = "getOperatingSystem"
}
@get:Internal
internal val osName: String
get() = stdout.toString().trim()
private val stdout = ByteArrayOutputStream()
override fun exec() {
standardOutput = stdout
commandLine = listOf("uname", "-s")
super.exec()
}
}
fun Project.registerGetOSNameTask(): GetOSNameTask = tasks.create(
GetOSNameTask.TASK_NAME_GET_OPERATING_SYSTEM,
GetOSNameTask::class.java
) { getOsTask ->
getOsTask.doLast {
println("Operating System: ${getOsTask.osName}")
}
}
| 0 | Kotlin | 0 | 3 | 8a57c2da88899a82c6a456bf326a9f93455795ea | 849 | Sherlock | Apache License 2.0 |
app/src/main/java/com/example/vehiclecontacting/Web/DiscussController/Comment.kt | Bngel | 366,048,859 | false | null | package com.example.vehiclecontacting.Web.DiscussController
import android.os.Parcel
import android.os.Parcelable
data class Comment(
val commentCounts: Int,
val comments: String,
val createTime: String,
val id: String,
val likeCounts: Int,
val number: String,
val replyDescription1: String,
val replyDescription2: String,
val replyDescription3: String,
val replyId1: String,
val replyId2: String,
val replyId3: String,
val replyNumber1: String,
val replyNumber2: String,
val replyNumber3: String,
val replyUsername1: String,
val replyUsername2: String,
val replyUsername3: String,
val secondReplyUsername1: String,
val secondReplyUsername2: String,
val secondReplyUsername3: String,
val sex: String,
val userPhoto: String,
val username: String
) : Parcelable {
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(p0: Parcel?, p1: Int) {
p0?.writeInt(commentCounts)
p0?.writeString(comments)
p0?.writeString(createTime)
p0?.writeString(id)
p0?.writeInt(likeCounts)
p0?.writeString(number)
p0?.writeString(replyDescription1)
p0?.writeString(replyDescription2)
p0?.writeString(replyDescription3)
p0?.writeString(replyId1)
p0?.writeString(replyId2)
p0?.writeString(replyId3)
p0?.writeString(replyNumber1)
p0?.writeString(replyNumber2)
p0?.writeString(replyNumber3)
p0?.writeString(replyUsername1)
p0?.writeString(replyUsername2)
p0?.writeString(replyUsername3)
p0?.writeString(secondReplyUsername1)
p0?.writeString(secondReplyUsername2)
p0?.writeString(secondReplyUsername3)
p0?.writeString(sex)
p0?.writeString(userPhoto)
p0?.writeString(username)
}
companion object CREATOR: Parcelable.Creator<Comment> {
override fun createFromParcel(p0: Parcel?): Comment {
p0 !!
return Comment(
p0.readInt(),
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readInt(),
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:"",
p0.readString()?:""
)
}
override fun newArray(p0: Int): Array<Comment?> {
return arrayOfNulls(p0)
}
}
} | 0 | Kotlin | 0 | 0 | 759ffa90c487d4472a79e20bf51ca35454cc7e65 | 3,069 | VehicleContacting | Apache License 2.0 |
app/src/main/java/com/karthik/splash/root/SplashAppModule.kt | adb-shell | 110,352,693 | false | null | package com.karthik.splash.root
import android.content.Context
import com.karthik.splash.misc.InternetHandler
import com.karthik.splash.storage.MemoryCache
import com.karthik.splash.storage.db.SplashDatabase
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class SplashAppModule(private val context: Context, private val splashDatabase: SplashDatabase) {
@Provides
fun providesContext() =
context
@Singleton
@Provides
fun providesCache() =
MemoryCache(context)
@Singleton
@Provides
fun providesDatabaseDao() =
splashDatabase.getDatabaseDao()
@Singleton
@Provides
fun providesInternetHandler() =
InternetHandler(context)
}
| 0 | Kotlin | 0 | 0 | e801f36da18ff33bc8fc49ba3497a21653677261 | 753 | Splash | The Unlicense |
SpringBootApplication/src/main/kotlin/com/server/repository/user/UserRepository.kt | PhilJay | 233,428,899 | false | null | package com.server.repository.user
import com.server.repository.MongoRepositoryBase
interface UserRepository : MongoRepositoryBase<User> {
/**
* Searches for a user with the provided username.
* @param username: The username to search for.
*/
fun findByUsername(username: String?): User?
} | 18 | Kotlin | 2 | 9 | e16756de45a503f7f52ada6505ecb177793aa6ae | 314 | SpringAngular | Apache License 2.0 |
app/src/main/java/com/example/connectionsmanagement/ResultActivity.kt | toyyx | 674,488,487 | false | null | package com.example.connectionsmanagement
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.core.view.marginLeft
import androidx.core.view.marginRight
import androidx.drawerlayout.widget.DrawerLayout
import com.allen.library.CircleImageView
import com.coorchice.library.SuperTextView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationView
import java.io.File
import java.io.FileOutputStream
import java.time.LocalDateTime
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.result_activity_layout)
Toast.makeText(this,"create",Toast.LENGTH_SHORT).show()
//设置toolbar
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.let {
it.setDisplayHomeAsUpEnabled(true)
// it.setHomeAsUpIndicator(R.mipmap.ic_result_menu) //设置home键图标 即:toolbar最左侧按钮
}
//设置左滑菜单
val draLayout = findViewById<DrawerLayout>(R.id.resultShow)
val navView = findViewById<NavigationView>(R.id.navView)
navView.setCheckedItem(R.id.navMain)
navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.navMain -> {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
R.id.navConnections -> {
val intent = Intent(this, ResultActivity::class.java)
startActivity(intent)
}
R.id.navAbout -> {
AlertDialog.Builder(this).apply {
setTitle("关于本软件")
setMessage("软件名称:人脉管理\n\n软件说明:用于科学管理人际关系\n\n开发人员:姚扬鑫 徐润 张凯璇 陆孜逸")
setCancelable(false)
setPositiveButton("OK") { _, _ -> }
show()
}
}
}
draLayout.closeDrawers()
true
}
}
override fun onStart() {
super.onStart()
Toast.makeText(this,"onStart",Toast.LENGTH_SHORT).show()
}
override fun onResume() {
super.onResume()
Toast.makeText(this,"resume",Toast.LENGTH_SHORT).show()
refresh() //刷新关系图
}
override fun onPause() {
super.onPause()
Toast.makeText(this,"onPause",Toast.LENGTH_SHORT).show()
}
override fun onStop() {
super.onStop()
Toast.makeText(this,"onStop",Toast.LENGTH_SHORT).show()
}
override fun onRestart() {
super.onRestart()
Toast.makeText(this,"onRestart",Toast.LENGTH_SHORT).show()
}
override fun onDestroy() {
super.onDestroy()
Toast.makeText(this,"onDestroy",Toast.LENGTH_SHORT).show()
}
//刷新人脉图谱
@SuppressLint("Range")
fun refresh(){
//连接数据库
val dbHelper=ConnectionsDatabaseHelper(this,"ConnectionsStore.db",1)
val db=dbHelper.writableDatabase
val cursor=db.query("Human",null,null,null,null,null,null)
if(cursor.moveToFirst()){
val relativeHumanLayout=findViewById<RelativeLayout>(R.id.ConnectionsHumanMap)
val relativeLineLayout=findViewById<RelativeLayout>(R.id.ConnectionsLineMap)
val connectionsList: ArrayList<MySuperTextView> = arrayListOf()
do{
val id=cursor.getInt(cursor.getColumnIndex("id"))
val name=cursor.getString(cursor.getColumnIndex("name"))
val notes=cursor.getString(cursor.getColumnIndex("notes"))
//从数据库取出Bitmap数据
val imageByteArray=cursor.getBlob(cursor.getColumnIndex("image_data"))
val imageBitmap = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.size)
//显示数据库信息 (仅测试阶段使用)
Toast.makeText(this,"姓名:${name}备注:${notes}图片ByteArray:${imageByteArray}",Toast.LENGTH_SHORT).show()
//创建人物视图
val mySuperTextView=MySuperTextView(imageBitmap,name)
//将视图存入关系队列
connectionsList.add(mySuperTextView)
}while(cursor.moveToNext())
//在关系图上进行绘制
createGraph(connectionsList,relativeHumanLayout,relativeLineLayout)
}
cursor.close()
}
//人脉关系图绘制 备注:目前已实现人物围绕中心绕圈分布,重叠时圆圈自动外扩,展现一圈圈的人脉关系图
private fun createGraph(mySuperTextViewList: ArrayList<MySuperTextView>,relativeHumanLayout:RelativeLayout,relativeLineLayout:RelativeLayout){
val baseRadius = 300 //基础半径
val centerView = mySuperTextViewList[0] //中心人物 即:用户自身
//每次刷新时清空关系图
relativeHumanLayout.removeAllViews()
relativeLineLayout.removeAllViews()
//将中心人物放置关系图中心
val centerViewParams=RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
centerViewParams.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE)
relativeHumanLayout.addView(centerView,centerViewParams)
//待中心视图布置完成后,添加其余人物视图
centerView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
//获取中心人物视图的位置
val centerX = centerView.x
val centerY = centerView.y
//视图重叠最大间距
val viewSpacing =sqrt(centerView.width.toDouble().pow(2.0) + centerView.height.toDouble().pow(2.0))
val finishedViewGroup: ArrayList<MySuperTextView> = arrayListOf() //本圈视图队列
//绘制其余人物视图
refreshAll(mySuperTextViewList,finishedViewGroup,centerX,centerY,baseRadius,relativeHumanLayout,relativeLineLayout,viewSpacing,1)
// 完成了需要在此回调中做的操作,注销监听器,以避免多次调用
centerView.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
//在两个视图之间连线
fun drawLineBetweenViews(layout: RelativeLayout, view1: View, view2: View) {
// 计算两个视图的中心点
val startX = view1.x + view1.width / 2
val startY = view1.y + view1.height / 2
val endX = view2.x + view2.width / 2
val endY = view2.y + view2.height / 2
// 创建一个新的View作为线条
val line = View(this)
line.setBackgroundColor(Color.BLACK) // 设置线条颜色
// 计算线条的位置和大小
val width = sqrt((startX - endX).toDouble().pow(2.0) + (startY - endY).toDouble().pow(2.0)).toInt()
val height=5
val angle = atan2((endY - startY).toDouble(), (endX - startX).toDouble()) * 180 / Math.PI
line.layoutParams = RelativeLayout.LayoutParams(width, height)
// 设置线条的位置和旋转角度
line.x = (startX + endX)/2- width/2
line.y = (startY + endY)/2- height/ 2
line.rotation = angle.toFloat()
// 将线条添加到布局中
layout.addView(line)
}
//判断两视图是否重叠
fun viewsOverlap(view1: View, view2: View,viewSpacing:Double): Boolean {
val viewDistance=sqrt((view1.x-view2.x).toDouble().pow(2.0) + (view1.y-view2.y).toDouble().pow(2.0))
return viewDistance<viewSpacing
}
fun viewsOverlap(viewX: Int,viewY: Int,compareView: View,viewSpacing:Double): Boolean {
val viewDistance=sqrt((viewX-compareView.x).toDouble().pow(2.0) + (viewY-compareView.y).toDouble().pow(2.0))
return viewDistance<viewSpacing
}
//判断视图与视图组是否重叠
fun viewsGroupOverlap(newView: View,currentViewGroup:ArrayList<MySuperTextView>,viewSpacing:Double):Boolean{
var result = false
for(tempView in currentViewGroup){
if(viewsOverlap(newView,tempView,viewSpacing)){
result=true
}
}
return result
}
fun viewsGroupOverlap(newViewX: Int,newViewY: Int,currentViewGroup:ArrayList<MySuperTextView>,viewSpacing:Double):Boolean{
var result = false
for(tempView in currentViewGroup){
if(viewsOverlap(newViewX,newViewY,tempView,viewSpacing)){
result=true
}
}
return result
}
//将视图放入布局
fun arrangeView(newView: View,X:Int,Y:Int,relativeLayout:RelativeLayout){
val viewParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
viewParams.leftMargin = X
viewParams.topMargin = Y
relativeLayout.addView(newView, viewParams)
}
//刷新除中心外的所有视图 备注:需要在中心视图布置完成后使用
fun refreshAll(mySuperTextViewList:ArrayList<MySuperTextView>,finishedViewGroup:ArrayList<MySuperTextView>,centerX:Float,centerY:Float,currentRadius:Int,humanLayout:RelativeLayout,lineLayout:RelativeLayout,viewSpacing:Double,location:Int){
//判断当前布置视图进度
if(location+1>mySuperTextViewList.size){
//当完成所有视图的布置后,进行视图与中心的连线
for(view in mySuperTextViewList){
drawLineBetweenViews(lineLayout,humanLayout.getChildAt(0),view)
}
}else{
//视图布置进行中,开始新视图布置
val newView=mySuperTextViewList[location] //新视图
finishedViewGroup.add(newView) //加入本圈视图队列
val currentViewSize=finishedViewGroup.size //本圈视图数量
var currentAngle= 0.0 //当前角度
var angleIncrement=2 * Math.PI/currentViewSize //本圈角度增加量
var curRadius=currentRadius //当前半径
val radiusIncrement=100 //扩圈时的半径增加量
//调整本圈其余视图位置
for (i in humanLayout.childCount-currentViewSize+1 until humanLayout.childCount) {
humanLayout.getChildAt(i).x = (centerX + curRadius * cos(currentAngle)).toFloat()
humanLayout.getChildAt(i).y = (centerY - curRadius * sin(currentAngle)).toFloat()
currentAngle += angleIncrement
}
//布置本圈新视图
var x = (centerX + curRadius * cos(currentAngle)).toInt() //x坐标
var y = (centerY - curRadius * sin(currentAngle)).toInt() //y坐标
arrangeView(newView, x, y, humanLayout)
//设置本圈恢复标志
var restoreFlag=false
//布置新视图后判断是否重叠
while(viewsGroupOverlap(x, y,ArrayList(mySuperTextViewList.take(location)),viewSpacing)){
//重叠后恢复本圈其余视图至正确位置
if(!restoreFlag){
currentAngle=0.0
angleIncrement=2 * Math.PI/(currentViewSize-1)
for (i in humanLayout.childCount-currentViewSize until humanLayout.childCount) {
humanLayout.getChildAt(i).x = (centerX + curRadius * cos(currentAngle)).toFloat()
humanLayout.getChildAt(i).y = (centerY - curRadius * sin(currentAngle)).toFloat()
currentAngle += angleIncrement
}
restoreFlag=true //本圈已恢复
}
//移除新视图,清空本圈视图队列
finishedViewGroup.clear()
humanLayout.removeView(newView)
//开启新圈
finishedViewGroup.add(newView) //新视图为新圈第一个视图
curRadius += radiusIncrement //新圈半径
x = (centerX + curRadius * cos(0.0)).toInt() //x坐标
y = (centerY - curRadius * sin(0.0)).toInt() //y坐标
arrangeView(newView,x,y,humanLayout) //布置新视图
}
//待当前视图布局完成后,进行下一个视图的布局
newView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
newView.viewTreeObserver.removeOnGlobalLayoutListener(this)
refreshAll(mySuperTextViewList,finishedViewGroup,centerX,centerY,curRadius,humanLayout,lineLayout,viewSpacing,location+1)
}
})
}
}
// //视角回归中心 备注:目前未使用
// fun toCenter(){
// val connectionsMapLayout= findViewById<RelativeLayout>(R.id.ConnectionsMap)
// val displayMetrics = resources.displayMetrics
// val screenWidth = displayMetrics.widthPixels
// val screenHeight = displayMetrics.heightPixels
// connectionsMapLayout.translationX = - dpToPx(1500)+screenWidth/2
// connectionsMapLayout.translationY = - dpToPx(1500)+screenHeight/2
// }
//关系图界面的顶部菜单
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.result_toolbar, menu)
return true
}
//顶部菜单的功能
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
//打开侧边菜单
android.R.id.home -> {val draLayout=findViewById<DrawerLayout>(R.id.resultShow)
draLayout.openDrawer(GravityCompat.START)}
//添加人物
R.id.addHuman -> {val intent=Intent(this,PopAddHumanActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)}
//待定...
R.id.delHuman -> Toast.makeText(this, "You clicked delHuman",
Toast.LENGTH_SHORT).show()
}
return true
}
}
| 0 | Kotlin | 0 | 0 | 9271f39e8a8470c8e03bba82a5783294c4d781b2 | 14,532 | ConnectionsManagement | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/unit/transformer/DocumentTransformerTest.kt | ministryofjustice | 515,276,548 | false | {"Kotlin": 6885855, "Shell": 8075, "Dockerfile": 1780} | package uk.gov.justice.digital.hmpps.approvedpremisesapi.unit.transformer
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.Document
import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.DocumentLevel
import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.DocumentFactory
import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.GroupedDocumentsFactory
import uk.gov.justice.digital.hmpps.approvedpremisesapi.transformer.DocumentTransformer
import java.time.Instant
import java.time.LocalDateTime
import java.util.UUID
class DocumentTransformerTest {
private val documentTransformer = DocumentTransformer()
@Test
fun `transformToApi transforms correctly - filters out convictions other than one specified`() {
val groupedDocuments = GroupedDocumentsFactory()
.withOffenderLevelDocument(
DocumentFactory()
.withId(UUID.fromString("b0df5ec4-5685-4b02-8a95-91b6da80156f").toString())
.withDocumentName("offender_level_doc.pdf")
.withTypeCode("TYPE-1")
.withTypeDescription("Type 1 Description")
.withCreatedAt(LocalDateTime.parse("2022-12-07T11:40:00"))
.withExtendedDescription("Extended Description 1")
.produce(),
)
.withConvictionLevelDocument(
"12345",
DocumentFactory()
.withId(UUID.fromString("457af8a5-82b1-449a-ad03-032b39435865").toString())
.withDocumentName("conviction_level_doc.pdf")
.withoutAuthor()
.withTypeCode("TYPE-2")
.withTypeDescription("Type 2 Description")
.withCreatedAt(LocalDateTime.parse("2022-12-07T10:40:00"))
.withExtendedDescription("Extended Description 2")
.produce(),
)
.withConvictionLevelDocument(
"6789",
DocumentFactory()
.withId(UUID.fromString("e20589b3-7f83-4502-a0df-c8dd645f3f44").toString())
.withDocumentName("conviction_level_doc_2.pdf")
.withTypeCode("TYPE-2")
.withTypeDescription("Type 2 Description")
.withCreatedAt(LocalDateTime.parse("2022-12-07T10:40:00"))
.withExtendedDescription("Extended Description 2")
.produce(),
)
.produce()
val result = documentTransformer.transformToApi(groupedDocuments, 12345)
assertThat(result).containsExactlyInAnyOrder(
Document(
id = UUID.fromString("b0df5ec4-5685-4b02-8a95-91b6da80156f").toString(),
level = DocumentLevel.offender,
fileName = "offender_level_doc.pdf",
createdAt = Instant.parse("2022-12-07T11:40:00Z"),
typeCode = "TYPE-1",
typeDescription = "Type 1 Description",
description = "Extended Description 1",
),
Document(
id = UUID.fromString("457af8a5-82b1-449a-ad03-032b39435865").toString(),
level = DocumentLevel.conviction,
fileName = "conviction_level_doc.pdf",
createdAt = Instant.parse("2022-12-07T10:40:00Z"),
typeCode = "TYPE-2",
typeDescription = "Type 2 Description",
description = "Extended Description 2",
),
)
}
}
| 9 | Kotlin | 1 | 4 | bc7d57577d3f4c2521132c4a3da340e23729b0e5 | 3,223 | hmpps-approved-premises-api | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/apigatewayv2/ApiMappingPropsDsl.kt | F43nd1r | 643,016,506 | false | {"Kotlin": 5407210} | package com.faendir.awscdkkt.generated.services.apigatewayv2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.apigatewayv2.ApiMappingProps
@Generated
public fun buildApiMappingProps(initializer: @AwsCdkDsl ApiMappingProps.Builder.() -> Unit = {}):
ApiMappingProps = ApiMappingProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 4 | e80fe2769852069fdf68382f2ee677cc32dbe73f | 408 | aws-cdk-kt | Apache License 2.0 |
application/src/main/kotlin/tw/waterballsa/gaas/application/usecases/GetRoomsUseCase.kt | Game-as-a-Service | 623,554,204 | false | null | package tw.waterballsa.gaas.application.usecases
import tw.waterballsa.gaas.application.model.Pagination
import tw.waterballsa.gaas.application.repositories.RoomRepository
import tw.waterballsa.gaas.domain.Room
import javax.inject.Named
@Named
class GetRoomsUseCase(
private val roomRepository: RoomRepository,
) {
fun execute(request: Request, presenter: GetRoomsPresenter) =
roomRepository.findByStatus(request.status, request.toPagination())
.also { presenter.present(it) }
class Request(
val status: Room.Status,
val page: Int,
val offset: Int
)
interface GetRoomsPresenter {
fun present(rooms: Pagination<Room>)
}
}
private fun GetRoomsUseCase.Request.toPagination(): Pagination<Any> =
Pagination(page, offset)
| 17 | null | 7 | 30 | 7ade0300a63adc7345349e9af2923b32b5f05a6e | 802 | Lobby-Platform-Service | Apache License 2.0 |
src/main/kotlin/com/atlassian/performance/tools/infrastructure/api/browser/Chrome.kt | konradmars | 411,616,266 | true | {"Kotlin": 167481} | package com.atlassian.performance.tools.infrastructure.api.browser
import com.atlassian.performance.tools.infrastructure.ChromedriverInstaller
import com.atlassian.performance.tools.infrastructure.api.os.Ubuntu
import com.atlassian.performance.tools.ssh.api.SshConnection
import java.net.URI
import java.time.Duration.ofMinutes
/**
* We have no control over the chrome version. We install the latest stable chrome version. It may cause not repeatable builds.
*/
class Chrome : Browser {
private val ubuntu = Ubuntu()
override fun install(ssh: SshConnection) {
ubuntu.addKey(ssh, "<KEY>")
ubuntu.addRepository(ssh, "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main", "google-chrome")
Ubuntu().install(ssh, listOf("google-chrome-stable"), ofMinutes(5))
val installedMinorVersion = getInstalledMinorVersion(ssh)
val version = ChromedriverInstaller.getLatestVersion(installedMinorVersion)
ChromedriverInstaller(URI("https://chromedriver.storage.googleapis.com/$version/chromedriver_linux64.zip")).install(ssh)
}
private fun getInstalledMinorVersion(ssh: SshConnection): String? {
val versionString = ssh.execute("/usr/bin/google-chrome --version").output
return Regex("Google Chrome ([0-9]+\\.[0-9]+\\.[0-9]+)\\.[0-9]+").find(versionString)?.groupValues?.getOrNull(1)
}
}
| 0 | null | 0 | 0 | 861bef3a23c541d01e2d3f8f18efe1ef2a3002ec | 1,380 | infrastructure | Apache License 2.0 |
viewmodel/src/commonMain/kotlin/tech/skot/core/components/SKScreen.kt | skot-framework | 235,318,194 | false | {"Kotlin": 773248, "Shell": 117} | package tech.skot.core.components
import tech.skot.core.components.presented.SKBottomSheet
import tech.skot.core.components.presented.SKDialog
import tech.skot.core.view.SKTransition
abstract class SKScreen<V : SKScreenVC>: SKComponent<SKScreenVC>(), SKVisiblityListener {
var parent: SKStack? = null
var presenterBottomSheet: SKBottomSheet? = null
var presenterDialog: SKDialog? = null
//CallSuper!!
override fun onResume(){
}
//CallSuper!!
override fun onPause(){
}
fun push(screen: SKScreen<*>) {
parent?.push(screen) ?:
SKRootStack.push(screen)
// throw IllegalStateException("This ${this::class.simpleName} has currently no stack parent")
}
fun removeAllScreensOnTop() {
parent?.let { stack ->
val currentStackScreens = stack.state.screens
val indexOfThisScreen = currentStackScreens.indexOf(this)
if (indexOfThisScreen != -1 && currentStackScreens.size > indexOfThisScreen + 1) {
stack.state = SKStack.State(screens = currentStackScreens.subList(0, indexOfThisScreen +1))
}
} ?: throw IllegalStateException("This ${this::class.simpleName} has currently no stack parent")
}
fun replaceWith(screen: SKScreen<*>) {
parent?.replace(this, screen) ?: throw IllegalStateException("This ${this::class.simpleName} has currently no stack parent")
}
fun finish(transition:SKTransition? = null) {
parent?.remove(this, transition) ?: throw IllegalStateException("This ${this::class.simpleName} has currently no stack parent")
}
fun finishIfInAStack() {
parent?.remove(this)
}
fun dismiss() {
presenterBottomSheet?.dismiss() ?: presenterDialog?.dismiss() ?: throw IllegalStateException("This ${this::class.simpleName} is not currently displayed as a BottomSheet or Dialog")
}
@Deprecated("User dismissIfPresented instead")
fun dismissIfBottomSheet() {
presenterBottomSheet?.dismiss()
}
fun dismissIfPresented() {
presenterBottomSheet?.dismiss()
presenterDialog?.dismiss()
}
fun kill() {
SKRootStack.state = SKStack.State(emptyList())
}
} | 1 | Kotlin | 4 | 6 | 8fcff82c719c9775e63da9c3808817704068cbba | 2,229 | skot | Apache License 2.0 |
tests/comparison.kt | gaultier | 306,967,556 | false | {"C": 199555, "Kotlin": 8333, "Makefile": 2654, "DTrace": 1635, "Dockerfile": 526} | fun main() {
println(1 < 2) // expect: true
println(5 >= 5) // expect: true
println(5 >= 6) // expect: false
println(0 <= 0) // expect: true
println(0>1) // expect: false
println(100>=999) // expect: false
println(1 == 1) // expect: true
println(0>1 == 100>=999) // expect: true
println(2 != 2) // expect: false
println(2 != 3) // expect: true
}
| 0 | C | 0 | 4 | 67c65e046c26923e376fa7b7f3e842459b572759 | 348 | microkt | Creative Commons Zero v1.0 Universal |
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/GithubMarkdownCss.kt | ingokegel | 72,937,917 | true | null | /*
* 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.intellij.datavis.r.inlays.components
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.util.*
/** github-markdown.css as String, dependent form current IDE theme. */
class GithubMarkdownCss {
companion object {
private var storedCss: String? = null
private var isStoredDarkula = false
private fun getResourceAsString(resource: String): String {
val inputStream = GithubMarkdownCss::class.java.classLoader.getResourceAsStream(resource)
val scanner = Scanner(inputStream).useDelimiter("\\A")
return if (scanner.hasNext()) scanner.next() else ""
}
val css: String
get() {
if (storedCss != null && isStoredDarkula == UIUtil.isUnderDarcula()) {
return storedCss!!
}
storedCss = if (UIUtil.isUnderDarcula()) {
isStoredDarkula = true
getResourceAsString("/css/github-darcula.css")
}
else {
getResourceAsString("/css/github-intellij.css")
}
val index = storedCss!!.indexOf("font-size: 16px;")
if (index != -1) {
storedCss = storedCss!!.replaceRange(index + 11, index + 13, JBUI.scaleFontSize(14f).toString())
}
return storedCss!!
}
}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,411 | intellij-community | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.