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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/mindorks/framework/mvp/data/network/ApiHelper.kt | janishar | 115,260,052 | false | {"Kotlin": 103126} | package com.mindorks.framework.mvp.data.network
import io.reactivex.Observable
/**
* Created by jyotidubey on 04/01/18.
*/
interface ApiHelper {
fun performServerLogin(request: LoginRequest.ServerLoginRequest): Observable<LoginResponse>
fun performFBLogin(request: LoginRequest.FacebookLoginRequest): Observable<LoginResponse>
fun performGoogleLogin(request: LoginRequest.GoogleLoginRequest): Observable<LoginResponse>
fun performLogoutApiCall(): Observable<LogoutResponse>
fun getBlogApiCall(): Observable<BlogResponse>
fun getOpenSourceApiCall(): Observable<OpenSourceResponse>
} | 17 | Kotlin | 199 | 702 | 5ac97334d417aff636dd587c82ad97c661c38666 | 616 | android-kotlin-mvp-architecture | Apache License 2.0 |
app/src/main/java/de/jannis_jahr/motioncapturingapp/ui/user/UserFragment.kt | Sinnaj94 | 323,361,585 | false | null | package de.jannis_jahr.motioncapturingapp.ui.user
import android.net.Uri
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import de.jannis_jahr.motioncapturingapp.R
import de.jannis_jahr.motioncapturingapp.ui.observers.AddVideoObservable
import de.jannis_jahr.motioncapturingapp.ui.observers.AddVideoObserver
class UserFragment : Fragment(), AddVideoObservable {
var path : Uri? = null
override val observers: ArrayList<AddVideoObserver> = arrayListOf()
private lateinit var userViewModel: UserViewModel
companion object {
val TAG = "ADD_FRAGMENT"
val Image_Capture_Code = 1
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.send_menu, menu)
super.onCreateOptionsMenu(menu, inflater);
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
} | 0 | Kotlin | 0 | 0 | c88729d3761ed334963c19f778f195c027e1429d | 973 | multipose-service-app | MIT License |
src/main/kotlin/icu/windea/pls/script/formatter/ParadoxScriptBlock.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.script.formatter
import com.intellij.formatting.*
import com.intellij.formatting.Indent
import com.intellij.lang.*
import com.intellij.psi.*
import com.intellij.psi.codeStyle.*
import com.intellij.psi.formatter.common.*
import com.intellij.psi.tree.*
import icu.windea.pls.core.*
import icu.windea.pls.script.*
import icu.windea.pls.script.codeStyle.*
import icu.windea.pls.script.psi.ParadoxScriptElementTypes.*
class ParadoxScriptBlock(
node: ASTNode,
private val settings: CodeStyleSettings,
) : AbstractBlock(node, createWrap(), createAlignment()) {
companion object {
private val MEMBERS = TokenSet.create(SCRIPTED_VARIABLE, PROPERTY, BOOLEAN, INT, FLOAT, STRING, COLOR, INLINE_MATH, PARAMETER, BLOCK, PARAMETER_CONDITION)
private val SEPARATORS = TokenSet.create(EQUAL_SIGN, NOT_EQUAL_SIGN, LT_SIGN, GT_SIGN, LE_SIGN, GE_SIGN, QUESTION_EQUAL_SIGN)
private val INLINE_MATH_OPERATORS = TokenSet.create(PLUS_SIGN, MINUS_SIGN, TIMES_SIGN, DIV_SIGN, MOD_SIGN, LABS_SIGN, RABS_SIGN, LP_SIGN, RP_SIGN)
private val SHOULD_INDENT_PARENT_TYPES = TokenSet.create(BLOCK, PARAMETER_CONDITION)
private val SHOULD_INDENT_TYPES = TokenSet.create(SCRIPTED_VARIABLE, PROPERTY, BOOLEAN, INT, FLOAT, STRING, COLOR, INLINE_MATH, PARAMETER, BLOCK, PARAMETER_CONDITION, COMMENT)
private val SHOULD_CHILD_INDENT_TYPES = TokenSet.create(BLOCK, PARAMETER_CONDITION, PARAMETER_CONDITION_EXPRESSION)
private fun createWrap(): Wrap? {
return null
}
private fun createAlignment(): Alignment? {
return null
}
private fun createSpacingBuilder(settings: CodeStyleSettings): SpacingBuilder {
//变量声明分隔符周围的空格,属性分隔符周围的空格
val customSettings = settings.getCustomSettings(ParadoxScriptCodeStyleSettings::class.java)
return SpacingBuilder(settings, ParadoxScriptLanguage)
.between(MEMBERS, MEMBERS).spaces(1) //封装变量/属性/值/参数条件块之间需要有空格或者换行
.aroundInside(SEPARATORS, SCRIPTED_VARIABLE).spaceIf(customSettings.SPACE_AROUND_SCRIPTED_VARIABLE_SEPARATOR) //间隔符周围按情况可能需要空格
.aroundInside(SEPARATORS, PROPERTY).spaceIf(customSettings.SPACE_AROUND_PROPERTY_SEPARATOR) //间隔符周围按情况可能需要空格
.around(INLINE_MATH_OPERATORS).spaceIf(customSettings.SPACE_AROUND_INLINE_MATH_OPERATOR) //内联数学表达式操作符周围按情况可能需要空格
.between(LEFT_BRACE, RIGHT_BRACE).none()//花括号之间总是不需要空格
.withinPair(LEFT_BRACE, RIGHT_BRACE).spaceIf(customSettings.SPACE_WITHIN_BRACES, true) //花括号内侧按情况可能需要空格
.between(NESTED_LEFT_BRACKET, NESTED_RIGHT_BRACKET).none() //参数条件表达式如果为空则不需要空格(尽管这是语法错误)
.withinPair(NESTED_LEFT_BRACKET, NESTED_RIGHT_BRACKET).spaceIf(customSettings.SPACE_WITHIN_PARAMETER_CONDITION_EXPRESSION_BRACKETS) //参数条件表达式内侧非换行按情况可能需要空格
.between(NESTED_RIGHT_BRACKET, RIGHT_BRACKET).none() //参数条件代码块如果为空则不需要空格
.between(NESTED_RIGHT_BRACKET, MEMBERS).spaceIf(customSettings.SPACE_WITHIN_PARAMETER_CONDITION_BRACKETS, true)
.between(MEMBERS, RIGHT_BRACKET).spaceIf(customSettings.SPACE_WITHIN_PARAMETER_CONDITION_BRACKETS, true)
.between(INLINE_MATH_START, INLINE_MATH_END).none() //内联数字表达式如果为空则不需要空格(尽管这是语法错误)
.withinPair(INLINE_MATH_START, INLINE_MATH_END).spaceIf(customSettings.SPACE_WITHIN_INLINE_MATH_BRACKETS, true) //内联数学表达式内侧按情况可能需要空格
}
}
private val spacingBuilder = createSpacingBuilder(settings)
override fun buildChildren(): List<Block> {
val children = mutableListOf<Block>()
myNode.processChild { node ->
node.takeUnless(TokenType.WHITE_SPACE)?.let { ParadoxScriptBlock(it, settings) }?.also { children.add(it) }
true
}
return children
}
override fun getIndent(): Indent? {
//配置缩进
//block和parameter_condition中的variable、property、value、parameter_condition和comment需要缩进
val elementType = myNode.elementType
val parentElementType = myNode.treeParent?.elementType
return when {
parentElementType in SHOULD_INDENT_PARENT_TYPES && elementType in SHOULD_INDENT_TYPES -> Indent.getNormalIndent()
else -> Indent.getNoneIndent()
}
}
override fun getChildIndent(): Indent? {
//配置换行时的自动缩进
//在file和rootBlock中不要缩进
//在block、parameter_condition、parameter_condition_expression中需要缩进
val elementType = myNode.elementType
return when {
elementType is IFileElementType -> Indent.getNoneIndent()
elementType == ROOT_BLOCK -> Indent.getNoneIndent()
elementType in SHOULD_CHILD_INDENT_TYPES -> Indent.getNormalIndent()
else -> null
}
}
override fun getSpacing(child1: Block?, child2: Block): Spacing? {
return spacingBuilder.getSpacing(this, child1, child2)
}
override fun isLeaf(): Boolean {
//顶级块不是叶子节点
return myNode.firstChildNode == null
}
}
| 7 | null | 5 | 41 | 99e8660a23f19642c7164c6d6fcafd25b5af40ee | 5,106 | Paradox-Language-Support | MIT License |
src/de/serienstream/src/eu/kanade/tachiyomi/animeextension/de/serienstream/Serienstream.kt | almightyhak | 817,607,446 | false | null | package eu.kanade.tachiyomi.animeextension.de.serienstream
import android.app.Application
import android.content.SharedPreferences
import android.text.InputType
import android.util.Log
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.lib.doodextractor.DoodExtractor
import eu.kanade.tachiyomi.lib.streamtapeextractor.StreamTapeExtractor
import eu.kanade.tachiyomi.lib.voeextractor.VoeExtractor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
class Serienstream : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val name = "Serienstream"
override val baseUrl = "https://s.to"
private val baseLogin by lazy { SConstants.getPrefBaseLogin(preferences) }
private val basePassword by lazy { SConstants.getPrefBasePassword(preferences) }
override val lang = "de"
override val supportsLatest = true
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
override val client: OkHttpClient = network.client.newBuilder()
.addInterceptor(DdosGuardInterceptor(network.client))
.build()
private val authClient = network.client.newBuilder()
.addInterceptor(SerienstreamInterceptor(client, preferences))
.build()
private val json: Json by injectLazy()
val context = Injekt.get<Application>()
// ===== POPULAR ANIME =====
override fun popularAnimeSelector(): String = "div.seriesListContainer div"
override fun popularAnimeNextPageSelector(): String? = null
override fun popularAnimeRequest(page: Int): Request {
return GET("$baseUrl/beliebte-serien")
}
override fun popularAnimeFromElement(element: Element): SAnime {
context
val anime = SAnime.create()
val linkElement = element.selectFirst("a")
anime.url = linkElement.attr("href")
anime.thumbnail_url = linkElement.selectFirst("img").attr("data-src")
anime.title = element.selectFirst("h3").text()
return anime
}
// ===== LATEST ANIME =====
override fun latestUpdatesSelector(): String = "div.seriesListContainer div"
override fun latestUpdatesNextPageSelector(): String? = null
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/neu")
override fun latestUpdatesFromElement(element: Element): SAnime {
val anime = SAnime.create()
val linkElement = element.selectFirst("a")
anime.url = linkElement.attr("href")
anime.thumbnail_url = baseUrl + linkElement.selectFirst("img").attr("data-src")
anime.title = element.selectFirst("h3").text()
return anime
}
// ===== SEARCH =====
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val headers = Headers.Builder()
.add("Referer", "https://s.to/search")
.add("origin", baseUrl)
.add("connection", "keep-alive")
.add("user-agent", "Mozilla/5.0 (Linux; Android 12; Pixel 5 Build/SP2A.220405.004; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/100.0.4896.127 Safari/537.36")
.add("Upgrade-Insecure-Requests", "1")
.add("content-length", query.length.plus(8).toString())
.add("cache-control", "")
.add("accept", "*/*")
.add("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
.add("x-requested-with", "XMLHttpRequest")
.build()
return POST("$baseUrl/ajax/search", body = FormBody.Builder().add("keyword", query).build(), headers = headers)
}
override fun searchAnimeSelector() = throw UnsupportedOperationException("Not used.")
override fun searchAnimeNextPageSelector() = throw UnsupportedOperationException("Not used.")
override fun searchAnimeParse(response: Response): AnimesPage {
val body = response.body!!.string()
val results = json.decodeFromString<JsonArray>(body)
val animes = results.filter {
val link = it.jsonObject["link"]!!.jsonPrimitive.content
link.startsWith("/serie/stream/") &&
link.count { c -> c == '/' } == 3
}.map {
animeFromSearch(it.jsonObject)
}
return AnimesPage(animes, false)
}
private fun animeFromSearch(result: JsonObject): SAnime {
val anime = SAnime.create()
val title = result["title"]!!.jsonPrimitive.content
val link = result["link"]!!.jsonPrimitive.content
anime.title = title.replace("<em>", "").replace("</em>", "")
val thumpage = client.newCall(GET("$baseUrl$link")).execute().asJsoup()
anime.thumbnail_url = thumpage.selectFirst("div.seriesCoverBox img").attr("data-src")
anime.url = link
return anime
}
override fun searchAnimeFromElement(element: Element) = throw UnsupportedOperationException("Not used.")
// ===== ANIME DETAILS =====
override fun animeDetailsParse(document: Document): SAnime {
val anime = SAnime.create()
anime.title = document.selectFirst("div.series-title h1 span").text()
anime.thumbnail_url = document.selectFirst("div.seriesCoverBox img").attr("data-src")
anime.genre = document.select("div.genres ul li").joinToString { it.text() }
anime.description = document.selectFirst("p.seri_des").attr("data-full-description")
document.selectFirst("div.cast li:contains(Produzent:) ul")?.let {
val author = it.select("li").joinToString { li -> li.text() }
anime.author = author
}
anime.status = SAnime.UNKNOWN
return anime
}
// ===== EPISODE =====
override fun episodeListSelector() = throw UnsupportedOperationException("Not used.")
override fun episodeListParse(response: Response): List<SEpisode> {
val document = response.asJsoup()
val episodeList = mutableListOf<SEpisode>()
val seasonsElements = document.select("#stream > ul:nth-child(1) > li > a")
if (seasonsElements.attr("href").contains("/filme")) {
seasonsElements.forEach {
val seasonEpList = parseMoviesFromSeries(it)
episodeList.addAll(seasonEpList)
}
} else {
seasonsElements.forEach {
val seasonEpList = parseEpisodesFromSeries(it)
episodeList.addAll(seasonEpList)
}
}
return episodeList.reversed()
}
private fun parseEpisodesFromSeries(element: Element): List<SEpisode> {
val seasonId = element.attr("abs:href")
val episodesHtml = authClient.newCall(GET(seasonId)).execute().asJsoup()
val episodeElements = episodesHtml.select("table.seasonEpisodesList tbody tr")
return episodeElements.map { episodeFromElement(it) }
}
private fun parseMoviesFromSeries(element: Element): List<SEpisode> {
val seasonId = element.attr("abs:href")
val episodesHtml = authClient.newCall(GET(seasonId)).execute().asJsoup()
val episodeElements = episodesHtml.select("table.seasonEpisodesList tbody tr")
return episodeElements.map { episodeFromElement(it) }
}
override fun episodeFromElement(element: Element): SEpisode {
val episode = SEpisode.create()
if (element.select("td.seasonEpisodeTitle a").attr("href").contains("/film")) {
val num = element.attr("data-episode-season-id")
episode.name = "Film $num" + " : " + element.select("td.seasonEpisodeTitle a span").text()
episode.episode_number = element.attr("data-episode-season-id").toFloat()
episode.url = element.selectFirst("td.seasonEpisodeTitle a").attr("href")
} else {
val season = element.select("td.seasonEpisodeTitle a").attr("href")
.substringAfter("staffel-").substringBefore("/episode")
val num = element.attr("data-episode-season-id")
episode.name = "Staffel $season Folge $num" + " : " + element.select("td.seasonEpisodeTitle a span").text()
episode.episode_number = element.select("td meta").attr("content").toFloat()
episode.url = element.selectFirst("td.seasonEpisodeTitle a").attr("href")
}
return episode
}
// ===== VIDEO SOURCES =====
override fun videoListSelector() = throw UnsupportedOperationException("Not used.")
override fun videoListParse(response: Response): List<Video> {
val document = response.asJsoup()
val redirectlink = document.select("ul.row li")
val videoList = mutableListOf<Video>()
val hosterSelection = preferences.getStringSet(SConstants.HOSTER_SELECTION, null)
val redirectInterceptor = client.newBuilder().addInterceptor(RedirectInterceptor()).build()
redirectlink.forEach {
val langkey = it.attr("data-lang-key")
val language = getlanguage(langkey)
val redirectgs = baseUrl + it.selectFirst("a.watchEpisode").attr("href")
val redirects = redirectInterceptor.newCall(GET(redirectgs)).execute().request.url.toString()
if (hosterSelection != null) {
when {
redirects.contains("https://voe.sx") || redirects.contains("https://launchreliantcleaverriver") ||
redirects.contains("https://fraudclatterflyingcar") && hosterSelection.contains(SConstants.NAME_VOE) -> {
val quality = "Voe $language"
val video = VoeExtractor(client).videoFromUrl(redirects, quality)
if (video != null) {
videoList.add(video)
}
}
redirects.contains("https://dood") && hosterSelection.contains(SConstants.NAME_DOOD) -> {
val quality = "Doodstream $language"
val video = DoodExtractor(client).videoFromUrl(redirects, quality)
if (video != null) {
videoList.add(video)
}
}
redirects.contains("https://streamtape") && hosterSelection.contains(SConstants.NAME_STAPE) -> {
val quality = "Streamtape $language"
val video = StreamTapeExtractor(client).videoFromUrl(redirects, quality)
if (video != null) {
videoList.add(video)
}
}
}
}
}
return videoList
}
private fun getlanguage(langkey: String): String? {
when {
langkey.contains("${SConstants.KEY_GER_SUB}") -> {
return "Deutscher Sub"
}
langkey.contains("${SConstants.KEY_GER_DUB}") -> {
return "Deutscher Dub"
}
langkey.contains("${SConstants.KEY_ENG_SUB}") -> {
return "Englischer Sub"
}
else -> {
return null
}
}
}
override fun videoFromElement(element: Element): Video = throw Exception("not Used")
override fun List<Video>.sort(): List<Video> {
val hoster = preferences.getString(SConstants.PREFERRED_HOSTER, null)
val subPreference = preferences.getString(SConstants.PREFERRED_LANG, "Sub")!!
val hosterList = mutableListOf<Video>()
val otherList = mutableListOf<Video>()
if (hoster != null) {
for (video in this) {
if (video.url.contains(hoster)) {
hosterList.add(video)
} else {
otherList.add(video)
}
}
} else otherList += this
val newList = mutableListOf<Video>()
var preferred = 0
for (video in hosterList) {
if (video.quality.contains(subPreference)) {
newList.add(preferred, video)
preferred++
} else newList.add(video)
}
for (video in otherList) {
if (video.quality.contains(subPreference)) {
newList.add(preferred, video)
preferred++
} else newList.add(video)
}
return newList
}
override fun videoUrlParse(document: Document): String = throw UnsupportedOperationException("Not used.")
// ===== PREFERENCES ======
@Suppress("UNCHECKED_CAST")
override fun setupPreferenceScreen(screen: PreferenceScreen) {
val hosterPref = ListPreference(screen.context).apply {
key = SConstants.PREFERRED_HOSTER
title = "Standard-Hoster"
entries = SConstants.HOSTER_NAMES
entryValues = SConstants.HOSTER_URLS
setDefaultValue(SConstants.URL_STAPE)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
val subPref = ListPreference(screen.context).apply {
key = SConstants.PREFERRED_LANG
title = "Bevorzugte Sprache"
entries = SConstants.LANGS
entryValues = SConstants.LANGS
setDefaultValue(SConstants.LANG_GER_SUB)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}
val hosterSelection = MultiSelectListPreference(screen.context).apply {
key = SConstants.HOSTER_SELECTION
title = "Hoster auswählen"
entries = SConstants.HOSTER_NAMES
entryValues = SConstants.HOSTER_NAMES
setDefaultValue(SConstants.HOSTER_NAMES.toSet())
setOnPreferenceChangeListener { _, newValue ->
preferences.edit().putStringSet(key, newValue as Set<String>).commit()
}
}
screen.addPreference(screen.editTextPreference(SConstants.LOGIN_TITLE, SConstants.LOGIN_DEFAULT, baseLogin, false, ""))
screen.addPreference(screen.editTextPreference(SConstants.PASSWORD_TITLE, SConstants.PASSWORD_DEFAULT, basePassword, true, ""))
screen.addPreference(subPref)
screen.addPreference(hosterPref)
screen.addPreference(hosterSelection)
}
private fun PreferenceScreen.editTextPreference(title: String, default: String, value: String, isPassword: Boolean = false, placeholder: String): EditTextPreference {
return EditTextPreference(context).apply {
key = title
this.title = title
summary = value.ifEmpty { placeholder }
this.setDefaultValue(default)
dialogTitle = title
if (isPassword) {
setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
}
}
setOnPreferenceChangeListener { _, newValue ->
try {
val res = preferences.edit().putString(title, newValue as String).commit()
Toast.makeText(context, "Starte Aniyomi neu, um die Einstellungen zu übernehmen.", Toast.LENGTH_LONG).show()
res
} catch (e: Exception) {
Log.e("Anicloud", "Fehler beim festlegen der Einstellung.", e)
false
}
}
}
}
}
| 55 | null | 28 | 93 | 507dddff536702999357b17577edc48353eab5ad | 17,130 | aniyomi-extensions | Apache License 2.0 |
sbhyi-akts/src/main/java/com/outs/utils/android/IntentExt.kt | Outs3 | 424,166,410 | false | {"Kotlin": 246550} | package com.outs.utils.android
import android.app.Activity
import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
/**
* author: Outs3
* e-mail: [email protected]
* date: 2021/4/27 15:37
* desc:
*/
fun Activity.injectIntent() = inject(intent?.extras)
inline fun <reified F : Fragment> F.withArgs(vararg pairs: Pair<String, Any>) = this.also {
it.arguments = bundleOf(*pairs)
}
inline fun <reified F : Fragment> F.withArgs(arguments: Bundle) = this.also {
it.arguments = arguments
}
fun Fragment.injectArgs() = inject(arguments)
| 0 | Kotlin | 0 | 4 | 4d26addd6af6f63cc9206b2de88f824f3c7ed0cd | 589 | subahayai | MIT License |
app/src/main/java/com/petnagy/navigatordemo/modules/dashboard/PreferenceFragment.kt | petnagy | 185,669,652 | false | null | package com.petnagy.navigatordemo.modules.dashboard
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.petnagy.navigatordemo.R
import com.petnagy.navigatordemo.databinding.FragmentPreferenceBinding
import com.petnagy.navigatordemo.event.AppEvents
import com.petnagy.navigatordemo.modules.dashboard.viewmodel.PreferenceViewModel
import com.petnagy.navigatordemo.modules.dashboard.viewmodel.PreferenceViewModelFactory
import com.petnagy.navigatordemo.modules.userdata.UserDataActivity
import com.petnagy.navigatordemo.nav.goToOnboarding
import com.petnagy.navigatordemo.nav.goToUserData
import dagger.android.support.DaggerFragment
import timber.log.Timber
import javax.inject.Inject
class PreferenceFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: PreferenceViewModelFactory
private lateinit var viewModel: PreferenceViewModel
companion object {
fun newInstance() = PreferenceFragment()
private const val USER_DATA_REQUEST_CODE = 235
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this, viewModelFactory).get(PreferenceViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding: FragmentPreferenceBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_preference, container, false)
val view = binding.root
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.preferenceEvent.observe(viewLifecycleOwner, Observer { event ->
event.getContentIfNotHandled()?.let {
when(it) {
AppEvents.REQUEST_USER_DATA -> requestUserData()
AppEvents.LOGOUT_PRESSED -> logout()
else -> {
// do not implemented
}
}
}
})
}
private fun logout() {
context?.let {
val intent = goToOnboarding(it)
activity?.startActivity(intent)
activity?.finish()
}
}
private fun requestUserData() {
context?.let {
val intent = goToUserData(it)
startActivityForResult(intent, USER_DATA_REQUEST_CODE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Timber.d("on activity result")
if (requestCode == USER_DATA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
data?.let {
Timber.d("There is intent: $it")
val userData = it.getStringExtra(UserDataActivity.USER_NAME_TEXT) ?: ""
viewModel.saveUserData(userData)
}
}
}
} | 0 | Kotlin | 0 | 0 | 5e62c771dc4c7a3d606d079c3ea7e6987b15f263 | 3,306 | navigator | Apache License 2.0 |
lcc-content/src/main/kotlin/com/joshmanisdabomb/lcc/abstracts/challenges/MinesweeperAltarChallenge.kt | joshmanisdabomb | 537,458,013 | false | {"Kotlin": 2724329, "Java": 138822} | package com.joshmanisdabomb.lcc.abstracts.challenges
import com.joshmanisdabomb.lcc.block.BombBoardBlock
import com.joshmanisdabomb.lcc.block.entity.SapphireAltarBlockEntity
import com.joshmanisdabomb.lcc.directory.LCCBlocks
import com.joshmanisdabomb.lcc.directory.LCCCriteria
import com.joshmanisdabomb.lcc.extensions.NBT_STRING
import com.joshmanisdabomb.lcc.extensions.addString
import com.joshmanisdabomb.lcc.extensions.transform
import com.joshmanisdabomb.lcc.extensions.transformInt
import com.joshmanisdabomb.lcc.world.feature.structure.SapphireAltarStructure
import net.minecraft.block.BlockState
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.nbt.NbtCompound
import net.minecraft.nbt.NbtList
import net.minecraft.nbt.NbtString
import net.minecraft.server.world.ServerWorld
import net.minecraft.state.property.Properties
import net.minecraft.text.Text
import net.minecraft.util.math.BlockBox
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Box
import net.minecraft.util.math.Direction
import net.minecraft.util.math.random.Random
import net.minecraft.world.StructureWorldAccess
import net.minecraft.world.World
import kotlin.math.*
class MinesweeperAltarChallenge : AltarChallenge() {
override fun initialData(random: Random, nbt: NbtCompound): NbtCompound {
val a = random.nextInt(5).plus(5).times(2).plus(1)
val b = random.nextInt(4).plus(6).times(2).plus(1)
nbt.putInt("Width", max(a, b))
nbt.putInt("Depth", min(a, b))
return nbt
}
override fun generate(world: StructureWorldAccess, piece: SapphireAltarStructure.Piece, yOffset: Int, boundingBox: BlockBox, data: NbtCompound, random: Random) {
val width = data.getInt("Width")
val depth = data.getInt("Depth")
for (i in 0 until width) {
for (j in 0 until depth) {
piece.addBlock(world, LCCBlocks.bomb_board_block.defaultState.with(Properties.AXIS, Direction.Axis.Y).with(BombBoardBlock.mine_state, 0), i+1, yOffset, j+4, boundingBox)
}
}
}
override fun start(world: World, state: BlockState, pos: BlockPos, be: SapphireAltarBlockEntity, player: PlayerEntity): Boolean {
val data = be.data
val facing = state[Properties.HORIZONTAL_FACING].opposite
val width = data.getInt("Width")
val depth = data.getInt("Depth")
if (!verifyAltar(world, facing, pos, width, depth)) {
player.sendMessage(Text.translatable("block.lcc.sapphire_altar.minesweeper.malformed"), true)
return false
}
var attempts = 0
var board: List<List<Boolean>>
do {
val bombs = (width * depth).toDouble().pow(0.7).times(world.random.nextDouble().times(0.7).plus(0.8)).roundToInt()
board = generateBoard(width, depth, bombs, world.random)
attempts++
println("Attempt $attempts at generating bomb board @ $pos")
} while (attempts < 200 && !solveBoard(board))
if (attempts >= 200) {
player.sendMessage(Text.translatable("block.lcc.sapphire_altar.minesweeper.unsolvable"), true)
return false
}
val pos2 = be.pos.offset(facing, 3).down()
val bbstate = LCCBlocks.bomb_board_block.defaultState.with(Properties.AXIS, Direction.Axis.Y)
foreachPlane(pos2, facing, width, depth) { p, x, y -> world.setBlockState(p, bbstate.with(BombBoardBlock.mine_state, board[x][y].transformInt(BombBoardBlock.mine, BombBoardBlock.mystery)), 18) }
val pos3 = pos2.offset(facing, depth.div(2))
world.setBlockState(pos3, bbstate.with(BombBoardBlock.mine_state, LCCBlocks.bomb_board_block.getAdjacentMines(world, bbstate, pos3)))
val nbtBoard = NbtList()
board.forEach { nbtBoard.addString(it.joinToString("") { it.transform("x", " ") }) }
data.put("Board", nbtBoard)
if (!world.isClient) {
val range = Box(pos).expand(40.0, 40.0, 40.0)
val players = world.server!!.playerManager.playerList
be.challengers = players.filter { it.uuid == player.uuid || (it.world.dimension == world.dimension && range.intersects(it.boundingBox)) }.map { it.uuid }.toMutableList()
}
return true
}
override fun verify(world: World, state: BlockState, pos: BlockPos, be: SapphireAltarBlockEntity): ChallengeState {
val data = be.data
val facing = state[Properties.HORIZONTAL_FACING].opposite
val width = data.getInt("Width")
val depth = data.getInt("Depth")
val nbtBoard = data.getList("Board", NBT_STRING)
val board = nbtBoard.map { (it as? NbtString)?.asString()?.map { it != ' ' } ?: List(width) { false } }
return when (verifyBoard(world, facing, pos, board, width, depth)) {
true -> ChallengeState.COMPLETED
false -> ChallengeState.FAILED
null -> ChallengeState.ACTIVE
}
}
override fun verifyTick(world: World, state: BlockState, pos: BlockPos, be: SapphireAltarBlockEntity): ChallengeState {
val data = be.data
val facing = state[Properties.HORIZONTAL_FACING].opposite
val width = data.getInt("Width")
val depth = data.getInt("Depth")
return if (verifyAltar(world, facing, pos, width, depth)) ChallengeState.ACTIVE else ChallengeState.FAILED_AGGRESSIVE
}
fun generateBoard(width: Int, height: Int, bombs: Int, random: Random): List<List<Boolean>> {
val board = MutableList(width) { MutableList(height) { false } }
for (i in 0 until bombs) {
for (attempt in 0 until 60) {
val x = random.nextInt(width)
val y = random.nextInt(height)
if (board[x][y]) continue
val xd = abs(x - width.div(2))
val yd = abs(y - height.div(2))
if (xd <= 1 && yd <= 1) continue
if (xd <= 3 && yd <= 3 && random.nextInt(5-(xd+yd).div(2)) != 0) continue
board[x][y] = true
break
}
}
return board
}
fun solveBoard(board: List<List<Boolean>>): Boolean {
val width = board.size
val height = board.first().size
val board = board.map { it.map { it.transformInt(-2, -1).toByte() }.toMutableList() }.toMutableList()
//reveal middle tile
if (!solveBoardClick(board, width.div(2), height.div(2))) return false
//run routine
var ideas: Int
do {
ideas = 0
var ideas3x3: Int
do {
ideas3x3 = solveBoard3x3Flag(board)
if (ideas3x3 > 0 && !solveBoard3x3Reveal(board)) {
return false
}
} while (ideas3x3 > 0)
ideas += ideas3x3
/*var ideasTank: Int
do {
ideasTank = 0
val borders = solveBoardTankBorders(board)
solveBoardDebug(board, 9)
} while (false)
ideas += ideasTank*/
if (solveBoardFinished(board)) {
return true
}
} while (ideas > 0)
return false
}
fun solveBoardClick(board: MutableList<MutableList<Byte>>, x: Int, y: Int): Boolean {
val value = board[x][y]
if (value == (-2).toByte() || value == (-4).toByte()) {
return false
} else if (value == (-1).toByte() || value == (-3).toByte()) {
val adjacent = solveBoardAdjacent(board, x, y, -2, -4)
board[x][y] = adjacent
if (adjacent == 0.toByte()) {
for (i in -1..1) {
for (j in -1..1) {
if (i == 0 && j == 0) continue
if (x+i !in board.indices) continue
if (y+j !in board.first().indices) continue
solveBoardClick(board, x+i, y+j)
}
}
}
}
return true
}
fun solveBoardFlag(board: MutableList<MutableList<Byte>>, x: Int, y: Int): Boolean {
val value = board[x][y]
if (value !in -2..-1) return false
board[x][y] = value.minus(2).toByte()
return true
}
fun solveBoardAdjacent(board: List<List<Byte>>, x: Int, y: Int, vararg valid: Byte): Byte {
var count = 0
for (i in -1..1) {
for (j in -1..1) {
if (i == 0 && j == 0) continue
if (valid.any { board.getOrNull(x+i)?.getOrNull(y+j) == it }) count++
}
}
return count.toByte()
}
fun solveBoard3x3Flag(board: MutableList<MutableList<Byte>>): Int {
var count = 0
for (x in board.indices) {
for (y in board[x].indices) {
val value = board[x][y]
if (value <= 0) continue
if (value == solveBoardAdjacent(board, x, y, -1, -2, -3, -4)) {
for (i in -1..1) {
for (j in -1..1) {
if (i == 0 && j == 0) continue
if (x+i !in board.indices) continue
if (y+j !in board.first().indices) continue
if (solveBoardFlag(board, x+i, y+j)) count++
}
}
}
}
}
return count
}
fun solveBoard3x3Reveal(board: MutableList<MutableList<Byte>>): Boolean {
for (x in board.indices) {
for (y in board[x].indices) {
val value = board[x][y]
if (value <= 0) continue
if (value == solveBoardAdjacent(board, x, y, -3, -4)) {
for (i in -1..1) {
for (j in -1..1) {
if (i == 0 && j == 0) continue
if (x+i !in board.indices) continue
if (y+j !in board.first().indices) continue
if (board[x+i][y+j] < -2) continue
if (!solveBoardClick(board, x+i, y+j)) return false
}
}
}
}
}
return true
}
/*fun solveBoardTankBorders(board: List<List<Byte>>): List<List<Pair<Int, Int>>> {
val unsplit = mutableListOf<Pair<Int, Int>>()
for (x in board.indices) {
for (y in board[x].indices) {
val value = board[x][y]
if (value in -2..-1 && solveBoardAdjacent(board, x, y, 0, 1, 2, 3, 4, 5, 6, 7, 8) > 0) {
unsplit.add(Pair(x, y))
}
}
}
val regions = mutableListOf<MutableList<Pair<Int, Int>>>()
val reverse = mutableMapOf<Pair<Int, Int>, Int>()
for (t in unsplit) {
val region = reverse[t] ?: regions.size
reverse[t] = region
for (i in -1..1) {
for (j in -1..1) {
if (i == 0 && j == 0) continue
val t2 = Pair(t.first + i, t.second + j)
if (unsplit.contains(t2)) {
if (region >= regions.size) {
regions.add(mutableListOf())
}
reverse[t2] = region
regions[region].add(t2)
}
}
}
}
for (x in board.indices) {
for (y in board[x].indices) {
val t = Pair(x, y)
if (!reverse.containsKey(t)) continue
(board[x] as MutableList)[y] = reverse[t]?.plus(10)?.toByte() ?: continue
}
}
return regions
}*/
fun solveBoardFinished(board: List<List<Byte>>) = !board.any { it.any { it in -2..-1 } }
/*private fun solveBoardDebug(board: List<List<Byte>>, stage: Int) {
println("Board at Stage $stage")
for (l in board.transpose().asReversed()) {
println(l.joinToString(separator = "") {
when (it.toInt()) {
-4 -> "[F]"
-3 -> "[!]"
-2 -> "[*]"
-1 -> "[-]"
0 -> "[ ]"
else -> "[$it]"
}
})
}
}*/
fun verifyAltar(world: World, facing: Direction, origin: BlockPos, width: Int, depth: Int): Boolean {
var flag = false
foreachPlane(origin.offset(facing, 2).down(), facing, width+2, depth+2) { p, x, y ->
if (flag) return@foreachPlane
val state2 = world.getBlockState(p)
if (x == 0 || x == width+1 || y == 0 || y == depth+1) {
if (!state2.isOf(LCCBlocks.sapphire_altar_brick)) {
flag = true
}
} else {
if (!state2.isOf(LCCBlocks.bomb_board_block) || state2[Properties.AXIS] != Direction.Axis.Y) {
flag = true
}
}
}
return !flag
}
fun verifyBoard(world: World, facing: Direction, origin: BlockPos, board: List<List<Boolean>>, width: Int, depth: Int): Boolean? {
var flag: Boolean? = true
foreachPlane(origin.offset(facing, 3).down(), facing, width, depth) { p, x, y ->
if (flag == false) return@foreachPlane
val state2 = world.getBlockState(p)
when (state2[BombBoardBlock.mine_state]) {
BombBoardBlock.mine -> {
if (!board[x][y]) {
flag = false
}
}
BombBoardBlock.mystery -> {
if (board[x][y]) {
flag = false
}
else flag = null
}
else -> {
if (board[x][y]) flag = false
}
}
}
return flag
}
override fun handleState(cstate: ChallengeState, world: ServerWorld, pos: BlockPos, state: BlockState, entity: SapphireAltarBlockEntity): Boolean {
when (cstate) {
ChallengeState.COMPLETED -> {
val challengers = world.server.playerManager.playerList.filter { entity.challengers?.contains(it.uuid) == true }
challengers.forEach {
LCCCriteria.sapphire_altar.trigger(it, this, cstate.getRewards(state))
}
entity.challengers = null
}
}
return super.handleState(cstate, world, pos, state, entity)
}
} | 0 | Kotlin | 0 | 0 | a836162eaf64a75ca97daffa02c1f9e66bdde1b4 | 14,716 | loosely-connected-concepts | Creative Commons Zero v1.0 Universal |
tea-time-travel-plugin/src/main/java/io/github/xlopec/tea/time/travel/plugin/integration/PluginComponent.kt | Xlopec | 188,455,731 | false | null | /*
* Copyright (C) 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.
*/
@file:Suppress("FunctionName")
package io.github.xlopec.tea.time.travel.plugin.integration
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.trace
import io.github.xlopec.tea.core.Component
import io.github.xlopec.tea.core.Initial
import io.github.xlopec.tea.core.Initializer
import io.github.xlopec.tea.core.Interceptor
import io.github.xlopec.tea.core.Regular
import io.github.xlopec.tea.core.Snapshot
import io.github.xlopec.tea.core.with
import io.github.xlopec.tea.time.travel.plugin.util.PluginId
import io.github.xlopec.tea.time.travel.plugin.util.settings
import io.github.xlopec.tea.time.travel.plugin.model.State
import io.github.xlopec.tea.time.travel.plugin.model.Stopped
import kotlinx.coroutines.Dispatchers.IO
import com.intellij.openapi.diagnostic.Logger as PlatformLogger
fun PluginComponent(
environment: Environment,
properties: PropertiesComponent,
): Component<Message, State, Command> =
Component<Message, Command, State>(
initializer = AppInitializer(properties),
resolver = { c, ctx -> with(environment) { resolve(c, ctx) } },
updater = { m, s -> with(environment) { update(m, s) } },
scope = environment
).with(Logger(PlatformLogger.getInstance(PluginId)))
private fun AppInitializer(
properties: PropertiesComponent
): Initializer<State, Command> =
Initializer(IO) { Initial(Stopped(properties.settings), emptySet()) }
private fun Logger(
logger: PlatformLogger
): Interceptor<Message, State, Command> =
{ snapshot ->
logger.info(snapshot.infoMessage)
logger.debug { snapshot.debugMessage }
logger.trace { snapshot.traceMessage }
}
private val Snapshot<*, *, *>.infoMessage: String
get() = when (this) {
is Initial -> "Init class=${currentState?.javaClass}, commands=${commands.size}"
is Regular -> """
Regular with new state=${currentState?.javaClass},
previousState state=${previousState?.javaClass},
caused by message=${message?.javaClass},
commands=${commands.size}"}
""".trimIndent()
}
private val Snapshot<*, *, *>.debugMessage: String
get() = when (this) {
is Initial -> "Init class=${currentState?.javaClass}" +
if (commands.isEmpty()) "" else ", commands=${commands.joinToString { it?.javaClass.toString() }}"
is Regular -> """
Regular with new state=${currentState?.javaClass},
prev state=${previousState?.javaClass},
caused by message=${message?.javaClass}
${if (commands.isEmpty()) "" else "\ncommands=${commands.joinToString { it?.javaClass.toString() }}"}
""".trimIndent()
}
private val Snapshot<*, *, *>.traceMessage: String
get() = when (this) {
is Initial -> "Init with state=$currentState" +
if (commands.isEmpty()) "" else ", commands=$commands"
is Regular -> """
Regular with new state=$currentState,
previousState state=$previousState,
caused by message=$message
${if (commands.isEmpty()) "" else "\ncommands=$commands"}
""".trimIndent()
}
| 0 | Kotlin | 1 | 10 | 1f0d3bbd4f7ad050a2e39e287a7c19d36dc36ede | 3,775 | Tea-bag | MIT License |
twitter-core/src/main/java/com/twitter/sdk/android/core/internal/oauth/OAuthConstants.kt | takke | 195,917,891 | false | {"Gradle": 8, "INI": 2, "Markdown": 4, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Java Properties": 2, "XML": 79, "Java": 94, "JSON": 13, "Kotlin": 27} | /*
* Copyright (C) 2015 Twitter, 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.twitter.sdk.android.core.internal.oauth
object OAuthConstants {
// OAuth1.0a parameter constants.
const val PARAM_TOKEN = "oauth_token"
const val PARAM_VERIFIER = "oauth_verifier"
}
| 1 | null | 1 | 1 | 33c16785b9adeb3e54299dff85280bdfafce4873 | 814 | simple-twitter-auth-android | Apache License 2.0 |
infra/src/main/kotlin/fr/sacane/jmanager/infrastructure/rest/tag/DTO.kt | Sacane | 531,082,439 | false | {"Kotlin": 115428, "Vue": 43310, "TypeScript": 18019, "JavaScript": 602, "CSS": 134} | package fr.sacane.jmanager.infrastructure.rest.tag
data class TagDTO(
val tagId: Long,
val label: String,
val colorDTO: ColorDTO = ColorDTO(0, 0, 0),
val isDefault: Boolean = false
)
data class ColorDTO(
val red: Int,
val green: Int,
val blue: Int
)
data class UserTagDTO(
val userId: Long,
val tagLabel: String,
val colorDTO: ColorDTO
) | 1 | Kotlin | 0 | 0 | 9238109ddfd0f25846eb8b9acb8e2ba19bb79eb5 | 380 | JManager | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/arnscoordinatorapi/oasys/controller/OasysController.kt | ministryofjustice | 858,719,887 | false | {"Kotlin": 270210, "Makefile": 2528, "Dockerfile": 1185} | package uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.responses.ApiResponses
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.validation.Valid
import jakarta.validation.constraints.Size
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.config.Constraints
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.OasysCoordinatorService
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.request.OasysCounterSignRequest
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.request.OasysCreateRequest
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.request.OasysGenericRequest
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.request.OasysMergeRequest
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.request.OasysRollbackRequest
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.request.OasysSignRequest
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.response.OasysAssociationsResponse
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.response.OasysGetResponse
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.response.OasysMessageResponse
import uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.controller.response.OasysVersionedEntityResponse
import uk.gov.justice.hmpps.kotlin.common.ErrorResponse
@RestController
@Tag(name = "OASys")
@RequestMapping("\${app.self.endpoints.oasys}")
class OasysController(
private val oasysCoordinatorService: OasysCoordinatorService,
) {
@RequestMapping(path = ["/{oasysAssessmentPK}"], method = [RequestMethod.GET])
@Operation(description = "Get the latest version of entities associated with an OASys Assessment PK")
@PreAuthorize("hasRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(
responseCode = "200",
description = "Entities found",
content = arrayOf(Content(schema = Schema(implementation = OasysGetResponse::class))),
),
ApiResponse(
responseCode = "404",
description = "No associated entities were found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun get(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
): ResponseEntity<*> {
return when (val result = oasysCoordinatorService.get(oasysAssessmentPK)) {
is OasysCoordinatorService.GetOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
is OasysCoordinatorService.GetOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result.errorMessage)
is OasysCoordinatorService.GetOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(result.errorMessage)
}
}
@RequestMapping(path = ["/create"], method = [RequestMethod.POST])
@Operation(description = "Create entities and associate them with an OASys assessment PK")
@PreAuthorize("hasRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(
responseCode = "201",
description = "Entities and associations created successfully",
content = arrayOf(Content(schema = Schema(implementation = OasysVersionedEntityResponse::class))),
),
ApiResponse(
responseCode = "404",
description = "Previous association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "An association already exists for the provided OASys Assessment PK",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun create(
@RequestBody @Valid request: OasysCreateRequest,
): ResponseEntity<Any> {
val result = if (request.previousOasysAssessmentPk === null) {
oasysCoordinatorService.create(request)
} else {
oasysCoordinatorService.clone(request)
}
return when (result) {
is OasysCoordinatorService.CreateOperationResult.Success ->
ResponseEntity.status(HttpStatus.CREATED).body(result.data)
is OasysCoordinatorService.CreateOperationResult.ConflictingAssociations ->
ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.CreateOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.CreateOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/merge"], method = [RequestMethod.POST])
@Operation(description = "Transfer associated entities from one PK to another")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Entities associated successfully"),
ApiResponse(
responseCode = "404",
description = "Previous association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "An association already exists for the provided OASys Assessment PK",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun merge(
@RequestBody @Valid request: OasysMergeRequest,
): OasysMessageResponse {
/**
* TODO: Implement logic to merge two or more associated OASys Assessment PKs together
* 1. Loop over each OASys Assessment PK pair
* 2. Update all associations in DB that have old PK, replace with new PK
*/
return OasysMessageResponse("Successfully processed all ${request.merge.size} merge elements")
}
@RequestMapping(path = ["/{oasysAssessmentPK}/sign"], method = [RequestMethod.POST])
@Operation(description = "Signs the latest version of all entities associated with the provided OASys Assessment PK")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(
responseCode = "200",
description = "Entity versions signed successfully",
content = arrayOf(Content(schema = Schema(implementation = OasysVersionedEntityResponse::class))),
),
ApiResponse(
responseCode = "404",
description = "Association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "An entity could not be signed. See details in error message.",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun sign(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
@RequestBody @Valid request: OasysSignRequest,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.sign(request, oasysAssessmentPK)) {
is OasysCoordinatorService.SignOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
is OasysCoordinatorService.SignOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.SignOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.SignOperationResult.Conflict ->
ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/{oasysAssessmentPK}/counter-sign"], method = [RequestMethod.POST])
@Operation(description = "Marks the entity version's as counter-signed.")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Entity versions counter-signed successfully"),
ApiResponse(
responseCode = "404",
description = "Association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "An entity could not be counter-signed. See details in error message.",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun counterSign(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
@RequestBody @Valid request: OasysCounterSignRequest,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.counterSign(oasysAssessmentPK, request)) {
is OasysCoordinatorService.CounterSignOperationResult.Failure -> ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.CounterSignOperationResult.NoAssociations -> ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.CounterSignOperationResult.Success -> ResponseEntity.status(HttpStatus.OK)
.body(result.data)
is OasysCoordinatorService.CounterSignOperationResult.Conflict -> ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/{oasysAssessmentPK}/lock"], method = [RequestMethod.POST])
@Operation(description = "Locks the latest version of all associated entities.")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Entities locked successfully"),
ApiResponse(
responseCode = "404",
description = "Association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "The latest version of an entity has already been locked. See details in error message.",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun lock(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid
oasysAssessmentPK: String,
@RequestBody @Valid
request: OasysGenericRequest,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.lock(request, oasysAssessmentPK)) {
is OasysCoordinatorService.LockOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
is OasysCoordinatorService.LockOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.LockOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.LockOperationResult.Conflict ->
ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/{oasysAssessmentPK}/rollback"], method = [RequestMethod.POST])
@Operation(description = "Create a new \"ROLLBACK\" version of specified entities")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "ROLLBACK version created"),
ApiResponse(
responseCode = "404",
description = "Association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "Unable to create ROLLBACK for latest entity version",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun rollback(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
@RequestBody @Valid
request: OasysRollbackRequest,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.rollback(request, oasysAssessmentPK)) {
is OasysCoordinatorService.RollbackOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
is OasysCoordinatorService.RollbackOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.RollbackOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.RollbackOperationResult.Conflict ->
ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/{oasysAssessmentPK}/soft-delete"], method = [RequestMethod.POST])
@Operation(description = "Soft-deletes associations for OASys Assessment PK")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Associations have been soft-deleted"),
ApiResponse(
responseCode = "404",
description = "Association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "Unable to soft-delete an association that has already been soft-deleted",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun softDelete(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
@RequestBody @Valid request: OasysGenericRequest,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.softDelete(request, oasysAssessmentPK)) {
is OasysCoordinatorService.SoftDeleteOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
is OasysCoordinatorService.SoftDeleteOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.SoftDeleteOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.SoftDeleteOperationResult.Conflict ->
ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/{oasysAssessmentPK}/undelete"], method = [RequestMethod.POST])
@Operation(description = "Undeletes associations for OASys Assessment PK")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Associations have been undeleted"),
ApiResponse(
responseCode = "404",
description = "Association/entity not found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "409",
description = "No associations are marked as deleted, cannot undelete",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun undelete(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
@RequestBody @Valid request: OasysGenericRequest,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.undelete(request, oasysAssessmentPK)) {
is OasysCoordinatorService.UndeleteOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
is OasysCoordinatorService.UndeleteOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(
ErrorResponse(
status = HttpStatus.NOT_FOUND,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.UndeleteOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
userMessage = result.errorMessage,
),
)
is OasysCoordinatorService.UndeleteOperationResult.Conflict ->
ResponseEntity.status(HttpStatus.CONFLICT).body(
ErrorResponse(
status = HttpStatus.CONFLICT,
userMessage = result.errorMessage,
),
)
}
}
@RequestMapping(path = ["/{oasysAssessmentPK}/associations"], method = [RequestMethod.GET])
@Operation(description = "Return the associations for OASys Assessment PK")
@PreAuthorize("hasAnyRole('ROLE_STRENGTHS_AND_NEEDS_OASYS')")
@ApiResponses(
value = [
ApiResponse(
responseCode = "200",
description = "Associations returned",
content = arrayOf(Content(schema = Schema(implementation = OasysAssociationsResponse::class))),
),
ApiResponse(
responseCode = "404",
description = "No associations found",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
ApiResponse(
responseCode = "500",
description = "Unexpected error",
content = arrayOf(Content(schema = Schema(implementation = ErrorResponse::class))),
),
],
)
fun associations(
@Parameter(description = "OASys Assessment PK", required = true, example = "oasys-pk-goes-here")
@PathVariable
@Size(min = Constraints.OASYS_PK_MIN_LENGTH, max = Constraints.OASYS_PK_MAX_LENGTH)
@Valid oasysAssessmentPK: String,
): ResponseEntity<Any> {
return when (val result = oasysCoordinatorService.getAssociations(oasysAssessmentPK)) {
is OasysCoordinatorService.GetOperationResult.Failure ->
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result.errorMessage)
is OasysCoordinatorService.GetOperationResult.NoAssociations ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body(result.errorMessage)
is OasysCoordinatorService.GetOperationResult.Success ->
ResponseEntity.status(HttpStatus.OK).body(result.data)
}
}
}
| 2 | Kotlin | 0 | 0 | c7ce9fdb04301a23268b4c1713e2d7bcb24a83d4 | 24,222 | hmpps-assess-risks-and-needs-coordinator-api | MIT License |
idea/testData/intentions/foldInitializerAndIfToElvis/ifStatementPriority.kt | JakeWharton | 99,388,807 | false | null | // WITH_RUNTIME
fun test(a: String?, b: String): String {
val x = if (true) a else b
<caret>if (x == null) throw Exception()
return x
} | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 147 | kotlin | Apache License 2.0 |
domain/src/main/java/br/com/pebmed/domain/base/usecase/BaseUseCase.kt | PEBMED | 199,354,796 | false | null | package br.com.mobiplus.gitclient.domain.base.usecase
abstract class BaseUseCase<RESULT, PARAMS> : UseCase<RESULT, PARAMS> {
override suspend fun runAsync(): RESULT {
throw InvalidUseCaseCall("If you want to run without params and asynchronously, you should extend NoParamsBaseAsyncUseCase")
}
override fun runSync(): RESULT {
throw InvalidUseCaseCall("If you want to run without params and synchronously, you should extend NoParamsBaseUseCase")
}
override suspend fun runAsync(params: PARAMS): RESULT {
throw InvalidUseCaseCall("If you want to run with params and asynchronously, you should extend BaseAsyncUseCase")
}
} | 2 | Kotlin | 5 | 7 | 424c1405cdc4a27a9ae03d6ec4e64dd48e347109 | 672 | android-base-architecture | MIT License |
app/src/main/java/com/syncday/lab/SecondAdapter.kt | Syncday | 679,389,793 | false | null | package com.syncday.lab
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.syncday.lab.databinding.ItemMainBinding
class SecondAdapter(diffCallback: DiffUtil.ItemCallback<HomeBean> = object : DiffUtil.ItemCallback<HomeBean>() {
override fun areItemsTheSame(oldItem: HomeBean, newItem: HomeBean): Boolean {
return oldItem==newItem
}
override fun areContentsTheSame(oldItem: HomeBean, newItem: HomeBean): Boolean {
return true
}
}) : ListAdapter<HomeBean, SecondAdapter.VH>(diffCallback) {
class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val binding = ItemMainBinding.bind(itemView)
fun bind(data:HomeBean){
binding.title.text = data.title
binding.subTitle.text = data.author
binding.cover.setImageResource(data.resId)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
return VH(LayoutInflater.from(parent.context).inflate(R.layout.item_second,parent,false))
}
override fun onBindViewHolder(holder: VH, position: Int) {
holder.bind(getItem(position))
}
} | 0 | Kotlin | 0 | 0 | f09212748ca8b548cee2fe20f5a5a0d144ccd53f | 1,333 | Android-XML-Theme-RT | MIT License |
common/src/main/kotlin/io/portone/sdk/server/webhook/WebhookVerificationException.kt | portone-io | 809,427,199 | false | {"Kotlin": 385115, "Java": 331} | package io.portone.sdk.server.webhook
/**
* Thrown to indicate that the webhook verification failed.
*/
public class WebhookVerificationException internal constructor(message: String, cause: Throwable? = null) : Exception(message, cause) {
public companion object {
@Suppress("ConstPropertyName")
private const val serialVersionUID: Long = 6521886437375683450L
}
}
| 0 | Kotlin | 0 | 2 | f984c4cc31aa64aad5cd0fa0497bdd490a0fe33a | 392 | server-sdk-jvm | MIT License |
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeFieldPublicFix.kt | ingokegel | 72,937,917 | true | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.elementType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifier
class MakeFieldPublicFix(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.let { property ->
val currentVisibilityModifier = property.visibilityModifier()
if (currentVisibilityModifier != null && currentVisibilityModifier.elementType != KtTokens.PUBLIC_KEYWORD) {
property.removeModifier(currentVisibilityModifier.elementType as KtModifierKeywordToken)
}
if (!KotlinPsiHeuristics.hasAnnotation(property, JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME.shortName())) {
ShortenReferences.DEFAULT.process(
property.addAnnotationEntry(KtPsiFactory(project).createAnnotationEntry("@kotlin.jvm.JvmField"))
)
}
}
}
override fun getText(): String = familyName
override fun getFamilyName(): String = element?.name?.let { KotlinBundle.message("fix.make.field.public", it) } ?: ""
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,914 | intellij-community | Apache License 2.0 |
core/src/main/java/org/linus/core/utils/extension/ModifierExt.kt | Linus-DuJun | 538,978,918 | false | {"Kotlin": 209703} | package org.linus.core.utils.extension
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.isFinite
object Layout {
val bodyMargin: Dp
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0 .. 599 -> 16.dp
in 600 ..904 -> 32.dp
in 905 .. 1239 -> 0.dp
in 1240 .. 1439 -> 200.dp
else -> 0.dp
}
val gutter: Dp
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> 8.dp
in 600..904 -> 16.dp
in 905..1239 -> 16.dp
in 1240..1439 -> 32.dp
else -> 32.dp
}
val bodyMaxWidth: Dp
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> Dp.Infinity
in 600..904 -> Dp.Infinity
in 905..1239 -> 840.dp
in 1240..1439 -> Dp.Infinity
else -> 1040.dp
}
val columns: Int
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> 4
in 600..904 -> 8
else -> 12
}
}
fun Modifier.bodyWidth() = fillMaxWidth()
.wrapContentWidth(align = Alignment.CenterHorizontally)
.composed {
val bodyMaxWidth = Layout.bodyMaxWidth
if (bodyMaxWidth.isFinite) widthIn(max = bodyMaxWidth) else this
}
.composed {
padding(
WindowInsets.systemBars.only(WindowInsetsSides.Horizontal).asPaddingValues()
)
} | 0 | Kotlin | 0 | 1 | 26abe848e5d01f9342882c5c1770eb607a2b822e | 1,828 | CustomerManagerCompose | Apache License 2.0 |
common/kotlinx-coroutines-core-common/src/Await.kt | objcode | 159,731,828 | false | null | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.atomicfu.*
import kotlin.coroutines.*
/**
* Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values
* when all deferred computations are complete or resumes with the first thrown exception if any of computations
* complete exceptionally including cancellation.
*
* This function is **not** equivalent to `deferreds.map { it.await() }` which fails only when it sequentially
* gets to wait for the failing deferred, while this `awaitAll` fails immediately as soon as any of the deferreds fail.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun <T> awaitAll(vararg deferreds: Deferred<T>): List<T> =
if (deferreds.isEmpty()) emptyList() else AwaitAll(deferreds).await()
/**
* Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values
* when all deferred computations are complete or resumes with the first thrown exception if any of computations
* complete exceptionally including cancellation.
*
* This function is **not** equivalent to `this.map { it.await() }` which fails only when when it sequentially
* gets to wait the failing deferred, while this `awaitAll` fails immediately as soon as any of the deferreds fail.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun <T> Collection<Deferred<T>>.awaitAll(): List<T> =
if (isEmpty()) emptyList() else AwaitAll(toTypedArray()).await()
/**
* Suspends current coroutine until all given jobs are complete.
* This method is semantically equivalent to joining all given jobs one by one with `jobs.forEach { it.join() }`.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun joinAll(vararg jobs: Job): Unit = jobs.forEach { it.join() }
/**
* Suspends current coroutine until all given jobs are complete.
* This method is semantically equivalent to joining all given jobs one by one with `forEach { it.join() }`.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun Collection<Job>.joinAll(): Unit = forEach { it.join() }
private class AwaitAll<T>(private val deferreds: Array<out Deferred<T>>) {
private val notCompletedCount = atomic(deferreds.size)
suspend fun await(): List<T> = suspendCancellableCoroutine { cont ->
// Intricate dance here
// Step 1: Create nodes and install them as completion handlers, they may fire!
val nodes = Array(deferreds.size) { i ->
val deferred = deferreds[i]
deferred.start() // To properly await lazily started deferreds
AwaitAllNode(cont).apply {
handle = deferred.invokeOnCompletion(asHandler)
}
}
val disposer = DisposeHandlersOnCancel(nodes)
// Step 2: Set disposer to each node
nodes.forEach { it.disposer = disposer }
// Here we know that if any code the nodes complete, it will dispose the rest
// Step 3: Now we can check if continuation is complete
if (cont.isCompleted) {
// it is already complete while handlers were being installed -- dispose them all
disposer.disposeAll()
} else {
cont.invokeOnCancellation(handler = disposer.asHandler)
}
}
private inner class DisposeHandlersOnCancel(private val nodes: Array<AwaitAllNode>) : CancelHandler() {
fun disposeAll() {
nodes.forEach { it.handle.dispose() }
}
override fun invoke(cause: Throwable?) { disposeAll() }
override fun toString(): String = "DisposeHandlersOnCancel[$nodes]"
}
private inner class AwaitAllNode(private val continuation: CancellableContinuation<List<T>>) : JobNode() {
lateinit var handle: DisposableHandle
private val _disposer = atomic<DisposeHandlersOnCancel?>(null)
var disposer: DisposeHandlersOnCancel?
get() = _disposer.value
set(value) { _disposer.value = value }
override fun invoke(cause: Throwable?) {
if (cause != null) {
val token = continuation.tryResumeWithException(cause)
if (token != null) {
continuation.completeResume(token)
// volatile read of disposer AFTER continuation is complete
// and if disposer was already set (all handlers where already installed, then dispose them all)
disposer?.disposeAll()
}
} else if (notCompletedCount.decrementAndGet() == 0) {
continuation.resume(deferreds.map { it.getCompleted() })
// Note that all deferreds are complete here, so we don't need to dispose their nodes
}
}
}
}
| 295 | null | 2 | 5 | 46741db4b0c2863475d5cc6fc75eafadd8e6199d | 6,486 | kotlinx.coroutines | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/neptune/CfnDBInstanceDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.neptune
import cloudshift.awscdk.common.CdkDslMarker
import cloudshift.awscdk.dsl.CfnTagDsl
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.neptune.CfnDBInstance
import software.constructs.Construct
/**
* The `AWS::Neptune::DBInstance` type creates an Amazon Neptune DB instance.
*
* *Updating DB Instances*
*
* You can set a deletion policy for your DB instance to control how AWS CloudFormation handles the
* instance when the stack is deleted. For Neptune DB instances, you can choose to *retain* the
* instance, to *delete* the instance, or to *create a snapshot* of the instance. The default AWS
* CloudFormation behavior depends on the `DBClusterIdentifier` property:
*
* * For `AWS::Neptune::DBInstance` resources that don't specify the `DBClusterIdentifier` property,
* AWS CloudFormation saves a snapshot of the DB instance.
* * For `AWS::Neptune::DBInstance` resources that do specify the `DBClusterIdentifier` property,
* AWS CloudFormation deletes the DB instance.
*
* *Deleting DB Instances*
*
*
* If a DB instance is deleted or replaced during an update, AWS CloudFormation deletes all
* automated snapshots. However, it retains manual DB snapshots. During an update that requires
* replacement, you can apply a stack policy to prevent DB instances from being replaced.
*
*
* When properties labeled *Update requires: Replacement* are updated, AWS CloudFormation first
* creates a replacement DB instance, changes references from other dependent resources to point to the
* replacement DB instance, and finally deletes the old DB instance.
*
*
* We highly recommend that you take a snapshot of the database before updating the stack. If you
* don't, you lose the data when AWS CloudFormation replaces your DB instance. To preserve your data,
* perform the following procedure:
*
* * Deactivate any applications that are using the DB instance so that there's no activity on the
* DB instance.
* * Create a snapshot of the DB instance.
* * If you want to restore your instance using a DB snapshot, modify the updated template with your
* DB instance changes and add the `DBSnapshotIdentifier` property with the ID of the DB snapshot that
* you want to use.
* * Update the stack.
*
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.neptune.*;
* CfnDBInstance cfnDBInstance = CfnDBInstance.Builder.create(this, "MyCfnDBInstance")
* .dbInstanceClass("dbInstanceClass")
* // the properties below are optional
* .allowMajorVersionUpgrade(false)
* .autoMinorVersionUpgrade(false)
* .availabilityZone("availabilityZone")
* .dbClusterIdentifier("dbClusterIdentifier")
* .dbInstanceIdentifier("dbInstanceIdentifier")
* .dbParameterGroupName("dbParameterGroupName")
* .dbSnapshotIdentifier("dbSnapshotIdentifier")
* .dbSubnetGroupName("dbSubnetGroupName")
* .preferredMaintenanceWindow("preferredMaintenanceWindow")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html)
*/
@CdkDslMarker
public class CfnDBInstanceDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnDBInstance.Builder = CfnDBInstance.Builder.create(scope, id)
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* Indicates that major version upgrades are allowed.
*
* Changing this parameter doesn't result in an outage and the change is asynchronously applied as
* soon as possible. This parameter must be set to true when specifying a value for the EngineVersion
* parameter that is a different major version than the DB instance's current version.
*
* When you change this parameter for an existing DB cluster, CloudFormation will replace your
* existing DB cluster with a new, empty one that uses the engine version you specified.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-allowmajorversionupgrade)
* @param allowMajorVersionUpgrade Indicates that major version upgrades are allowed.
*/
public fun allowMajorVersionUpgrade(allowMajorVersionUpgrade: Boolean) {
cdkBuilder.allowMajorVersionUpgrade(allowMajorVersionUpgrade)
}
/**
* Indicates that major version upgrades are allowed.
*
* Changing this parameter doesn't result in an outage and the change is asynchronously applied as
* soon as possible. This parameter must be set to true when specifying a value for the EngineVersion
* parameter that is a different major version than the DB instance's current version.
*
* When you change this parameter for an existing DB cluster, CloudFormation will replace your
* existing DB cluster with a new, empty one that uses the engine version you specified.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-allowmajorversionupgrade)
* @param allowMajorVersionUpgrade Indicates that major version upgrades are allowed.
*/
public fun allowMajorVersionUpgrade(allowMajorVersionUpgrade: IResolvable) {
cdkBuilder.allowMajorVersionUpgrade(allowMajorVersionUpgrade)
}
/**
* Indicates that minor version patches are applied automatically.
*
* When updating this property, some interruptions may occur.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-autominorversionupgrade)
* @param autoMinorVersionUpgrade Indicates that minor version patches are applied automatically.
*/
public fun autoMinorVersionUpgrade(autoMinorVersionUpgrade: Boolean) {
cdkBuilder.autoMinorVersionUpgrade(autoMinorVersionUpgrade)
}
/**
* Indicates that minor version patches are applied automatically.
*
* When updating this property, some interruptions may occur.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-autominorversionupgrade)
* @param autoMinorVersionUpgrade Indicates that minor version patches are applied automatically.
*/
public fun autoMinorVersionUpgrade(autoMinorVersionUpgrade: IResolvable) {
cdkBuilder.autoMinorVersionUpgrade(autoMinorVersionUpgrade)
}
/**
* Specifies the name of the Availability Zone the DB instance is located in.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-availabilityzone)
* @param availabilityZone Specifies the name of the Availability Zone the DB instance is located
* in.
*/
public fun availabilityZone(availabilityZone: String) {
cdkBuilder.availabilityZone(availabilityZone)
}
/**
* If the DB instance is a member of a DB cluster, contains the name of the DB cluster that the DB
* instance is a member of.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-dbclusteridentifier)
* @param dbClusterIdentifier If the DB instance is a member of a DB cluster, contains the name of
* the DB cluster that the DB instance is a member of.
*/
public fun dbClusterIdentifier(dbClusterIdentifier: String) {
cdkBuilder.dbClusterIdentifier(dbClusterIdentifier)
}
/**
* Contains the name of the compute and memory capacity class of the DB instance.
*
* If you update this property, some interruptions may occur.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-dbinstanceclass)
* @param dbInstanceClass Contains the name of the compute and memory capacity class of the DB
* instance.
*/
public fun dbInstanceClass(dbInstanceClass: String) {
cdkBuilder.dbInstanceClass(dbInstanceClass)
}
/**
* Contains a user-supplied database identifier.
*
* This identifier is the unique key that identifies a DB instance.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-dbinstanceidentifier)
* @param dbInstanceIdentifier Contains a user-supplied database identifier.
*/
public fun dbInstanceIdentifier(dbInstanceIdentifier: String) {
cdkBuilder.dbInstanceIdentifier(dbInstanceIdentifier)
}
/**
* The name of an existing DB parameter group or a reference to an AWS::Neptune::DBParameterGroup
* resource created in the template.
*
* If any of the data members of the referenced parameter group are changed during an update, the
* DB instance might need to be restarted, which causes some interruption. If the parameter group
* contains static parameters, whether they were changed or not, an update triggers a reboot.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-dbparametergroupname)
* @param dbParameterGroupName The name of an existing DB parameter group or a reference to an
* AWS::Neptune::DBParameterGroup resource created in the template.
*/
public fun dbParameterGroupName(dbParameterGroupName: String) {
cdkBuilder.dbParameterGroupName(dbParameterGroupName)
}
/**
* This parameter is not supported.
*
* `AWS::Neptune::DBInstance` does not support restoring from snapshots.
*
* `AWS::Neptune::DBCluster` does support restoring from snapshots.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-dbsnapshotidentifier)
* @param dbSnapshotIdentifier This parameter is not supported.
*/
public fun dbSnapshotIdentifier(dbSnapshotIdentifier: String) {
cdkBuilder.dbSnapshotIdentifier(dbSnapshotIdentifier)
}
/**
* A DB subnet group to associate with the DB instance.
*
* If you update this value, the new subnet group must be a subnet group in a new virtual private
* cloud (VPC).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-dbsubnetgroupname)
* @param dbSubnetGroupName A DB subnet group to associate with the DB instance.
*/
public fun dbSubnetGroupName(dbSubnetGroupName: String) {
cdkBuilder.dbSubnetGroupName(dbSubnetGroupName)
}
/**
* Specifies the weekly time range during which system maintenance can occur, in Universal
* Coordinated Time (UTC).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-preferredmaintenancewindow)
* @param preferredMaintenanceWindow Specifies the weekly time range during which system
* maintenance can occur, in Universal Coordinated Time (UTC).
*/
public fun preferredMaintenanceWindow(preferredMaintenanceWindow: String) {
cdkBuilder.preferredMaintenanceWindow(preferredMaintenanceWindow)
}
/**
* An arbitrary set of tags (key-value pairs) for this DB instance.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-tags)
* @param tags An arbitrary set of tags (key-value pairs) for this DB instance.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* An arbitrary set of tags (key-value pairs) for this DB instance.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html#cfn-neptune-dbinstance-tags)
* @param tags An arbitrary set of tags (key-value pairs) for this DB instance.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
public fun build(): CfnDBInstance {
if(_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 12,728 | awscdk-dsl-kotlin | Apache License 2.0 |
exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Alias.kt | JetBrains | 11,765,017 | false | null | package org.jetbrains.exposed.sql
class Alias<out T : Table>(val delegate: T, val alias: String) : Table() {
override val tableName: String get() = alias
val tableNameWithAlias: String = "${delegate.tableName} $alias"
private fun <T : Any?> Column<T>.clone() = Column<T>(this@Alias, name, columnType)
fun <R> originalColumn(column: Column<R>): Column<R>? {
@Suppress("UNCHECKED_CAST")
return if (column.table == this)
delegate.columns.first { column.name == it.name } as Column<R>
else
null
}
override val columns: List<Column<*>> = delegate.columns.map { it.clone() }
override val fields: List<Expression<*>> = columns
override fun createStatement() = throw UnsupportedOperationException("Unsupported for aliases")
override fun dropStatement() = throw UnsupportedOperationException("Unsupported for aliases")
override fun modifyStatement() = throw UnsupportedOperationException("Unsupported for aliases")
override fun equals(other: Any?): Boolean {
if (other !is Alias<*>) return false
return this.tableNameWithAlias == other.tableNameWithAlias
}
override fun hashCode(): Int = tableNameWithAlias.hashCode()
@Suppress("UNCHECKED_CAST")
operator fun <T : Any?> get(original: Column<T>): Column<T> =
delegate.columns.find { it == original }?.let { it.clone() as? Column<T> }
?: error("Column not found in original table")
}
class ExpressionAlias<T>(val delegate: Expression<T>, val alias: String) : Expression<T>() {
override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append(delegate).append(" $alias") }
fun aliasOnlyExpression(): Expression<T> {
return if (delegate is ExpressionWithColumnType<T>) {
object : Function<T>(delegate.columnType) {
override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append(alias) }
}
} else {
object : Expression<T>() {
override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append(alias) }
}
}
}
}
class QueryAlias(val query: AbstractQuery<*>, val alias: String) : ColumnSet() {
override fun describe(s: Transaction, queryBuilder: QueryBuilder) = queryBuilder {
append("(")
query.prepareSQL(queryBuilder)
append(") ", alias)
}
override val columns: List<Column<*>>
get() = query.set.source.columns.filter { it in query.set.fields }.map { it.clone() }
@Suppress("UNCHECKED_CAST")
operator fun <T : Any?> get(original: Column<T>): Column<T> =
query.set.source.columns.find { it == original }?.clone() as? Column<T>
?: error("Column not found in original table")
@Suppress("UNCHECKED_CAST")
operator fun <T : Any?> get(original: Expression<T>): Expression<T> {
val expressionAlias = query.set.fields.find { it == original } as? ExpressionAlias<T>
?: error("Field not found in original table fields")
return expressionAlias.delegate.alias("$alias.${expressionAlias.alias}").aliasOnlyExpression()
}
override fun join(otherTable: ColumnSet, joinType: JoinType, onColumn: Expression<*>?, otherColumn: Expression<*>?, additionalConstraint: (SqlExpressionBuilder.() -> Op<Boolean>)?): Join =
Join(this, otherTable, joinType, onColumn, otherColumn, additionalConstraint)
override infix fun innerJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.INNER)
override infix fun leftJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.LEFT)
override infix fun rightJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.RIGHT)
override infix fun fullJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.FULL)
override infix fun crossJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.CROSS)
private fun <T : Any?> Column<T>.clone() = Column<T>(table.alias(alias), name, columnType)
}
fun <T : Table> T.alias(alias: String) = Alias(this, alias)
fun <T : AbstractQuery<*>> T.alias(alias: String) = QueryAlias(this, alias)
fun <T> Expression<T>.alias(alias: String) = ExpressionAlias(this, alias)
fun Join.joinQuery(on: (SqlExpressionBuilder.(QueryAlias) -> Op<Boolean>), joinType: JoinType = JoinType.INNER, joinPart: () -> AbstractQuery<*>): Join {
val qAlias = joinPart().alias("q${joinParts.count { it.joinPart is QueryAlias }}")
return join(qAlias, joinType, additionalConstraint = { on(qAlias) })
}
fun Table.joinQuery(on: (SqlExpressionBuilder.(QueryAlias) -> Op<Boolean>), joinType: JoinType = JoinType.INNER, joinPart: () -> AbstractQuery<*>) =
Join(this).joinQuery(on, joinType, joinPart)
val Join.lastQueryAlias: QueryAlias? get() = joinParts.map { it.joinPart as? QueryAlias }.firstOrNull()
fun <T : Any> wrapAsExpression(query: AbstractQuery<*>) = object : Expression<T?>() {
override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder {
append("(")
query.prepareSQL(this)
append(")")
}
}
| 5 | null | 650 | 7,599 | aff82167165d4e35481a74aaa9c4ede3139aedbf | 5,148 | Exposed | Apache License 2.0 |
app/src/main/java/app/eluvio/wallet/screens/property/DynamicPageLayoutState.kt | eluv-io | 719,801,077 | false | {"Kotlin": 842368, "Java": 29738} | package app.eluvio.wallet.screens.property
import androidx.compose.runtime.Immutable
import androidx.compose.ui.text.AnnotatedString
import androidx.media3.exoplayer.source.MediaSource
import app.eluvio.wallet.data.FabricUrl
import app.eluvio.wallet.data.entities.MediaEntity
import app.eluvio.wallet.data.entities.RedeemableOfferEntity
import app.eluvio.wallet.data.entities.v2.SearchFiltersEntity
import app.eluvio.wallet.data.entities.v2.display.DisplaySettings
import app.eluvio.wallet.data.permissions.PermissionContext
import app.eluvio.wallet.navigation.NavigationEvent
import app.eluvio.wallet.screens.property.DynamicPageLayoutState.CarouselItem
/**
* Currently this is only used by PropertyPages, but we were planning to use it as the new
* NFTDetail page, so we made it more generic so different ViewModels can provide dynamic layouts.
*/
@Immutable
data class DynamicPageLayoutState(
val backgroundImageUrl: String? = null,
val sections: List<Section> = emptyList(),
val searchNavigationEvent: NavigationEvent? = null,
// For cross-app deeplinks
val backLinkUrl: String? = null,
val backButtonLogo: String? = null,
) {
fun isEmpty() = sections.isEmpty() && backgroundImageUrl == null
sealed interface Section {
val sectionId: String
// TODO: maybe combine Title and Description into a single "Text" Row type,
// but then we'd have to start passing around predefined styles or something
@Immutable
data class Title(override val sectionId: String, val text: AnnotatedString) : Section
@Immutable
data class Description(override val sectionId: String, val text: AnnotatedString) : Section
// Note: This has nothing to do with BannerWrapper and we should probably just remove this
// section type.
@Immutable
data class Banner(override val sectionId: String, val imageUrl: String) : Section
@Immutable
data class Carousel(
val permissionContext: PermissionContext,
val displaySettings: DisplaySettings? = null,
val viewAllNavigationEvent: NavigationEvent? = null,
val items: List<CarouselItem>,
val filterAttribute: SearchFiltersEntity.Attribute? = null,
) : Section {
override val sectionId: String =
requireNotNull(permissionContext.sectionId) { "PermissionContext.sectionId is null" }
}
}
sealed interface CarouselItem {
val permissionContext: PermissionContext
@Immutable
data class Media(
override val permissionContext: PermissionContext,
val entity: MediaEntity,
val displayOverrides: DisplaySettings? = null,
) : CarouselItem
@Immutable
data class PageLink(
override val permissionContext: PermissionContext,
// Property ID to link to
val propertyId: String,
// Page ID to link to
val pageId: String?,
val displaySettings: DisplaySettings?,
) : CarouselItem
@Immutable
data class RedeemableOffer(
override val permissionContext: PermissionContext,
val offerId: String,
val name: String,
val fulfillmentState: RedeemableOfferEntity.FulfillmentState,
val contractAddress: String,
val tokenId: String,
val imageUrl: String?,
val animation: MediaSource?,
) : CarouselItem
@Immutable
data class CustomCard(
override val permissionContext: PermissionContext,
val imageUrl: FabricUrl?,
val title: String,
val aspectRatio: Float = 1f,
val onClick: (() -> Unit)
) : CarouselItem
@Immutable
data class ItemPurchase(
override val permissionContext: PermissionContext,
val displaySettings: DisplaySettings?,
) : CarouselItem
/**
* Any type of item can appear inside a section with display_type="banner".
* In that case it will (should) have a "banner_image" defined and we'll display that
* instead of the item's "normal" UI. However the onClick behavior still works the same, so
* instead of this being a standalone SectionItem type, it wraps the "real" item, which
* we'll use for the onClick behavior.
*/
@Immutable
data class BannerWrapper(
val delegate: CarouselItem,
val bannerImageUrl: String
) : CarouselItem by delegate
}
}
/**
* Convenience method to "convert" any CarouselItem to look like a banner.
*/
fun CarouselItem.asBanner(bannerImageUrl: String): CarouselItem {
return when (this) {
is CarouselItem.BannerWrapper -> copy(bannerImageUrl = bannerImageUrl)
else -> CarouselItem.BannerWrapper(this, bannerImageUrl)
}
}
| 8 | Kotlin | 1 | 0 | 77794a0186781b5d7580fd3ab55c8bc17359367b | 4,963 | elv-wallet-android | MIT License |
kotlin/api/src/test/kotlin/org/diffkt/ops/PowerTest.kt | facebookresearch | 495,505,391 | false | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package org.diffkt.ops
import io.kotest.core.spec.style.AnnotationSpec
import io.kotest.matchers.floats.shouldBeExactly
import org.diffkt.*
import kotlin.math.pow
import kotlin.test.assertTrue
import testutils.*
class PowerTest : AnnotationSpec() {
@Test fun testPow() {
val f = { x: DTensor -> x.pow(3f)}
val t1 = tensorOf(2F, 3F)
val t2 = f(t1)
assertTrue(t2 is FloatTensor)
t2 shouldBeExactly tensorOf(8F, 27F)
}
@Test fun testPowInversion() {
val f = { x: DTensor -> x.pow(-1f)}
val t1 = tensorOf(2F, 3F)
val t2 = f(t1)
assertTrue(t2 is FloatTensor)
t2 shouldBeExactly tensorOf(0.5F, 1/3F)
}
@Test fun testForwardDerivativePow() {
val t1 = tensorOf(2F, 3F)
val d1 = forwardDerivative1(t1) { x: DTensor -> x.pow(3f)}
val d2 = forwardDerivative2(t1) { x: DTensor -> x.pow(3f) }
d1 shouldBeExactly tensorOf(12F, 0F, 0F, 27F).reshape(2,2)
d2 shouldBeExactly tensorOf(12f, 0f, 0f, 0f, 0f, 0f, 0f, 18f).reshape(Shape(2, 2, 2))
}
@Test fun testReverseDerivativePow() {
val t1 = tensorOf(2F, 3F)
val d1 = reverseDerivative(t1) { x: DTensor -> x.pow(3f) }
val d2 = reverseDerivative2(t1) { x: DTensor -> x.pow(3f) }
d1 shouldBeExactly tensorOf(12F, 0F, 0F, 27F).reshape(2,2)
d2 shouldBeExactly tensorOf(12f, 0f, 0f, 0f, 0f, 0f, 0f, 18f).reshape(Shape(2, 2, 2))
}
@Test fun testForwardDerivativePowNegativeBase() {
val t1 = tensorOf(-2F, -3F)
val d1 = forwardDerivative(t1) { x: DTensor -> x.pow(3)}
val d2 = forwardDerivative2(t1) { x: DTensor -> x.pow(3)}
d1 shouldBeExactly tensorOf(12F, 0F, 0F, 27F).reshape(2,2)
d2 shouldBeExactly tensorOf(-12f, 0f, 0f, 0f, 0f, 0f, 0f, -18f).reshape(Shape(2, 2, 2))
}
@Test fun testReverseDerivativePowNegativeBase() {
val t1 = tensorOf(-2F, -3F)
val d1 = reverseDerivative(t1) { x: DTensor -> x.pow(3) }
val d2 = reverseDerivative2(t1) { x: DTensor -> x.pow(3)}
d1 shouldBeExactly tensorOf(12F, 0F, 0F, 27F).reshape(2,2)
d2 shouldBeExactly tensorOf(-12f, 0f, 0f, 0f, 0f, 0f, 0f, -18f).reshape(Shape(2, 2, 2))
}
@Test fun testForwardDerivativePow3D() {
val t1 = FloatTensor(Shape(2,3,2)) { it.toFloat() }
val d1 = forwardDerivative(t1) { x: DTensor -> x.pow(3f)}
d1 shouldBeExactly tensorOf(
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 3f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 12f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 27f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 48f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 75f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 108f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 147f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 192f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 243f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 300f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 363f
).reshape(2,3,2,2,3,2)
}
@Test fun testReverseDerivativePow3D() {
val t1 = FloatTensor(Shape(2,3,2)) { it.toFloat() }
val d1 = reverseDerivative(t1) { x: DTensor -> x.pow(3f)}
d1 shouldBeExactly tensorOf(
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 3f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 12f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 27f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 48f, 0f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 75f, 0f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 108f, 0f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 147f, 0f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 192f, 0f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 243f, 0f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 300f, 0f,
0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 363f
).reshape(2,3,2,2,3,2)
}
@Test fun testForwardDerivativePowInversion() {
val t1 = tensorOf(2F, 3F)
val d1 = forwardDerivative1(t1) { x: DTensor -> x.pow(-1f)}
d1 shouldBeExactly tensorOf(-0.25F, 0F, 0F, -1F/9F).reshape(2,2)
}
@Test fun testReverseDerivativePowInversion() {
val t1 = tensorOf(2F, 3F)
val d1 = reverseDerivative(t1) { x: DTensor -> x.pow(-1f)}
d1 shouldBeExactly tensorOf(-0.25F, 0F, 0F, -1F/9F).reshape(2,2)
}
@Test fun testForwardDerivativeRoot() {
val t1 = tensorOf(4F, 16F)
val d1 = forwardDerivative1(t1) { x: DTensor -> x.pow(1.5f)}
d1 shouldBeExactly tensorOf(3F, 0F, 0F, 6F).reshape(2,2)
}
@Test fun testReverseDerivativeRoot() {
val t1 = tensorOf(4F, 16F)
val d1 = reverseDerivative(t1) { x: DTensor -> x.pow(1.5f)}
d1 shouldBeExactly tensorOf(3F, 0F, 0F, 6F).reshape(2,2)
}
@Test fun testPowGradientShape01() {
val t1 = tensorOf(1F, 2F, 3F, 4F, 5F, 6F).reshape(2, 3)
val d1 = forwardDerivative(t1) { x: DTensor ->
val result = x.reshape(6).pow(2)
result
}
d1 shouldBeExactly tensorOf(
2f, 0f, 0f, 0f, 0f, 0f,
0f, 4f, 0f, 0f, 0f, 0f,
0f, 0f, 6f, 0f, 0f, 0f,
0f, 0f, 0f, 8f, 0f, 0f,
0f, 0f, 0f, 0f, 10f, 0f,
0f, 0f, 0f, 0f, 0f, 12f
).reshape(Shape(6, 2, 3))
}
@Test fun testPowGradientShape02() {
val t1 = tensorOf(1F, 2F, 3F, 4F, 5F, 6F).reshape(2, 3)
val d1 = reverseDerivative(t1) { x: DTensor ->
val result = x.pow(2).reshape(6)
result
}
d1 shouldBeExactly tensorOf(
2f, 0f, 0f, 0f, 0f, 0f,
0f, 4f, 0f, 0f, 0f, 0f,
0f, 0f, 6f, 0f, 0f, 0f,
0f, 0f, 0f, 8f, 0f, 0f,
0f, 0f, 0f, 0f, 10f, 0f,
0f, 0f, 0f, 0f, 0f, 12f
).reshape(Shape(2, 3, 6))
}
@Test fun divideByZero() {
val t1 = tensorOf(2F, 0F)
t1.pow(-0.2F) shouldBeExactly tensorOf(2F.pow(-0.2F), 0F.pow(-0.2F))
}
@Test fun noRealRoot() {
val t1 = tensorOf(2F, -5F)
t1.pow(3.2F) shouldBeExactly tensorOf(2F.pow(3.2F), (-5F).pow(3.2F))
}
@Test fun powDScalar01() {
val baseValue = tensorOf(2F, 3F)
val exponent = FloatScalar(2F)
baseValue.pow(exponent) shouldBeExactly tensorOf(4F, 9F)
forwardDerivative(exponent as DTensor) { EXP: DTensor -> baseValue.pow(EXP as DScalar) } shouldBeExactly tensorOf(2.7725887F, 9.88751F)
reverseDerivative(exponent as DTensor) { EXP: DTensor -> baseValue.pow(EXP as DScalar) } shouldBeExactly tensorOf(2.7725887F, 9.88751F)
}
@Test fun powDScalar02() {
val baseValue = FloatScalar(1.1f)
val exponent = FloatScalar(2.2f)
val result: DScalar = baseValue.pow(exponent)
result.value shouldBeExactly 1.1f.pow(2.2f)
}
@Test fun powTwoTensors() {
val base = tensorOf(2F, 3F)
val exponent = tensorOf(3F, 2f)
base.pow(exponent) shouldBeExactly tensorOf(8f, 9f)
}
@Test fun powTwoTensorsForward() {
val base = tensorOf(2F, 3F)
val exponent = tensorOf(3F, 2f)
val (dBase, dExp) = forwardDerivative(base, exponent) { b, e -> b.pow(e) }
dBase shouldBeExactly tensorOf( 12F, 0F, 0F, 6F).reshape(Shape(2, 2))
dExp shouldBeExactly tensorOf( 5.5451775F, 0.0F, 0.0F, 9.88751F).reshape(Shape(2, 2))
}
@Test fun powTwoTensorsReverse() {
val base = tensorOf(2F, 3F)
val exponent = tensorOf(3F, 2f)
val (dBase, dExp) = reverseDerivative(base, exponent) { b, e -> b.pow(e) }
dBase shouldBeExactly tensorOf( 12F, 0F, 0F, 6F).reshape(Shape(2, 2))
dExp shouldBeExactly tensorOf( 5.5451775F, 0.0F, 0.0F, 9.88751F).reshape(Shape(2, 2))
}
}
| 62 | Jupyter Notebook | 3 | 55 | 710f403719bb89e3bcf00d72e53313f8571d5230 | 8,284 | diffkt | MIT License |
oauth2-authorization-server-starter/src/main/kotlin/com/labijie/infra/oauth2/serialization/jackson/ITwoFactorUserDetailsSerializer.kt | hongque-pro | 308,310,231 | false | {"Kotlin": 251261} | package com.labijie.infra.oauth2.serialization.jackson
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.core.type.WritableTypeId
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.jsontype.TypeSerializer
import com.labijie.infra.oauth2.ITwoFactorUserDetails
import com.labijie.infra.oauth2.toPlainObject
class ITwoFactorUserDetailsSerializer : JsonSerializer<ITwoFactorUserDetails>() {
override fun serialize(value: ITwoFactorUserDetails, gen: JsonGenerator, serializers: SerializerProvider) {
val plain = value.toPlainObject()
serializers.defaultSerializeValue(plain, gen)
}
override fun serializeWithType(
value: ITwoFactorUserDetails,
gen: JsonGenerator,
serializers: SerializerProvider,
typeSer: TypeSerializer
) {
val typeId = typeSer.typeId(value, ITwoFactorUserDetails::class.java, JsonToken.START_OBJECT)
typeId.include = WritableTypeId.Inclusion.METADATA_PROPERTY
val typeDefine = typeSer.writeTypePrefix(gen, typeId)
/*
var userid:String = "",
var username:String = "",
var credentialsNonExpired:Boolean = false,
var enabled:Boolean = false,
var password:String = "",
var accountNonExpired:Boolean = false,
var accountNonLocked:Boolean = false,
var twoFactorEnabled: Boolean = false,
var authorities: ArrayList<String> = arrayListOf(),
var attachedFields: Map<String, String> = mapOf()
* */
val plain = value.toPlainObject()
serializers.defaultSerializeField(plain::userid.name, plain.userid, gen)
serializers.defaultSerializeField(plain::username.name, plain.username, gen)
serializers.defaultSerializeField(plain::credentialsNonExpired.name, plain.credentialsNonExpired, gen)
serializers.defaultSerializeField(plain::enabled.name, plain.enabled, gen)
serializers.defaultSerializeField(plain::password.name, plain.password, gen)
serializers.defaultSerializeField(plain::accountNonExpired.name, plain.accountNonExpired, gen)
serializers.defaultSerializeField(plain::accountNonLocked.name, plain.accountNonLocked, gen)
serializers.defaultSerializeField(plain::twoFactorEnabled.name, plain.twoFactorEnabled, gen)
serializers.defaultSerializeField(plain::authorities.name, plain.authorities, gen)
serializers.defaultSerializeField(plain::attachedFields.name, plain.attachedFields, gen)
typeSer.writeTypeSuffix(gen, typeDefine)
}
} | 0 | Kotlin | 0 | 5 | fb4c08f022db25503eb7fd23549b7acaed2688d3 | 2,694 | infra-oauth2 | Apache License 2.0 |
src/main/kotlin/no/nav/tiltaksarrangor/ingest/jobs/Ryddejobb.kt | navikt | 616,496,742 | false | null | package no.nav.tiltaksarrangor.ingest.jobs
import no.nav.tiltaksarrangor.ingest.jobs.leaderelection.LeaderElection
import no.nav.tiltaksarrangor.repositories.DeltakerRepository
import no.nav.tiltaksarrangor.repositories.DeltakerlisteRepository
import no.nav.tiltaksarrangor.repositories.model.DAGER_AVSLUTTET_DELTAKER_VISES
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDate
@Component
class Ryddejobb(
private val leaderElection: LeaderElection,
private val deltakerlisteRepository: DeltakerlisteRepository,
private val deltakerRepository: DeltakerRepository,
) {
private val log = LoggerFactory.getLogger(javaClass)
@Scheduled(cron = "0 0 3 * * *") // kl 03.00 hver natt
fun slettUtdaterteDeltakerlisterOgDeltakere() {
if (leaderElection.isLeader()) {
val slettesDato = LocalDate.now().minusDays(DAGER_AVSLUTTET_DELTAKER_VISES)
val deltakerlisterSomSkalSlettes = deltakerlisteRepository.getDeltakerlisterSomSkalSlettes(slettesDato)
deltakerlisterSomSkalSlettes.forEach { deltakerlisteRepository.deleteDeltakerlisteOgDeltakere(it) }
log.info("Slettet ${deltakerlisterSomSkalSlettes.size} deltakerlister med deltakere")
val deltakereSomSkalSlettes = deltakerRepository.getDeltakereSomSkalSlettes(slettesDato)
deltakereSomSkalSlettes.forEach { deltakerRepository.deleteDeltaker(it) }
log.info("Slettet ${deltakereSomSkalSlettes.size} deltakere")
} else {
log.info("Kjører ikke ryddejobb siden denne podden ikke er leader")
}
}
}
| 2 | Kotlin | 0 | 2 | e90af6c6655c35141497074c782a978e41669d11 | 1,583 | amt-tiltaksarrangor-bff | MIT License |
bitapp/src/main/java/com/atech/bit/ui/activity/main/toggleDrawer.kt | BIT-Lalpur-App | 489,575,997 | false | {"Kotlin": 782234} | package com.atech.bit.ui.activity.main
import androidx.compose.material3.DrawerValue
fun toggleDrawer(communicatorViewModel: MainViewModel) =
if (communicatorViewModel.toggleDrawerState.value == DrawerValue.Closed)
DrawerValue.Open else DrawerValue.Closed | 0 | Kotlin | 4 | 13 | e4bd5f23c80901fb6853dc8641c221dbb141c81c | 269 | BIT-App | MIT License |
src/test/kotlin/slak/test/CommonTest.kt | slak44 | 156,277,498 | false | null | package slak.test
import slak.ckompiler.*
import slak.ckompiler.analysis.CFG
import slak.ckompiler.lexer.*
import slak.ckompiler.FSPath
import slak.ckompiler.analysis.CFGFactory
import slak.ckompiler.analysis.CFGOptions
import slak.ckompiler.parser.ExternalDeclaration
import slak.ckompiler.parser.FunctionDefinition
import slak.ckompiler.parser.Parser
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
internal fun Preprocessor.assertNoDiagnostics() = assertEquals(emptyList(), diags)
internal fun Parser.assertNoDiagnostics() = assertEquals(emptyList(), diags)
internal fun IDebugHandler.assertNoDiagnostics() = assertEquals(emptyList(), diags)
internal val <T : Any> T.source get() = "<test/${this::class.simpleName}>"
internal fun <T : Any> T.resource(s: String) = File(javaClass.classLoader.getResource(s)!!.file)
internal fun preparePP(s: String, source: SourceFileName): Preprocessor {
val incs = IncludePaths(
emptyList(),
listOf(FSPath(IncludePaths.resource("include")), FSPath(IncludePaths.resource("headers/system"))),
listOf(FSPath(IncludePaths.resource("headers/users")))
)
val pp = Preprocessor(
sourceText = s,
srcFileName = source,
includePaths = incs + IncludePaths.defaultPaths,
targetData = MachineTargetData.x64,
currentDir = FSPath(File("."))
)
pp.diags.forEach { it.print() }
return pp
}
internal fun prepareCode(s: String, source: SourceFileName): Parser {
val pp = preparePP(s, source)
pp.assertNoDiagnostics()
val p = Parser(pp.tokens, source, s, MachineTargetData.x64)
p.diags.forEach { it.print() }
return p
}
internal fun prepareCFG(s: String, source: SourceFileName, functionName: String? = null): CFGFactory {
val p = prepareCode(s, source)
p.assertNoDiagnostics()
val func = if (functionName == null) {
p.root.decls.firstFun()
} else {
p.root.decls.first { it is FunctionDefinition && it.name == functionName } as FunctionDefinition
}
val options = CFGOptions(forceReturnZero = true)
return CFGFactory(func, MachineTargetData.x64, source, s, options)
}
internal fun prepareCFG(file: File, source: SourceFileName, functionName: String? = null): CFGFactory {
return prepareCFG(file.readText(), source, functionName)
}
@JvmName("cli_array")
internal fun cli(args: Array<String>): Pair<CLI, ExitCodes> = cli({ System.`in`.readAllBytes() }, *args)
@JvmName("cli_vararg")
internal fun cli(vararg args: String): Pair<CLI, ExitCodes> = cli({ System.`in`.readAllBytes() }, *args)
internal fun cli(readStdin: () -> ByteArray, vararg args: String): Pair<CLI, ExitCodes> {
val cli = CLI()
val exitCode = cli.parse(args.toList().toTypedArray(), readStdin)
cli.diags.forEach(Diagnostic::print)
return cli to exitCode
}
internal fun cliCmd(commandLine: String?): Pair<CLI, ExitCodes> {
return cli(commandLine?.split(" ")?.toTypedArray() ?: emptyArray())
}
internal fun List<ExternalDeclaration>.firstFun(): FunctionDefinition =
first { it is FunctionDefinition } as FunctionDefinition
internal val List<Diagnostic>.ids get() = map { it.id }
internal fun Preprocessor.assertDiags(vararg ids: DiagnosticId) =
assertEquals(ids.toList(), diags.ids)
internal fun Parser.assertDiags(vararg ids: DiagnosticId) = assertEquals(ids.toList(), diags.ids)
internal fun IDebugHandler.assertDiags(vararg ids: DiagnosticId) =
assertEquals(ids.toList(), diags.ids)
internal fun assertPPDiagnostic(s: String, source: SourceFileName, vararg ids: DiagnosticId) {
val diagnostics = preparePP(s, source).diags
assertEquals(ids.toList(), diagnostics.ids)
}
internal fun <T : Any> parseSimpleTokens(it: T): LexicalToken = when (it) {
is LexicalToken -> it
is Punctuators -> Punctuator(it)
is Keywords -> Keyword(it)
is Int -> IntegralConstant(it.toString(), IntegralSuffix.NONE, Radix.DECIMAL)
is Double -> FloatingConstant(it.toString(), FloatingSuffix.NONE, Radix.DECIMAL, null)
is String -> StringLiteral(it, StringEncoding.CHAR)
else -> throw IllegalArgumentException("Bad type for simple token")
}
internal fun <T : Any> Preprocessor.assertDefine(name: String, vararg replacementList: T) {
val replList = defines[Identifier(name)]
assertNotNull(replList, "$name is not defined")
assertEquals(replacementList.map(::parseSimpleTokens).toList(), replList)
}
internal fun Preprocessor.assertNotDefined(name: String) {
assert(Identifier(name) !in defines.keys)
}
internal fun <T : Any> Preprocessor.assertTokens(vararg tokens: T) =
assertEquals(tokens.map(::parseSimpleTokens).toList(), this.tokens)
internal fun <T : LexicalToken> Preprocessor.assertTokens(tokens: List<T>) =
assertEquals(tokens, this.tokens)
| 0 | null | 0 | 19 | 37ae8984e418c1917305a87ac25ebce3a0d9efe7 | 4,713 | ckompiler | MIT License |
core/common/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/core/common/job_util.kt | ls1intum | 537,104,541 | false | {"Kotlin": 1964466, "Dockerfile": 1306, "Shell": 1187} | package de.tum.informatics.www1.artemis.native_app.core.common
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.ListenableWorker
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkRequest
import java.util.concurrent.TimeUnit
inline fun <reified T : ListenableWorker> defaultInternetWorkRequest(
inputData: Data,
configure: OneTimeWorkRequest.Builder.() -> Unit = {}
): OneTimeWorkRequest {
return OneTimeWorkRequestBuilder<T>()
// Only run when the device is connected to the internet.
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
WorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.setInputData(inputData)
.apply(configure)
.build()
} | 9 | Kotlin | 0 | 6 | 40c2f09bbedf5b561a0fa34f73a53154e77f13ef | 1,053 | artemis-android | MIT License |
core/common/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/core/common/job_util.kt | ls1intum | 537,104,541 | false | {"Kotlin": 1964466, "Dockerfile": 1306, "Shell": 1187} | package de.tum.informatics.www1.artemis.native_app.core.common
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.ListenableWorker
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkRequest
import java.util.concurrent.TimeUnit
inline fun <reified T : ListenableWorker> defaultInternetWorkRequest(
inputData: Data,
configure: OneTimeWorkRequest.Builder.() -> Unit = {}
): OneTimeWorkRequest {
return OneTimeWorkRequestBuilder<T>()
// Only run when the device is connected to the internet.
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
WorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.setInputData(inputData)
.apply(configure)
.build()
} | 9 | Kotlin | 0 | 6 | 40c2f09bbedf5b561a0fa34f73a53154e77f13ef | 1,053 | artemis-android | MIT License |
composeApp/src/commonMain/kotlin/data/service/networkingFactories.kt | poetofcode | 766,501,233 | false | {"Kotlin": 57786} | package data.service
import io.ktor.client.*
interface NetworkingFactory {
fun createHttpClient() : HttpClient
fun createApi() : FreshApi
}
class NetworkingFactoryImpl : NetworkingFactory {
override fun createHttpClient(): HttpClient {
return HttpClientFactory(
baseUrl = BASE_URL,
apiKey = API_KEY
).createClient()
}
override fun createApi(): FreshApi {
return FreshApi(
httpClient = createHttpClient(),
baseUrl = BASE_URL
)
}
private companion object {
// TODO вынести в buildConfig
const val BASE_URL = "http://91.215.153.157:8080"
const val API_KEY = "secret-api-key"
}
} | 4 | Kotlin | 0 | 0 | 59bc1548153d02a8907548e86a774044a97ffc0c | 725 | FreshApp | Apache License 2.0 |
core/src/commonMain/kotlin/maryk/core/properties/references/ObjectReferencePropertyReference.kt | marykdb | 290,454,412 | false | null | package maryk.core.properties.references
import maryk.core.extensions.bytes.calculateVarIntWithExtraInfoByteSize
import maryk.core.extensions.bytes.writeVarIntWithExtraInfo
import maryk.core.models.IsRootDataModel
import maryk.core.properties.definitions.IsFixedStorageBytesEncodable
import maryk.core.properties.definitions.index.IndexKeyPartType
import maryk.core.properties.definitions.index.toReferenceStorageByteArray
import maryk.core.properties.definitions.wrapper.ReferenceDefinitionWrapper
import maryk.core.properties.exceptions.RequiredException
import maryk.core.properties.types.Bytes
import maryk.core.properties.types.Key
import maryk.core.values.AbstractValues
import maryk.core.values.IsValuesGetter
/**
* Reference to a value property containing keys for data model of [DM].
* The property is defined by Property Definition Wrapper [propertyDefinition] of type [D]
* and referred by parent PropertyReference of type [P].
*/
open class ObjectReferencePropertyReference<
DM: IsRootDataModel,
TO : Any,
out D : ReferenceDefinitionWrapper<TO, DM, *, *>,
out P : AnyPropertyReference
> internal constructor(
propertyDefinition: D,
parentReference: P?
) :
CanHaveComplexChildReference<Key<DM>, D, P, AbstractValues<*, *>>(propertyDefinition, parentReference),
IsPropertyReferenceForValues<Key<DM>, TO, D, P>,
IsValuePropertyReference<Key<DM>, TO, D, P>,
IsFixedBytesPropertyReference<Key<DM>>,
IsFixedStorageBytesEncodable<Key<DM>> by propertyDefinition {
override val name = propertyDefinition.name
override val completeName by lazy(this::generateCompleteName)
override val byteSize = propertyDefinition.byteSize
override val indexKeyPartType = IndexKeyPartType.Reference
override val referenceStorageByteArray by lazy { Bytes(this.toReferenceStorageByteArray()) }
override fun calculateStorageByteLength(value: Key<DM>) = this.byteSize
override fun calculateReferenceStorageByteLength(): Int {
val refLength = this.calculateStorageByteLength()
return refLength.calculateVarIntWithExtraInfoByteSize() + refLength
}
override fun writeReferenceStorageBytes(writer: (Byte) -> Unit) {
val refLength = this.calculateStorageByteLength()
refLength.writeVarIntWithExtraInfo(
this.indexKeyPartType.index.toByte(),
writer
)
this.writeStorageBytes(writer)
}
override fun isCompatibleWithModel(dataModel: IsRootDataModel): Boolean =
dataModel.compatibleWithReference(this)
override fun getValue(values: IsValuesGetter) =
values[this] ?: throw RequiredException(this)
override fun isForPropertyReference(propertyReference: IsPropertyReference<*, *, *>) =
propertyReference == this
override fun toQualifierStorageByteArray() = this.toStorageByteArray()
}
| 1 | null | 1 | 8 | 5deaf02648955657790192934d9647094a6cec58 | 2,863 | maryk | Apache License 2.0 |
wear/wear/src/androidTest/java/androidx/wear/widget/ArcLayoutTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.widget
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.AttributeSet
import android.view.InputDevice
import android.view.MotionEvent
import android.view.View
import android.view.View.MeasureSpec
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.view.children
import androidx.core.view.forEach
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.GeneralClickAction
import androidx.test.espresso.action.Press
import androidx.test.espresso.action.Tap
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.filters.MediumTest
import androidx.test.screenshot.AndroidXScreenshotTestRule
import androidx.test.screenshot.assertAgainstGolden
import androidx.wear.test.R
import androidx.wear.widget.ArcLayout.LayoutParams.VERTICAL_ALIGN_CENTER
import androidx.wear.widget.ArcLayout.LayoutParams.VERTICAL_ALIGN_INNER
import androidx.wear.widget.ArcLayout.LayoutParams.VERTICAL_ALIGN_OUTER
import androidx.wear.widget.util.AsyncViewActions.waitForMatchingView
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.any
import org.hamcrest.Matcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(Parameterized::class)
@MediumTest
class ArcLayoutTest(private val testHeight: Int) {
private val testWidth: Int = SCREEN_SIZE_DEFAULT
private val renderDoneLatch = CountDownLatch(1)
@get:Rule
val screenshotRule = AndroidXScreenshotTestRule("wear/wear")
private fun doOneTest(
key: String,
views: List<View>,
backgroundColor: Int = Color.GRAY,
interactiveFunction: (FrameLayout.() -> Unit)? = null
) {
val bitmap = Bitmap.createBitmap(testWidth, testHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
// Set the main frame.
val mainFrame = FrameLayout(ApplicationProvider.getApplicationContext())
mainFrame.setBackgroundColor(backgroundColor)
for (view in views) {
mainFrame.addView(view)
}
val screenWidth = MeasureSpec.makeMeasureSpec(testWidth, MeasureSpec.EXACTLY)
val screenHeight = MeasureSpec.makeMeasureSpec(testHeight, MeasureSpec.EXACTLY)
mainFrame.measure(screenWidth, screenHeight)
mainFrame.layout(0, 0, testWidth, testHeight)
mainFrame.draw(canvas)
// If an interactive function is set, call it now and redraw.
// The function will generate mouse events and then we draw again to see the result
// displayed on the views (the test records and shows mouse events in the view)
interactiveFunction?.let {
it(mainFrame)
mainFrame.draw(canvas)
}
renderDoneLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)
bitmap.assertAgainstGolden(screenshotRule, key + "_" + testHeight)
}
private fun createArc(text1: String = "SWEEP", text2: String = "Default") =
ArcLayout(ApplicationProvider.getApplicationContext())
.apply {
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = text1
textColor = Color.BLUE
setBackgroundColor(Color.rgb(100, 100, 0))
setSweepRangeDegrees(45f, 360f)
}
)
addView(
TextView(ApplicationProvider.getApplicationContext()).apply {
text = "TXT"
setTextColor(Color.GREEN)
layoutParams =
ArcLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
}
)
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = text2
textColor = Color.RED
setBackgroundColor(Color.rgb(0, 100, 100))
}
)
}
private fun createMixedArc() =
ArcLayout(ApplicationProvider.getApplicationContext())
.apply {
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = "One"
setBackgroundColor(Color.rgb(100, 100, 100))
setSweepRangeDegrees(0f, 20f)
isClockwise = true
}
)
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = "Two"
setBackgroundColor(Color.rgb(150, 150, 150))
setSweepRangeDegrees(0f, 20f)
isClockwise = false
}
)
addView(
TextView(ApplicationProvider.getApplicationContext()).apply {
text = "TXT"
setTextColor(Color.GREEN)
layoutParams =
ArcLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
).apply { isRotated = false }
}
)
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = "Three"
setBackgroundColor(Color.rgb(100, 100, 100))
setSweepRangeDegrees(0f, 20f)
isClockwise = true
}
)
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = "Four"
setBackgroundColor(Color.rgb(150, 150, 150))
setSweepRangeDegrees(0f, 20f)
isClockwise = false
}
)
}
@Test
@Throws(Exception::class)
fun testArcs() {
doOneTest(
"basic_arcs_screenshot",
listOf(
createArc(),
createArc("SWEEP", "Start").apply {
anchorAngleDegrees = 90f
anchorType = ArcLayout.ANCHOR_START
},
createArc("SWEEP", "End").apply {
anchorAngleDegrees = 270f
anchorType = ArcLayout.ANCHOR_END
},
createArc("SWEEP", "Center").apply {
anchorAngleDegrees = 315f
anchorType = ArcLayout.ANCHOR_CENTER
}
)
)
}
@Test
@Throws(Exception::class)
fun testArcsCcw() {
doOneTest(
"basic_arcs_ccw_screenshot",
listOf(
createArc(),
createArc("SWEEP", "Start").apply {
anchorAngleDegrees = 270f
anchorType = ArcLayout.ANCHOR_START
},
createArc("SWEEP", "End").apply {
anchorAngleDegrees = 90f
anchorType = ArcLayout.ANCHOR_END
},
createArc("SWEEP", "Center").apply {
anchorAngleDegrees = 45f
anchorType = ArcLayout.ANCHOR_CENTER
}
).apply { forEach { it.isClockwise = false } }
)
}
@Test
@Throws(Exception::class)
fun testArcsMixed() {
doOneTest(
"basic_arcs_mix_screenshot",
listOf(
createMixedArc(),
createMixedArc().apply {
isClockwise = false
}
)
)
}
// We keep track of the color of added widgets, to use on touch tests.
// We should try to avoid using white since it have special meaning.
var colorProcessor: (Int) -> Int = { color ->
when (color) {
Color.WHITE -> 0xFFCCCCCC.toInt()
else -> color or 0xFF000000.toInt()
}
}
var testColors = mutableListOf<Int>()
@Before
fun setup() {
testColors = mutableListOf(0) // Used when no view got the event
}
// Extension functions to make the margin test more readable.
fun ArcLayout.addSeparator(angle: Float = 10f) {
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.apply {
text = " "
setSweepRangeDegrees(angle, 360f)
setBackgroundColor(Color.rgb(100, 100, 100))
isClockwise = true
textSize = 40f
}
)
testColors.add(colorProcessor(Color.rgb(150, 150, 150)))
}
fun ArcLayout.addCurvedText(
text: String,
color: Int,
marginLeft: Int? = null,
marginTop: Int? = null,
marginRight: Int? = null,
marginBottom: Int? = null,
margin: Int? = null,
paddingLeft: Int? = null,
paddingTop: Int? = null,
paddingRight: Int? = null,
paddingBottom: Int? = null,
padding: Int? = null,
vAlign: Int = VERTICAL_ALIGN_CENTER,
clockwise: Boolean = true,
textSize: Float = 14f,
textAlignment: Int = View.TEXT_ALIGNMENT_TEXT_START,
minSweep: Float = 0f
) {
addView(
CurvedTextView(ApplicationProvider.getApplicationContext())
.also {
it.text = text
it.setBackgroundColor(color)
it.isClockwise = clockwise
it.textSize = textSize
it.textAlignment = textAlignment
it.setSweepRangeDegrees(minSweep, 360f)
it.setPadding(
paddingLeft ?: padding ?: 0,
paddingTop ?: padding ?: 0,
paddingRight ?: padding ?: 0,
paddingBottom ?: padding ?: 0
)
it.layoutParams = ArcLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
).apply {
setMargins(
marginLeft ?: margin ?: 0,
marginTop ?: margin ?: 0,
marginRight ?: margin ?: 0,
marginBottom ?: margin ?: 0
)
verticalAlignment = vAlign
}
}
)
testColors.add(colorProcessor(color))
}
fun ArcLayout.addTextView(
text: String,
color: Int,
textSize: Float = 14f
) {
addView(
TextView(context).also {
it.text = text
it.background = ColorDrawable(color)
it.textSize = textSize
}
)
testColors.add(colorProcessor(color))
}
fun ArcLayout.addInvisibleTextView() {
addView(
TextView(context).also {
it.text = "Invisible"
it.visibility = View.INVISIBLE
}
)
testColors.add(0xFF13579B.toInt())
}
fun ArcLayout.addGoneTextView() {
addView(
TextView(context).also {
it.text = "Gone"
it.visibility = View.GONE
}
)
testColors.add(0xFF13579B.toInt())
}
private fun createArcWithMargin() =
ArcLayout(ApplicationProvider.getApplicationContext())
.apply {
anchorType = ArcLayout.ANCHOR_CENTER
addSeparator()
addCurvedText("RI", Color.RED, marginTop = 16, vAlign = VERTICAL_ALIGN_INNER)
addCurvedText(
"GI",
Color.GREEN,
marginTop = 8,
marginBottom = 8,
vAlign = VERTICAL_ALIGN_INNER
)
addCurvedText("BI", Color.BLUE, marginBottom = 16, vAlign = VERTICAL_ALIGN_INNER)
addSeparator()
addCurvedText("Red", Color.RED, marginTop = 16)
addCurvedText("Green", Color.GREEN, marginTop = 8, marginBottom = 8)
addCurvedText("Blue", Color.BLUE, marginBottom = 16)
addSeparator()
addCurvedText("RO", Color.RED, marginTop = 16, vAlign = VERTICAL_ALIGN_OUTER)
addCurvedText(
"GO",
Color.GREEN,
marginTop = 8,
marginBottom = 8,
vAlign = VERTICAL_ALIGN_OUTER
)
addCurvedText("BO", Color.BLUE, marginBottom = 16, vAlign = VERTICAL_ALIGN_OUTER)
addSeparator()
addCurvedText("L", Color.WHITE, marginRight = 20)
addSeparator()
addCurvedText("C", Color.WHITE, marginRight = 10, marginLeft = 10)
addSeparator()
addCurvedText("R", Color.WHITE, marginLeft = 20)
addSeparator()
}
private fun createTwoArcsWithMargin() = listOf(
// First arc goes on top
createArcWithMargin(),
// Second arc in the bottom, and we change al children to go counterclockwise.
createArcWithMargin().apply {
anchorAngleDegrees = 180f
children.forEach {
(it as? CurvedTextView)?.isClockwise = false
}
}
)
@Test
fun testMargins() {
doOneTest("margin_test", createTwoArcsWithMargin())
}
@Test
fun testMarginsCcw() {
doOneTest(
"margin_ccw_test",
createTwoArcsWithMargin().map {
it.apply { isClockwise = false }
}
)
}
@Test
fun testInvisibleAndGone() {
doOneTest(
"inivisible_gone_test",
listOf(
ArcLayout(ApplicationProvider.getApplicationContext())
.apply {
anchorType = ArcLayout.ANCHOR_CENTER
addCurvedText("Initial", Color.RED, textSize = 30f)
addInvisibleTextView()
addCurvedText("Second", Color.GREEN, textSize = 30f)
addGoneTextView()
addCurvedText("Third", Color.BLUE, textSize = 30f)
addSeparator()
addCurvedText("Initial", Color.RED, textSize = 30f, clockwise = false)
addInvisibleTextView()
addCurvedText("Second", Color.GREEN, textSize = 30f, clockwise = false)
addGoneTextView()
addCurvedText("Third", Color.BLUE, textSize = 30f, clockwise = false)
}
)
)
}
private fun createArcsWithPaddingAndMargins() = listOf(
ArcLayout(ApplicationProvider.getApplicationContext())
.apply {
anchorType = ArcLayout.ANCHOR_CENTER
listOf(VERTICAL_ALIGN_INNER, VERTICAL_ALIGN_CENTER, VERTICAL_ALIGN_OUTER).forEach {
align ->
addSeparator()
addCurvedText("None", 0xFFFF0000.toInt(), vAlign = align)
addSeparator(angle = 1f)
addCurvedText("Pad", 0xFF80FF00.toInt(), padding = 8, vAlign = align)
addSeparator(angle = 1f)
addCurvedText("Mar", 0xFF00FFFF.toInt(), margin = 8, vAlign = align)
addSeparator(angle = 1f)
addCurvedText(
"Both",
0xFF8000FF.toInt(),
padding = 8,
margin = 8,
vAlign = align
)
}
addSeparator()
},
ArcLayout(ApplicationProvider.getApplicationContext())
.apply {
anchorType = ArcLayout.ANCHOR_CENTER
anchorAngleDegrees = 180f
addSeparator()
addCurvedText("Top", 0xFFFF0000.toInt(), paddingTop = 16)
addSeparator()
addCurvedText("Bottom", 0xFF80FF00.toInt(), paddingBottom = 16)
addSeparator()
addCurvedText("Left", 0xFF00FFFF.toInt(), paddingLeft = 16)
addSeparator()
addCurvedText("Right", 0xFF8000FF.toInt(), paddingRight = 16)
addSeparator()
}
)
@Test
fun testMarginsAndPadding() {
doOneTest(
"margin_padding_test",
createArcsWithPaddingAndMargins()
)
}
@Test
fun testMarginsAndPaddingCcw() {
doOneTest(
"margin_padding_ccw_test",
// For each WearArcLayout, change all WearCurvedTextView children to counter-clockwise
createArcsWithPaddingAndMargins().map {
it.apply {
children.forEach { child ->
(child as? CurvedTextView)?.let { cv -> cv.isClockwise = false }
}
}
}
)
}
@Test
fun testLayoutRtl() {
doOneTest(
"layout_rtl",
listOf(
ArcLayout(ApplicationProvider.getApplicationContext()).apply {
anchorAngleDegrees = 0f
anchorType = ArcLayout.ANCHOR_CENTER
layoutDirection = View.LAYOUT_DIRECTION_RTL
isClockwise = true
listOf("a", "b", "c").forEach { text ->
addSeparator()
addCurvedText(text, 0xFFFF0000.toInt())
}
},
ArcLayout(ApplicationProvider.getApplicationContext()).apply {
anchorAngleDegrees = 180f
anchorType = ArcLayout.ANCHOR_CENTER
layoutDirection = View.LAYOUT_DIRECTION_RTL
isClockwise = false
listOf("d", "e", "f").forEach { text ->
addSeparator()
addCurvedText(text, 0xFFFF0000.toInt())
}
},
)
)
}
// Generates a click in the x,y coordinates in the view's coordinate system.
fun customClick(x: Float, y: Float) = ViewActions.actionWithAssertions(
GeneralClickAction(
Tap.SINGLE,
{ view ->
val xy = IntArray(2)
view.getLocationOnScreen(xy)
floatArrayOf(x + xy[0], y + xy[1])
},
Press.PINPOINT,
InputDevice.SOURCE_UNKNOWN,
MotionEvent.BUTTON_PRIMARY
)
)
// Sending clicks is slow, around a quarter of a second each, on a desktop emulator.
@Test(timeout = 100000)
fun testTouchEvents() {
val bitmap = Bitmap.createBitmap(testWidth, testHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val scenario = ActivityScenario.launch(TouchTestActivity::class.java)
val STEP = 30
DrawableSurface.radius = 6f
// Find the main FrameLayout that contains all widgets under test.
val theView = Espresso.onView(withId(R.id.curved_frame))
.perform(
waitForMatchingView(
allOf(
withId(R.id.curved_frame),
isDisplayed()
),
2000
)
)
theView.perform(object : ViewAction {
override fun getConstraints(): Matcher<View> = any(View::class.java)
override fun getDescription(): String = "Resize view to fit the test."
override fun perform(uiController: UiController?, view: View?) {
(view as? FrameLayout)?.layoutParams =
FrameLayout.LayoutParams(testWidth, testHeight)
}
})
// Setup on-click handlers for each view so we can get the index of the clicked view.
var clicked: Int
scenario.onActivity {
listOf(
R.id.curved_text1, R.id.curved_text2, R.id.curved_text3,
R.id.curved_text4, R.id.text5, R.id.curved_text6
).mapIndexed { ix, viewId ->
it.findViewById<View>(viewId)?.setOnClickListener {
clicked = ix
}
}
}
// Simulate clicks in a grid all over the screen and draw a circle centered in the
// position of the click and which color indicates the view that got clicked.
// Black means no view got the click event, white means a out of range value.
for (y in STEP / 2 until testHeight step STEP) {
val points = mutableListOf<ColoredPoint>()
for (x in STEP / 2 until testWidth step STEP) {
// Perform a click, and record a point colored according to which view was clicked.
clicked = -1
theView.perform(customClick(x.toFloat(), y.toFloat()))
points.add(
ColoredPoint(
x.toFloat(), y.toFloat(),
// Color the circle.
listOf(
Color.BLACK, // no view got the event.
Color.RED, Color.GREEN, Color.BLUE,
Color.YELLOW, Color.MAGENTA, Color.CYAN
).elementAtOrNull(clicked + 1) ?: Color.WHITE
)
)
}
// Add all circles on the current line to the DrawableSurface.
// Points are batched to improve performance a bit.
Espresso.onView(withId(R.id.drawable_surface)).perform(object : ViewAction {
override fun getConstraints(): Matcher<View> = any(View::class.java)
override fun getDescription(): String = "Add Points"
override fun perform(uiController: UiController?, view: View?) {
(view as? DrawableSurface)?.addPoints(points)
}
})
}
// At the end, get a screenshot to compare against the golden
scenario.onActivity {
it.findViewById<View>(R.id.curved_frame).draw(canvas)
}
bitmap.assertAgainstGolden(screenshotRule, "touch_screenshot" + "_" + testHeight)
}
// This is not testing the full event journey as the previous method does, but it's faster so
// we can make more tests, and test more points in them.
private fun testEventsFast(key: String, testViews: List<View>) {
val context: Context = ApplicationProvider.getApplicationContext()
// We setup the "mouse event display" view (on top, with a semi-transparent background)
// and the views under test.
val drawableSurface = DrawableSurface(context)
drawableSurface.background = ColorDrawable(0x40000000.toInt())
val views = testViews + drawableSurface
// Setup the click handlers
var clicked: Int
var viewNumber = 0
// We need this function because we want each listener to capture it's view number by value,
// (and a reference to the clicked variable).
val onTouchListenerGenerator = { myNumber: Int ->
{ _: View, _: MotionEvent ->
clicked = myNumber
true
}
}
views.forEach { view ->
(view as? ArcLayout)?.let { arcLayout ->
arcLayout.forEach { innerView ->
if (innerView is TextView || innerView is CurvedTextView) {
innerView.setOnTouchListener(onTouchListenerGenerator(viewNumber++))
}
}
}
}
// Do the test, sending the events
var time = 0L
DrawableSurface.radius = 1.5f
doOneTest(
key, views,
backgroundColor = Color.rgb(0xFF, 0xFF, 0xC0)
) {
val STEP = 4
// Simulate clicks in a grid all over the screen and draw a circle centered in the
// position of the click and which color indicates the view that got clicked.
// Black means no view got the click event, white means a out of range value.
for (y in STEP / 2 until testHeight step STEP) {
for (x in STEP / 2 until testWidth step STEP) {
// Perform a click, and record a point colored according to which view was clicked.
clicked = -1
val down_event = MotionEvent.obtain(
time, time, MotionEvent.ACTION_DOWN,
x.toFloat(), y.toFloat(), 0
)
dispatchTouchEvent(down_event)
val up_event = MotionEvent.obtain(
time, time + 5, MotionEvent.ACTION_UP,
x.toFloat(), y.toFloat(), 0
)
dispatchTouchEvent(up_event)
time += 10
drawableSurface.addPoints(
listOf(
ColoredPoint(
x.toFloat(), y.toFloat(),
// Color the circle.
// We use Transparent for not touched and white for out of index
testColors.elementAtOrNull(clicked + 1) ?: Color.WHITE
)
)
)
}
}
}
}
@Test(timeout = 5000)
fun testBasicTouch() {
val context: Context = ApplicationProvider.getApplicationContext()
// This views are the same as the test testTouchEvents()
val views = listOf(
ArcLayout(context).apply {
anchorAngleDegrees = 0f
anchorType = ArcLayout.ANCHOR_CENTER
isClockwise = true
addCurvedText(
"Left", color = 0x66FF0000, textSize = 48f, minSweep = 60f,
textAlignment = View.TEXT_ALIGNMENT_TEXT_START
)
addGoneTextView()
addCurvedText(
"Center", color = 0x6600FF00, textSize = 48f, minSweep = 60f,
textAlignment = View.TEXT_ALIGNMENT_CENTER
)
addCurvedText(
"Right", color = 0x660000FF, textSize = 48f, minSweep = 60f,
textAlignment = View.TEXT_ALIGNMENT_TEXT_END
)
addGoneTextView()
},
ArcLayout(context).apply {
anchorAngleDegrees = 180f
anchorType = ArcLayout.ANCHOR_CENTER
isClockwise = true
addGoneTextView()
addCurvedText(
"ACL", color = 0x66FFFF00, textSize = 48f, minSweep = 40f,
textAlignment = View.TEXT_ALIGNMENT_TEXT_START
)
addTextView(text = "N-TXT", color = 0x66FF00FF, textSize = 20f)
addCurvedText(
"ACR", color = 0x6600FFFF, textSize = 60f, minSweep = 50f,
textAlignment = View.TEXT_ALIGNMENT_TEXT_END, clockwise = false
)
}
)
testEventsFast("touch_fast_screenshot", views)
}
@Test(timeout = 10000)
fun testMarginTouch() {
val views = createTwoArcsWithMargin()
testEventsFast("touch_fast_margin_screenshot", views)
}
companion object {
private const val SCREEN_SIZE_DEFAULT = 390
private const val SCREEN_SIZE_DIFF = 100
private const val TIMEOUT_MS = 1000L
@JvmStatic
@Parameterized.Parameters(name = "testHeight={0}")
fun initParameters() = listOf(
SCREEN_SIZE_DEFAULT,
SCREEN_SIZE_DEFAULT + SCREEN_SIZE_DIFF,
SCREEN_SIZE_DEFAULT - SCREEN_SIZE_DIFF
)
}
}
// Helper activity for testing touch.
class TouchTestActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.wear_arc_layout_touch_test)
}
}
data class ColoredPoint(val x: Float, val y: Float, val c: Int)
// Helper class to draw some point/circles of different colors. Used by the touch test.
open class DrawableSurface @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private var points = mutableListOf<ColoredPoint>()
override fun onDraw(canvas: Canvas) {
val paint = Paint().apply {
strokeWidth = radius / 2f
style = Paint.Style.STROKE
alpha = 0
}
points.forEach { p ->
paint.color = p.c
canvas.drawCircle(p.x, p.y, radius, paint)
}
}
fun addPoints(newPoints: Collection<ColoredPoint>) {
points.addAll(newPoints)
invalidate()
}
companion object {
var radius = 6f
}
}
| 29 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 31,498 | androidx | Apache License 2.0 |
app/src/main/java/shvyn22/flexingfreegames/util/Constants.kt | shvyn22 | 505,396,757 | false | {"Kotlin": 107488} | package shvyn22.flexingfreegames.util
const val BASE_URL = "https://www.freetogame.com/api/"
const val DATABASE_NAME = "appDatabase"
const val DATASTORE_FILENAME = "preferences"
val PLATFORMS = listOf("all", "pc", "browser")
val SORT_TYPES = listOf("release-date", "popularity", "alphabetical", "relevance")
val CATEGORIES = listOf(
null,
"mmorpg",
"shooter",
"strategy",
"moba",
"racing",
"sports",
"social",
"sandbox",
"open-world",
"survival",
"pvp",
"pve",
"pixel",
"voxel",
"zombie",
"turn-based",
"first-person",
"third-person",
"top-down",
"tank",
"space",
"sailing",
"side-scroller",
"superhero",
"permadeath",
"card",
"battle-royale",
"mmo",
"mmofps",
"mmotps",
"3d",
"2d",
"anime",
"fantasy",
"sci-fi",
"fighting",
"action-rpg",
"action",
"military",
"martial-arts",
"flight",
"low-spec",
"tower-defense",
"horror",
"mmorts"
)
| 0 | Kotlin | 0 | 2 | cf61370993c8c7fb40a8722e7d46bd807b407732 | 1,024 | FlexingFreeGames | MIT License |
core/src/commonMain/kotlin/com/maxkeppeker/sheets/core/CoreView.kt | maxkeppeler | 523,345,776 | false | null | /*
* Copyright (C) 2022-2023. <NAME> (https://www.maxkeppeler.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalMaterial3Api::class)
package com.maxkeppeker.sheets.core
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import com.maxkeppeker.sheets.core.models.CoreSelection
import com.maxkeppeker.sheets.core.models.base.Header
import com.maxkeppeker.sheets.core.models.base.SheetState
import com.maxkeppeker.sheets.core.views.ButtonsComponent
import com.maxkeppeker.sheets.core.views.base.FrameBase
/**
* Core view that functions as the base of a custom use-case.
* @param sheetState The state of the sheet.
* @param selection The selection configuration for the dialog view.
* @param header The header to be displayed at the top of the dialog view.
* @param body The body content to be displayed inside the dialog view.
* @param onPositiveValid If the positive button is valid and therefore enabled.
*/
@ExperimentalMaterial3Api
@Composable
fun CoreView(
sheetState: SheetState,
selection: CoreSelection,
header: Header? = null,
body: @Composable () -> Unit,
onPositiveValid: Boolean = true
) {
FrameBase(
header = header,
layout = { body() },
buttonsVisible = selection.withButtonView
) {
ButtonsComponent(
onPositiveValid = onPositiveValid,
selection = selection,
onNegative = { selection.onNegativeClick?.invoke() },
onPositive = { selection.onPositiveClick?.invoke() },
onClose = sheetState::finish
)
}
}
| 8 | null | 6 | 816 | 2af41f317228e982e261522717b6ef5838cd8b58 | 2,160 | sheets-compose-dialogs | Apache License 2.0 |
demo/src/desktopMain/kotlin/org/pushingpixels/aurora/demo/svg/flags/gb.kt | kirill-grouchnikov | 297,981,405 | false | null | package org.pushingpixels.aurora.demo.svg.flags
import androidx.compose.ui.geometry.*
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.graphics.painter.Painter
import java.lang.ref.WeakReference
import java.util.*
import kotlin.math.min
/**
* This class has been automatically generated using
* <a href="https://github.com/kirill-grouchnikov/aurora">Aurora SVG transcoder</a>.
*/
class gb : Painter() {
@Suppress("UNUSED_VARIABLE") private var shape: Outline? = null
@Suppress("UNUSED_VARIABLE") private var generalPath: Path? = null
@Suppress("UNUSED_VARIABLE") private var brush: Brush? = null
@Suppress("UNUSED_VARIABLE") private var stroke: Stroke? = null
@Suppress("UNUSED_VARIABLE") private var clip: Shape? = null
private var alpha = 1.0f
private var blendMode = DrawScope.DefaultBlendMode
private var alphaStack = mutableListOf(1.0f)
private var blendModeStack = mutableListOf(DrawScope.DefaultBlendMode)
@Suppress("UNUSED_VARIABLE", "UNUSED_VALUE", "VARIABLE_WITH_REDUNDANT_INITIALIZER", "UNNECESSARY_NOT_NULL_ASSERTION")
private fun _paint0(drawScope : DrawScope) {
var shapeText: Outline?
var generalPathText: Path? = null
var alphaText = 0.0f
var blendModeText = DrawScope.DefaultBlendMode
with(drawScope) {
//
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
// _0
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
withTransform({
transform(
Matrix(values=floatArrayOf(
1.0240000486373901f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0240000486373901f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
-256.0f, 0.0f, 0.0f, 1.0f)
))}){
// _0_0
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
// _0_0_0
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
// _0_0_0_0
if (generalPath == null) {
generalPath = Path()
} else {
generalPath!!.reset()
}
generalPath?.run {
moveTo(0.0f, 0.0f)
lineTo(1000.02f, 0.0f)
lineTo(1000.02f, 500.01f)
lineTo(0.0f, 500.01f)
close()
}
shape = Outline.Generic(generalPath!!)
brush = SolidColor(Color(0, 0, 102, 255))
drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode)
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
// _0_0_0_1
if (generalPath == null) {
generalPath = Path()
} else {
generalPath!!.reset()
}
generalPath?.run {
moveTo(0.0f, 0.0f)
lineTo(0.0f, 55.903f)
lineTo(888.218f, 500.013f)
lineTo(1000.02f, 500.013f)
lineTo(1000.02f, 444.11f)
lineTo(111.802f, 0.003f)
lineTo(0.0f, 0.003f)
close()
moveTo(1000.02f, 0.0f)
lineTo(1000.02f, 55.9f)
lineTo(111.802f, 500.01f)
lineTo(0.0f, 500.01f)
lineTo(0.0f, 444.11002f)
lineTo(888.218f, 0.0f)
lineTo(1000.02f, 0.0f)
close()
}
shape = Outline.Generic(generalPath!!)
brush = SolidColor(Color(255, 255, 255, 255))
drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode)
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
// _0_0_0_2
if (generalPath == null) {
generalPath = Path()
} else {
generalPath!!.reset()
}
generalPath?.run {
moveTo(416.675f, 0.0f)
lineTo(416.675f, 500.01f)
lineTo(583.345f, 500.01f)
lineTo(583.345f, 0.0f)
lineTo(416.675f, 0.0f)
close()
moveTo(0.0f, 166.67f)
lineTo(0.0f, 333.34f)
lineTo(1000.02f, 333.34f)
lineTo(1000.02f, 166.67f)
lineTo(0.0f, 166.67f)
close()
}
shape = Outline.Generic(generalPath!!)
brush = SolidColor(Color(255, 255, 255, 255))
drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode)
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
alphaStack.add(0, alpha)
alpha *= 1.0f
blendModeStack.add(0, BlendMode.SrcOver)
blendMode = BlendMode.SrcOver
// _0_0_0_3
if (generalPath == null) {
generalPath = Path()
} else {
generalPath!!.reset()
}
generalPath?.run {
moveTo(0.0f, 200.004f)
lineTo(0.0f, 300.00598f)
lineTo(1000.02f, 300.00598f)
lineTo(1000.02f, 200.004f)
lineTo(0.0f, 200.004f)
close()
moveTo(450.01f, 0.0f)
lineTo(450.01f, 500.01f)
lineTo(550.01f, 500.01f)
lineTo(550.01f, 0.0f)
lineTo(450.01f, 0.0f)
close()
moveTo(0.0f, 500.01f)
lineTo(333.34f, 333.34003f)
lineTo(407.875f, 333.34003f)
lineTo(74.535f, 500.01f)
lineTo(0.0f, 500.01f)
close()
moveTo(0.0f, 0.0f)
lineTo(333.34f, 166.67f)
lineTo(258.805f, 166.67f)
lineTo(0.0f, 37.27f)
lineTo(0.0f, 0.0f)
close()
moveTo(592.145f, 166.67f)
lineTo(925.485f, 0.0f)
lineTo(1000.02f, 0.0f)
lineTo(666.68f, 166.67f)
lineTo(592.145f, 166.67f)
close()
moveTo(1000.02f, 500.01f)
lineTo(666.68f, 333.34f)
lineTo(741.21497f, 333.34f)
lineTo(1000.01996f, 462.74298f)
lineTo(1000.01996f, 500.00998f)
close()
}
shape = Outline.Generic(generalPath!!)
brush = SolidColor(Color(204, 0, 0, 255))
drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode)
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
}
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
alpha = alphaStack.removeAt(0)
blendMode = blendModeStack.removeAt(0)
}
}
private fun innerPaint(drawScope: DrawScope) {
_paint0(drawScope)
shape = null
generalPath = null
brush = null
stroke = null
clip = null
alpha = 1.0f
}
companion object {
/**
* Returns the X of the bounding box of the original SVG image.
*
* @return The X of the bounding box of the original SVG image.
*/
fun getOrigX(): Double {
return 1.2159347534179688E-5
}
/**
* Returns the Y of the bounding box of the original SVG image.
*
* @return The Y of the bounding box of the original SVG image.
*/
fun getOrigY(): Double {
return 0.0
}
/**
* Returns the width of the bounding box of the original SVG image.
*
* @return The width of the bounding box of the original SVG image.
*/
fun getOrigWidth(): Double {
return 512.0
}
/**
* Returns the height of the bounding box of the original SVG image.
*
* @return The height of the bounding box of the original SVG image.
*/
fun getOrigHeight(): Double {
return 512.0
}
}
override val intrinsicSize: Size
get() = Size.Unspecified
override fun DrawScope.onDraw() {
clipRect {
// Use the original icon bounding box and the current icon dimension to compute
// the scaling factor
val fullOrigWidth = getOrigX() + getOrigWidth()
val fullOrigHeight = getOrigY() + getOrigHeight()
val coef1 = size.width / fullOrigWidth
val coef2 = size.height / fullOrigHeight
val coef = min(coef1, coef2).toFloat()
// Use the original icon bounding box and the current icon dimension to compute
// the offset pivot for the scaling
var translateX = -getOrigX()
var translateY = -getOrigY()
if (coef1 != coef2) {
if (coef1 < coef2) {
val extraDy = ((fullOrigWidth - fullOrigHeight) / 2.0f).toFloat()
translateY += extraDy
} else {
val extraDx = ((fullOrigHeight - fullOrigWidth) / 2.0f).toFloat()
translateX += extraDx
}
}
val translateXDp = translateX.toFloat().toDp().value
val translateYDp = translateY.toFloat().toDp().value
// Create a combined scale + translate + clip transform before calling the transcoded painting instructions
withTransform({
scale(scaleX = coef, scaleY = coef, pivot = Offset.Zero)
translate(translateXDp, translateYDp)
clipRect(left = 0.0f, top = 0.0f, right = fullOrigWidth.toFloat(), bottom = fullOrigHeight.toFloat(), clipOp = ClipOp.Intersect)
}) {
innerPaint(this)
}
}
}
}
| 8 | null | 7 | 570 | c9aa4a852fa2843a72473e710f3cf9a4ebd63f6d | 9,097 | aurora | Apache License 2.0 |
data/src/main/java/com/me/data/repository/CommentRepositoryImpl.kt | MohamedHatemAbdu | 205,669,482 | false | null | package com.me.data.repository
import com.me.data.datasource.CommentCacheDataSource
import com.me.data.datasource.CommentRemoteDataSource
import com.me.domain.entities.CommentEntity
import com.me.domain.repositories.CommentRepository
import io.reactivex.Flowable
class CommentRepositoryImpl(
val commentCacheDataSource: CommentCacheDataSource,
val commentRemoteDataSource: CommentRemoteDataSource
) : CommentRepository {
override fun getComments(postId: String, refresh: Boolean): Flowable<List<CommentEntity>> =
when (refresh) {
true -> {
commentRemoteDataSource.getComments(postId).flatMap {
commentCacheDataSource.setComments(postId, it)
}
}
false -> commentCacheDataSource.getComments(postId)
.onErrorResumeNext { t: Throwable -> getComments(postId, true) }
}
} | 0 | Kotlin | 1 | 2 | ed6c429aafb94510fb0ec2e7a0e4744ed705e4bb | 901 | fake-posts-sample | Apache License 2.0 |
TeacherHelperAndroid/shared/src/commonMain/kotlin/com/tzeentch/teacherhelper/utils/UiState.kt | Tzeentch-Hack | 687,878,509 | false | {"Kotlin": 101434, "Python": 45413, "Swift": 342} | package com.tzeentch.teacherhelper.utils
import com.tzeentch.teacherhelper.dto.DetailsDto
import com.tzeentch.teacherhelper.dto.RequestDto
sealed class AuthUiState {
object Init : AuthUiState()
object Loading : AuthUiState()
object ToOptionalScreen : AuthUiState()
}
sealed class MainUiState {
object Loading : MainUiState()
data class ReceiveListOfTask(val requestList: List<RequestDto>) : MainUiState()
data class Error(val error: String) : MainUiState()
}
sealed class DetailsUiState {
object Loading : DetailsUiState()
data class ReceiveTask(val detailsDto: DetailsDto) : DetailsUiState()
data class Error(val error: String) : DetailsUiState()
}
sealed class CameraUiState {
object Initial : CameraUiState()
object GotoOptionalScreen : CameraUiState()
object Loading : CameraUiState()
}
| 0 | Kotlin | 0 | 0 | b339a459c79f35da54ce0a492f3edb2d32ee349d | 855 | TeacherHelper | MIT License |
app/src/main/java/com/nikitosii/studyrealtorapp/util/annotation/AnnotationUtil.kt | meanswar | 702,052,508 | false | {"Kotlin": 730795, "HTML": 262565} | package com.nikitosii.studyrealtorapp.util.annotation
import com.nikitosii.studyrealtorapp.flow.base.BaseViewModel
object AnnotationUtil {
fun findViewModelClass(any: Any): Class<out BaseViewModel> {
return any.javaClass.getAnnotation(RequiresViewModel::class.java)!!.value.java
}
fun hasInject(any: Any) = any.javaClass.isAnnotationPresent(RequiresInject::class.java)
fun hasViewModel(any: Any) = any.javaClass.isAnnotationPresent(RequiresViewModel::class.java)
} | 2 | Kotlin | 0 | 0 | 20c281e8954fe900812e1923600ff0fd9b82d2b4 | 492 | StudyRealtorApp | MIT License |
presentation/src/main/java/com/anytypeio/anytype/presentation/templates/TemplateBlankViewModel.kt | anyproto | 647,371,233 | false | {"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334} | package com.anytypeio.anytype.presentation.templates
import androidx.lifecycle.viewModelScope
import com.anytypeio.anytype.core_models.Block
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.core_models.ObjectType
import com.anytypeio.anytype.core_models.ObjectTypeIds
import com.anytypeio.anytype.core_models.Relations
import com.anytypeio.anytype.core_models.ext.asMap
import com.anytypeio.anytype.presentation.common.BaseViewModel
import com.anytypeio.anytype.presentation.editor.Editor
import com.anytypeio.anytype.presentation.editor.EditorViewModel
import com.anytypeio.anytype.presentation.editor.editor.model.BlockView
import com.anytypeio.anytype.presentation.editor.render.BlockViewRenderer
import com.anytypeio.anytype.presentation.editor.render.DefaultBlockViewRenderer
import com.anytypeio.anytype.presentation.templates.TemplateView.Companion.DEFAULT_TEMPLATE_ID_BLANK
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import timber.log.Timber
class TemplateBlankViewModel(
private val renderer: DefaultBlockViewRenderer,
) : BaseViewModel(), BlockViewRenderer by renderer {
val state = MutableStateFlow<List<BlockView>>(emptyList())
private val TEMPLATE_TYPE_NAME = "Template"
fun onStart(typeId: Id, typeName: String, layout: Int) {
Timber.d("onStart, typeId: $typeId, typeName: $typeName, layout: $layout")
val blockTitle = Block(
id = "blockTitle",
content = Block.Content.Text(
text = "",
style = Block.Content.Text.Style.TITLE,
marks = emptyList()
),
children = emptyList(),
fields = Block.Fields.empty(),
)
val featuredRelationsBlock = Block(
id = Relations.FEATURED_RELATIONS,
content = Block.Content.FeaturedRelations,
children = emptyList(),
fields = Block.Fields.empty(),
)
val headerBlock = if (layout != ObjectType.Layout.NOTE.code) {
Block(
id = "header",
content = Block.Content.Layout(
type = Block.Content.Layout.Type.HEADER
),
children = listOf(blockTitle.id, featuredRelationsBlock.id),
fields = Block.Fields.empty(),
)
} else {
Block(
id = "header",
content = Block.Content.Layout(
type = Block.Content.Layout.Type.HEADER
),
children = listOf(featuredRelationsBlock.id),
fields = Block.Fields.empty(),
)
}
val rootBlock = Block(
id = DEFAULT_TEMPLATE_ID_BLANK,
content = Block.Content.Smart,
children = listOf(headerBlock.id),
fields = Block.Fields.empty(),
)
val featuredRelations = listOf(Relations.TYPE)
val page = listOf(rootBlock, headerBlock, blockTitle, featuredRelationsBlock)
val objectDetails = Block.Fields(
mapOf(
Relations.ID to DEFAULT_TEMPLATE_ID_BLANK,
Relations.LAYOUT to layout,
Relations.TYPE to typeId,
Relations.FEATURED_RELATIONS to featuredRelations,
Relations.IS_DELETED to false
)
)
val typeDetails = Block.Fields(
mapOf(
Relations.ID to typeId,
Relations.UNIQUE_KEY to ObjectTypeIds.TEMPLATE,
Relations.NAME to TEMPLATE_TYPE_NAME,
Relations.TYPE_UNIQUE_KEY to ObjectTypeIds.TEMPLATE
)
)
val customDetails =
Block.Details(mapOf(DEFAULT_TEMPLATE_ID_BLANK to objectDetails, typeId to typeDetails))
viewModelScope.launch {
state.value = page.asMap().render(
mode = Editor.Mode.Read,
root = page.first(),
focus = com.anytypeio.anytype.domain.editor.Editor.Focus.empty(),
anchor = page.first().id,
indent = EditorViewModel.INITIAL_INDENT,
details = customDetails,
relationLinks = emptyList(),
restrictions = emptyList(),
selection = emptySet()
)
}
}
} | 45 | Kotlin | 43 | 528 | c708958dcb96201ab7bb064c838ffa8272d5f326 | 4,362 | anytype-kotlin | RSA Message-Digest License |
src/main/kotlin/com/hwx/led_panel/capture/Scanner.kt | zalman778 | 463,221,048 | false | {"Kotlin": 62523, "Dockerfile": 432} | package com.hwx.led_panel.capture
import be.tarsos.dsp.AudioDispatcher
import be.tarsos.dsp.AudioEvent
import be.tarsos.dsp.AudioProcessor
import be.tarsos.dsp.io.jvm.JVMAudioInputStream
import be.tarsos.dsp.util.fft.FFT
import com.hwx.led_panel.Config
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import org.springframework.stereotype.Component
import java.io.IOException
import java.util.*
import javax.sound.sampled.*
interface ISoundScanner {
fun init()
fun run()
fun clear()
val data: Flow<Result>
data class Result(
val hzAmplArr: List<List<Double>>,
val maxHz: Double,
val minHz: Double
)
}
/**
* Created by Hiwoo on 06.02.2018.
*/
@Component
class Scanner : ISoundScanner {
private val bufferSize = 4096
private val fftSize = bufferSize / 2
private val sampleRate = 48000
//массив: частота - амплитуда
//private Double[][] hzAmplArr = new Double[fftSize][2];
private val hzAmplArr = ArrayList<ArrayList<Double>>()
private var maxHz = 0.0
private var minHz = 0.0
private val format = AudioFormat(sampleRate.toFloat(), 16, 1, true, true)
private val line = AudioSystem.getTargetDataLine(format)
private val stream = AudioInputStream(line)
private val audioStream = JVMAudioInputStream(stream)
private val audioProcessor = object : AudioProcessor {
override fun process(event: AudioEvent) = onProcessorEvent(event)
override fun processingFinished() {
val t = 1
}
}
private val audioDispatcher = AudioDispatcher(audioStream, bufferSize, 0).apply {
addAudioProcessor(audioProcessor)
}
private val fft = FFT(bufferSize)
private val amplitudes = FloatArray(fftSize)
override val data = MutableSharedFlow<ISoundScanner.Result>(1)
override fun run() {
audioDispatcher.run()
}
private fun onProcessorEvent(audioEvent: AudioEvent): Boolean {
//System.out.println("new loop of process:");
val audioBuffer = audioEvent.floatBuffer
fft.forwardTransform(audioBuffer)
fft.modulus(audioBuffer, amplitudes)
//creating array of Hz - Ampl value
//hzAmplArr = new Double[amplitudes.length][2];
//hzAmplArr = new ArrayList<>(Collections.nCopies(amplitudes.length, new ArrayList<>()));
hzAmplArr.clear()
for (i in amplitudes.indices) {
hzAmplArr.add(ArrayList())
}
minHz = Config.MAX_HZ.toDouble()
maxHz = 0.0
for (i in amplitudes.indices) {
//System.out.printf("Amplitude at %3d Hz: %8.3f ", (int) fft.binToHz(i, sampleRate) , amplitudes[i]);
//получаем частоту
//hzAmplArr[i][0] = fft.binToHz(i, sampleRate);
hzAmplArr[i].add(fft.binToHz(i, sampleRate.toFloat()))
//специальное занижение ампитуды частоты (сабик громкий)
if (hzAmplArr[i][0] < Config.MID_HZ_MLT_LOW_BOUND) //hzAmplArr[i][1] = (double) (amplitudes[i] * Config.LOW_HZ_MLT);
hzAmplArr[i].add((amplitudes[i] * Config.LOW_HZ_MLT) as Double) else if (hzAmplArr[i][0] >= Config.MID_HZ_MLT_LOW_BOUND
&& hzAmplArr[i][0] < Config.MID_HZ_MLT_HIGH_BOUND
) //hzAmplArr[i][1] = (double) amplitudes[i] * Config.MID_HZ_MLT;
hzAmplArr[i].add(amplitudes[i].toDouble() * Config.MID_HZ_MLT) else //hzAmplArr[i][1] = (double) amplitudes[i] * Config.HIGH_HZ_MLT;
hzAmplArr[i].add(amplitudes[i].toDouble() * Config.HIGH_HZ_MLT)
//min and max
if (minHz > hzAmplArr[i][0]) minHz = hzAmplArr[i][0]
if (maxHz < hzAmplArr[i][0]) maxHz = hzAmplArr[i][0]
}
//System.out.println(minHz+" "+maxHz);
//limiting maxHz
if (maxHz > Config.MAX_HZ) maxHz = Config.MAX_HZ.toDouble()
val result = ISoundScanner.Result(hzAmplArr.toList(), maxHz, minHz)
data.tryEmit(result)
return true
}
override fun clear() {
//cleaning previous
try {
audioDispatcher.stop()
audioStream.close()
stream.close()
line.close()
System.gc()
} catch (e: IOException) {
e.printStackTrace()
}
}
override fun init() {
//clear()
try {
line.open(format, bufferSize)
line.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
} | 0 | Kotlin | 0 | 0 | c1170aa36f3f2b4b2c4597a741fde7764d1235ef | 4,525 | led_panel | MIT License |
interceptor-http2-test-grpc/src/test/kotlin/GrpcTest.kt | Drill4J | 598,096,157 | false | null | /**
* Copyright 2020 - 2022 EPAM Systems
*
* 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.
*/
import bindings.Bindings
import io.grpc.*
import io.grpc.examples.helloworld.GreeterGrpc
import io.grpc.examples.helloworld.HelloReply
import io.grpc.examples.helloworld.HelloRequest
import io.grpc.stub.StreamObserver
import org.junit.*
import java.util.concurrent.TimeUnit
class GrpcTest {
private lateinit var server: Server
internal class GreeterImpl : GreeterGrpc.GreeterImplBase() {
override fun sayHello(req: HelloRequest, responseObserver: StreamObserver<HelloReply>) {
val reply = HelloReply.newBuilder().setMessage("Hello ${req.name}").build()
responseObserver.onNext(reply)
responseObserver.onCompleted()
}
}
@Before
fun setup() {
server = ServerBuilder.forPort(0).addService(GreeterImpl()).build().start()
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
server.shutdown()
}
})
}
@Test
fun shouldSendGrpcRequest() {
Bindings.addHttpHook()
// server.awaitTermination()
repeat(1) {
ls()
}
}
private fun ls() {
val client = Client("localhost", server.port)
try {
client.greet("world")
} finally {
client.shutdown()
}
}
}
class Client(
host: String,
port: Int,
private val channel: ManagedChannel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build()
) {
private val blockingStub: GreeterGrpc.GreeterBlockingStub = GreeterGrpc.newBlockingStub(channel)
fun shutdown() {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)
}
fun greet(name: String) {
val request = HelloRequest.newBuilder().setName(name).build()
val response: HelloReply = try {
blockingStub.sayHello(request)
} catch (e: StatusRuntimeException) {
return
}
println(response)
}
}
| 3 | null | 0 | 1 | b20b9a97e2bd96a22b47cd2b07ffa264f9ab7b28 | 2,596 | lib-jvm-shared | Apache License 2.0 |
app/src/main/java/com/example/ktdemo/MainActivity.kt | DevaLee | 578,107,401 | false | null | package com.example.ktdemo
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings.Global
import android.view.View
import android.view.ViewTreeObserver
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.example.ktdemo.service.ServiceStartDemo
import com.example.ktdemo.testdat.DataParcel
import com.example.ktdemo.testdat.DataTestExamine
import kotlinx.coroutines.*
import java.lang.Thread.sleep
import kotlin.concurrent.thread
class MyLogger {
var tag = "TAG"
fun e(msg: String) {
println("$tag $msg")
}
fun tag(tagStr: String) {
tag = tagStr
}
}
class DbConfig {
var url = ""
var username = ""
var password = ""
override fun toString(): String {
return "uri: $url, username: $username, password: $password"
}
}
class DbConnection {
fun config(config: DbConfig){
println(config)
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
"kotlin".also {
println("结果: ${it.plus("-java")}")
}.also {
println("结果:${it.plus("-php")}")
}
"kotlin".apply {
println("结果: ${this.plus("-java")}")
}.apply {
println("结果: ${this.plus("-php")}")
}
var btn = findViewById<Button>(R.id.button3)
btn.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
var height = btn.height
var width = btn.width
println("btn width: $width, height: $height")
btn.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
});
btn.post(object : java.lang.Runnable{
override fun run() {
println("runnable width: ${btn.width}, height:${btn.height}")
}
})
// val conn = DbConnection()
// conn.config(DbConfig().apply { url = "mysql:22:33:212:44"
// username = "<NAME>"
// password = "<PASSWORD>"
// })
// val logger = MyLogger()
//
// with(logger) {
// tag("Kotlin")
// e("It is a good language")
// }
// weightLight()
// substractFun();
startService()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
var btn = findViewById<Button>(R.id.button3);
println("btn: width: ${btn.width}")
var displayMetrics = resources.displayMetrics
println("screen width: ${displayMetrics.widthPixels}, height: ${displayMetrics.heightPixels}")
var layoutParam = btn.layoutParams
layoutParam.width = 300
layoutParam.height = 100
btn.layoutParams = layoutParam
}
private fun startService(){
startService(Intent(applicationContext, ServiceStartDemo::class.java))
}
fun toNextActivity(view: View){
// var intent = Intent(applicationContext, ForResultFirstAct::class.java)
// startActivityForResult(intent, 10)
// registerForActivityResult()
// registerForActivityResult(ActivityResultContracts.StartActivityForResult()
// ) {
// val data = it.data
// val resultCode = it.resultCode
// }.launch(intent)
startService()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
10 -> {
println("case 10")
if (resultCode == RESULT_OK) {
println("RESULT_OK")
if (data != null) {
var title = data.getStringExtra(ForResultFirstAct.K_TITLE)
var subTitle = data.getStringExtra(ForResultFirstAct.K_SUB_TITLE)
Toast.makeText(applicationContext, "title:$title, subtitle: $subTitle", Toast.LENGTH_LONG).show()
}else {
Toast.makeText(applicationContext, "返回不成功", Toast.LENGTH_LONG).show()
}
}
}
else -> {
println("未识别")
}
}
println("onActivityResult: ${requestCode}, $resultCode, $data")
}
fun toNext(){
var intent = Intent(applicationContext, SendParamsDemo::class.java)
intent.putExtra(SendParamsDemo.K_INT, 1)
intent.putExtra(SendParamsDemo.K_BOOL, true)
intent.putExtra(SendParamsDemo.k_STR, "eewwww")
intent.putExtra(SendParamsDemo.K_INPUT_DATA, DataTestExamine(id = 89, name = "稽核看监控"))
intent.putExtra(SendParamsDemo.K_Parcel_DATA, DataParcel(number = 10, str1 = "书后", str2 = "户籍", noSave = "878787hggh"))
startActivity(intent)
}
fun weightLight(){
runBlocking {
for (t in 1..10000) {
launch {
delay(500L * t)
// delay(t * 500)
println(".")
}
}
}
}
fun waitCoroutineComplete(){
runBlocking {
var job1 = GlobalScope.launch {
println("job1 start")
delay(300)
println("job1 done")
}
var job2: Job = GlobalScope.launch {
println("job2 start")
delay(800)
println("job2 done")
}
job2.join();
job1.join()
println(">>>>>>>>> end")
}
}
fun cnstructureConcurrancy(){
runBlocking {
println("主线程id: ${Thread.currentThread().id}")
launch {
println("协程1所在线程的id: ${Thread.currentThread().id}")
delay(300)
println("协程1执行完毕")
}
launch {
println("协程2所在线程的id: ${Thread.currentThread().id}")
delay(500)
println("协程2执行完毕")
}
println("主线程执行完毕")
}
}
fun scopeBuilder(){
runBlocking {
launch {
delay(200)
println("协程1 ${Thread.currentThread().id}")
}
coroutineScope {
launch {
delay(500)
println("内部协程2-1 ${Thread.currentThread().id}")
}
delay(100)
println("协程2 ${Thread.currentThread().id}")
}
println("主任务完毕")
}
}
fun substractFun(){
runBlocking {
launch {
r1()
}
// r1()
}
}
suspend fun r1() {
delay(300)
println("提取出来的函数")
}
} | 0 | Kotlin | 0 | 0 | c09e99edfceac1a041875843637864f3b1293e4a | 7,146 | ktdemo | MIT License |
skellig-performance-junit-runner/src/main/kotlin/org/skellig/performance/runner/junit/annotation/SkelligPerformanceOptions.kt | skellig-framework | 263,021,995 | false | {"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165} | package org.skellig.performance.runner.junit.annotation
import org.skellig.teststep.runner.context.SkelligTestContext
import java.lang.annotation.Inherited
import kotlin.reflect.KClass
/**
* Annotation used to provide performance options for a Skellig test.
*
* @property testName The name of the performance test step.
* @property testSteps The steps of the performance test.
* @property config Path to Skellig Config file relative to the current 'resources' folder.
* @property context The subclass of SkelligTestContext to be used (default is SkelligTestContext).
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@Inherited
annotation class SkelligPerformanceOptions(val testName: String,
val testSteps: Array<String>,
val config: String = "",
val context: KClass<out SkelligTestContext> = SkelligTestContext::class)
| 8 | Kotlin | 0 | 3 | ed375268b0e444f1928f22f4ac27603e9d1fb66b | 984 | skellig-core | Apache License 2.0 |
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/FileClassLowering.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.jvm.lower
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl
import java.util.*
class FileClassLowering(val context: JvmBackendContext) : FileLoweringPass {
override fun lower(irFile: IrFile) {
val classes = ArrayList<IrClass>()
val fileClassMembers = ArrayList<IrDeclaration>()
irFile.declarations.forEach {
if (it is IrClass)
classes.add(it)
else
fileClassMembers.add(it)
}
if (fileClassMembers.isEmpty()) return
val fileClassDescriptor = context.descriptorsFactory.createFileClassDescriptor(irFile.fileEntry, irFile.packageFragmentDescriptor)
val irFileClass = IrClassImpl(0, irFile.fileEntry.maxOffset, IrDeclarationOrigin.DEFINED, fileClassDescriptor, fileClassMembers)
classes.add(irFileClass)
irFile.declarations.clear()
irFile.declarations.addAll(classes)
}
}
| 12 | null | 4 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,911 | kotlin | Apache License 2.0 |
app/src/main/java/cn/wthee/pcrtool/ui/tool/storyevent/StoryEventListViewModel.kt | wthee | 277,015,110 | false | null | package cn.wthee.pcrtool.ui.tool.storyevent
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.wthee.pcrtool.data.db.repository.EventRepository
import cn.wthee.pcrtool.data.db.view.StoryEventData
import cn.wthee.pcrtool.ui.LoadingState
import cn.wthee.pcrtool.ui.components.DateRange
import cn.wthee.pcrtool.ui.updateLoadingState
import cn.wthee.pcrtool.utils.LogReportUtil
import cn.wthee.pcrtool.utils.compareAllTypeEvent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* 页面状态:剧情活动
*/
@Immutable
data class StoryEventListUiState(
//日期
val dateRange: DateRange = DateRange(),
//日期选择弹窗
val openDialog: Boolean = false,
//剧情活动列表
val storyList: List<StoryEventData>? = null,
val loadingState: LoadingState = LoadingState.Loading
)
/**
* 剧情活动 ViewModel
*
* @param eventRepository
*/
@HiltViewModel
class StoryEventListViewModel @Inject constructor(
private val eventRepository: EventRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(StoryEventListUiState())
val uiState: StateFlow<StoryEventListUiState> = _uiState.asStateFlow()
/**
* 日期选择更新
*/
fun changeRange(dateRange: DateRange) {
viewModelScope.launch {
_uiState.update {
it.copy(
dateRange = dateRange
)
}
}
getStoryEventHistory(dateRange)
}
/**
* 弹窗状态更新
*/
fun changeDialog(openDialog: Boolean) {
viewModelScope.launch {
_uiState.update {
it.copy(
openDialog = openDialog
)
}
}
}
/**
* 获取剧情活动记录
*/
private fun getStoryEventHistory(dateRange: DateRange) {
viewModelScope.launch {
try {
var list = eventRepository.getAllEvents(Int.MAX_VALUE)
if (dateRange.hasFilter()) {
list = list.filter {
dateRange.predicate(it.startTime)
}
}
list = list.sortedWith(compareAllTypeEvent())
_uiState.update {
it.copy(
storyList = list,
loadingState = updateLoadingState(list)
)
}
} catch (e: Exception) {
LogReportUtil.upload(e, "getStoryEventHistory")
}
}
}
/**
* 重置
*/
fun reset() {
viewModelScope.launch {
_uiState.update {
it.copy(
dateRange = DateRange()
)
}
}
getStoryEventHistory(DateRange())
}
}
| 1 | null | 5 | 90 | c60547933372fbbc595da93c7b0ea30319bbf124 | 3,029 | pcr-tool | Apache License 2.0 |
src/backend/codecc/quartz/biz-quartz/src/main/kotlin/com/tencent/bk/codecc/quartz/service/impl/JobManageServiceImpl.kt | zijiaone | 256,159,886 | true | {"Kotlin": 12267630, "Vue": 3567501, "Java": 1436323, "JavaScript": 907817, "CSS": 428463, "TSQL": 316166, "Lua": 144868, "Go": 136780, "HTML": 46195, "TypeScript": 32681, "Shell": 29974, "Python": 3714, "PLSQL": 2378, "Batchfile": 2174, "Makefile": 669} | package com.tencent.bk.codecc.quartz.service.impl
import com.tencent.bk.codecc.quartz.dao.JobCompensateRepository
import com.tencent.bk.codecc.quartz.dao.JobInstanceRepository
import com.tencent.bk.codecc.quartz.model.JobCompensateEntity
import com.tencent.bk.codecc.quartz.model.JobInstanceEntity
import com.tencent.bk.codecc.quartz.pojo.JobExternalDto
import com.tencent.bk.codecc.quartz.pojo.JobInfoVO
import com.tencent.bk.codecc.quartz.pojo.OperationType
import com.tencent.bk.codecc.quartz.service.JobManageService
import com.tencent.devops.common.api.util.UUIDUtil
import org.apache.commons.codec.digest.DigestUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class JobManageServiceImpl @Autowired constructor(
private val jobInstanceRepository: JobInstanceRepository,
private val jobCompensateRepository: JobCompensateRepository
) : JobManageService {
companion object {
private val logger = LoggerFactory.getLogger(JobManageServiceImpl::class.java)
}
//确保操作是线程安全的
private val jobNameList = mutableListOf<JobInstanceEntity>()
override fun findAllJobs(): List<JobInstanceEntity> {
val jobInstanceList = jobInstanceRepository.findAll()
jobNameList.clear()
jobNameList.addAll(jobInstanceList)
return jobInstanceList
}
override fun findCachedJobs(): List<JobInstanceEntity> {
return jobNameList
}
override fun saveJob(jobExternalDto: JobExternalDto): JobInstanceEntity {
val jobInstance = JobInstanceEntity()
val cronMd5 = DigestUtils.md5Hex(jobExternalDto.cronExpression)
val key = "${UUIDUtil.generate()}_$cronMd5"
jobInstance.jobName = if(jobExternalDto.jobName.isNullOrBlank()) key else jobExternalDto.jobName
jobInstance.triggerName = if(jobExternalDto.jobName.isNullOrBlank()) key else jobExternalDto.jobName
jobInstance.classUrl = jobExternalDto.classUrl
jobInstance.className = jobExternalDto.className
jobInstance.cronExpression = jobExternalDto.cronExpression
jobInstance.jobParam = jobExternalDto.jobCustomParam
jobInstance.createdBy = "sysadmin"
jobInstance.createdDate = System.currentTimeMillis()
jobInstance.updatedBy = "sysadmin"
jobInstance.updatedDate = System.currentTimeMillis()
return jobInstanceRepository.save(jobInstance)
}
override fun findJobsByName(jobNames: List<String>): List<JobInstanceEntity> {
return jobInstanceRepository.findByJobNameIn(jobNames)
}
override fun findJobByName(jobName: String): JobInstanceEntity {
return jobInstanceRepository.findByJobName(jobName)
}
override fun saveJobs(jobInstances: List<JobInstanceEntity>): List<JobInstanceEntity> {
jobInstances.forEach {
it.updatedBy = "sysadmin"
it.updatedDate = System.currentTimeMillis()
}
return jobInstanceRepository.save(jobInstances)
}
override fun saveJobCompensate(jobCompensateEntity: JobCompensateEntity): JobCompensateEntity {
jobCompensateEntity.createdBy = "sysadmin"
jobCompensateEntity.createdDate = System.currentTimeMillis()
jobCompensateEntity.updatedBy = "sysadmin"
jobCompensateEntity.updatedDate = System.currentTimeMillis()
return jobCompensateRepository.save(jobCompensateEntity)
}
override fun saveJob(jobInstance: JobInstanceEntity): JobInstanceEntity {
jobInstance.updatedBy = "sysadmin"
jobInstance.updatedDate = System.currentTimeMillis()
return jobInstanceRepository.save(jobInstance)
}
override fun deleteJob(jobName: String?) {
jobInstanceRepository.deleteByJobName(jobName)
}
override fun addOrRemoveJobToCache(jobInstance: JobInstanceEntity, operType: OperationType) {
when (operType) {
OperationType.ADD -> {
jobNameList.add(jobInstance)
}
OperationType.REMOVE -> {
jobNameList.removeIf { it.jobName == jobInstance.jobName }
}
}
}
override fun deleteAllJobs(){
jobInstanceRepository.deleteAll()
}
override fun deleteAllCacheJobs(){
jobNameList.clear()
}
override fun convert(jobInstanceEntity: JobInstanceEntity): JobInfoVO {
return with(jobInstanceEntity) {
JobInfoVO(
classUrl = classUrl,
className = className,
jobName = jobName,
triggerName = triggerName,
cronExpression = cronExpression,
jobParam = jobParam,
shardTag = shardTag
)
}
}
} | 0 | Kotlin | 0 | 0 | 14b4167ee2cde66f4900dc67af73020a5401055a | 4,783 | bk-ci | MIT License |
app/src/main/java/com/paradise/ptpt/one/ui/running/reference/ReferenceRunningFragment.kt | sksowk156 | 624,277,724 | false | {"Kotlin": 573107} | package com.paradise.ptpt.one.ui.running.reference
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.ktx.Firebase
import com.paradise.ptpt.multi.home.HomeActivity
import com.paradise.ptpt.R
import com.paradise.ptpt.databinding.FragmentReferenceRunningBinding
import com.paradise.ptpt.one.ui.running.save.SaveRunningRecordFragment
import com.paradise.ptpt.one.ui.viewmodel.RecordViewModel
import com.paradise.ptpt.one.ui.viewmodel.RunningViewModel
import com.paradise.ptpt.one.util.Utils.SELECT_REFERENCE
import com.paradise.ptpt.one.util.base.BaseFragment
import com.paradise.ptpt.one.util.model.RunningRecord
import com.paradise.ptpt.one.util.widget.ItemRunningRecordListClickInterfase
class ReferenceRunningFragment :
BaseFragment<FragmentReferenceRunningBinding>(R.layout.fragment_reference_running),
ItemRunningRecordListClickInterfase {
lateinit var referenceRunningAdapter: ReferenceRunningAdapter
lateinit var runningViewModel: RunningViewModel
lateinit var recordViewModel: RecordViewModel
lateinit var mAuth: FirebaseAuth
private lateinit var runningDB: DatabaseReference
override fun init() {
runningDB = FirebaseDatabase.getInstance().reference
mAuth = Firebase.auth
runningViewModel = (activity as HomeActivity).runningViewModel
recordViewModel = (activity as HomeActivity).recordViewModel
initAppbar(binding.referencerunningToolbar, null, true, "기준 목록")
initRecyclerview()
}
fun initRecyclerview() {
referenceRunningAdapter = ReferenceRunningAdapter(this)
recordViewModel.AllRunningReferenceData.observe(this@ReferenceRunningFragment, Observer {
when (it) {
is com.paradise.ptpt.one.data.NetworkResult.Loading -> {
binding.referencerunningProgressbar.visibility = View.VISIBLE
}
is com.paradise.ptpt.one.data.NetworkResult.Success -> {
if (it.data != null) {
referenceRunningAdapter.submitList(it.data)
}
binding.referencerunningProgressbar.visibility = View.INVISIBLE
}
is com.paradise.ptpt.one.data.NetworkResult.Error -> {
showToast("네트워크에 문제가 있습니다.")
binding.referencerunningProgressbar.visibility = View.INVISIBLE
Log.e("ReferenceRunningFragment", "${it.message}")
}
else -> {}
}
})
binding.referencerunningRecyclerviewReference.apply {
layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
adapter = referenceRunningAdapter
}
}
override fun onItemRunningRecordListClick(runningRecord: RunningRecord) {
if (runningRecord.reference != null && runningRecord.reference!!.size > 0) {
recordViewModel.pageMode(SELECT_REFERENCE)
runningViewModel.setRunningRecord(runningRecord)
parentFragmentManager.beginTransaction()
.add(R.id.runningbase_layout, SaveRunningRecordFragment(), "saverecord")
.addToBackStack("reference")
.commitAllowingStateLoss()
} else {
showToast("저장된 기준점이 없습니다.")
}
}
override fun onItemRunningRecordListLongClick(runningRecord: Pair<String, RunningRecord>) {
}
override fun onDestroyView() {
super.onDestroyView()
recordViewModel.resetALLRunningReferenceData()
}
} | 0 | Kotlin | 0 | 1 | f498af23b88d27870467efca989a12a2be7b851a | 3,872 | Hellth | Apache License 2.0 |
vector/src/main/java/im/vector/app/features/roomdirectory/picker/RoomDirectoryItem.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright 2019 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.features.roomdirectory.picker
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import im.vector.app.R
import im.vector.app.core.epoxy.VectorEpoxyHolder
import im.vector.app.core.epoxy.VectorEpoxyModel
import im.vector.app.core.extensions.setTextOrHide
import im.vector.app.core.glide.GlideApp
@EpoxyModelClass(layout = R.layout.item_room_directory)
abstract class RoomDirectoryItem : VectorEpoxyModel<RoomDirectoryItem.Holder>() {
@EpoxyAttribute
var directoryAvatarUrl: String? = null
@EpoxyAttribute
var directoryName: String? = null
@EpoxyAttribute
var directoryDescription: String? = null
@EpoxyAttribute
var includeAllNetworks: Boolean = false
@EpoxyAttribute
var checked: Boolean = false
@EpoxyAttribute
var globalListener: (() -> Unit)? = null
override fun bind(holder: Holder) {
super.bind(holder)
holder.rootView.setOnClickListener { globalListener?.invoke() }
// Avatar
GlideApp.with(holder.avatarView)
.load(directoryAvatarUrl)
.apply {
if (!includeAllNetworks) {
placeholder(R.drawable.network_matrix)
}
}
.into(holder.avatarView)
holder.avatarView.isInvisible = directoryAvatarUrl.isNullOrBlank() && includeAllNetworks
holder.nameView.text = directoryName
holder.descriptionView.setTextOrHide(directoryDescription)
holder.checkedView.isVisible = checked
}
class Holder : VectorEpoxyHolder() {
val rootView by bind<ViewGroup>(R.id.itemRoomDirectoryLayout)
val avatarView by bind<ImageView>(R.id.itemRoomDirectoryAvatar)
val nameView by bind<TextView>(R.id.itemRoomDirectoryName)
val descriptionView by bind<TextView>(R.id.itemRoomDirectoryDescription)
val checkedView by bind<View>(R.id.itemRoomDirectoryChecked)
}
}
| 55 | Kotlin | 418 | 9 | 9bd50a49e0a5a2a17195507ef3fe96594ddd739e | 2,777 | tchap-android | Apache License 2.0 |
compiler/testData/diagnostics/tests/resolve/invoke/kt9805.kt | JakeWharton | 99,388,807 | false | null | class A {
val foo: B.() -> Unit get() = null!!
}
class B
fun test(a: A, b: B) {
with(b) {
a.<!INAPPLICABLE_CANDIDATE!>foo<!>() // here must be error, because a is not extension receiver
a.foo(this)
(a.foo)()
(a.foo)(this)
}
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 275 | kotlin | Apache License 2.0 |
app/src/main/java/dev/kxxcn/maru/view/register/RegisterFragment.kt | kxxcn | 281,122,468 | false | null | package dev.kxxcn.maru.view.register
import android.app.DatePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import dev.kxxcn.maru.R
import dev.kxxcn.maru.data.Task
import dev.kxxcn.maru.data.User
import dev.kxxcn.maru.databinding.RegisterFragmentBinding
import dev.kxxcn.maru.util.extension.*
import dev.kxxcn.maru.view.register.RegisterFilterType.*
import org.jetbrains.anko.sdk27.coroutines.onTouch
import java.util.*
import javax.inject.Inject
class RegisterFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val viewModel by viewModels<RegisterViewModel> { viewModelFactory }
private lateinit var filterType: RegisterFilterType
private lateinit var binding: RegisterFragmentBinding
private var datePicker: DatePickerDialog? = null
private val today = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
private var name = ""
private var wedding = 0L
private var editable = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = RegisterFragmentBinding.inflate(
inflater,
container,
false
).apply {
viewModel = [email protected]
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupLifecycle()
setupDatePicker()
setupFilterType()
setupMotionLayout()
setupEditText()
setupBackPressed()
}
override fun onDestroyView() {
datePicker?.dismiss()
datePicker = null
super.onDestroyView()
}
private fun setupLifecycle() {
binding.lifecycleOwner = viewLifecycleOwner
}
private fun setupDatePicker() {
val ctx = context ?: return
datePicker = DatePickerDialog(
ctx,
{ _, y, m, d ->
Calendar.getInstance().run {
set(y, m, d, 0, 0, 0)
set(Calendar.MILLISECOND, 0)
timeInMillis.also { wedding = it }
}.also { viewModel.setInputText(it.msToDate()) }
}, today.year(), today.month(), today.day()
).also { it.datePicker.minDate = today.timeInMillis }
}
private fun setupFilterType() {
REGISTER_NAME.also { filter ->
filterType = filter
viewModel.setFiltering(filter)
}
}
private fun setupMotionLayout() {
binding.registerMotion.apply {
transitionToEnd()
setTransitionCompleteListener { _, _ ->
if (editable) {
editable = false
setFiltering()
transitionToEnd()
}
}
}
viewModel.motion.observe(viewLifecycleOwner, Observer {
hideKeyboard()
if (filterType == REGISTER_BUDGET) {
val iconIds = resources.getStringArray(R.array.task_icons)
val budget = binding.infoEdit.text.toString().replace(",", "").toLong()
viewModel.saveUser(
User(
name = name,
wedding = wedding,
budget = budget
),
resources.getStringArray(R.array.task_list).mapIndexed { index, name ->
Task(
name = name,
iconId = iconIds[index]
)
}
)
RegisterFragmentDirections.actionRegisterFragmentToHomeFragment().also {
findNavController().navigate(it)
}
return@Observer
} else if (filterType == REGISTER_NAME) {
name = binding.infoEdit.text.toString()
}
editable = true
binding.registerMotion.transitionToStart()
})
}
private fun setupEditText() {
with(binding.infoEdit) {
onTouch { _, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
if (filterType == REGISTER_WEDDING) {
showDatePicker()
}
}
}
}
}
private fun setFiltering() {
when (filterType) {
REGISTER_NAME -> REGISTER_WEDDING
REGISTER_WEDDING -> REGISTER_BUDGET
else -> REGISTER_COMPLETE
}.also {
filterType = it
viewModel.setFiltering(it)
}
binding.infoEdit.text = null
}
private fun setupBackPressed() {
viewModel.backPressedEvent.observe(viewLifecycleOwner, {
findNavController().popBackStack()
})
}
private fun showDatePicker() {
if (datePicker?.isShowing == true) {
datePicker?.dismiss()
return
}
datePicker?.show()
}
}
| 0 | Kotlin | 0 | 0 | c301d8155cc13e459eb20acfc0fb89ab56d9c3dc | 5,596 | maru | Apache License 2.0 |
VCL/src/main/java/io/velocitycareerlabs/impl/data/usecases/GenerateOffersUseCaseImpl.kt | velocitycareerlabs | 525,006,413 | false | {"Kotlin": 799091} | /**
* Created by Michael Avoyan on 10/05/2021.
*
* Copyright 2022 Velocity Career Labs inc.
* SPDX-License-Identifier: Apache-2.0
*/
package io.velocitycareerlabs.impl.data.usecases
import io.velocitycareerlabs.api.entities.*
import io.velocitycareerlabs.api.entities.error.VCLError
import io.velocitycareerlabs.impl.domain.infrastructure.executors.Executor
import io.velocitycareerlabs.impl.domain.repositories.GenerateOffersRepository
import io.velocitycareerlabs.impl.domain.usecases.GenerateOffersUseCase
import io.velocitycareerlabs.impl.domain.verifiers.OffersByDeepLinkVerifier
import io.velocitycareerlabs.impl.utils.VCLLog
internal class GenerateOffersUseCaseImpl(
private val generateOffersRepository: GenerateOffersRepository,
private val offersByDeepLinkVerifier: OffersByDeepLinkVerifier,
private val executor: Executor
): GenerateOffersUseCase {
private val TAG = GenerateOffersUseCaseImpl::class.simpleName
override fun generateOffers(
generateOffersDescriptor: VCLGenerateOffersDescriptor,
sessionToken: VCLToken,
completionBlock: (VCLResult<VCLOffers>) -> Unit
) {
executor.runOnBackground {
generateOffersRepository.generateOffers(
generateOffersDescriptor,
sessionToken
) {
it.handleResult({ offers ->
verifyOffersByDeepLink(offers,generateOffersDescriptor, completionBlock)
},{ error ->
onError(error, completionBlock)
})
}
}
}
private fun verifyOffersByDeepLink(
offers: VCLOffers,
generateOffersDescriptor: VCLGenerateOffersDescriptor,
completionBlock: (VCLResult<VCLOffers>) -> Unit
) {
generateOffersDescriptor.credentialManifest.deepLink?.let { deepLink ->
offersByDeepLinkVerifier.verifyOffers(offers, deepLink) {
it.handleResult({ isVerified ->
VCLLog.d(TAG, "Offers deep link verification result: $isVerified")
executor.runOnMain {
completionBlock(VCLResult.Success(offers))
}
}, { error ->
onError(error, completionBlock)
})
}
} ?: run {
VCLLog.d(TAG, "Deep link was not provided => nothing to verify")
executor.runOnMain {
completionBlock(VCLResult.Success(offers))
}
}
}
private fun <T> onError(
error: VCLError,
completionBlock: (VCLResult<T>) -> Unit
) {
completionBlock(VCLResult.Failure(error))
}
} | 2 | Kotlin | 0 | 1 | 98a70d770d5a334aea2e0e8996e409f39170f053 | 2,691 | WalletAndroid | Apache License 2.0 |
ses-plugin-server/src/test/kotlin/jetbrains/buildServer/sesPlugin/bounceHandler/DisableEmailOnBounceTest.kt | JetBrains | 105,000,686 | false | null | /*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.sesPlugin.bounceHandler
import jetbrains.buildServer.sesPlugin.email.DisabledEMailStateProvider
import jetbrains.buildServer.sesPlugin.teamcity.SESIntegrationConfig
import jetbrains.buildServer.sesPlugin.util.check
import jetbrains.buildServer.sesPlugin.util.mock
import jetbrains.buildServer.sesPlugin.util.mocking
import jetbrains.buildServer.users.SUser
import org.jmock.Expectations
import org.testng.annotations.Test
class DisableEmailOnBounceTest {
@Test
fun testHandleBounce() {
mocking {
val sesIntegrationConfig = mock(SESIntegrationConfig::class)
val disabledEMailStateProvider = mock(DisabledEMailStateProvider::class)
val user = mock(SUser::class)
val description = "Got bounce for email someMail"
check {
one(sesIntegrationConfig).isDisableSendingMailOnBounce(); will(Expectations.returnValue(true));
one(user).email; will(Expectations.returnValue("someMail"));
one(disabledEMailStateProvider).disable(user, description);
}
val disableEmailOnBounce = DisableEmailOnBounce(sesIntegrationConfig, disabledEMailStateProvider)
disableEmailOnBounce.handleBounce(user)
}
}
@Test
fun testHandleBounceDisabled() {
mocking {
val sesIntegrationConfig = mock(SESIntegrationConfig::class)
val disabledEMailStateProvider = mock(DisabledEMailStateProvider::class)
val user = mock(SUser::class)
val description = "Got bounce for email someMail"
check {
one(sesIntegrationConfig).isDisableSendingMailOnBounce(); will(Expectations.returnValue(false));
never(disabledEMailStateProvider).disable(user, description);
}
val disableEmailOnBounce = DisableEmailOnBounce(sesIntegrationConfig, disabledEMailStateProvider)
disableEmailOnBounce.handleBounce(user)
}
}
} | 4 | Kotlin | 2 | 2 | 388be7a713de4f028c5f7c8b6c5d00a3258b0dfa | 2,624 | TeamCity.SESPlugin | Apache License 2.0 |
src/main/kotlin/epgx/models/PgTable.kt | hamza1311 | 267,640,230 | true | {"Kotlin": 24784} | package epgx.models
import epgx.models.values.TsVector
import epgx.types.Generated
import epgx.types.JsonbColumnType
import epgx.types.TsVectorColumnType
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.Expression
import org.jetbrains.exposed.sql.SqlExpressionBuilder
import org.jetbrains.exposed.sql.Table
/**
* Wrapper around [Exposed's `Table`][Table] to include postgres-specific extension functions on the column DSL
*
* @author Benjozork
*/
open class PgTable(name: String = "") : Table(name) {
@Suppress("UNCHECKED_CAST")
fun <T, C : Column<T>> C.generated(generator: SqlExpressionBuilder.() -> Expression<*>): C {
val newColumn: C = Column<T>(table, name, Generated(this.columnType, generator)) as C
newColumn.foreignKey = foreignKey
return replaceColumn(this, newColumn)
}
/**
* Creates a column storing instances of [T] using the [JsonbColumnType] type.
*
* @param serializer see [JsonbColumnType]
* @param deserializer see [JsonbColumnType]
*/
fun <T : Any?> jsonb(name: String, serializer: (T) -> String, deserializer: (String) -> T): Column<T> {
return registerColumn(name, JsonbColumnType(serializer, deserializer))
}
/**
* Creates a column storing instances of [T] using the [JsonbColumnType] type.
*
* @param converter see [JsonbColumnType]
*/
fun <T : Any?> jsonb(name: String, converter: JsonbColumnType.Converter<T>): Column<T> {
return registerColumn(name, JsonbColumnType(converter::serializer, converter::deserializer))
}
/**
* Creates a column storing plain JSON strings using the [JsonbColumnType] type.
*/
fun jsonb(name: String): Column<String> = registerColumn(name, JsonbColumnType({ it }, { it }))
/**
* Creates a column using the [TsVectorColumnType] type.
*/
fun tsvector(name: String): Column<TsVector> = registerColumn(name, TsVectorColumnType())
}
| 0 | Kotlin | 0 | 0 | 02be2def0d4e78b8d4c62caf39b6d138cdd4c896 | 1,980 | exposed-postgres-extensions | MIT License |
app/shared/state-machine/ui/public/src/commonTest/kotlin/build/wallet/statemachine/settings/full/device/DeviceSettingsUiStateMachineImplTests.kt | proto-at-block | 761,306,853 | false | null | package build.wallet.statemachine.settings.full.device
import app.cash.turbine.plusAssign
import build.wallet.availability.AppFunctionalityStatus
import build.wallet.availability.AppFunctionalityStatusProviderMock
import build.wallet.availability.F8eUnreachable
import build.wallet.coachmark.CoachmarkServiceMock
import build.wallet.coroutines.turbine.turbines
import build.wallet.db.DbError
import build.wallet.firmware.FirmwareDeviceInfoDaoMock
import build.wallet.fwup.FirmwareData.FirmwareUpdateState.PendingUpdate
import build.wallet.fwup.FirmwareDataPendingUpdateMock
import build.wallet.fwup.FirmwareDataServiceFake
import build.wallet.fwup.FirmwareDataUpToDateMock
import build.wallet.fwup.FwupDataMock
import build.wallet.nfc.NfcCommandsMock
import build.wallet.nfc.NfcSessionFake
import build.wallet.statemachine.ScreenStateMachineMock
import build.wallet.statemachine.core.awaitScreenWithBody
import build.wallet.statemachine.core.awaitScreenWithBodyModelMock
import build.wallet.statemachine.core.form.FormBodyModel
import build.wallet.statemachine.core.form.FormMainContentModel.*
import build.wallet.statemachine.core.form.FormMainContentModel.DataList.Data
import build.wallet.statemachine.core.test
import build.wallet.statemachine.data.keybox.ActiveKeyboxLoadedDataMock
import build.wallet.statemachine.fwup.FwupNfcUiProps
import build.wallet.statemachine.fwup.FwupNfcUiStateMachine
import build.wallet.statemachine.nfc.NfcSessionUIStateMachine
import build.wallet.statemachine.nfc.NfcSessionUIStateMachineProps
import build.wallet.statemachine.recovery.losthardware.LostHardwareRecoveryProps
import build.wallet.statemachine.recovery.losthardware.LostHardwareRecoveryUiStateMachine
import build.wallet.statemachine.settings.full.device.fingerprints.EntryPoint
import build.wallet.statemachine.settings.full.device.fingerprints.ManagingFingerprintsProps
import build.wallet.statemachine.settings.full.device.fingerprints.ManagingFingerprintsUiStateMachine
import build.wallet.statemachine.settings.full.device.resetdevice.ResettingDeviceProps
import build.wallet.statemachine.settings.full.device.resetdevice.ResettingDeviceUiStateMachine
import build.wallet.time.DateTimeFormatterMock
import build.wallet.time.DurationFormatterFake
import build.wallet.time.TimeZoneProviderMock
import build.wallet.ui.model.toolbar.ToolbarAccessoryModel.IconAccessory
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.get
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeInstanceOf
import kotlinx.datetime.Instant
class DeviceSettingsUiStateMachineImplTests : FunSpec({
val firmwareDeviceInfoDao = FirmwareDeviceInfoDaoMock(turbines::create)
val appFunctionalityStatusProvider = AppFunctionalityStatusProviderMock()
val firmwareDataService = FirmwareDataServiceFake()
val stateMachine =
DeviceSettingsUiStateMachineImpl(
lostHardwareRecoveryUiStateMachine =
object : LostHardwareRecoveryUiStateMachine,
ScreenStateMachineMock<LostHardwareRecoveryProps>(
"initiate hw recovery"
) {},
nfcSessionUIStateMachine =
object : NfcSessionUIStateMachine, ScreenStateMachineMock<NfcSessionUIStateMachineProps<*>>(
"firmware metadata"
) {},
fwupNfcUiStateMachine =
object : FwupNfcUiStateMachine, ScreenStateMachineMock<FwupNfcUiProps>(
"fwup-nfc"
) {},
dateTimeFormatter = DateTimeFormatterMock(),
timeZoneProvider = TimeZoneProviderMock(),
durationFormatter = DurationFormatterFake(),
firmwareDeviceInfoDao = firmwareDeviceInfoDao,
appFunctionalityStatusProvider = appFunctionalityStatusProvider,
managingFingerprintsUiStateMachine = object : ManagingFingerprintsUiStateMachine,
ScreenStateMachineMock<ManagingFingerprintsProps>(
id = "managing fingerprints"
) {},
resettingDeviceUiStateMachine =
object : ResettingDeviceUiStateMachine, ScreenStateMachineMock<ResettingDeviceProps>(
"resetting device"
) {},
coachmarkService = CoachmarkServiceMock(turbineFactory = turbines::create),
firmwareDataService = firmwareDataService
)
val onBackCalls = turbines.create<Unit>("on back calls")
val props = DeviceSettingsProps(
accountData = ActiveKeyboxLoadedDataMock,
onBack = { onBackCalls += Unit },
onUnwindToMoneyHome = {}
)
val nfcCommandsMock = NfcCommandsMock(turbines::create)
beforeTest {
firmwareDeviceInfoDao.reset()
firmwareDataService.reset()
}
test("metadata is appropriately formatted with update") {
firmwareDataService.firmwareData.value =
FirmwareDataUpToDateMock.copy(
firmwareUpdateState = PendingUpdate(FwupDataMock)
)
stateMachine.test(props) {
awaitScreenWithBody<FormBodyModel> {
mainContentList[0].apply {
shouldBeInstanceOf<DataList>()
hero.shouldNotBeNull().apply {
title.shouldBe("Update available")
subtitle.shouldBe("1.2.3")
button.shouldNotBeNull().text.shouldBe("Update to fake")
}
items.verifyMetadataDataList()
buttons.size.shouldBe(1)
}
}
}
}
test("metadata is appropriately formatted with no update") {
stateMachine.test(props) {
awaitScreenWithBody<FormBodyModel> {
mainContentList[0].apply {
shouldBeInstanceOf<DataList>()
hero.shouldNotBeNull().apply {
title.shouldBe("Up to date")
subtitle.shouldBe("1.2.3")
button.shouldBeNull()
}
items.verifyMetadataDataList()
buttons.size.shouldBe(1)
}
}
}
}
test("sync device info") {
firmwareDeviceInfoDao.getDeviceInfo().get().shouldBeNull()
stateMachine.test(props) {
// Device settings
awaitScreenWithBody<FormBodyModel> {
mainContentList[0].apply {
shouldBeInstanceOf<DataList>()
buttons.first().onClick()
}
}
// Syncing info via NFC
awaitScreenWithBodyModelMock<NfcSessionUIStateMachineProps<Result<Unit, DbError>>> {
session(NfcSessionFake(), nfcCommandsMock)
onSuccess(Ok(Unit))
firmwareDeviceInfoDao.getDeviceInfo().get().shouldNotBeNull()
}
// Back to device settings
awaitScreenWithBody<FormBodyModel>()
}
}
test("lost or stolen device") {
stateMachine.test(props) {
awaitScreenWithBody<FormBodyModel> {
mainContentList[2].apply {
shouldBeInstanceOf<Button>()
item.text.shouldBe("Replace device")
item.onClick()
}
}
awaitScreenWithBodyModelMock<LostHardwareRecoveryProps>()
}
}
test("onBack calls") {
stateMachine.test(props) {
awaitScreenWithBody<FormBodyModel> {
val icon =
toolbar.shouldNotBeNull()
.leadingAccessory
.shouldBeInstanceOf<IconAccessory>()
icon.model.onClick.shouldNotBeNull()
.invoke()
}
onBackCalls.awaitItem().shouldBe(Unit)
}
}
test("fwup") {
val version = "fake-version"
firmwareDataService.firmwareData.value = FirmwareDataPendingUpdateMock.copy(
firmwareUpdateState =
PendingUpdate(
fwupData = FwupDataMock.copy(version = version)
)
)
stateMachine.test(props) {
// Device settings
awaitScreenWithBody<FormBodyModel> {
mainContentList[0].apply {
shouldBeInstanceOf<DataList>()
val updateButton = hero.shouldNotBeNull().button.shouldNotBeNull()
updateButton.text.shouldBe("Update to $version")
updateButton.onClick()
}
}
// FWUP-ing
awaitScreenWithBodyModelMock<FwupNfcUiProps> {
onDone()
}
// Back to device settings
awaitScreenWithBody<FormBodyModel>()
}
}
test("Replace device button should be disabled given limited functionality") {
stateMachine.test(props) {
awaitScreenWithBody<FormBodyModel> {
mainContentList[2].apply {
shouldBeInstanceOf<Button>()
item.text.shouldBe("Replace device")
item.isEnabled.shouldBeTrue()
}
}
appFunctionalityStatusProvider.appFunctionalityStatusFlow.emit(
AppFunctionalityStatus.LimitedFunctionality(
cause = F8eUnreachable(Instant.DISTANT_PAST)
)
)
awaitScreenWithBody<FormBodyModel> {
mainContentList[2].apply {
shouldBeInstanceOf<Button>()
item.text.shouldBe("Replace device")
item.isEnabled.shouldBeFalse()
}
}
}
}
test("tap on manage fingerprints") {
stateMachine.test(props) {
// Tap the Fingerprint button
awaitScreenWithBody<FormBodyModel> {
mainContentList[1].apply {
shouldBeInstanceOf<ListGroup>()
listGroupModel.items[0].onClick!!()
}
}
// Going to manage fingerprints
awaitScreenWithBodyModelMock<ManagingFingerprintsProps> {
onBack()
}
// Back on the device settings screen
awaitScreenWithBody<FormBodyModel>()
}
}
test("tap on manage fingerprints but need fwup") {
firmwareDataService.firmwareData.value = FirmwareDataPendingUpdateMock
stateMachine.test(props) {
// Tap the Fingerprint button
awaitScreenWithBody<FormBodyModel> {
mainContentList[1].apply {
shouldBeInstanceOf<ListGroup>()
listGroupModel.items[0].onClick!!()
}
}
awaitScreenWithBodyModelMock<ManagingFingerprintsProps> {
entryPoint.shouldBe(EntryPoint.DEVICE_SETTINGS)
onFwUpRequired()
}
// Device settings screen should be showing with a bottom sheet modal
with(awaitItem()) {
bottomSheetModel.shouldNotBeNull()
.body.shouldBeInstanceOf<FormBodyModel>().apply {
header.shouldNotBeNull()
.headline.shouldBe("Update your hardware device")
secondaryButton.shouldNotBeNull().apply {
text.shouldBe("Update hardware")
onClick.invoke()
}
}
}
// FWUP-ing
awaitScreenWithBodyModelMock<FwupNfcUiProps> {
onDone()
}
// Back to device settings
awaitScreenWithBody<FormBodyModel>()
}
}
test("tap on reset device") {
stateMachine.test(props) {
// Tap the Reset Device button
awaitScreenWithBody<FormBodyModel> {
mainContentList[1].apply {
shouldBeInstanceOf<ListGroup>()
listGroupModel.items[1].onClick!!()
}
}
// Going to manage reset device
awaitScreenWithBodyModelMock<ResettingDeviceProps> {
onBack()
}
// Back on the device settings screen
awaitScreenWithBody<FormBodyModel>()
}
}
})
private fun List<Data>.verifyMetadataDataList() {
forEachIndexed { index, data ->
when (index) {
0 -> data.verifyMetadataData("Model name", "Bitkey")
1 -> data.verifyMetadataData("Model number", "evtd")
2 -> data.verifyMetadataData("Serial number", "serial")
3 -> data.verifyMetadataData("Firmware version", "1.2.3")
4 -> data.verifyMetadataData(
"Last known charge",
"100%"
) // Not 89% due to battery level masking
5 -> data.verifyMetadataData("Last sync", "date-time")
}
}
}
private fun Data.verifyMetadataData(
title: String,
sideText: String,
) {
this.title.shouldBe(title)
this.sideText.shouldBe(sideText)
}
| 3 | null | 16 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 11,885 | bitkey | MIT License |
presentation/src/main/kotlin/com/kazakago/blueprint/presentation/hierarchy/githuborgs/GithubOrgRow.kt | KazaKago | 60,256,062 | false | null | package com.kazakago.blueprint.presentation.view.hierarchy.github
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.kazakago.blueprint.domain.model.hierarchy.github.GithubOrg
import com.kazakago.blueprint.domain.model.hierarchy.github.GithubOrgId
import com.kazakago.blueprint.domain.model.hierarchy.github.GithubOrgName
import com.kazakago.blueprint.presentation.view.R
import com.kazakago.blueprint.presentation.view.global.theme.PreviewTheme
import com.kazakago.blueprint.presentation.view.global.util.clickableWithRipple
import java.net.URL
@Composable
fun GithubOrgRow(
githubOrg: GithubOrg,
onClickItem: (githubOrg: GithubOrg) -> Unit,
) {
Row(
modifier = Modifier
.clickableWithRipple(onClick = { onClickItem(githubOrg) })
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(githubOrg.imageUrl.toString())
.crossfade(true)
.build(),
contentDescription = null,
modifier = Modifier
.size(32.dp)
.clip(RoundedCornerShape(6.dp)),
)
Spacer(modifier = Modifier.width(16.dp))
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = stringResource(R.string.id, githubOrg.id.value),
style = MaterialTheme.typography.labelMedium,
)
Spacer(modifier = Modifier.size(2.dp))
Text(
text = githubOrg.name.value,
style = MaterialTheme.typography.titleLarge,
)
}
}
}
@Preview(showBackground = true)
@Composable
fun PreviewGithubOrgRow() {
PreviewTheme {
Surface {
GithubOrgRow(
githubOrg = GithubOrg(id = GithubOrgId(1), name = GithubOrgName("kazakago"), imageUrl = URL("https://avatars.githubusercontent.com/u/7742104?v=4")),
onClickItem = {},
)
}
}
}
| 9 | null | 1 | 4 | 91dddf287b8df6e8a69d34627ef55f6556240bb0 | 2,673 | blueprint_android | Apache License 2.0 |
OpenNSFW/src/main/java/com/zwy/opennsfw/core/Config.kt | kenuoseclab | 262,616,728 | true | {"Kotlin": 94284} | package com.zwy.opennsfw.core
import android.content.Context
data class Config(
/**
* 是否开启GPU加速
*/
var isOpenGPU: Boolean = true,
var numThreads: Int = 1,
var context: Context?
) | 0 | Kotlin | 0 | 0 | 1f2b750ead5a4823e9de9467cef05149ccf9b847 | 206 | open_nsfw_android | Apache License 2.0 |
feature/discover/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/discover/view/implementation/ui/SearchField.kt | savvasdalkitsis | 485,908,521 | false | null | /*
Copyright 2022 <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 com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.clickable
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.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.windowsizeclass.WindowHeightSizeClass
import androidx.compose.runtime.Composable
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.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.seam.actions.ChangeFocus
import com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.seam.actions.DiscoverAction
import com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.seam.actions.QueryChanged
import com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.seam.actions.SearchFor
import com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.seam.actions.UpsellLoginFromSearch
import com.savvasdalkitsis.uhuruphotos.feature.discover.view.implementation.ui.state.DiscoverState
import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string
import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.window.LocalWindowSize
@Composable
fun SearchField(
state: DiscoverState,
action: (DiscoverAction) -> Unit,
) {
var query by remember(state.queryCacheKey) { mutableStateOf(state.latestQuery) }
Column(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp)
.clip(MaterialTheme.shapes.large)
) {
fun changeQuery(newQuery: String) {
query = newQuery
action(QueryChanged(newQuery))
}
val modifier = remember(state.isSearchEnabled) {
Modifier
.fillMaxWidth()
.onFocusChanged { action(ChangeFocus(it.isFocused)) }
.run {
if (state.isSearchEnabled)
this
else
clickable { action(UpsellLoginFromSearch) }
}
}
TextField(
modifier = modifier,
enabled = state.isSearchEnabled,
maxLines = 1,
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent,
),
trailingIcon = {
Row {
AnimatedVisibility(
visible = state.showClearButton,
enter = fadeIn(),
exit = fadeOut()
) {
IconButton(onClick = {
changeQuery("")
}) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = stringResource(string.clear)
)
}
}
IconButton(
enabled = state.isSearchEnabled,
onClick = { action(SearchFor(query)) }
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = stringResource(string.search_icon)
)
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(
autoCorrect = true,
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Search,
),
keyboardActions = KeyboardActions(
onSearch = { action(SearchFor(query)) }
),
placeholder = { Text(stringResource(string.search_for_something)) },
value = query,
onValueChange = ::changeQuery
)
val heightShort = LocalWindowSize.current.heightSizeClass == WindowHeightSizeClass.Compact
AnimatedVisibility(
visible = !heightShort && query.isNotEmpty() && state.searchSuggestions.isNotEmpty(),
) {
SearchSuggestions(state, action) {
query = it
action(SearchFor(it))
}
}
}
} | 51 | null | 16 | 258 | 5cab4fea988d3f0f077552d079a250267d8c2c97 | 6,136 | uhuruphotos-android | Apache License 2.0 |
src/main/kotlin/no/nav/k9/vaktmester/Meldinger.kt | navikt | 310,015,240 | false | {"Kotlin": 68944, "Dockerfile": 193} | package no.nav.k9.vaktmester
import org.json.JSONArray
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.lang.Thread.currentThread
import java.time.ZonedDateTime
internal object Meldinger {
private val logger = LoggerFactory.getLogger(Meldinger::class.java)
private val filnavn = System.getenv("MELDINGER_FILNAVN")
@JvmStatic
internal val ignorerteMeldinger : Map<String, String> = when (filnavn) {
null -> emptyMap()
else -> JSONObject("ignorer".resourcePath().fraResources()).toMap()
.mapValues { it.value.toString() }.also {
logger.info("Ignorerer ${it.size} meldinger")
}
}
@JvmStatic
internal val behovPåVent : Set<String> = when (filnavn) {
null -> emptySet()
else -> JSONArray("behovPåVent".resourcePath().fraResources()).map {
it.toString()
}.toSet().also {
logger.info("Behov satt på vent $it")
}
}
@JvmStatic
internal val fjernLøsning : Set<FjernLøsning> = when (filnavn) {
null -> emptySet()
else -> JSONArray("fjernLøsning".resourcePath().fraResources())
.map { it as JSONObject }
.map { FjernLøsning(
id = it.getString("@id")!!,
sistEndret = ZonedDateTime.parse(it.getString("@sistEndret")),
løsning = it.getString("løsning")!!
)}
.toSet().also {
logger.info("Fjerner løsning på ${it.size} meldinger")
}
}
@JvmStatic
internal val fjernBehov : Set<FjernBehov> = when (filnavn) {
null -> emptySet()
else -> JSONArray("fjernBehov".resourcePath().fraResources())
.map { it as JSONObject }
.map { FjernBehov(
id = it.getString("@id")!!,
sistEndret = ZonedDateTime.parse(it.getString("@sistEndret")),
behov = it.getString("behov")!!
)}
.toSet().also {
logger.info("Fjerner behov på ${it.size} meldinger")
}
}
@JvmStatic
internal val leggTilLøsning : Set<LeggTilLøsning> = when (filnavn) {
null -> emptySet()
else -> JSONArray("leggTilLøsning".resourcePath().fraResources())
.map { it as JSONObject }
.map { LeggTilLøsning(
id = it.getString("@id")!!,
sistEndret = ZonedDateTime.parse(it.getString("@sistEndret")),
løsningsbeskrivelse = it.getString("løsningsbeskrivelse")!!,
behov = it.getString("behov")!!
)}
.toSet().also {
logger.info("Legger til løsning for ${it.size} meldinger")
}
}
@JvmStatic
internal val nyeMeldinger : Set<NyMelding> = when (filnavn) {
null -> emptySet()
else -> JSONArray("nyeMeldinger".resourcePath().fraResources())
.map { it as JSONObject }
.map { NyMelding(
id = it.getString("@id")!!,
sistEndret = ZonedDateTime.parse(it.getString("@sistEndret")),
correlationId = it.getString("@correlationId")!!,
behovssekvens = it.toString()
)}
.toSet()
.also {
logger.info("Publiserer ${it.size} nye meldinger")
}
}
private fun String.resourcePath() = "meldinger/$this/$filnavn"
private fun String.fraResources() = requireNotNull(currentThread().contextClassLoader.getResource(this)) {
"Finner ikke JSON-fil på resource path '$this'"
}.readText(charset = Charsets.UTF_8)
internal interface MeldingId {
val id: String
val sistEndret: ZonedDateTime
}
internal data class FjernLøsning(
override val id: String,
override val sistEndret: ZonedDateTime,
internal val løsning: String) : MeldingId
internal data class FjernBehov(
override val id: String,
override val sistEndret: ZonedDateTime,
internal val behov: String) : MeldingId
internal data class LeggTilLøsning(
override val id: String,
override val sistEndret: ZonedDateTime,
internal val behov: String,
internal val løsningsbeskrivelse: String) : MeldingId
internal data class NyMelding(
override val id: String,
override val sistEndret: ZonedDateTime,
internal val correlationId: String,
internal val behovssekvens: String) : MeldingId {
internal fun erAktuell() = ZonedDateTime.now().minusHours(6).isBefore(sistEndret)
}
} | 2 | Kotlin | 1 | 0 | 9172c646bfd65e78331a333ba011350021a90b44 | 4,674 | k9-vaktmester | MIT License |
authorizer-app-backend/src/main/java/org/radarbase/authorizer/doa/RestSourceUserRepositoryImpl.kt | RADAR-base | 142,870,020 | false | null | /*
* Copyright 2020 The Hyve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.radarbase.authorizer.doa
import jakarta.inject.Provider
import jakarta.persistence.EntityManager
import jakarta.ws.rs.core.Context
import org.radarbase.authorizer.api.Page
import org.radarbase.authorizer.api.RestOauth2AccessToken
import org.radarbase.authorizer.api.RestSourceUserDTO
import org.radarbase.authorizer.doa.entity.RestSourceUser
import org.radarbase.jersey.exception.HttpConflictException
import org.radarbase.jersey.exception.HttpNotFoundException
import org.radarbase.jersey.hibernate.HibernateRepository
import org.radarbase.jersey.service.AsyncCoroutineService
import java.time.Duration
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.UUID
class RestSourceUserRepositoryImpl(
@Context em: Provider<EntityManager>,
@Context asyncService: AsyncCoroutineService,
) : RestSourceUserRepository, HibernateRepository(em, asyncService) {
override suspend fun create(user: RestSourceUserDTO): RestSourceUser = transact {
val existingUser = createQuery(
"""
SELECT u
FROM RestSourceUser u
WHERE u.sourceType = :sourceType
AND u.userId = :userId
""".trimIndent(),
RestSourceUser::class.java,
)
.setParameter("sourceType", user.sourceType)
.setParameter("userId", user.userId)
.resultList.firstOrNull()
if (existingUser != null) {
throw HttpConflictException("user_exists", "User ${user.userId} already exists.")
}
RestSourceUser(
projectId = user.projectId,
userId = user.userId,
sourceId = user.sourceId ?: UUID.randomUUID().toString(),
sourceType = user.sourceType,
createdAt = Instant.now(),
version = Instant.now().toString(),
startDate = user.startDate,
endDate = user.endDate,
).also {
persist(it)
}
}
private fun RestSourceUser.setToken(token: RestOauth2AccessToken?) {
if (token != null) {
if (token.externalUserId != null) {
this.externalUserId = token.externalUserId
}
this.authorized = true
this.accessToken = token.accessToken
this.refreshToken = token.refreshToken
this.expiresIn = token.expiresIn
this.expiresAt = Instant.now().plusSeconds(token.expiresIn.toLong()) - expiryTimeMargin
} else {
this.externalUserId = null
this.authorized = false
this.accessToken = null
this.refreshToken = null
this.expiresIn = null
this.expiresAt = null
}
}
override suspend fun updateToken(token: RestOauth2AccessToken?, user: RestSourceUser): RestSourceUser = transact {
user.apply {
setToken(token)
merge(this)
}
}
override suspend fun read(id: Long): RestSourceUser? = transact { find(RestSourceUser::class.java, id) }
override suspend fun update(userId: Long, user: RestSourceUserDTO): RestSourceUser = transact {
val existingUser = find(RestSourceUser::class.java, userId)
?: throw HttpNotFoundException("user_not_found", "User with ID $userId not found")
existingUser.apply {
this.version = Instant.now().toString()
this.timesReset += 1
this.startDate = user.startDate
this.endDate = user.endDate
merge(this)
}
}
override suspend fun query(
page: Page,
projectIds: List<String>,
sourceType: String?,
search: String?,
userIds: List<String>,
isAuthorized: Boolean?,
): Pair<List<RestSourceUser>, Page> {
val queryString = "SELECT u FROM RestSourceUser u WHERE u.projectId IN :projectIds"
val countQueryString = "SELECT count(u) FROM RestSourceUser u WHERE u.projectId IN :projectIds"
var whereClauses = ""
if (sourceType != null) {
whereClauses += " AND u.sourceType = :sourceType"
}
if (search != null) {
whereClauses += " AND (u.userId LIKE :search OR u.userId IN :userIds)"
}
if (isAuthorized != null) {
whereClauses += " AND u.authorized = :isAuthorized"
}
val actualPage = page.createValid(maximum = Integer.MAX_VALUE)
return transact {
val query = createQuery(queryString + whereClauses, RestSourceUser::class.java)
.setFirstResult(actualPage.offset)
.setMaxResults(actualPage.pageSize)
val countQuery = createQuery(countQueryString + whereClauses)
query.setParameter("projectIds", projectIds)
countQuery.setParameter("projectIds", projectIds)
if (sourceType != null) {
query.setParameter("sourceType", sourceType)
countQuery.setParameter("sourceType", sourceType)
}
if (search != null) {
// user IDs are always lower case in MP.
val searchMatch = "%${search.lowercase()}%"
query.setParameter("search", searchMatch)
query.setParameter("userIds", userIds)
countQuery.setParameter("search", searchMatch)
countQuery.setParameter("userIds", userIds)
}
if (isAuthorized != null) {
query.setParameter("isAuthorized", isAuthorized)
countQuery.setParameter("isAuthorized", isAuthorized)
}
val users = query.resultList
val count = countQuery.singleResult as Long
Pair(users, actualPage.copy(totalElements = count))
}
}
override suspend fun queryAllWithElapsedEndDate(
sourceType: String?,
): List<RestSourceUser> {
var queryString = """
SELECT u
FROM RestSourceUser u
WHERE u.endDate < :prevFourteenDays
""".trimIndent()
if (sourceType != null) {
queryString += " AND u.sourceType = :sourceType"
}
return transact {
createQuery(queryString, RestSourceUser::class.java).apply {
if (sourceType != null) {
setParameter("sourceType", sourceType)
}
setParameter("prevFourteenDays", Instant.now().minus(14, ChronoUnit.DAYS))
}.resultList
}
}
override suspend fun findByExternalId(
externalId: String,
sourceType: String,
): RestSourceUser? {
val result = transact {
createQuery(
"""
SELECT u
FROM RestSourceUser u
WHERE u.externalUserId = :externalId
AND u.sourceType = :sourceType
""".trimIndent(),
RestSourceUser::class.java,
).apply {
setParameter("sourceType", sourceType)
setParameter("externalId", externalId)
}.resultList
}
return if (result.isEmpty()) null else result[0]
}
override suspend fun delete(user: RestSourceUser) = transact {
remove(merge(user))
}
override suspend fun reset(user: RestSourceUser, startDate: Instant, endDate: Instant?) = transact {
user.apply {
this.version = Instant.now().toString()
this.timesReset += 1
this.startDate = startDate
this.endDate = endDate
}.also { merge(it) }
}
companion object {
private val expiryTimeMargin = Duration.ofMinutes(5)
}
}
| 43 | null | 1 | 2 | 24d5b4602910ead721969377cc3630c1c906c502 | 8,323 | RADAR-Rest-Source-Auth | Apache License 2.0 |
app/src/main/java/com/example/android/dagger/settings/SettingsViewModel.kt | googlecodelabs | 271,125,046 | 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.example.android.dagger.settings
import com.example.android.dagger.user.UserDataRepository
import com.example.android.dagger.user.UserManager
import javax.inject.Inject
class SettingsViewModel(
private val userDataRepository: UserDataRepository,
private val userManager: UserManager
) {
fun refreshNotifications() {
userDataRepository.refreshUnreadNotifications()
}
fun logout() {
userManager.logout()
}
}
| 6 | null | 32 | 93 | f6cbebeccec3188d4becffaf28fd24284ac77ad7 | 1,083 | android-dagger-to-hilt | Apache License 2.0 |
app/src/main/java/org/ergoplatform/android/transactions/ChooseSpendingWalletFragmentDialog.kt | Anoninuk | 412,749,887 | false | null | package org.ergoplatform.android.transactions
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import org.ergoplatform.android.*
import org.ergoplatform.android.databinding.FragmentSendFundsWalletChooserBinding
import org.ergoplatform.android.databinding.FragmentSendFundsWalletChooserItemBinding
import org.ergoplatform.android.ui.FullScreenFragmentDialog
import org.ergoplatform.android.ui.navigateSafe
import org.ergoplatform.android.wallet.getBalanceForAllAddresses
/**
* Deep link to send funds: Choose wallet to spend from
*/
class ChooseSpendingWalletFragmentDialog : FullScreenFragmentDialog() {
private var _binding: FragmentSendFundsWalletChooserBinding? = null
// This property is only valid between onCreateDialog and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSendFundsWalletChooserBinding.inflate(inflater, container, false)
// Inflate the layout for this fragment
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val query = requireActivity().intent.data?.encodedQuery
if (query == null) {
dismiss()
return
}
val content = parseContentFromQuery(query)
binding.receiverAddress.text = content?.address
val amount = content?.amount ?: ErgoAmount.ZERO
binding.grossAmount.amount = amount.toDouble()
binding.grossAmount.visibility = if (amount.nanoErgs > 0) View.VISIBLE else View.GONE
AppDatabase.getInstance(requireContext()).walletDao().getWalletsWithStates()
.observe(viewLifecycleOwner, {
binding.listWallets.removeAllViews()
val walletsWithoutReadonly = it.filter { it.walletConfig.secretStorage != null }
if (walletsWithoutReadonly.size == 1) {
// immediately switch to send funds screen
navigateToSendFundsScreen(walletsWithoutReadonly.first().walletConfig.id)
}
walletsWithoutReadonly.forEach { wallet ->
val itemBinding = FragmentSendFundsWalletChooserItemBinding.inflate(
layoutInflater, binding.listWallets, true
)
itemBinding.walletBalance.amount =
ErgoAmount(wallet.getBalanceForAllAddresses()).toDouble()
itemBinding.walletName.text = wallet.walletConfig.displayName
itemBinding.root.setOnClickListener {
navigateToSendFundsScreen(wallet.walletConfig.id)
}
}
})
}
private fun navigateToSendFundsScreen(walletId: Int) {
val navBuilder = NavOptions.Builder()
val navOptions =
navBuilder.setPopUpTo(R.id.chooseSpendingWalletFragmentDialog, true).build()
NavHostFragment.findNavController(requireParentFragment())
.navigateSafe(
ChooseSpendingWalletFragmentDialogDirections.actionChooseSpendingWalletFragmentDialogToSendFundsFragment(
requireActivity().intent.data?.encodedQuery!!, walletId
), navOptions
)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | null | 0 | 1 | 3c8d9d94aeea79eca831382f09d5b896d6a1652e | 3,689 | ergo-wallet-android | Apache License 2.0 |
app/spotifyapi/src/main/java/com/kpstv/spotifyapi/data/methods/SearchApi.kt | KaustubhPatange | 269,351,196 | false | null | package com.kpstv.spotifyapi.data.methods
import com.kpstv.spotifyapi.ResponseAction
import com.kpstv.spotifyapi.SpotifyClient
import com.kpstv.spotifyapi.data.models.Search
import com.kpstv.spotifyapi.enumerations.Type
import java.net.URLEncoder
class SearchApi(
private val client: SpotifyClient
) {
/**
* Get Spotify Catalog information about albums, artists, playlists, tracks,
* shows or episodes that match a keyword string.
*/
fun searchItem(
query: String,
types: Array<Type>,
limit: Int = 10,
offset: Int = 5,
responseAction: ResponseAction<Search>
) {
client.commonWorkFlow { b, _, exception ->
if (!b) {
responseAction.onError(exception ?: client.comExp)
return@commonWorkFlow
}
client.executeGETMethod(
url = "https://api.spotify.com/v1/search?q=${URLEncoder.encode(
query,
"UTF-8"
)}&limit=${limit}&offset=${offset}&type=${types.joinToString(",") { it.type }}",
type = Search::class.java,
responseAction = responseAction
)
}
}
} | 0 | Kotlin | 0 | 9 | 51410cfa2a8008da06689bd8c82928e4123efd13 | 1,219 | Unofficial-Spotify-SDK | Apache License 2.0 |
app/src/main/java/com/sniped/ui/main/detail/validator/MinLengthValidator.kt | ovitrif | 149,505,913 | false | null | package com.sniped.ui.main.detail.validator
import com.sniped.ui.validator.Validator
class MinLengthValidator(private val value: String) : Validator {
override fun isValid() = value.count() > 3
}
| 0 | Kotlin | 2 | 2 | ccf51fb07455ab975a5b0cfbc855f0eba0ec6792 | 203 | android-sniped | MIT License |
src/test/kotlin/partitions/File.kt | freemlang | 658,320,863 | false | {"Kotlin": 16229} | package partitions
import org.freem.compiler.frontend.Partition
import org.freem.compiler.frontend.PartitionField
class File private constructor(
val name: String,
val package_: Package,
val imports: List<Package>,
) {
companion object: Partition<File> {
override fun PartitionField.initialize(): File {
TODO("Not yet implemented")
}
}
} | 0 | Kotlin | 0 | 0 | c8ca97bfe00fb777545135df7c074d51b6af61f5 | 387 | freem | Apache License 2.0 |
app/src/main/kotlin/dev/mbo/dbq/task/dbqueue/jsonschema/JsonSchemaValidator.kt | mbogner | 487,622,806 | false | {"Kotlin": 77379, "PLpgSQL": 4569} | /*
* Copyright 2022 mbo.dev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.mbo.dbq.task.dbqueue.jsonschema
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.stereotype.Component
@Component
class JsonSchemaValidator(
private val jsonSchemaCache: JsonSchemaCache,
private val objectMapper: ObjectMapper,
) {
fun validatePayload(hash: String, schemaStr: String, payload: String): JsonNode {
val schema = jsonSchemaCache.parse(hash, schemaStr)
val json = objectMapper.readTree(payload)
val validationMessages = schema.validate(json)
if (validationMessages.isNotEmpty()) {
throw ListedJsonSchemaException(validationMessages)
}
return json
}
} | 0 | Kotlin | 0 | 0 | d89d18513f04f69a61e2a955db496548349e19a1 | 1,323 | dbq | Apache License 2.0 |
lib-test/src/main/java/io/sellmair/kompass/app/Identified.kt | nairobi222 | 181,482,076 | false | null | package io.sellmair.kompass.app
import android.graphics.Color
enum class Target {
FragmentOne,
FragmentTwo,
FragmentThree,
FragmentFour,
FragmentFive,
FragmentSix,
FragmentSeven,
FragmentEight,
FragmentNine,
FragmentTen,
ViewOne,
ViewTwo,
ViewThree,
ViewFour,
ViewFive
}
interface TargetIdentifiable {
val id: Target
}
val Target.color: Int
get() {
val targets = Target.values().size
val hueMax = 360f
val hue = ordinal.toFloat() / targets.toFloat() * hueMax
val saturation = 0.8f
val value = 0.8f
val hsv = floatArrayOf(hue, saturation, value)
return Color.HSVToColor(hsv)
}
| 1 | null | 1 | 1 | 855e3905f5367a41c00c7a45e5eaf35905c8f893 | 710 | kompass | Apache License 2.0 |
feature/qrcode/src/main/kotlin/com/masselis/tpmsadvanced/qrcode/interfaces/QRCodeViewModel.kt | VincentMasselis | 501,773,706 | false | null | package com.masselis.tpmsadvanced.qrcode.interfaces
import androidx.camera.view.CameraController
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.masselis.tpmsadvanced.core.feature.usecase.CurrentVehicleUseCase
import com.masselis.tpmsadvanced.data.vehicle.model.Vehicle
import com.masselis.tpmsadvanced.qrcode.model.SensorMap
import com.masselis.tpmsadvanced.qrcode.usecase.BoundSensorMapUseCase
import com.masselis.tpmsadvanced.qrcode.usecase.QrCodeAnalyserUseCase
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.BUFFERED
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class)
internal class QRCodeViewModel @AssistedInject constructor(
private val qrCodeAnalyserUseCase: QrCodeAnalyserUseCase,
private val boundSensorMapUseCase: BoundSensorMapUseCase,
private val currentVehicleUseCase: CurrentVehicleUseCase,
@Assisted private val controller: CameraController
) : ViewModel() {
@AssistedFactory
interface Factory : (CameraController) -> QRCodeViewModel
sealed class State {
data object Scanning : State()
sealed class AskForBinding : State() {
abstract val sensorMap: SensorMap
data class Compatible(override val sensorMap: SensorMap) : AskForBinding()
data class Missing(
override val sensorMap: SensorMap,
val localisations: Set<Vehicle.Kind.Location>
) : AskForBinding()
}
}
sealed class Event {
data object Leave : Event()
}
private val mutableStateFlow = MutableStateFlow<State>(State.Scanning)
val stateFlow = mutableStateFlow.asStateFlow()
private val channel = Channel<Event>(BUFFERED)
val eventChannel: ReceiveChannel<Event> = channel
init {
stateFlow
.flatMapLatest { state ->
when (state) {
is State.AskForBinding -> emptyFlow()
State.Scanning -> qrCodeAnalyserUseCase
.analyse(controller)
.flatMapLatest { sensorMap ->
currentVehicleUseCase
.map { it.vehicle.kind }
.distinctUntilChanged()
.map { vehicleKind ->
val missing = vehicleKind.locations
.subtract(vehicleKind.computeLocations(sensorMap.keys))
if (missing.isEmpty())
State.AskForBinding.Compatible(sensorMap)
else
State.AskForBinding.Missing(sensorMap, missing)
}
}
}
}.onEach { mutableStateFlow.value = it }
.launchIn(viewModelScope)
}
fun bindSensors() = viewModelScope.launch {
val state = mutableStateFlow.value
if (state !is State.AskForBinding)
return@launch
boundSensorMapUseCase.bind(state.sensorMap)
channel.send(Event.Leave)
}
fun scanAgain() {
mutableStateFlow.value = State.Scanning
}
}
| 6 | null | 1 | 1 | 6c0624dc94da5a1ce54c03eb156aa8f489ebf82f | 3,861 | TPMS-advanced | Apache License 2.0 |
commons/ui/src/main/java/es/littledavity/commons/ui/navigation/NavigationCommand.kt | Benderinos | 260,322,264 | false | null | /*
* Copyright 2021 dalodev
*/
package es.littledavity.commons.ui.navigation
import androidx.navigation.NavDirections
import androidx.navigation.fragment.FragmentNavigator
sealed class NavigationCommand {
data class To(val directions: NavDirections, val extras: FragmentNavigator.Extras? = null) : NavigationCommand()
object Back : NavigationCommand()
data class BackTo(val destinationId: Int) : NavigationCommand()
object ToRoot : NavigationCommand()
}
| 0 | Kotlin | 0 | 1 | 4f7f9d251c4da8e130a9f2b64879867bfecb44e8 | 474 | ChorboAgenda | Apache License 2.0 |
ktor-server/ktor-server-plugins/ktor-server-forwarded-header/jvmAndNix/src/io/ktor/server/plugins/forwardedheaders/ForwardedHeaders.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("DEPRECATION_ERROR")
package io.ktor.server.plugins.forwardedheaders
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.application.hooks.*
import io.ktor.server.plugins.*
import io.ktor.server.request.*
import io.ktor.util.*
import io.ktor.utils.io.*
/**
* A key for the application call attribute that is used to cache parsed header values.
*/
public val FORWARDED_PARSED_KEY: AttributeKey<List<ForwardedHeaderValue>> =
AttributeKey("ForwardedParsedKey")
/**
* A configuration for the [ForwardedHeaders] plugin.
*/
@KtorDsl
public class ForwardedHeadersConfig {
internal var forwardedHeadersHandler: (MutableOriginConnectionPoint, List<ForwardedHeaderValue>) -> Unit =
{ _, _ -> }
init {
useFirstValue()
}
/**
* Custom logic to extract the value from the Forward headers when multiple values are present.
* You need to modify [MutableOriginConnectionPoint] based on headers from [ForwardedHeaderValue].
*/
public fun extractValue(block: (MutableOriginConnectionPoint, List<ForwardedHeaderValue>) -> Unit) {
forwardedHeadersHandler = block
}
/**
* Takes the first value from the Forward header when multiple values are present.
*/
public fun useFirstValue() {
extractValue { connectionPoint, headers ->
setValues(connectionPoint, headers.firstOrNull())
}
}
/**
* Takes the last value from Forward header when multiple values are present.
*/
public fun useLastValue() {
extractValue { connectionPoint, headers ->
setValues(connectionPoint, headers.lastOrNull())
}
}
/**
* Takes [proxiesCount] before the last value from Forward header when multiple values are present.
*/
public fun skipLastProxies(proxiesCount: Int) {
extractValue { connectionPoint, headers ->
setValues(connectionPoint, headers.getOrElse(headers.size - proxiesCount - 1) { headers.last() })
}
}
/**
* Removes known [hosts] from the end of the list and takes the last value
* from Forward headers when multiple values are present.
*/
public fun skipKnownProxies(hosts: List<String>) {
extractValue { connectionPoint, headers ->
val forValues = headers.map { it.forParam }
var proxiesCount = 0
while (
hosts.lastIndex >= proxiesCount &&
forValues.lastIndex >= proxiesCount &&
hosts[hosts.size - proxiesCount - 1].trim() == forValues[forValues.size - proxiesCount - 1]?.trim()
) {
proxiesCount++
}
setValues(connectionPoint, headers.getOrElse(headers.size - proxiesCount - 1) { headers.last() })
}
}
private fun setValues(
connectionPoint: MutableOriginConnectionPoint,
forward: ForwardedHeaderValue?
) {
if (forward == null) {
return
}
if (forward.proto != null) {
val proto: String = forward.proto
connectionPoint.scheme = proto
URLProtocol.byName[proto]?.let { p ->
connectionPoint.port = p.defaultPort
connectionPoint.serverPort = p.defaultPort
}
}
if (forward.forParam != null) {
val remoteHostOrAddress = forward.forParam.split(",").first().trim()
if (remoteHostOrAddress.isNotBlank()) {
connectionPoint.remoteHost = remoteHostOrAddress
if (remoteHostOrAddress.isNotHostAddress()) {
connectionPoint.remoteAddress = remoteHostOrAddress
}
}
}
if (forward.host != null) {
val host = forward.host.substringBefore(':')
val port = forward.host.substringAfter(':', "")
connectionPoint.host = host
connectionPoint.serverHost = host
port.toIntOrNull()?.let {
connectionPoint.port = it
connectionPoint.serverPort = it
} ?: URLProtocol.byName[connectionPoint.scheme]?.let {
connectionPoint.port = it.defaultPort
connectionPoint.serverPort = it.defaultPort
}
}
}
}
/**
* Parsed a forwarded header value. All fields are optional as proxy could provide different fields.
* @property host field value (optional)
* @property by field value (optional)
* @property forParam field value (optional)
* @property proto field value (optional)
* @property others contains custom field values passed by proxy
*/
public data class ForwardedHeaderValue(
val host: String?,
val by: String?,
val forParam: String?,
val proto: String?,
val others: Map<String, String>
)
/**
* A plugin that allows you to handle reverse proxy headers to get information
* about the original request when a Ktor server is placed behind a reverse proxy.
*
* To learn how to install and use [ForwardedHeaders], see
* [Forwarded headers](https://ktor.io/docs/forward-headers.html).
*/
public val ForwardedHeaders: ApplicationPlugin<ForwardedHeadersConfig> = createApplicationPlugin(
"ForwardedHeaders",
::ForwardedHeadersConfig
) {
fun parseForwardedValue(value: HeaderValue): ForwardedHeaderValue {
val map = value.params.associateByTo(HashMap(), { it.name }, { it.value })
return ForwardedHeaderValue(
map.remove("host"),
map.remove("by"),
map.remove("for"),
map.remove("proto"),
map
)
}
fun ApplicationRequest.forwardedHeaders() =
headers.getAll(HttpHeaders.Forwarded)
?.flatMap { it.split(',') }
?.flatMap { parseHeaderValue(";$it") }?.map {
parseForwardedValue(it)
}
on(CallSetup) { call ->
val forwardedHeaders = call.request.forwardedHeaders() ?: return@on
call.attributes.put(FORWARDED_PARSED_KEY, forwardedHeaders)
pluginConfig.forwardedHeadersHandler.invoke(call.mutableOriginConnectionPoint, forwardedHeaders)
}
}
| 269 | Kotlin | 962 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 6,304 | ktor | Apache License 2.0 |
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/presentation/validators/parcel/StakeTargetDetailsParcelModel.kt | novasamatech | 415,834,480 | false | {"Kotlin": 7667771, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_staking_impl.presentation.validators.parcel
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
class StakeTargetDetailsParcelModel(
val accountIdHex: String,
val isSlashed: Boolean,
val stake: StakeTargetStakeParcelModel,
val identity: IdentityParcelModel?,
) : Parcelable
| 17 | Kotlin | 6 | 9 | 67cd6fd77aae24728a27b81eb7f26ac586463aaa | 359 | nova-wallet-android | Apache License 2.0 |
app/src/main/java/com/laotoua/dawnislandk/util/GlobalExtensions.kt | yudanhezhongweijie | 250,138,603 | false | null | /*
* Copyright 2020 Fishballzzz
* *
* * 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.laotoua.dawnislandk.util
import android.app.Activity
import android.content.Intent
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Parcelable
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Transformations
import com.laotoua.dawnislandk.BuildConfig
import com.laotoua.dawnislandk.data.local.entity.Comment
import timber.log.Timber
fun <T> lazyOnMainOnly(initializer: () -> T): Lazy<T> = lazy(LazyThreadSafetyMode.NONE, initializer)
fun List<Comment>?.equalsWithServerComments(targetList: List<Comment>?): Boolean {
return if (this == null || targetList == null) false
else if (this.size != targetList.size) false
else {
this.zip(targetList).all { (r1, r2) ->
r1.equalsWithServerData(r2)
}
}
}
fun <T> getLocalDataResource(cache: LiveData<T>): LiveData<DataResource<T>> {
return Transformations.map(cache) {
Timber.d("Got ${if (it == null) "NO" else ""} data from database")
val status: LoadingStatus =
if (it == null) LoadingStatus.NO_DATA else LoadingStatus.SUCCESS
DataResource.create(status, it)
}
}
fun <T> getLocalListDataResource(cache: LiveData<List<T>>): LiveData<DataResource<List<T>>> {
return Transformations.map(cache) {
Timber.d("Got ${it.size} rows from database")
val status: LoadingStatus = if (it.isNullOrEmpty()) LoadingStatus.NO_DATA else LoadingStatus.SUCCESS
DataResource.create(status, it)
}
}
// data only in local cache, but remote acts as a message transmitter
fun <T> getLocalLiveDataAndRemoteResponse(
cache: LiveData<DataResource<T>>,
remote: LiveData<DataResource<T>>
): LiveData<DataResource<T>> {
val result = MediatorLiveData<DataResource<T>>()
result.value = DataResource.create()
result.addSource(cache) {
result.value = it
}
result.addSource(remote) {
if (it.status == LoadingStatus.NO_DATA || it.status == LoadingStatus.ERROR) {
result.value = it
}
}
return result
}
fun openLinksWithOtherApps(uri: String, activity: Activity) {
val activities: List<ResolveInfo> =
activity.packageManager.queryIntentActivities(Intent(Intent.ACTION_VIEW, Uri.parse(uri)), 0)
val packageNameToHide = BuildConfig.APPLICATION_ID
val targetIntents: ArrayList<Intent> = ArrayList()
for (currentInfo in activities) {
val packageName: String = currentInfo.activityInfo.packageName
if (packageNameToHide != packageName) {
val targetIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
targetIntent.setPackage(packageName)
targetIntents.add(targetIntent)
}
}
if (targetIntents.isNotEmpty()) {
val chooserIntent: Intent = Intent.createChooser(targetIntents.removeAt(0), "请使用以下软件打开链接")
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(arrayOf<Parcelable>()))
activity.startActivity(chooserIntent)
} else {
Toast.makeText(activity, "没有找到可以打开链接的软件,请和开发者联系", Toast.LENGTH_SHORT).show()
}
}
| 4 | null | 6 | 53 | fb4d00107a7c66abb9222c175f2090a782da92e4 | 3,817 | DawnIslandK | Apache License 2.0 |
urbanairship-core/src/test/java/com/urbanairship/channel/ChannelBatchUpdateManagerTest.kt | urbanairship | 58,972,818 | false | null | package com.urbanairship.channel
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.urbanairship.PreferenceDataStore
import com.urbanairship.audience.AudienceOverrides
import com.urbanairship.audience.AudienceOverridesProvider
import com.urbanairship.http.RequestResult
import com.urbanairship.json.JsonValue
import com.urbanairship.json.jsonListOf
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.slot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
public class ChannelBatchUpdateManagerTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val preferenceDataStore = PreferenceDataStore.inMemoryStore(context)
private val pendingAudienceDelegate = slot<(String) -> AudienceOverrides.Channel>()
private val mockAudienceOverridesProvider = mockk<AudienceOverridesProvider> {
every {
[email protected] = capture(pendingAudienceDelegate)
} just runs
}
private val mockApiClient = mockk<ChannelBatchUpdateApiClient>()
private val testDispatcher = StandardTestDispatcher()
private val manager = ChannelBatchUpdateManager(
preferenceDataStore,
mockApiClient,
mockAudienceOverridesProvider
)
@Before
public fun setup() {
Dispatchers.setMain(testDispatcher)
}
@After
public fun tearDown() {
Dispatchers.resetMain()
}
@Test
public fun testAddUpdate(): TestResult = runTest {
manager.addUpdate(
tags = listOf(TagGroupsMutation.newSetTagsMutation("some group", setOf("tag")))
)
manager.addUpdate(
subscriptions = listOf(SubscriptionListMutation.newSubscribeMutation("some list", 100))
)
manager.addUpdate(
attributes = listOf(AttributeMutation.newRemoveAttributeMutation("some attribute", 100))
)
val expectedPending = AudienceOverrides.Channel(
listOf(TagGroupsMutation.newSetTagsMutation("some group", setOf("tag"))),
listOf(AttributeMutation.newRemoveAttributeMutation("some attribute", 100)),
listOf(SubscriptionListMutation.newSubscribeMutation("some list", 100))
)
assertEquals(expectedPending, pendingAudienceDelegate.captured.invoke("anything"))
}
@Test
public fun testClearPending(): TestResult = runTest {
manager.addUpdate(
tags = listOf(TagGroupsMutation.newSetTagsMutation("some group", setOf("tag"))),
subscriptions = listOf(SubscriptionListMutation.newSubscribeMutation("some list", 100)),
attributes = listOf(AttributeMutation.newRemoveAttributeMutation("some attribute", 100))
)
assertTrue(manager.hasPending)
manager.clearPending()
assertEquals(AudienceOverrides.Channel(), pendingAudienceDelegate.captured.invoke("anything"))
assertFalse(manager.hasPending)
}
@Test
public fun testClearPendingNoUpdates(): TestResult = runTest {
assertEquals(AudienceOverrides.Channel(), pendingAudienceDelegate.captured.invoke("anything"))
manager.clearPending()
assertEquals(AudienceOverrides.Channel(), pendingAudienceDelegate.captured.invoke("anything"))
}
@Test
public fun testMigrate(): TestResult = runTest {
// Attributes are stored as a list of lists
preferenceDataStore.put(
"com.urbanairship.push.ATTRIBUTE_DATA_STORE",
jsonListOf(
listOf(
AttributeMutation.newRemoveAttributeMutation("some attribute", 100),
AttributeMutation.newRemoveAttributeMutation("some other attribute", 100)
),
listOf(
AttributeMutation.newSetAttributeMutation("some attribute", JsonValue.wrapOpt("neat"), 100)
)
)
)
// Subscriptions are stored as a list of lists
preferenceDataStore.put(
"com.urbanairship.push.PENDING_SUBSCRIPTION_MUTATIONS",
jsonListOf(
listOf(
SubscriptionListMutation.newSubscribeMutation("some list", 100),
SubscriptionListMutation.newUnsubscribeMutation("some other list", 100)
),
listOf(
SubscriptionListMutation.newSubscribeMutation("some other list", 100)
)
)
)
// Tags are stored as a list of mutations
preferenceDataStore.put(
"com.urbanairship.push.PENDING_TAG_GROUP_MUTATIONS",
jsonListOf(
TagGroupsMutation.newSetTagsMutation("some group", setOf("tag")),
TagGroupsMutation.newSetTagsMutation("some other group", setOf("tag"))
)
)
manager.migrateData()
// Verify its deleted
assertFalse(preferenceDataStore.isSet("com.urbanairship.push.PENDING_TAG_GROUP_MUTATIONS"))
assertFalse(preferenceDataStore.isSet("com.urbanairship.push.PENDING_SUBSCRIPTION_MUTATIONS"))
assertFalse(preferenceDataStore.isSet("com.urbanairship.push.ATTRIBUTE_DATA_STORE"))
// Check expected
val expectedPending = AudienceOverrides.Channel(
listOf(
TagGroupsMutation.newSetTagsMutation("some group", setOf("tag")),
TagGroupsMutation.newSetTagsMutation("some other group", setOf("tag"))
),
listOf(
AttributeMutation.newRemoveAttributeMutation("some attribute", 100),
AttributeMutation.newRemoveAttributeMutation("some other attribute", 100),
AttributeMutation.newSetAttributeMutation("some attribute", JsonValue.wrapOpt("neat"), 100)
),
listOf(
SubscriptionListMutation.newSubscribeMutation("some list", 100),
SubscriptionListMutation.newUnsubscribeMutation("some other list", 100),
SubscriptionListMutation.newSubscribeMutation("some other list", 100)
)
)
assertEquals(expectedPending, pendingAudienceDelegate.captured.invoke("anything"))
}
@Test
public fun testUploadNoUpdates(): TestResult = runTest {
manager.clearPending()
assertTrue(manager.uploadPending("some channel"))
}
@Test
public fun testUpload(): TestResult = runTest {
manager.addUpdate(
tags = listOf(
TagGroupsMutation.newAddTagsMutation("some group", setOf("tag")),
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
)
)
manager.addUpdate(
attributes = listOf(
AttributeMutation.newRemoveAttributeMutation("some attribute", 100),
AttributeMutation.newRemoveAttributeMutation("some other attribute", 100),
AttributeMutation.newSetAttributeMutation("some attribute", JsonValue.wrapOpt("neat"), 100)
)
)
manager.addUpdate(
subscriptions = listOf(
SubscriptionListMutation.newSubscribeMutation("some list", 100),
SubscriptionListMutation.newUnsubscribeMutation("some other list", 100),
SubscriptionListMutation.newSubscribeMutation("some other list", 100)
)
)
manager.addUpdate(
liveUpdates = listOf(
LiveUpdateMutation.Remove("some event", 100, 100),
LiveUpdateMutation.Set("some other event", 100, 100)
)
)
coEvery { mockApiClient.update(any(), any(), any(), any(), any()) } returns RequestResult(
status = 200,
value = null,
body = null,
headers = null
)
coEvery { mockAudienceOverridesProvider.recordChannelUpdate(any(), any(), any(), any()) } just runs
assertTrue(manager.uploadPending("some channel id"))
coVerify {
mockApiClient.update(
channelId = "some channel id",
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
),
attributes = listOf(
AttributeMutation.newRemoveAttributeMutation("some other attribute", 100),
AttributeMutation.newSetAttributeMutation("some attribute", JsonValue.wrapOpt("neat"), 100)
),
subscriptions = listOf(
SubscriptionListMutation.newSubscribeMutation("some list", 100),
SubscriptionListMutation.newSubscribeMutation("some other list", 100)
),
liveUpdates = listOf(
LiveUpdateMutation.Remove("some event", 100, 100),
LiveUpdateMutation.Set("some other event", 100, 100)
)
)
}
coVerify {
mockAudienceOverridesProvider.recordChannelUpdate(
channelId = "some channel id",
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
),
attributes = listOf(
AttributeMutation.newRemoveAttributeMutation("some other attribute", 100),
AttributeMutation.newSetAttributeMutation("some attribute", JsonValue.wrapOpt("neat"), 100)
),
subscriptions = listOf(
SubscriptionListMutation.newSubscribeMutation("some list", 100),
SubscriptionListMutation.newSubscribeMutation("some other list", 100)
),
)
}
assertFalse(manager.hasPending)
}
@Test
public fun testUploadFailsServerError(): TestResult = runTest {
manager.addUpdate(
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
)
)
coEvery { mockApiClient.update(any(), any(), any(), any(), any()) } returns RequestResult(
status = 500,
value = null,
body = null,
headers = null
)
assertFalse(manager.uploadPending("some channel id"))
coVerify {
mockApiClient.update(
channelId = "some channel id",
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
),
attributes = emptyList(),
subscriptions = emptyList(),
liveUpdates = emptyList(),
)
}
assertTrue(manager.hasPending)
}
@Test
public fun testUploadClientError(): TestResult = runTest {
manager.addUpdate(
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
)
)
coEvery { mockApiClient.update(any(), any(), any(), any(), any()) } returns RequestResult(
status = 400,
value = null,
body = null,
headers = null
)
// We treat a client error as success since we pop the pending changes
assertTrue(manager.uploadPending("some channel id"))
coVerify {
mockApiClient.update(
channelId = "some channel id",
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
),
attributes = emptyList(),
subscriptions = emptyList(),
liveUpdates = emptyList(),
)
}
assertFalse(manager.hasPending)
}
@Test
public fun testUploadException(): TestResult = runTest {
manager.addUpdate(
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
)
)
coEvery { mockApiClient.update(any(), any(), any(), any(), any()) } returns RequestResult(
exception = IllegalArgumentException()
)
assertFalse(manager.uploadPending("some channel id"))
coVerify {
mockApiClient.update(
channelId = "some channel id",
tags = listOf(
TagGroupsMutation.newRemoveTagsMutation("some group", setOf("tag"))
),
attributes = emptyList(),
subscriptions = emptyList(),
liveUpdates = emptyList(),
)
}
assertTrue(manager.hasPending)
}
}
| 2 | null | 122 | 111 | 21d49c3ffd373e3ba6b51a706a4839ab3713db11 | 13,378 | android-library | Apache License 2.0 |
kvision-modules/kvision-material/src/jsMain/kotlin/io/kvision/material/slot/TextSlots.kt | rjaros | 120,835,750 | false | {"Kotlin": 3524783, "CSS": 25183, "JavaScript": 16390, "HTML": 2425} | /*
* Copyright (c) 2017-present <NAME>
* Copyright (c) 2024 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.kvision.material.slot
import io.kvision.html.Div
private inline fun textSlot(text: String, block: (Div) -> Unit): Div {
return Div(content = text).also(block)
}
/**
* Sets the [text] to the content slot.
*/
fun HasContentSlot.content(text: String) = textSlot(text, ::content)
/**
* Sets the [text] to the headline slot.
*/
fun HasHeadlineSlot.headline(text: String) = textSlot(text, ::headline)
/**
* Sets the [text] to the supporting text slot.
*/
fun HasSupportingTextSlot.supportingText(text: String) = textSlot(text, ::supportingText)
/**
* Sets the [text] to the trailing supporting text slot.
*/
fun HasTrailingSupportingTextSlot.trailingSupportingText(text: String) =
textSlot(text, ::trailingSupportingText)
| 17 | Kotlin | 65 | 1,235 | 7daa34594be70c037bfbaeefbfd1e3d7629e1e0b | 1,907 | kvision | MIT License |
grow.kotlin/arieldossantos/src/main/kotlin/com/growth/response/GrowthListCountResponse.kt | jeffotoni | 384,337,098 | false | null | package com.growth.response
data class GrowthListCountResponse(
val msg: String,
val testValue: Double? = null,
val count: Int = 0
)
| 2 | Go | 17 | 40 | 6e1c5906bfc25a4ffcb2ce74d18c786e449c9bef | 146 | growth | MIT License |
mvvm-dagger/src/main/java/com/nphau/android/shared/screens/UIBehaviour.kt | ThanhHuong98 | 432,947,065 | false | {"Kotlin": 165721, "Java": 1330, "Shell": 87} | package com.imstudio.android.shared.screens
import android.os.Bundle
interface UIBehaviour {
fun showError(message: String?)
fun onSyncViews(savedInstanceState: Bundle?)
fun onSyncEvents()
fun onSyncData()
fun makeVibrator()
fun doNotCare()
fun showLoading(isShow: Boolean, timeout: Long = 2_000)
}
| 0 | null | 0 | 1 | ac0402ae4734285ef5e647d1f53a1f9f4a8d98cd | 337 | android.clean-architecture.mvvm | Apache License 2.0 |
idea/src/org/jetbrains/kotlin/idea/filters/InlineFunctionHyperLinkInfo.kt | JetBrains | 278,369,660 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.execution.filters.FileHyperlinkInfo
import com.intellij.execution.filters.HyperlinkInfoBase
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.awt.RelativePoint
import org.jetbrains.annotations.Nls
import java.awt.Component
import javax.swing.JList
import javax.swing.ListCellRenderer
class InlineFunctionHyperLinkInfo(
private val project: Project,
private val inlineInfo: List<InlineInfo>
) : HyperlinkInfoBase(), FileHyperlinkInfo {
override fun navigate(project: Project, hyperlinkLocationPoint: RelativePoint?) {
if (inlineInfo.isEmpty()) return
if (inlineInfo.size == 1) {
OpenFileHyperlinkInfo(project, inlineInfo.first().file, inlineInfo.first().line).navigate(project)
} else {
val popup = JBPopupFactory.getInstance().createPopupChooserBuilder(inlineInfo)
.setTitle(KotlinDebuggerCoreBundle.message("filters.title.navigate.to"))
.setRenderer(InlineInfoCellRenderer())
.setItemChosenCallback { fileInfo ->
fileInfo?.let { OpenFileHyperlinkInfo(project, fileInfo.file, fileInfo.line).navigate(project) }
}
.createPopup()
if (hyperlinkLocationPoint != null) {
popup.show(hyperlinkLocationPoint)
} else {
popup.showInFocusCenter()
}
}
}
override fun getDescriptor(): OpenFileDescriptor? {
val file = inlineInfo.firstOrNull()
return file?.let { OpenFileDescriptor(project, file.file, file.line, 0) }
}
val callSiteDescriptor: OpenFileDescriptor?
get() {
val file = inlineInfo.firstOrNull { it is InlineInfo.CallSiteInfo }
return file?.let { OpenFileDescriptor(project, file.file, file.line, 0) }
}
sealed class InlineInfo(@Nls val prefix: String, val file: VirtualFile, val line: Int) {
class CallSiteInfo(file: VirtualFile, line: Int) :
InlineInfo(KotlinDebuggerCoreBundle.message("filters.text.inline.function.call.site"), file, line)
class InlineFunctionBodyInfo(file: VirtualFile, line: Int) :
InlineInfo(KotlinDebuggerCoreBundle.message("filters.text.inline.function.body"), file, line)
}
private class InlineInfoCellRenderer : SimpleColoredComponent(), ListCellRenderer<InlineInfo> {
init {
isOpaque = true
}
override fun getListCellRendererComponent(
list: JList<out InlineInfo>?,
value: InlineInfo?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
clear()
if (value != null) {
append(value.prefix)
}
if (isSelected) {
background = list?.selectionBackground
foreground = list?.selectionForeground
} else {
background = list?.background
foreground = list?.foreground
}
return this
}
}
}
| 191 | null | 4372 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 3,573 | intellij-kotlin | Apache License 2.0 |
saved-sites/saved-sites-impl/src/main/java/com/duckduckgo/savedsites/impl/sync/SavedSiteSyncPausedViewModel.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2023 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.autofill.sync
import android.annotation.SuppressLint
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.duckduckgo.anvil.annotations.ContributesViewModel
import com.duckduckgo.autofill.impl.R
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.di.scopes.ViewScope
import com.duckduckgo.sync.api.engine.FeatureSyncError
import javax.inject.Inject
import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
@SuppressLint("NoLifecycleObserver") // does not subscribe to app lifecycle
@ContributesViewModel(ViewScope::class)
class CredentialsSyncPausedViewModel @Inject constructor(
private val credentialsSyncStore: CredentialsSyncStore,
private val dispatcherProvider: DispatcherProvider,
) : ViewModel(), DefaultLifecycleObserver {
data class ViewState(
val message: Int? = null,
)
sealed class Command {
data object NavigateToCredentials : Command()
}
private val command = Channel<Command>(1, DROP_OLDEST)
fun viewState(): Flow<ViewState> = credentialsSyncStore.isSyncPausedFlow()
.map { syncPaused ->
val message = when (credentialsSyncStore.syncPausedReason) {
FeatureSyncError.COLLECTION_LIMIT_REACHED.name -> R.string.credentials_limit_warning
FeatureSyncError.INVALID_REQUEST.name -> R.string.credentials_invalid_request_warning
else -> null
}
ViewState(
message = message,
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), ViewState())
fun commands(): Flow<Command> = command.receiveAsFlow()
fun onWarningActionClicked() {
viewModelScope.launch {
command.send(Command.NavigateToCredentials)
}
}
}
| 67 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 2,754 | Android | Apache License 2.0 |
app/src/main/java/ac/id/unikom/codelabs/navigasee/utilities/service/foregroundconnect/LocationManager.kt | mnkadafi | 621,252,553 | false | null | package ac.id.unikom.codelabs.navigasee.utilities.service.foregroundconnect
import ac.id.unikom.codelabs.navigasee.MyApplication
import ac.id.unikom.codelabs.navigasee.data.source.UpdateStatusRepository
import ac.id.unikom.codelabs.navigasee.utilities.helper.Preferences
import android.os.Looper
import android.util.Log
import com.google.android.gms.location.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class LocationManager {
private val fusedLocationProviderClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MyApplication.getContext())
private var locationCallback: LocationCallback
private val preferences = Preferences.getInstance()
private var locationRequest: LocationRequest
init {
locationRequest = LocationRequest().apply {
// Sets the desired interval for active location updates. This interval is inexact. You
// may not receive updates at all if no location sources are available, or you may
// receive them less frequently than requested. You may also receive updates more
// frequently than requested if other applications are requesting location at a more
// frequent interval.
//
// IMPORTANT NOTE: Apps running on Android 8.0 and higher devices (regardless of
// targetSdkVersion) may receive updates less frequently than this interval when the app
// is no longer in the foreground.
val INTERVAL = 3000L
val FASTEST_INTERVAL = INTERVAL / 2
interval = INTERVAL
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates more frequently than this value.
fastestInterval = FASTEST_INTERVAL
// Sets the maximum time when batched location updates are delivered. Updates may be
// delivered sooner than this interval.
// maxWaitTime = TimeUnit.MINUTES.toMillis(1)
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
smallestDisplacement = 10F
}
// Step 1.4, Initialize the LocationCallback.
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
if (locationResult.lastLocation != null) {
// Normally, you want to save a new location to a database. We are simplifying
// things a bit and just saving it as a local variable, as we only need it again
// if a Notification is created (when user navigates away from app).
GlobalScope.launch(Dispatchers.IO) {
delay(36 * 100)
preferences.saveLocation(locationResult.lastLocation.longitude.toString(), locationResult.lastLocation.latitude.toString(), "")
val repo = UpdateStatusRepository.getInstance()
val lat = preferences.getLatitude()?.toDouble()
val long = preferences.getLongitude()?.toDouble()
repo.updateStatus(1, lat!!, long!!)
}
} else {
Log.d(this::class.java.simpleName, "Location information isn't available.")
}
}
}
}
fun stopMyLocation() {
try {
// Step 1.6, Unsubscribe to location changes.
val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)
removeTask.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(this::class.java.simpleName, "Location Callback removed.")
} else {
Log.d(this::class.java.simpleName, "Failed to remove Location Callback.")
}
}
} catch (unlikely: SecurityException) {
Log.d(this::class.java.simpleName, "Lost location permissions. Couldn't remove updates. $unlikely")
}
}
fun getMyLocation() {
try {
// Step 1.5, Subscribe to location changes.
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
} catch (unlikely: SecurityException) {
Log.e(this::class.java.simpleName, "Lost location permissions. Couldn't remove updates. $unlikely")
} catch (e: Exception) {
e.printStackTrace()
}
}
companion object {
// For Singleton instantiation
private var instance: LocationManager? = null
fun getInstance() = instance
?: LocationManager().also { instance = it }
}
} | 0 | Kotlin | 0 | 0 | 8c796c51ce1096bfbc8b9f71ae33395c56065fc3 | 4,950 | Voiye | Apache License 2.0 |
app/src/main/java/org/wikipedia/suggestededits/SuggestionsActivity.kt | wikimedia | 13,862,999 | false | null | package org.wikipedia.suggestededits
import android.content.Context
import android.content.Intent
import android.os.Bundle
import org.wikipedia.Constants
import org.wikipedia.Constants.INTENT_EXTRA_ACTION
import org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE
import org.wikipedia.activity.SingleFragmentActivity
import org.wikipedia.descriptions.DescriptionEditActivity.Action
import org.wikipedia.suggestededits.SuggestedEditsCardsFragment.Companion.newInstance
class SuggestionsActivity : SingleFragmentActivity<SuggestedEditsCardsFragment>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setImageZoomHelper()
}
override fun onBackPressed() {
if (fragment.topBaseChild()?.onBackPressed() == false) {
return
}
super.onBackPressed()
}
override fun createFragment(): SuggestedEditsCardsFragment {
return newInstance(intent.getSerializableExtra(INTENT_EXTRA_ACTION) as Action,
intent.getSerializableExtra(INTENT_EXTRA_INVOKE_SOURCE) as Constants.InvokeSource)
}
companion object {
const val EXTRA_SOURCE_ADDED_CONTRIBUTION = "addedContribution"
fun newIntent(context: Context, action: Action, source: Constants.InvokeSource): Intent {
return Intent(context, SuggestionsActivity::class.java)
.putExtra(INTENT_EXTRA_ACTION, action)
.putExtra(INTENT_EXTRA_INVOKE_SOURCE, source)
}
}
}
| 34 | null | 599 | 2,250 | 32b9315d26af6cab3f5bfde990ab8b6ee5444786 | 1,519 | apps-android-wikipedia | Apache License 2.0 |
inspector/src/main/kotlin/com/jakeout/gradle/inspector/InspectorConfig.kt | jakeouellette | 35,901,832 | false | null | package com.jakeout.gradle.inspector
import org.gradle.api.Task
import java.io.File
data class InspectorConfig(
val cleanUpEachTask: Boolean,
val compareBuild: Boolean,
val showInspection: Boolean,
val incrementalDir: File,
val inspectionRoot: File,
val projectBuildDir: File,
val reportDir: File,
val compareIncrementalDir: File,
val compareInspectionRoot: File,
val compareReportDir: File) {
fun taskOut(task: Task) = File(incrementalDir, task.nameString() + ".diff")
fun compareTaskOut(task: Task) = File(incrementalDir, task.nameString() + ".compare.diff")
fun taskReport(task: Task) = task.nameString() + "-report.html"
fun taskDir(task: Task) = File(incrementalDir, task.nameString())
fun compareTaskDir(task: Task) = File(compareIncrementalDir, task.nameString())
fun Task.nameString() = getName().replace(":", ".")
fun index() = File(reportDir, "index.html")
}
| 7 | JavaScript | 10 | 218 | 7ee81d50bdee4763ce6298a95ae589032ab4d749 | 980 | inspector | MIT License |
app/src/main/java/com/app/hcmut/mymovie/feature/movies/MoviesActivity.kt | youknowbaron | 186,788,809 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 45, "XML": 53, "Java": 1, "JSON": 3} | package com.app.hcmut.mymovie.feature.movies
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.viewpager.widget.ViewPager
import com.app.hcmut.mymovie.R
import com.app.hcmut.mymovie.ext.*
import com.app.hcmut.mymovie.feature.BaseActivity
import com.app.hcmut.mymovie.feature.movies.adapter.MoviesPagerAdapter
import com.app.hcmut.mymovie.feature.search.SearchResultActivity
import com.app.hcmut.mymovie.model.User
import com.bumptech.glide.Glide
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.tasks.Task
import com.roger.catloadinglibrary.CatLoadingView
import kotlinx.android.synthetic.main.activity_movies.*
import kotlinx.android.synthetic.main.content_movies.*
import kotlinx.android.synthetic.main.drawer_menu.*
import java.util.*
class MoviesActivity : BaseActivity(), ViewPager.OnPageChangeListener, SignInBottomDialog.IActionListener,
GoogleApiClient.OnConnectionFailedListener {
private var lastPage = 0
private lateinit var googleApiClient: GoogleApiClient
private var account: GoogleSignInAccount? = null
private lateinit var mGoogleSignInClient: GoogleSignInClient
private lateinit var callbackManager: CallbackManager
private var user: User? = null
private var bottomDialog: SignInBottomDialog? = null
private lateinit var loadingFragment: CatLoadingView
companion object {
const val GOOGLE_SIGN_IN_REQUEST_CODE = 1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_movies)
user = getUserPrefObj()
FacebookSdk.sdkInitialize(this.applicationContext)
loadingFragment = CatLoadingView()
initGoogleSignIn()
initToolbar()
initDrawerMenu()
initView()
callbackManager = CallbackManager.Factory.create()
initSignInFacebook()
}
private fun initToolbar() {
icDrawer.setOnClickListener {
drawerLayout.openDrawer(GravityCompat.START)
}
icSearch.setOnClickListener {
groupSearch.visible()
groupNormal.gone()
}
icClose.setOnClickListener {
groupSearch.gone()
groupNormal.visible()
edtSearch.setText("")
hideKeyboard()
}
tvSearch.setOnClickListener {
val query = edtSearch.text?.trim()
if (query?.isEmpty() == true) {
edtSearch.error = "Please enter keyword"
} else {
startActivity(SearchResultActivity.newInstance(this, query.toString()))
}
}
}
private fun initDrawerMenu() {
when (user) {
null -> {
tvName.text = ""
tvSignIn.text = getString(R.string.sign_in)
Glide.with(this).load(R.drawable.icon_avatar_empty).into(imvAvatar)
}
else -> {
tvSignIn.text = getString(R.string.sign_out)
Glide.with(this).load(user?.url).into(imvAvatar)
tvName.text = getString(R.string.hello_name, user?.name)
}
}
tvSavedMovie.setOnClickListener {
onClickSaved()
}
tvWatchedMovie.setOnClickListener {
onClickSaved()
}
tvSignIn.setOnClickListener {
if (tvSignIn.text == getString(R.string.sign_in)) {
bottomDialog = SignInBottomDialog.newInstance()
bottomDialog?.show(supportFragmentManager, bottomDialog?.tag)
} else if (tvSignIn.text == getString(R.string.sign_out)) {
showMessageHasChoose("Sign out", "Are you sure want to sign out?") {
signOut()
}
}
}
}
private fun onClickSaved() {
if (user == null) {
showMessage("Please sign in first")
} else {
showMessage("This feature will release soon")
}
}
private fun initGoogleSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
account = GoogleSignIn.getLastSignedInAccount(this)
// updateUI(account)
}
private fun signInGoogle() {
val signInIntent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, GOOGLE_SIGN_IN_REQUEST_CODE)
}
private fun initSignInFacebook() {
LoginManager.getInstance().registerCallback(callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
updateUIFacebook(loginResult.accessToken)
}
override fun onCancel() {
}
override fun onError(exception: FacebookException) {
showMessage("Something went wrong", "Error")
}
})
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == GOOGLE_SIGN_IN_REQUEST_CODE) {
// The Task returned from this call is always completed, no need to attach
// a listener.
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
} else {
callbackManager.onActivityResult(requestCode, resultCode, data)
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
account = completedTask.getResult(ApiException::class.java)
// Signed in successfully, show authenticated UI.
updateUIGoogle(account)
} catch (e: ApiException) {
showMessage("Something went wrong", "Error")
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("Gray", "signInResult:failed code=" + e.statusCode)
}
}
private fun updateUIGoogle(account: GoogleSignInAccount?) {
tvSignIn.text = getString(R.string.sign_out)
if (account?.photoUrl != null) Glide.with(this).load(account.photoUrl).into(imvAvatar)
val personName = account?.displayName
tvName.text = getString(R.string.hello_name, personName)
user = User(account?.photoUrl.toString(), personName)
this.saveUserPrefObj(user)
}
private fun updateUIFacebook(accessToken: AccessToken) {
val request =
GraphRequest.newMeRequest(
accessToken
) { `object`, _ ->
val name = `object`?.getString("name")
val url = "https://graph.facebook.com/" + `object`?.getString("id") + "/picture?type=large"
Glide.with(this@MoviesActivity)
.load(url)
.into(imvAvatar)
tvName.text = getString(R.string.hello_name, name)
tvSignIn.text = getString(R.string.sign_out)
user = User(url, name)
this.saveUserPrefObj(user)
}
val parameters = Bundle()
parameters.putString("fields", "id,name")
request.parameters = parameters
request.executeAsync()
}
override fun onConnectionFailed(p0: ConnectionResult) {
showMessage("Connection Failed", "Error")
}
override fun onClickGoogle() {
signInGoogle()
bottomDialog?.dismiss()
}
override fun onClickFacebook() {
if (AccessToken.getCurrentAccessToken() != null) LoginManager.getInstance().logOut()
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"))
bottomDialog?.dismiss()
}
override fun onStart() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
googleApiClient = GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
googleApiClient.connect()
super.onStart()
}
private fun initView() {
val pagerAdapter = MoviesPagerAdapter(supportFragmentManager, this)
viewPager.offscreenPageLimit = MoviesPagerAdapter.NUM_PAGE
viewPager.adapter = pagerAdapter
tabLayout.setupWithViewPager(viewPager)
tabLayout.getTabAt(0)?.customView = pagerAdapter.createTabView(0, true)
tabLayout.getTabAt(1)?.customView = pagerAdapter.createTabView(1)
tabLayout.getTabAt(2)?.customView = pagerAdapter.createTabView(2)
viewPager.addOnPageChangeListener(this)
}
override fun onPageScrollStateChanged(p0: Int) {}
override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {}
override fun onPageSelected(position: Int) {
tabLayout.getTabAt(position)?.customView?.findViewById<TextView>(R.id.tvTabTitle)?.apply {
setTextColor(ContextCompat.getColor(this@MoviesActivity, R.color.tab_selected))
typeface = Typeface.DEFAULT_BOLD
textSize = 20f
}
tabLayout.getTabAt(lastPage)?.customView?.findViewById<TextView>(R.id.tvTabTitle)?.apply {
setTextColor(ContextCompat.getColor(this@MoviesActivity, R.color.tab_unselected))
typeface = Typeface.DEFAULT
textSize = 14f
}
lastPage = position
}
private fun signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback {
tvSignIn.text = getString(R.string.sign_in)
tvName.text = ""
Glide.with(this).load(R.drawable.icon_avatar_empty).into(imvAvatar)
user = null
this.saveUserPrefObj(null)
}
GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE) {
LoginManager.getInstance().logOut()
tvSignIn.text = getString(R.string.sign_in)
tvName.text = ""
Glide.with(this).load(R.drawable.icon_avatar_empty).into(imvAvatar)
user = null
this.saveUserPrefObj(null)
}
showMessage("Signed out successfully")
}
} | 1 | null | 1 | 1 | cf0f30ef0e0c7efb71aa0c7a7307a5788421ee8e | 11,269 | Ass-MAD-FefaCinema | Apache License 2.0 |
src/main/kotlin/simplecalculator/Calculator.kt | xfl03 | 128,039,781 | false | null | package simplecalculator
import simplecalculator.util.Operator
import simplecalculator.util.ExpressionUtil
import simplecalculator.util.Fraction
import java.math.BigInteger
import java.text.ParseException
import java.util.*
/**
* Calculator Class
* @param expression
*/
class Calculator(private val expression: String) {
private var result = Fraction(0)
private val nums = Stack<Fraction>()
private val ops = Stack<Operator>()
private val util = ExpressionUtil.instance!!
init {
calculate()
}
@Throws(ParseException::class, ArithmeticException::class)
private fun calculate() {
var firstFlag = true
var numFlag = false//Is previous char a number?
var negativeFlag = false//Is next number negative?
var lastOp = Operator.PLUS// last Useful Operator
var index = -1
var lastPoint = -1
nums.push(Fraction(0))
ops.push(Operator.PLUS)
expression.chars().forEach {
index++
if (debugMode)
println("[Read In] ${it.toChar()}")
if (it.toChar() == ' ')//Ignore space
return@forEach
if (!util.isLegal(it))
throw ParseException("illegal char '${it.toChar()}'", index)
if (it.toChar() == '.') {
if (lastPoint >= 0)
throw ParseException("too more '.'", index)
lastPoint = 0
if (!numFlag)
nums.push(Fraction(0))
numFlag = true
} else if (util.isNum(it)) {
var num = util.toNum(it).toLong()
if (negativeFlag)
num = -num
if (numFlag)
if (lastPoint >= 0) {
nums.push(nums.pop().add(Fraction(num, BigInteger.TEN.pow(lastPoint + 1))))
lastPoint++
} else
nums.push(nums.pop().multiply(Fraction(10)).add(Fraction(num)))
else
nums.push(Fraction(num))
firstFlag = false
numFlag = true
} else {
lastPoint = -1
val op = util.getOperator(it)!!
if (firstFlag || (!numFlag && !util.isRightBracket(lastOp))) {
if (util.canBeginWith(op)) {
firstFlag = false
numFlag = false
if (op == Operator.MINUS) {
negativeFlag = !negativeFlag
return@forEach
}
if (op == Operator.PLUS)
return@forEach
} else {
throw ParseException("no left number for '${op.ch}'", index)
}
}
negativeFlag = false
var preOp = ops.pop()
if (util.isRightBracket(op)) {
if (!numFlag && !util.canEndWith(lastOp))
throw ParseException("no right number for '${lastOp.ch}'", index - 1)
if (preOp.priority != op.priority) {
ops.push(preOp)
try {
compute { it.priority != op.priority }
} catch (e: EmptyStackException) {
throw ParseException("no left bracket for '${op.ch}'", index)
}
ops.pop()
}
numFlag = false
lastOp = op
return@forEach
}
numFlag = false
lastOp = op
if (preOp.priority < op.priority || util.isLeftBracket(preOp) || ops.isEmpty())
ops.push(preOp)
else {
compute(preOp)
//For decline
preOp = ops.pop()
if (ops.isNotEmpty() && preOp.priority >= op.priority && !util.isLeftBracket(preOp))
compute(preOp)
else
ops.push(preOp)
}
ops.push(op)
}
}
if (!numFlag && !util.canEndWith(lastOp))
throw ParseException("no right number for '${lastOp.ch}'", expression.length - 1)
compute { ops.isNotEmpty() }
result = nums.pop()
}
@Throws(ParseException::class)
private fun compute(condition: (Operator) -> (Boolean)) {
//Back forward compute
var temp = ops.pop()
while (condition(temp)) {
if (util.isLeftBracket(temp)) {
if (!fixRight)
throw ParseException("no right bracket for '${temp.ch}'", expression.indexOf(temp.ch))
temp = ops.pop()
continue
}
compute(temp)
temp = ops.pop()
}
ops.push(temp)
}
private fun compute(operator: Operator) {
val right = nums.pop()
val left = nums.pop()
nums.push(util.computeOperator(left, operator, right))
}
override fun toString() = "$expression=$result"
/**
* get result of the expression
*/
fun getResult() = result
} | 0 | Kotlin | 0 | 1 | cdfdcd953d47fc2bedd2b2ffcd76528d4e2fd617 | 5,392 | SimpleCalculator | MIT License |
lpDevice/src/main/java/com/angcyo/laserpacker/device/firmware/FirmwareModel.kt | angcyo | 229,037,684 | false | {"Kotlin": 3467917, "JavaScript": 5542, "HTML": 1598} | package com.angcyo.laserpacker.device.firmware
import androidx.annotation.AnyThread
import androidx.lifecycle.ViewModel
import com.angcyo.bluetooth.fsc.*
import com.angcyo.bluetooth.fsc.laserpacker.LaserPeckerModel
import com.angcyo.bluetooth.fsc.laserpacker.command.DataCmd
import com.angcyo.bluetooth.fsc.laserpacker.command.ExitCmd
import com.angcyo.bluetooth.fsc.laserpacker.command.FirmwareUpdateCmd
import com.angcyo.bluetooth.fsc.laserpacker.parse.FirmwareUpdateParser
import com.angcyo.core.vmApp
import com.angcyo.http.download.download
import com.angcyo.laserpacker.device.R
import com.angcyo.library.component.VersionMatcher
import com.angcyo.library.ex._string
import com.angcyo.viewmodel.vmDataOnce
/**
* 固件升级模式
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/11/16
*/
class FirmwareModel : ViewModel() {
/**状态通知*/
val firmwareUpdateOnceData = vmDataOnce<FirmwareUpdateState>(null)
/**开始升级固件
* [url] 固件的在线地址
* */
@AnyThread
fun startUpdate(
url: String,
verifyMd5: Boolean = true,
verifyBin: Boolean = false,
action: (firmwareInfo: FirmwareInfo?, error: Throwable?) -> Unit = { firmwareInfo, error ->
firmwareInfo?.let {
startUpdate(it, verifyBin)
}
error?.let {
firmwareUpdateOnceData.postValue(
FirmwareUpdateState(FirmwareUpdateState.STATE_ERROR, -1, it)
)
}
}
) {
firmwareUpdateOnceData.postValue(FirmwareUpdateState(FirmwareUpdateState.STATE_DOWNLOAD))
url.download { task, error ->
if (task.isFinish) {
try {
val firmwareInfo = task.savePath.toFirmwareInfo(verifyMd5, verifyBin)
action(firmwareInfo, null)
} catch (e: FirmwareException) {
action(null, e)
}
}
error?.let {
action(null, it)
}
}
}
/**开始升级固件
* [verifyBin] 是否要验证bin的固件升级范围*/
@AnyThread
fun startUpdate(firmwareInfo: FirmwareInfo, verifyBin: Boolean = false) {
if (verifyBin) {
var result = true
vmApp<LaserPeckerModel>().productInfoData.value?.softwareVersion?.let {
result = VersionMatcher.matches(it, firmwareInfo.lpBin?.r, false)
}
if (!result) {
firmwareUpdateOnceData.postValue(
FirmwareUpdateState(
FirmwareUpdateState.STATE_ERROR,
-1,
FirmwareException(
_string(R.string.cannot_update_firmware_tip),
FirmwareException.TYPE_RANGE
)
)
)
return
}
}
firmwareUpdateOnceData.postValue(FirmwareUpdateState(FirmwareUpdateState.STATE_UPDATE, 0))
ExitCmd().enqueue()//先进入空闲模式
FirmwareUpdateCmd.update(firmwareInfo.data.size, firmwareInfo.version)
.enqueue { bean, error ->
val parser = bean?.parse<FirmwareUpdateParser>()
if (parser == null) {
firmwareUpdateOnceData.postValue(
FirmwareUpdateState(FirmwareUpdateState.STATE_ERROR, -1, error)
)
} else {
//进入模式成功, 开始发送数据
DataCmd.data(firmwareInfo.data).enqueue(CommandQueueHelper.FLAG_NO_RECEIVE)
listenerFinish()
}
}
}
var _waitReceivePacket: WaitReceivePacket? = null
/**监听是否接收数据完成, 数据接收完成设备自动重启*/
fun listenerFinish() {
_waitReceivePacket = listenerReceivePacket(progress = {
//进度
firmwareUpdateOnceData.postValue(
FirmwareUpdateState(
FirmwareUpdateState.STATE_UPDATE,
it.sendPacketPercentage
)
)
}) { receivePacket, bean, error ->
val isFinish = bean?.parse<FirmwareUpdateParser>()?.isUpdateFinish() == true
if (isFinish || (error != null && error !is ReceiveCancelException)) {
receivePacket.isCancel = true
}
if (isFinish) {
firmwareUpdateOnceData.postValue(
FirmwareUpdateState(
FirmwareUpdateState.STATE_FINISH,
100
)
)
}
error?.let {
firmwareUpdateOnceData.postValue(
FirmwareUpdateState(FirmwareUpdateState.STATE_ERROR, -1, it)
)
}
}
}
data class FirmwareUpdateState(
/**当前更新的状态*/
val state: Int,
/**当前状态下的记录*/
val progress: Int = -1,
/**失败时的错误信息*/
val error: Throwable? = null
) {
companion object {
const val STATE_NORMAL = 0
const val STATE_DOWNLOAD = 1
const val STATE_UPDATE = 2
const val STATE_FINISH = 3
const val STATE_ERROR = 4
}
}
} | 0 | Kotlin | 4 | 4 | fa83a724273f8b45f5879942a562df6455bf1b4b | 5,240 | UICoreEx | MIT License |
executor/instantiator/src/commonTest/kotlin/io/github/charlietap/chasm/executor/instantiator/runtime/allocation/memory/MemoryAllocatorTest.kt | CharlieTap | 743,980,037 | false | {"Kotlin": 2038087, "WebAssembly": 45714} | package io.github.charlietap.chasm.executor.instantiator.runtime.allocation.memory
import io.github.charlietap.chasm.executor.instantiator.allocation.memory.MemoryAllocatorImpl
import io.github.charlietap.chasm.executor.memory.factory.LinearMemoryFactory
import io.github.charlietap.chasm.executor.runtime.instance.MemoryInstance
import io.github.charlietap.chasm.executor.runtime.memory.LinearMemory
import io.github.charlietap.chasm.executor.runtime.store.Address
import io.github.charlietap.chasm.fixture.store
import io.github.charlietap.chasm.fixture.type.limits
import io.github.charlietap.chasm.fixture.type.memoryType
import kotlin.test.Test
import kotlin.test.assertEquals
class MemoryAllocatorImplTest {
@Test
fun `can allocate a memory instance`() {
val memories = mutableListOf<MemoryInstance>()
val store = store(
memories = memories,
)
val min = 3
val limits = limits(min.toUInt())
val type = memoryType(limits = limits)
val memory = object : LinearMemory {
override val min: LinearMemory.Pages
get() = LinearMemory.Pages(min)
override val max: LinearMemory.Pages?
get() = null
}
val memoryFactory: LinearMemoryFactory = { factoryMin, factoryMax ->
assertEquals(min, factoryMin)
assertEquals(null, factoryMax)
memory
}
val expected = MemoryInstance(
type = type,
data = memory,
)
val address = MemoryAllocatorImpl(store, type, memoryFactory)
assertEquals(Address.Memory(0), address)
assertEquals(expected, memories[0])
}
}
| 5 | Kotlin | 3 | 67 | dd6fa51262510ecc5ee5b03866b3fa5d1384433b | 1,706 | chasm | Apache License 2.0 |
src/main/java/me/ducpro/minecontroller/exceptions/InvalidParameterException.kt | DucPr0 | 495,636,657 | false | {"Kotlin": 23842} | package me.ducpro.minecontroller.exceptions
import java.lang.RuntimeException
class InvalidParameterException(s: String) : RuntimeException(s) | 0 | Kotlin | 0 | 2 | f88891a754ad948fe8d8a73a127daad0526bf1e2 | 144 | MineController | MIT License |
node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisUtils.kt | corda | 70,137,417 | false | null | @file:JvmName("ArtemisUtils")
package net.corda.nodeapi.internal
import net.corda.core.internal.declaredField
import org.apache.activemq.artemis.utils.actors.ProcessorBase
import java.nio.file.FileSystems
import java.nio.file.Path
import java.util.concurrent.Executor
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.atomic.AtomicInteger
/**
* Require that the [Path] is on a default file system, and therefore is one that Artemis is willing to use.
* @throws IllegalArgumentException if the path is not on a default file system.
*/
fun Path.requireOnDefaultFileSystem() {
require(fileSystem == FileSystems.getDefault()) { "Artemis only uses the default file system" }
}
fun requireMessageSize(messageSize: Int, limit: Int) {
require(messageSize <= limit) { "Message exceeds maxMessageSize network parameter, maxMessageSize: [$limit], message size: [$messageSize]" }
}
val Executor.rootExecutor: Executor get() {
var executor: Executor = this
while (executor is ProcessorBase<*>) {
executor = executor.declaredField<Executor>("delegate").value
}
return executor
}
fun Executor.setThreadPoolName(threadPoolName: String) {
(rootExecutor as? ThreadPoolExecutor)?.let { it.threadFactory = NamedThreadFactory(threadPoolName, it.threadFactory) }
}
private class NamedThreadFactory(poolName: String, private val delegate: ThreadFactory) : ThreadFactory {
companion object {
private val poolId = AtomicInteger(0)
}
private val prefix = "$poolName-${poolId.incrementAndGet()}-"
private val nextId = AtomicInteger(0)
override fun newThread(r: Runnable): Thread {
val thread = delegate.newThread(r)
thread.name = "$prefix${nextId.incrementAndGet()}"
return thread
}
}
| 62 | null | 1077 | 3,989 | d27aa0e6850d3804d0982024054376d452e7073a | 1,828 | corda | Apache License 2.0 |
src/main/java/zd/zero/waifu/motivator/plugin/assets/LocalStorageService.kt | diamondlee7 | 308,873,487 | true | {"Kotlin": 139102, "Java": 63057, "CSS": 538, "HTML": 283, "Shell": 80} | package zd.zero.waifu.motivator.plugin.assets
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.Optional
object LocalStorageService {
private val log = Logger.getInstance(this::class.java)
fun createDirectories(directoriesToCreate: Path) {
try {
Files.createDirectories(directoriesToCreate.parent)
} catch (e: IOException) {
log.error("Unable to create directories $directoriesToCreate for raisins", e)
}
}
fun getLocalAssetDirectory(): Optional<String> =
Optional.ofNullable(
PathManager.getConfigPath()
).map {
Paths.get(it, "waifuMotivationAssets").toAbsolutePath().toString()
}
}
| 0 | null | 0 | 0 | eae1e1affaf7c67900bbfb4671016a26ce21a4be | 872 | waifu-motivator-plugin | MIT License |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/mpp/pm20/KotlinPublicationConfigurator.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 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.gradle.plugin.mpp.pm20
interface KotlinPublicationConfigurator<in T : KotlinGradleVariant> : KotlinGradleFragmentFactory.FragmentConfigurator<T> {
object NoPublication : KotlinPublicationConfigurator<KotlinGradleVariant> {
override fun configure(fragment: KotlinGradleVariant) = Unit
}
object SingleVariantPublication : KotlinPublicationConfigurator<KotlinGradlePublishedVariantWithRuntime> {
override fun configure(fragment: KotlinGradlePublishedVariantWithRuntime) {
VariantPublishingConfigurator.get(fragment.project).configureSingleVariantPublication(fragment)
}
}
object NativeVariantPublication : KotlinPublicationConfigurator<KotlinNativeVariantInternal> {
override fun configure(fragment: KotlinNativeVariantInternal) {
VariantPublishingConfigurator.get(fragment.project).configureNativeVariantPublication(fragment)
}
}
}
| 132 | null | 5074 | 40,992 | 57fe6721e3afb154571eb36812fd8ef7ec9d2026 | 1,161 | kotlin | Apache License 2.0 |
spring-data-mongodb-kotlin-coroutine/src/main/kotlin/org/springframework/data/repository/coroutine/CoroutineCrudRepository.kt | konrad-kaminski | 88,795,239 | false | null | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.fu.module.data.mongodb.coroutine.data.repository.coroutine
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import org.springframework.data.repository.NoRepositoryBean
import org.springframework.data.repository.Repository
@NoRepositoryBean
interface CoroutineCrudRepository<T, ID>: Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity must not be null.
* @return the saved entity.
* @throws IllegalArgumentException in case the given `entity` is null.
*/
suspend fun <S : T> save(entity: S): S
/**
* Saves all given entities.
*
* @param entities must not be null.
* @return saved entities.
* @throws IllegalArgumentException in case the given [Iterable] `entities` is null.
*/
suspend fun <S : T> saveAll(entities: Iterable<S>): List<S>
/**
* Retrieves an entity by its id.
*
* @param id must not be null.
* @return the entity with the given id or null if none found.
* @throws IllegalArgumentException in case the given `id` is null.
*/
suspend fun findById(id: ID): T?
/**
* Returns whether an entity with the id exists.
*
* @param id must not be null.
* @return true if an entity with the given id exists, false otherwise.
* @throws IllegalArgumentException in case the given `id` is null.
*/
suspend fun existsById(id: ID): Boolean
/**
* Returns all instances of the type.
*
* @return [ReceiveChannel] emitting all entities.
*/
suspend fun findAll(): List<T>
/**
* Returns all instances with the given IDs.
*
* @param ids must not be null.
* @return found entities.
* @throws IllegalArgumentException in case the given [Iterable] `ids` is null.
*/
suspend fun findAllById(ids: Iterable<ID>): List<T>
/**
* Returns the number of entities available.
*
* @return the number of entities.
*/
suspend fun count(): Long
/**
* Deletes the entity with the given id.
*
* @param id must not be null.
* @throws IllegalArgumentException in case the given `id` is null.
*/
suspend fun deleteById(id: ID): Unit
/**
* Deletes a given entity.
*
* @param entity must not be null.
* @throws IllegalArgumentException in case the given entity is null.
*/
suspend fun delete(entity: T): Unit
/**
* Deletes the given entities.
*
* @param entities must not be null.
* @throws IllegalArgumentException in case the given [Iterable] `entities` is null.
*/
suspend fun deleteAll(entities: Iterable<T>): Unit
/**
* Deletes all entities managed by the repository.
*
*/
suspend fun deleteAll(): Unit
} | 24 | Kotlin | 66 | 424 | b88cda2c3ac60b0b51533c0cbe76c041437fadc2 | 3,555 | spring-kotlin-coroutine | Apache License 2.0 |
prime-router/src/test/kotlin/fhirengine/translation/SyncSchemaE2ETests.kt | CDCgov | 304,423,150 | false | {"Kotlin": 5464245, "CSS": 3370586, "TypeScript": 1881687, "Java": 1326278, "HCL": 285443, "MDX": 140603, "PLpgSQL": 77695, "Shell": 69067, "HTML": 68387, "SCSS": 66843, "Smarty": 51325, "RouterOS Script": 17080, "Python": 13724, "Makefile": 8166, "JavaScript": 8003, "Dockerfile": 3127} | package gov.cdc.prime.router.fhirengine.translation
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEmpty
import assertk.assertions.isNull
import com.github.ajalt.clikt.testing.test
import gov.cdc.prime.router.azure.BlobAccess
import gov.cdc.prime.router.azure.ValidateSchemasFunctions
import gov.cdc.prime.router.cli.SyncTranslationSchemaCommand
import gov.cdc.prime.router.common.TestcontainersUtils
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
@Testcontainers
class SyncSchemaE2ETests {
@Container
private val azuriteContainer1 = TestcontainersUtils.createAzuriteContainer(
customImageName = "azurite_syncschemae2e1",
customEnv = mapOf(
"AZURITE_ACCOUNTS" to "devstoreaccount1:keydevstoreaccount1"
)
)
@Container
private val azuriteContainer2 = TestcontainersUtils.createAzuriteContainer(
customImageName = "azurite_syncschemae2e2",
customEnv = mapOf(
"AZURITE_ACCOUNTS" to "devstoreaccount1:keydevstoreaccount1"
)
)
@BeforeEach
fun beforeEach() {
unmockkAll()
}
@AfterEach
fun afterEach() {
unmockkAll()
}
@Test
fun `test end-to-end sync schemas workflow`() {
val sourceBlobMetadata = TranslationSchemaManagerTests.createBlobMetadata(azuriteContainer1)
val destinationBlobMetadata = TranslationSchemaManagerTests.createBlobMetadata(azuriteContainer2)
TranslationSchemaManagerTests.setupValidState(destinationBlobMetadata)
TranslationSchemaManagerTests.setupValidState(sourceBlobMetadata)
TranslationSchemaManagerTests.setupSchemaInDir(
TranslationSchemaManager.SchemaType.FHIR, "sender/foo",
sourceBlobMetadata,
"/src/test/resources/fhirengine/translation/FHIR_to_FHIR"
)
val destinationStateBefore = TranslationSchemaManager().retrieveValidationState(
TranslationSchemaManager.SchemaType.FHIR,
destinationBlobMetadata
)
assertThat(destinationStateBefore.schemaBlobs).isEmpty()
assertThat(destinationStateBefore.validating).isNull()
val syncSchemasCommand = SyncTranslationSchemaCommand()
val result = syncSchemasCommand.test(
"-s",
"FHIR",
"-sb",
sourceBlobMetadata.connectionString,
"-sc",
"metadata",
"-db",
destinationBlobMetadata.connectionString,
"-dc",
"metadata"
)
assertThat(result.stderr).isEmpty()
mockkObject(BlobAccess.BlobContainerMetadata)
every { BlobAccess.BlobContainerMetadata.build(any(), any()) } returns destinationBlobMetadata
// Manually trigger the validation function
// In a real environment, this would be triggered by the validating.txt blob being added
ValidateSchemasFunctions().validateFHIRToFHIRSchemas(emptyArray())
val destinationStateAfter = TranslationSchemaManager().retrieveValidationState(
TranslationSchemaManager.SchemaType.FHIR,
destinationBlobMetadata
)
assertThat(destinationStateAfter.schemaBlobs).hasSize(3)
assertThat(destinationStateAfter.validating).isNull()
}
} | 1,478 | Kotlin | 40 | 71 | ad7119e2c47671e0e69b942dafd804876f104414 | 3,557 | prime-reportstream | Creative Commons Zero v1.0 Universal |
src/main/kotlin/Main.kt | jbaruch | 849,431,675 | false | {"Kotlin": 14296} | package jbaru.ch.telegram.hubitat
import com.github.kotlintelegrambot.bot
import com.github.kotlintelegrambot.dispatch
import com.github.kotlintelegrambot.dispatcher.command
import com.github.kotlintelegrambot.dispatcher.handlers.CommandHandlerEnvironment
import com.github.kotlintelegrambot.entities.ChatId
import io.ktor.client.*
import io.ktor.client.call.body
import io.ktor.client.engine.cio.*
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.http.HttpStatusCode
import jbaru.ch.telegram.hubitat.model.Device
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.lang.System.getenv
import com.github.kotlintelegrambot.logging.LogLevel
private val BOT_TOKEN = getenv("BOT_TOKEN") ?: throw IllegalStateException("BOT_TOKEN not set")
private val MAKER_API_APP_ID = getenv("MAKER_API_APP_ID") ?: throw IllegalStateException("MAKER_API_APP_ID not set")
private val MAKER_API_TOKEN = getenv("MAKER_API_TOKEN") ?: throw IllegalStateException("MAKER_API_TOKEN not set")
private lateinit var hubs: List<Device.Hub>
private val client = HttpClient(CIO)
private lateinit var deviceManager: DeviceManager
fun main() {
deviceManager = runBlocking {
DeviceManager(getDevicesJson())
}
hubs = runBlocking { initHubs() }
val bot = bot {
token = BOT_TOKEN
logLevel = LogLevel.Network.Basic
suspend fun CommandHandlerEnvironment.parseCommandWithArgs(command: String) {
(if (args.isEmpty()) {
"Specify what do you want to $command"
} else {
runCommandOnDevice(command, args.joinToString(" "))
}).also {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = it)
}
}
dispatch {
command("on") { parseCommandWithArgs("on") }
command("off") { parseCommandWithArgs("off") }
command("open") { parseCommandWithArgs("open") }
command("close") { parseCommandWithArgs("close") }
command("reboot") {parseCommandWithArgs("reboot") }
command("cancel_alerts") {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = runCommandOnHsm("cancelAlerts"))
}
command("update") {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = updateHubs().fold(
onSuccess = { it },
onFailure = {
it.printStackTrace()
it.message.toString()
}
))
}
command("refresh") {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = "Refresh finished, ${deviceManager.refreshDevices(getDevicesJson())} loaded")
}
}
}
println("Init successful, $deviceManager devices loaded, start polling")
bot.startPolling()
}
private suspend fun getDevicesJson(): String = client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/devices") {
parameter("access_token", MAKER_API_TOKEN)
}.body()
suspend fun runCommandOnDevice(command: String, device: String): String =
deviceManager.findDevice(device, command).fold(
onSuccess = { device ->
client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/devices/${device.id}/$command") {
parameter("access_token", MAKER_API_TOKEN)
}.status.description
},
onFailure = {
it.printStackTrace()
it.message.toString()
}
)
suspend fun runCommandOnHsm(command: String): String {
return client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/hsm/$command") {
parameter("access_token", MAKER_API_TOKEN)
}.status.description
}
suspend fun updateHubs(): Result<String> {
val statusMap = mutableMapOf<String, HttpStatusCode>()
for (hub in hubs) {
try {
val response = client.get("http://${hub.ip}/management/firmwareUpdate") {
parameter("token", hub.managementToken)
}
statusMap[hub.label] = response.status
} catch (_: Exception) {
statusMap[hub.label] = HttpStatusCode.InternalServerError
}
}
val failures = statusMap.filterValues { it != HttpStatusCode.OK }
return if (failures.isEmpty()) {
Result.success("All hub updates initialized successfully.")
} else {
val failureMessages = failures.entries.joinToString("\n") { (name, status) ->
"Failed to update hub $name Status: $status"
}
val successMessages = statusMap.filterValues { it == HttpStatusCode.OK }
.entries.joinToString("\n") { (name, _) ->
"Successfully issued update request to hub $name"
}
Result.failure(Exception("$failureMessages\n$successMessages"))
}
}
private suspend fun initHubs(): List<Device.Hub> {
val hubs = deviceManager.findDevicesByType(Device.Hub::class.java)
for (hub in hubs) {
val json: Map<String, JsonElement> =
Json.parseToJsonElement(client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/devices/${hub.id}") {
parameter("access_token", MAKER_API_TOKEN)
}.body<String>()).jsonObject
val ip = (json["attributes"] as JsonArray).find {
it.jsonObject["name"]!!.jsonPrimitive.content.toString() == "localIP"
}!!.jsonObject["currentValue"]!!.jsonPrimitive.content.toString()
hub.ip = ip
hub.managementToken = client.get("http://${ip}/hub/advanced/getManagementToken").body()
}
return hubs
}
| 0 | Kotlin | 2 | 0 | 34ab4f0e06912b4fd1778bf0e23c7125205f9032 | 5,896 | tg-hubitat-bot | Apache License 2.0 |
src/main/kotlin/Main.kt | jbaruch | 849,431,675 | false | {"Kotlin": 14296} | package jbaru.ch.telegram.hubitat
import com.github.kotlintelegrambot.bot
import com.github.kotlintelegrambot.dispatch
import com.github.kotlintelegrambot.dispatcher.command
import com.github.kotlintelegrambot.dispatcher.handlers.CommandHandlerEnvironment
import com.github.kotlintelegrambot.entities.ChatId
import io.ktor.client.*
import io.ktor.client.call.body
import io.ktor.client.engine.cio.*
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.http.HttpStatusCode
import jbaru.ch.telegram.hubitat.model.Device
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.lang.System.getenv
import com.github.kotlintelegrambot.logging.LogLevel
private val BOT_TOKEN = getenv("BOT_TOKEN") ?: throw IllegalStateException("BOT_TOKEN not set")
private val MAKER_API_APP_ID = getenv("MAKER_API_APP_ID") ?: throw IllegalStateException("MAKER_API_APP_ID not set")
private val MAKER_API_TOKEN = getenv("MAKER_API_TOKEN") ?: throw IllegalStateException("MAKER_API_TOKEN not set")
private lateinit var hubs: List<Device.Hub>
private val client = HttpClient(CIO)
private lateinit var deviceManager: DeviceManager
fun main() {
deviceManager = runBlocking {
DeviceManager(getDevicesJson())
}
hubs = runBlocking { initHubs() }
val bot = bot {
token = BOT_TOKEN
logLevel = LogLevel.Network.Basic
suspend fun CommandHandlerEnvironment.parseCommandWithArgs(command: String) {
(if (args.isEmpty()) {
"Specify what do you want to $command"
} else {
runCommandOnDevice(command, args.joinToString(" "))
}).also {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = it)
}
}
dispatch {
command("on") { parseCommandWithArgs("on") }
command("off") { parseCommandWithArgs("off") }
command("open") { parseCommandWithArgs("open") }
command("close") { parseCommandWithArgs("close") }
command("reboot") {parseCommandWithArgs("reboot") }
command("cancel_alerts") {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = runCommandOnHsm("cancelAlerts"))
}
command("update") {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = updateHubs().fold(
onSuccess = { it },
onFailure = {
it.printStackTrace()
it.message.toString()
}
))
}
command("refresh") {
bot.sendMessage(chatId = ChatId.fromId(message.chat.id), text = "Refresh finished, ${deviceManager.refreshDevices(getDevicesJson())} loaded")
}
}
}
println("Init successful, $deviceManager devices loaded, start polling")
bot.startPolling()
}
private suspend fun getDevicesJson(): String = client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/devices") {
parameter("access_token", MAKER_API_TOKEN)
}.body()
suspend fun runCommandOnDevice(command: String, device: String): String =
deviceManager.findDevice(device, command).fold(
onSuccess = { device ->
client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/devices/${device.id}/$command") {
parameter("access_token", MAKER_API_TOKEN)
}.status.description
},
onFailure = {
it.printStackTrace()
it.message.toString()
}
)
suspend fun runCommandOnHsm(command: String): String {
return client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/hsm/$command") {
parameter("access_token", MAKER_API_TOKEN)
}.status.description
}
suspend fun updateHubs(): Result<String> {
val statusMap = mutableMapOf<String, HttpStatusCode>()
for (hub in hubs) {
try {
val response = client.get("http://${hub.ip}/management/firmwareUpdate") {
parameter("token", hub.managementToken)
}
statusMap[hub.label] = response.status
} catch (_: Exception) {
statusMap[hub.label] = HttpStatusCode.InternalServerError
}
}
val failures = statusMap.filterValues { it != HttpStatusCode.OK }
return if (failures.isEmpty()) {
Result.success("All hub updates initialized successfully.")
} else {
val failureMessages = failures.entries.joinToString("\n") { (name, status) ->
"Failed to update hub $name Status: $status"
}
val successMessages = statusMap.filterValues { it == HttpStatusCode.OK }
.entries.joinToString("\n") { (name, _) ->
"Successfully issued update request to hub $name"
}
Result.failure(Exception("$failureMessages\n$successMessages"))
}
}
private suspend fun initHubs(): List<Device.Hub> {
val hubs = deviceManager.findDevicesByType(Device.Hub::class.java)
for (hub in hubs) {
val json: Map<String, JsonElement> =
Json.parseToJsonElement(client.get("http://hubitat.local/apps/api/${MAKER_API_APP_ID}/devices/${hub.id}") {
parameter("access_token", MAKER_API_TOKEN)
}.body<String>()).jsonObject
val ip = (json["attributes"] as JsonArray).find {
it.jsonObject["name"]!!.jsonPrimitive.content.toString() == "localIP"
}!!.jsonObject["currentValue"]!!.jsonPrimitive.content.toString()
hub.ip = ip
hub.managementToken = client.get("http://${ip}/hub/advanced/getManagementToken").body()
}
return hubs
}
| 0 | Kotlin | 2 | 0 | 34ab4f0e06912b4fd1778bf0e23c7125205f9032 | 5,896 | tg-hubitat-bot | Apache License 2.0 |
compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/stages/CheckCallableReferenceExpectedType.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.fir.resolve.calls
import org.jetbrains.kotlin.KtFakeSourceElementKind
import org.jetbrains.kotlin.KtSourceElement
import org.jetbrains.kotlin.builtins.functions.FunctionTypeKind
import org.jetbrains.kotlin.builtins.functions.isBasicFunctionOrKFunction
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.FirNamedArgumentExpression
import org.jetbrains.kotlin.fir.expressions.FirResolvedQualifier
import org.jetbrains.kotlin.fir.expressions.builder.buildNamedArgumentExpression
import org.jetbrains.kotlin.fir.resolve.BodyResolveComponents
import org.jetbrains.kotlin.fir.resolve.DoubleColonLHS
import org.jetbrains.kotlin.fir.resolve.createFunctionType
import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeUnsupportedCallableReferenceTarget
import org.jetbrains.kotlin.fir.resolve.inference.extractInputOutputTypesFromCallableReferenceExpectedType
import org.jetbrains.kotlin.fir.resolve.inference.model.ConeArgumentConstraintPosition
import org.jetbrains.kotlin.fir.resolve.scope
import org.jetbrains.kotlin.fir.scopes.FakeOverrideTypeCalculator
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.visitors.FirTransformer
import org.jetbrains.kotlin.fir.visitors.FirVisitor
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemOperation
import org.jetbrains.kotlin.resolve.calls.inference.runTransaction
import org.jetbrains.kotlin.resolve.calls.tower.isSuccess
import org.jetbrains.kotlin.types.expressions.CoercionStrategy
import org.jetbrains.kotlin.utils.addToStdlib.shouldNotBeCalled
internal object CheckCallableReferenceExpectedType : CheckerStage() {
override suspend fun check(candidate: Candidate, callInfo: CallInfo, sink: CheckerSink, context: ResolutionContext) {
val outerCsBuilder = callInfo.outerCSBuilder ?: return
val expectedType = callInfo.expectedType
if (candidate.symbol !is FirCallableSymbol<*>) return
val resultingReceiverType = when (callInfo.lhs) {
is DoubleColonLHS.Type -> callInfo.lhs.type.takeIf { callInfo.explicitReceiver !is FirResolvedQualifier }
else -> null
}
val fir: FirCallableDeclaration = candidate.symbol.fir
val (rawResultingType, callableReferenceAdaptation) = buildReflectionType(fir, resultingReceiverType, candidate, context)
val resultingType = candidate.substitutor.substituteOrSelf(rawResultingType)
if (callableReferenceAdaptation.needCompatibilityResolveForCallableReference()) {
if (!context.session.languageVersionSettings.supportsFeature(LanguageFeature.DisableCompatibilityModeForNewInference)) {
sink.reportDiagnostic(LowerPriorityToPreserveCompatibilityDiagnostic)
}
}
candidate.resultingTypeForCallableReference = resultingType
candidate.callableReferenceAdaptation = callableReferenceAdaptation
candidate.outerConstraintBuilderEffect = fun ConstraintSystemOperation.() {
addOtherSystem(candidate.system.currentStorage())
// Callable references are either arguments to a call or are wrapped in a synthetic call for resolution.
val position = ConeArgumentConstraintPosition(callInfo.callSite)
if (expectedType != null && !resultingType.contains {
it is ConeTypeVariableType && it.lookupTag !in outerCsBuilder.currentStorage().allTypeVariables
}
) {
addSubtypeConstraint(resultingType, expectedType, position)
}
}
var isApplicable = true
outerCsBuilder.runTransaction {
candidate.outerConstraintBuilderEffect!!(this)
isApplicable = !hasContradiction
false
}
if (!isApplicable) {
sink.yieldDiagnostic(InapplicableCandidate)
}
}
}
private fun buildReflectionType(
fir: FirCallableDeclaration,
receiverType: ConeKotlinType?,
candidate: Candidate,
context: ResolutionContext
): Pair<ConeKotlinType, CallableReferenceAdaptation?> {
val returnTypeRef = context.bodyResolveComponents.returnTypeCalculator.tryCalculateReturnType(fir)
return when (fir) {
is FirFunction -> {
val unboundReferenceTarget = if (receiverType != null) 1 else 0
val callableReferenceAdaptation =
context.bodyResolveComponents.getCallableReferenceAdaptation(
context.session,
fir,
candidate.callInfo.expectedType?.lowerBoundIfFlexible(),
unboundReferenceTarget
)
val parameters = mutableListOf<ConeKotlinType>()
if (fir.receiverParameter == null && receiverType != null) {
parameters += receiverType
}
val returnType = callableReferenceAdaptation?.let {
parameters += it.argumentTypes
if (it.coercionStrategy == CoercionStrategy.COERCION_TO_UNIT) {
context.session.builtinTypes.unitType.type
} else {
returnTypeRef.coneType
}
} ?: returnTypeRef.coneType.also {
fir.valueParameters.mapTo(parameters) { it.returnTypeRef.coneType }
}
val baseFunctionTypeKind = callableReferenceAdaptation?.suspendConversionStrategy?.kind
?: fir.specialFunctionTypeKind(context.session)
?: FunctionTypeKind.Function
return createFunctionType(
if (callableReferenceAdaptation == null) baseFunctionTypeKind.reflectKind() else baseFunctionTypeKind.nonReflectKind(),
parameters,
receiverType = receiverType.takeIf { fir.receiverParameter != null },
rawReturnType = returnType,
contextReceivers = fir.contextReceivers.map { it.typeRef.coneType }
) to callableReferenceAdaptation
}
is FirVariable -> createKPropertyType(fir, receiverType, returnTypeRef, candidate) to null
else -> ConeErrorType(ConeUnsupportedCallableReferenceTarget(candidate)) to null
}
}
internal class CallableReferenceAdaptation(
val argumentTypes: Array<ConeKotlinType>,
val coercionStrategy: CoercionStrategy,
val defaults: Int,
val mappedArguments: CallableReferenceMappedArguments,
val suspendConversionStrategy: CallableReferenceConversionStrategy
)
private fun CallableReferenceAdaptation?.needCompatibilityResolveForCallableReference(): Boolean {
// KT-13934: check containing declaration for companion object
if (this == null) return false
return defaults != 0 ||
suspendConversionStrategy != CallableReferenceConversionStrategy.NoConversion ||
coercionStrategy != CoercionStrategy.NO_COERCION ||
mappedArguments.values.any { it is ResolvedCallArgument.VarargArgument }
}
private fun BodyResolveComponents.getCallableReferenceAdaptation(
session: FirSession,
function: FirFunction,
expectedType: ConeKotlinType?,
unboundReceiverCount: Int
): CallableReferenceAdaptation? {
if (expectedType == null) return null
// Do not adapt references against KCallable type as it's impossible to map defaults/vararg to absent parameters of KCallable
if (expectedType.isKCallableType()) return null
val (inputTypes, returnExpectedType) = extractInputOutputTypesFromCallableReferenceExpectedType(expectedType, session) ?: return null
val expectedArgumentsCount = inputTypes.size - unboundReceiverCount
if (expectedArgumentsCount < 0) return null
val fakeArguments = createFakeArgumentsForReference(function, expectedArgumentsCount, inputTypes, unboundReceiverCount)
val originScope = function.dispatchReceiverType?.scope(
useSiteSession = session,
scopeSession = scopeSession,
fakeOverrideTypeCalculator = FakeOverrideTypeCalculator.DoNothing,
requiredMembersPhase = FirResolvePhase.STATUS,
)
val argumentMapping = mapArguments(fakeArguments, function, originScope = originScope, callSiteIsOperatorCall = false)
if (argumentMapping.diagnostics.any { !it.applicability.isSuccess }) return null
/**
* (A, B, C) -> Unit
* fun foo(a: A, b: B = B(), vararg c: C)
*/
var defaults = 0
var varargMappingState = VarargMappingState.UNMAPPED
val mappedArguments = linkedMapOf<FirValueParameter, ResolvedCallArgument>()
val mappedVarargElements = linkedMapOf<FirValueParameter, MutableList<FirExpression>>()
val mappedArgumentTypes = arrayOfNulls<ConeKotlinType?>(fakeArguments.size)
for ((valueParameter, resolvedArgument) in argumentMapping.parameterToCallArgumentMap) {
for (fakeArgument in resolvedArgument.arguments) {
val index = fakeArgument.index
val substitutedParameter = function.valueParameters.getOrNull(function.indexOf(valueParameter)) ?: continue
val mappedArgument: ConeKotlinType?
if (substitutedParameter.isVararg) {
val (varargType, newVarargMappingState) = varargParameterTypeByExpectedParameter(
inputTypes[index + unboundReceiverCount],
substitutedParameter,
varargMappingState
)
varargMappingState = newVarargMappingState
mappedArgument = varargType
when (newVarargMappingState) {
VarargMappingState.MAPPED_WITH_ARRAY -> {
// If we've already mapped an argument to this value parameter, it'll always be a type mismatch.
mappedArguments[valueParameter] = ResolvedCallArgument.SimpleArgument(fakeArgument)
}
VarargMappingState.MAPPED_WITH_PLAIN_ARGS -> {
mappedVarargElements.getOrPut(valueParameter) { ArrayList() }.add(fakeArgument)
}
VarargMappingState.UNMAPPED -> {
}
}
} else {
mappedArgument = substitutedParameter.returnTypeRef.coneType
mappedArguments[valueParameter] = resolvedArgument
}
mappedArgumentTypes[index] = mappedArgument
}
if (resolvedArgument == ResolvedCallArgument.DefaultArgument) {
defaults++
mappedArguments[valueParameter] = resolvedArgument
}
}
if (mappedArgumentTypes.any { it == null }) return null
for ((valueParameter, varargElements) in mappedVarargElements) {
mappedArguments[valueParameter] = ResolvedCallArgument.VarargArgument(varargElements)
}
var isThereVararg = mappedVarargElements.isNotEmpty()
for (valueParameter in function.valueParameters) {
if (valueParameter.isVararg && valueParameter !in mappedArguments) {
mappedArguments[valueParameter] = ResolvedCallArgument.VarargArgument(emptyList())
isThereVararg = true
}
}
val coercionStrategy = if (returnExpectedType.isUnitOrFlexibleUnit && !function.returnTypeRef.isUnit)
CoercionStrategy.COERCION_TO_UNIT
else
CoercionStrategy.NO_COERCION
val adaptedArguments = if (expectedType.isBaseTypeForNumberedReferenceTypes)
emptyMap()
else
mappedArguments
val expectedTypeFunctionKind = expectedType.functionTypeKind(session)?.takeUnless { it.isBasicFunctionOrKFunction }
val functionKind = function.specialFunctionTypeKind(session)
val conversionStrategy = if (expectedTypeFunctionKind != null && functionKind == null) {
CallableReferenceConversionStrategy.CustomConversion(expectedTypeFunctionKind)
} else {
CallableReferenceConversionStrategy.NoConversion
}
if (defaults == 0 && !isThereVararg &&
coercionStrategy == CoercionStrategy.NO_COERCION && conversionStrategy == CallableReferenceConversionStrategy.NoConversion
) {
// Do not create adaptation for trivial (id) conversion as it makes resulting type FunctionN instead of KFunctionN
// It happens because adapted references do not support reflection (see KT-40406)
return null
}
@Suppress("UNCHECKED_CAST")
return CallableReferenceAdaptation(
mappedArgumentTypes as Array<ConeKotlinType>,
coercionStrategy,
defaults,
adaptedArguments,
conversionStrategy
)
}
sealed class CallableReferenceConversionStrategy {
abstract val kind: FunctionTypeKind?
object NoConversion : CallableReferenceConversionStrategy() {
override val kind: FunctionTypeKind?
get() = null
}
class CustomConversion(override val kind: FunctionTypeKind) : CallableReferenceConversionStrategy()
}
private fun varargParameterTypeByExpectedParameter(
expectedParameterType: ConeKotlinType,
substitutedParameter: FirValueParameter,
varargMappingState: VarargMappingState,
): Pair<ConeKotlinType?, VarargMappingState> {
val elementType = substitutedParameter.returnTypeRef.coneType.arrayElementType()
?: error("Vararg parameter $substitutedParameter does not have vararg type")
return when (varargMappingState) {
VarargMappingState.UNMAPPED -> {
if (expectedParameterType.isPotentiallyArray()) {
elementType.createOutArrayType() to VarargMappingState.MAPPED_WITH_ARRAY
} else {
elementType to VarargMappingState.MAPPED_WITH_PLAIN_ARGS
}
}
VarargMappingState.MAPPED_WITH_PLAIN_ARGS -> {
if (expectedParameterType.isPotentiallyArray())
null to VarargMappingState.MAPPED_WITH_PLAIN_ARGS
else
elementType to VarargMappingState.MAPPED_WITH_PLAIN_ARGS
}
VarargMappingState.MAPPED_WITH_ARRAY ->
null to VarargMappingState.MAPPED_WITH_ARRAY
}
}
private enum class VarargMappingState {
UNMAPPED, MAPPED_WITH_PLAIN_ARGS, MAPPED_WITH_ARRAY
}
private fun FirFunction.indexOf(valueParameter: FirValueParameter): Int = valueParameters.indexOf(valueParameter)
val ConeKotlinType.isUnitOrFlexibleUnit: Boolean
get() {
val type = this.lowerBoundIfFlexible()
if (type.isNullable) return false
val classId = type.classId ?: return false
return classId == StandardClassIds.Unit
}
private val ConeKotlinType.isBaseTypeForNumberedReferenceTypes: Boolean
get() {
val classId = lowerBoundIfFlexible().classId ?: return false
return when (classId) {
StandardClassIds.KProperty,
StandardClassIds.KMutableProperty,
StandardClassIds.KCallable -> true
else -> false
}
}
private val FirExpression.index: Int
get() = when (this) {
is FirNamedArgumentExpression -> expression.index
is FirFakeArgumentForCallableReference -> index
else -> throw IllegalArgumentException()
}
private fun createFakeArgumentsForReference(
function: FirFunction,
expectedArgumentCount: Int,
inputTypes: List<ConeKotlinType>,
unboundReceiverCount: Int
): List<FirExpression> {
var afterVararg = false
var varargComponentType: ConeKotlinType? = null
var vararg = false
return (0 until expectedArgumentCount).map { index ->
val inputType = inputTypes.getOrNull(index + unboundReceiverCount)
if (vararg && varargComponentType != inputType) {
afterVararg = true
}
val valueParameter = function.valueParameters.getOrNull(index)
val name = if (afterVararg && valueParameter?.defaultValue != null)
valueParameter.name
else
null
if (valueParameter?.isVararg == true) {
varargComponentType = inputType
vararg = true
}
if (name != null) {
buildNamedArgumentExpression {
expression = FirFakeArgumentForCallableReference(index)
this.name = name
isSpread = false
}
} else {
FirFakeArgumentForCallableReference(index)
}
}
}
class FirFakeArgumentForCallableReference(
val index: Int
) : FirExpression() {
override val source: KtSourceElement?
get() = null
override val typeRef: FirTypeRef
get() = shouldNotBeCalled()
override val annotations: List<FirAnnotation>
get() = shouldNotBeCalled()
override fun replaceTypeRef(newTypeRef: FirTypeRef) {
shouldNotBeCalled()
}
override fun replaceAnnotations(newAnnotations: List<FirAnnotation>) {
shouldNotBeCalled()
}
override fun <D> transformAnnotations(transformer: FirTransformer<D>, data: D): FirNamedArgumentExpression {
shouldNotBeCalled()
}
override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {
shouldNotBeCalled()
}
override fun <D> transformChildren(transformer: FirTransformer<D>, data: D): FirElement {
shouldNotBeCalled()
}
}
fun ConeKotlinType.isKCallableType(): Boolean {
return this.classId == StandardClassIds.KCallable
}
private fun createKPropertyType(
propertyOrField: FirVariable,
receiverType: ConeKotlinType?,
returnTypeRef: FirResolvedTypeRef,
candidate: Candidate,
): ConeKotlinType {
val propertyType = returnTypeRef.type
return org.jetbrains.kotlin.fir.resolve.createKPropertyType(
receiverType,
propertyType,
isMutable = propertyOrField.canBeMutableReference(candidate)
)
}
private fun FirVariable.canBeMutableReference(candidate: Candidate): Boolean {
if (!isVar) return false
if (this is FirField) return true
val original = this.unwrapFakeOverridesOrDelegated()
return original.source?.kind == KtFakeSourceElementKind.PropertyFromParameter ||
(original.setter is FirMemberDeclaration &&
candidate.callInfo.session.visibilityChecker.isVisible(original.setter!!, candidate))
}
| 7 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 18,697 | kotlin | Apache License 2.0 |
codegen/src/androidMain/kotlin/com/freeletics/khonshu/codegen/internal/DestinationComponentLookup.kt | freeletics | 375,363,637 | false | null | package com.freeletics.khonshu.codegen.internal
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.freeletics.khonshu.navigation.BaseRoute
import com.freeletics.khonshu.navigation.internal.DestinationId
import com.freeletics.khonshu.navigation.internal.NavigationExecutor
import com.freeletics.khonshu.navigation.internal.destinationId
import java.io.Serializable
import kotlin.reflect.KClass
@InternalCodegenApi
public interface ComponentProvider<R : BaseRoute, T> : Serializable {
public fun provide(route: R, executor: NavigationExecutor, provider: ActivityComponentProvider): T
}
/**
* Creates a [ViewModel] for the given [destinationId]. The `ViewModel.Factory` will use [parentScope]
* to lookup a parent component instance. That component will then be passed to the given [factory]
* together with a [SavedStateHandle] and the passed in [destinationId].
*
* To be used in generated code.
*/
@InternalCodegenApi
public inline fun <reified C : Any, PC : Any, R : BaseRoute> component(
route: R,
executor: NavigationExecutor,
activityComponentProvider: ActivityComponentProvider,
parentScope: KClass<*>,
crossinline factory: (PC, SavedStateHandle, R) -> C,
): C {
val destinationId = route.destinationId
return executor.storeFor(destinationId).getOrCreate(C::class) {
val parentComponent = activityComponentProvider.provide<PC>(parentScope)
val savedStateHandle = executor.savedStateHandleFor(destinationId)
factory(parentComponent, savedStateHandle, route)
}
}
/**
* Creates a [ViewModel] for the given [destinationId]. The `ViewModel.Factory` will use [parentScope]
* to lookup a parent component instance. That component will then be passed to the given [factory]
* together with a [SavedStateHandle] and the passed in [destinationId].
*
* To be used in generated code.
*/
@InternalCodegenApi
public inline fun <reified C : Any, PC : Any, R : BaseRoute, PR : BaseRoute> componentFromParentRoute(
route: R,
executor: NavigationExecutor,
activityComponentProvider: ActivityComponentProvider,
parentScope: KClass<PR>,
crossinline factory: (PC, SavedStateHandle, R) -> C,
): C {
val destinationId = route.destinationId
return executor.storeFor(destinationId).getOrCreate(C::class) {
val parentDestinationId = DestinationId((parentScope))
@Suppress("UNCHECKED_CAST")
val parentComponentProvider = executor.extra(parentDestinationId) as ComponentProvider<PR, PC>
val parentRoute = executor.routeFor(parentDestinationId)
val parentComponent = parentComponentProvider.provide(parentRoute, executor, activityComponentProvider)
val savedStateHandle = executor.savedStateHandleFor(destinationId)
factory(parentComponent, savedStateHandle, route)
}
}
| 6 | null | 9 | 95 | eb5bc576d058ba24f6eb8f64c6d42066c664094e | 2,850 | khonshu | Apache License 2.0 |
app/src/androidTest/java/org/simple/clinic/login/LoginUserWithOtpServerIntegrationTest.kt | simpledotorg | 132,515,649 | false | null | package org.simple.clinic.login
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.simple.clinic.TestClinicApp
import org.simple.clinic.login.activateuser.ActivateUserRequest
import org.simple.clinic.rules.ServerAuthenticationRule
import org.simple.clinic.user.User
import org.simple.clinic.user.UserSession
import org.simple.clinic.user.UserStatus
import org.simple.sharedTestCode.util.Rules
import org.simple.clinic.util.toNullable
import javax.inject.Inject
import javax.inject.Named
class LoginUserWithOtpServerIntegrationTest {
@get:Rule
val ruleChain: RuleChain = Rules
.global()
.around(ServerAuthenticationRule())
@Inject
lateinit var userSession: UserSession
@Inject
lateinit var loginUserWithOtp: LoginUserWithOtp
@Inject
lateinit var usersApi: UsersApi
@Inject
@Named("user_pin")
lateinit var userPin: String
@Inject
@Named("user_otp")
lateinit var userOtp: String
@Before
fun setUp() {
TestClinicApp.appComponent().inject(this)
}
@Test
fun when_correct_login_params_are_given_then_login_should_happen_and_session_data_should_be_persisted() {
val user = userSession.loggedInUserImmediate()!!
usersApi.activate(ActivateUserRequest.create(user.uuid, userPin)).execute()
val loginResult = loginUserWithOtp.loginWithOtp(user.phoneNumber, userPin, userOtp)
.blockingGet()
assertThat(loginResult).isInstanceOf(LoginResult.Success::class.java)
val accessToken = userSession.accessToken().toNullable()
assertThat(accessToken).isNotNull()
val loggedInUser = userSession.loggedInUser().blockingFirst().get()
assertThat(userSession.isUserPresentLocally()).isTrue()
assertThat(loggedInUser.status).isEqualTo(UserStatus.ApprovedForSyncing)
assertThat(loggedInUser.loggedInStatus).isEqualTo(User.LoggedInStatus.LOGGED_IN)
}
}
| 3 | null | 73 | 236 | ff699800fbe1bea2ed0492df484777e583c53714 | 1,951 | simple-android | MIT License |
driver/src/main/kotlin/org/jlleitschuh/disclosure/automated/driver/GitHubSecurityAdvisoriesDriver.kt | JLLeitschuh | 339,857,300 | false | null | package org.jlleitschuh.disclosure.automated.driver
interface GitHubSecurityAdvisoriesDriver {
}
| 1 | Kotlin | 0 | 1 | d1848416efefbf487aa2128920c6b9a1df7b752c | 98 | automated-disclosure | MIT License |
src/main/kotlin/com/zeta/system/controller/SysFileController.kt | xia5800 | 449,936,024 | false | null | package com.zeta.system.controller
import com.zeta.system.model.entity.SysFile
import com.zeta.system.model.param.SysFileQueryParam
import com.zeta.system.service.ISysFileService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.zetaframework.base.controller.curd.DeleteController
import org.zetaframework.base.controller.curd.QueryController
import org.zetaframework.base.controller.SuperSimpleController
import org.zetaframework.base.result.ApiResult
import org.zetaframework.core.log.annotation.SysLog
import org.zetaframework.core.saToken.annotation.PreAuth
import org.zetaframework.core.saToken.annotation.PreCheckPermission
import org.zetaframework.core.saToken.annotation.PreMode
import javax.servlet.http.HttpServletResponse
/**
* <p>
* 系统文件 前端控制器
* </p>
*
* @author AutoGenerator
* @date 2022-04-11 11:18:44
*/
@Api(tags = ["系统文件"])
@PreAuth(replace = "sys:file")
@RestController
@RequestMapping("/api/system/file")
class SysFileController :
SuperSimpleController<ISysFileService, SysFile>(),
QueryController<SysFile, Long, SysFileQueryParam>,
DeleteController<SysFile, Long>
{
/**
* 上传文件
*
* 吐个槽:注解地狱
* @param file 文件对象
* @param bizType 业务类型 例如:order、user_avatar等 会影响文件url的值
*/
@SysLog(request = false)
@PreCheckPermission(value = ["{}:add", "{}:save"], mode = PreMode.OR)
@ApiOperation("上传文件")
@PostMapping("/upload")
fun upload(
@RequestParam
file: MultipartFile,
@RequestParam(required = false)
@ApiParam(value = "业务类型 例如:order、user_avatar等 会影响文件url的值", example = "avatar")
bizType: String? = null
): ApiResult<SysFile> {
return success(service.upload(file, bizType))
}
/**
* 下载文件
*
* @param request
* @param response
*/
@SysLog(response = false)
@PreCheckPermission(value = ["{}:export"])
@ApiOperation("下载文件")
@GetMapping(value = ["/download"], produces = ["application/octet-stream"])
fun download(@RequestParam @ApiParam("文件id") id: Long, response: HttpServletResponse) {
service.download(id, response)
}
/**
* 自定义单体删除文件
*
* @param id Id
* @return R<Boolean>
*/
override fun handlerDelete(id: Long): ApiResult<Boolean> {
return success(service.delete(id))
}
/**
* 自定义批量删除文件
*
* @param ids Id
* @return R<Boolean>
*/
override fun handlerBatchDelete(ids: MutableList<Long>): ApiResult<Boolean> {
return success(service.batchDelete(ids))
}
}
| 0 | null | 2 | 8 | 8c138e73e864836ddfa5e3eabf05ec05749fda56 | 2,724 | zeta-kotlin | MIT License |
verik-importer/src/main/kotlin/io/verik/importer/ast/element/EModule.kt | frwang96 | 269,980,078 | false | null | /*
* Copyright (c) 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
*
* 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 io.verik.importer.ast.element
import io.verik.importer.ast.property.PortReference
import io.verik.importer.common.Visitor
import io.verik.importer.core.Core
import io.verik.importer.message.SourceLocation
class EModule(
override val location: SourceLocation,
override val name: String,
val ports: List<EPort>,
val portReferences: List<PortReference>
) : EDeclaration() {
override var type = Core.C_Unit.toType()
init {
ports.forEach { it.parent = this }
}
override fun accept(visitor: Visitor) {
visitor.visitModule(this)
}
override fun acceptChildren(visitor: Visitor) {
ports.forEach { it.accept(visitor) }
}
}
| 0 | Kotlin | 1 | 5 | f11e0e7404d0461ec8b8c5d5635b2a4f6278a1f6 | 1,291 | verik | Apache License 2.0 |
SKIE/common/configuration/declaration/src/commonMain/kotlin/co/touchlab/skie/configuration/SkieConfigurationFlag.kt | touchlab | 685,579,240 | false | null | @file:Suppress("EnumEntryName")
package co.touchlab.skie.configuration
enum class SkieConfigurationFlag {
Feature_CoroutinesInterop,
Feature_DefaultArgumentsInExternalLibraries,
Build_SwiftLibraryEvolution,
Build_ParallelSwiftCompilation,
Build_ParallelSkieCompilation,
Build_ConcurrentSkieCompilation,
Migration_WildcardExport,
Migration_AnyMethodsAsFunctions,
Debug_VerifyDescriptorProviderConsistency,
Debug_DumpSwiftApiBeforeApiNotes,
Debug_DumpSwiftApiAfterApiNotes,
Debug_PrintSkiePerformanceLogs,
Debug_CrashOnSoftErrors,
Debug_LoadAllPlatformApiNotes,
Debug_GenerateFileForEachExportedClass,
Debug_UseStableTypeAliases,
Analytics_GradlePerformance,
Analytics_GradleEnvironment,
Analytics_Git,
Analytics_Hardware,
Analytics_CompilerEnvironment,
Analytics_SkiePerformance,
Analytics_Project,
Analytics_SkieConfiguration,
Analytics_CompilerConfiguration,
Analytics_Modules,
}
| 9 | null | 8 | 735 | b96044d4dec91e4b85c5b310226c6f56e3bfa2b5 | 992 | SKIE | Apache License 2.0 |
src/main/kotlin/io/github/jcarvalho/musicstore/service/SongService.kt | jcarvalho | 107,180,679 | false | null | package io.github.jcarvalho.musicstore.service
import io.github.jcarvalho.musicstore.repository.SongRepository
import org.springframework.stereotype.Service
@Service
class SongService(private val songRepository: SongRepository) {
fun findByAlbumId(albumId: String) = songRepository.findByAlbumId(albumId)
fun findSong(albumId: String, songId: String) = songRepository.findById(songId).filter { it.albumId == albumId }
}
| 0 | Kotlin | 0 | 1 | 5e26c671c5cac970480c1efad2cefb88cb86e324 | 433 | music-store | MIT License |
compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/NewCommonSuperTypeCalculator.kt | cr8tpro | 189,964,139 | false | null | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.calls
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.constants.IntegerLiteralTypeConstructor
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.*
import org.jetbrains.kotlin.types.AbstractNullabilityChecker.hasPathByNotMarkedNullableNodes
import org.jetbrains.kotlin.types.model.*
object NewCommonSuperTypeCalculator {
// TODO: Bridge for old calls
fun commonSuperType(types: List<UnwrappedType>): UnwrappedType {
val ctx = object : ClassicTypeSystemContext {}
return ctx.commonSuperType(types) as UnwrappedType
}
fun TypeSystemCommonSuperTypesContext.commonSuperType(types: List<KotlinTypeMarker>): KotlinTypeMarker {
val maxDepth = types.maxBy { it.typeDepth() }?.typeDepth() ?: 0
return commonSuperType(types, -maxDepth)
}
private fun TypeSystemCommonSuperTypesContext.commonSuperType(types: List<KotlinTypeMarker>, depth: Int): KotlinTypeMarker {
if (types.isEmpty()) throw IllegalStateException("Empty collection for input")
types.singleOrNull()?.let { return it }
var thereIsFlexibleTypes = false
val lowers = types.map {
when (it) {
is SimpleTypeMarker -> it
is FlexibleTypeMarker -> {
if (it.isDynamic()) return it
// raw types are allowed here and will be transformed to FlexibleTypes
thereIsFlexibleTypes = true
it.lowerBound()
}
else -> error("sealed")
}
}
val lowerSuperType = commonSuperTypeForSimpleTypes(lowers, depth)
if (!thereIsFlexibleTypes) return lowerSuperType
val upperSuperType = commonSuperTypeForSimpleTypes(types.map { it.upperBoundIfFlexible() }, depth)
return createFlexibleType(lowerSuperType, upperSuperType)
}
private fun TypeSystemCommonSuperTypesContext.commonSuperTypeForSimpleTypes(
types: List<SimpleTypeMarker>,
depth: Int
): SimpleTypeMarker {
// i.e. result type also should be marked nullable
val notAllNotNull = types.any { !AbstractNullabilityChecker.isSubtypeOfAny(this, it) }
val notNullTypes = if (notAllNotNull) types.map { it.withNullability(false) } else types
val commonSuperType = commonSuperTypeForNotNullTypes(notNullTypes, depth)
return if (notAllNotNull)
refineNullabilityForUndefinedNullability(types, commonSuperType) ?: commonSuperType.withNullability(true)
else
commonSuperType
}
private fun TypeSystemCommonSuperTypesContext.refineNullabilityForUndefinedNullability(
types: List<SimpleTypeMarker>,
commonSuperType: SimpleTypeMarker
): SimpleTypeMarker? {
if (!commonSuperType.canHaveUndefinedNullability()) return null
val actuallyNotNull =
types.all { hasPathByNotMarkedNullableNodes(it, commonSuperType.typeConstructor()) }
return if (actuallyNotNull) commonSuperType else null
}
// Makes representative sample, i.e. (A, B, A) -> (A, B)
private fun TypeSystemCommonSuperTypesContext.uniquify(types: List<SimpleTypeMarker>): List<SimpleTypeMarker> {
val uniqueTypes = arrayListOf<SimpleTypeMarker>()
for (type in types) {
val isNewUniqueType = uniqueTypes.all {
!AbstractTypeChecker.equalTypes(this, it, type) || it.typeConstructor().isIntegerLiteralTypeConstructor()
}
if (isNewUniqueType) {
uniqueTypes += type
}
}
return uniqueTypes
}
// This function leaves only supertypes, i.e. A0 is a strong supertype for A iff A != A0 && A <: A0
// Explanation: consider types (A : A0, B : B0, A0, B0), then CST(A, B, A0, B0) == CST(CST(A, A0), CST(B, B0)) == CST(A0, B0)
private fun TypeSystemCommonSuperTypesContext.filterSupertypes(list: List<SimpleTypeMarker>): List<SimpleTypeMarker> {
val supertypes = list.toMutableList()
val iterator = supertypes.iterator()
while (iterator.hasNext()) {
val potentialSubtype = iterator.next()
val isSubtype = supertypes.any { supertype ->
supertype !== potentialSubtype && AbstractTypeChecker.isSubtypeOf(this, potentialSubtype, supertype)
}
if (isSubtype) iterator.remove()
}
return supertypes
}
private fun TypeSystemCommonSuperTypesContext.commonSuperTypeForNotNullTypes(
types: List<SimpleTypeMarker>,
depth: Int
): SimpleTypeMarker {
if (types.size == 1) return types.single()
val uniqueTypes = uniquify(types)
if (uniqueTypes.size == 1) return uniqueTypes.single()
val explicitSupertypes = filterSupertypes(uniqueTypes)
if (explicitSupertypes.size == 1) return explicitSupertypes.single()
findCommonIntegerLiteralTypesSuperType(explicitSupertypes)?.let { return it }
// IntegerLiteralTypeConstructor.findCommonSuperType(explicitSupertypes)?.let { return it }
return findSuperTypeConstructorsAndIntersectResult(explicitSupertypes, depth)
}
private fun TypeSystemCommonSuperTypesContext.findSuperTypeConstructorsAndIntersectResult(
types: List<SimpleTypeMarker>,
depth: Int
): SimpleTypeMarker {
return intersectTypes(allCommonSuperTypeConstructors(types).map { superTypeWithGivenConstructor(types, it, depth) })
}
/**
* Note that if there is captured type C, then no one else is not subtype of C => lowerType cannot help here
*/
private fun TypeSystemCommonSuperTypesContext.allCommonSuperTypeConstructors(types: List<SimpleTypeMarker>): List<TypeConstructorMarker> {
val result = collectAllSupertypes(types.first())
for (type in types) {
if (type === types.first()) continue
result.retainAll(collectAllSupertypes(type))
}
return result.filterNot { target ->
result.any { other ->
other != target && other.supertypes().any { it.typeConstructor() == target }
}
}
}
private fun TypeSystemCommonSuperTypesContext.collectAllSupertypes(type: SimpleTypeMarker) =
LinkedHashSet<TypeConstructorMarker>().apply {
type.anySuperTypeConstructor { add(it); false }
}
private fun TypeSystemCommonSuperTypesContext.superTypeWithGivenConstructor(
types: List<SimpleTypeMarker>,
constructor: TypeConstructorMarker,
depth: Int
): SimpleTypeMarker {
if (constructor.parametersCount() == 0) return createSimpleType(
constructor,
emptyList(),
nullable = false
)
val typeCheckerContext = ClassicTypeCheckerContext(false)
/**
* Sometimes one type can have several supertypes with given type constructor, suppose A <: List<Int> and A <: List<Double>.
* Also suppose that B <: List<String>.
* Note that common supertype for A and B is CS(List<Int>, List<String>) & CS(List<Double>, List<String>),
* but it is too complicated and we will return not so accurate type: CS(List<Int>, List<Double>, List<String>)
*/
val correspondingSuperTypes = types.flatMap {
with(AbstractTypeChecker) {
typeCheckerContext.findCorrespondingSupertypes(it, constructor)
}
}
val arguments = ArrayList<TypeArgumentMarker>(constructor.parametersCount())
for (index in 0 until constructor.parametersCount()) {
val parameter = constructor.getParameter(index)
var thereIsStar = false
val typeProjections = correspondingSuperTypes.mapNotNull {
it.getArgumentOrNull(index)?.let {
if (it.isStarProjection()) {
thereIsStar = true
null
} else it
}
}
val argument =
if (thereIsStar || typeProjections.isEmpty()) {
createStarProjection(parameter)
} else {
calculateArgument(parameter, typeProjections, depth)
}
arguments.add(argument)
}
return createSimpleType(constructor, arguments, nullable = false)
}
// no star projections in arguments
private fun TypeSystemCommonSuperTypesContext.calculateArgument(
parameter: TypeParameterMarker,
arguments: List<TypeArgumentMarker>,
depth: Int
): TypeArgumentMarker {
if (depth > 3) {
return createStarProjection(parameter)
}
// Inv<A>, Inv<A> = Inv<A>
if (parameter.getVariance() == TypeVariance.INV && arguments.all { it.getVariance() == TypeVariance.INV }) {
val first = arguments.first()
if (arguments.all { it.getType() == first.getType() }) return first
}
val asOut: Boolean
if (parameter.getVariance() != TypeVariance.INV) {
asOut = parameter.getVariance() == TypeVariance.OUT
} else {
val thereIsOut = arguments.any { it.getVariance() == TypeVariance.OUT }
val thereIsIn = arguments.any { it.getVariance() == TypeVariance.IN }
if (thereIsOut) {
if (thereIsIn) {
// CS(Inv<out X>, Inv<in Y>) = Inv<*>
return createStarProjection(parameter)
} else {
asOut = true
}
} else {
asOut = !thereIsIn
}
}
// CS(Out<X>, Out<Y>) = Out<CS(X, Y)>
// CS(In<X>, In<Y>) = In<X & Y>
if (asOut) {
val type = commonSuperType(arguments.map { it.getType() }, depth + 1)
return if (parameter.getVariance() != TypeVariance.INV) return type.asTypeArgument() else createTypeArgument(
type,
TypeVariance.OUT
)
} else {
val type = intersectTypes(arguments.map { it.getType() })
return if (parameter.getVariance() != TypeVariance.INV) return type.asTypeArgument() else createTypeArgument(
type,
TypeVariance.IN
)
}
}
}
| 0 | null | 1 | 2 | dca23f871cc22acee9258c3d58b40d71e3693858 | 11,132 | kotlin | Apache License 2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.