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/example/wordsapp/LetterListFragment.kt | MatHazak | 648,875,628 | false | null | package com.example.wordsapp
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.asLiveData
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.wordsapp.data.SettingsDataStore
import com.example.wordsapp.databinding.FragmentLetterListBinding
import kotlinx.coroutines.launch
class LetterListFragment : Fragment(), MenuProvider {
private var _binding: FragmentLetterListBinding? = null
private val binding get() = _binding!!
private lateinit var recyclerView: RecyclerView
private lateinit var settingsDataStore: SettingsDataStore
private var isLinearLayoutManager = true
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentLetterListBinding.inflate(inflater, container, false)
requireActivity().addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
recyclerView = binding.recyclerView
chooseLayout()
settingsDataStore = SettingsDataStore(requireContext())
settingsDataStore.preferenceFlow.asLiveData().observe(viewLifecycleOwner) { value ->
isLinearLayoutManager = value
chooseLayout()
activity?.invalidateMenu()
}
}
override fun onCreateMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.layout_menu, menu)
val layoutButton = menu.findItem(R.id.action_switch_layout)
setIcon(layoutButton)
}
override fun onMenuItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.action_switch_layout -> {
isLinearLayoutManager = !isLinearLayoutManager
chooseLayout()
setIcon(item)
lifecycleScope.launch {
settingsDataStore.saveLayoutToPreferencesStore(
isLinearLayoutManager,
requireContext()
)
}
true
}
else -> false
}
private fun chooseLayout() {
if (isLinearLayoutManager) {
recyclerView.layoutManager = LinearLayoutManager(context)
} else {
recyclerView.layoutManager = GridLayoutManager(context, 4)
}
recyclerView.adapter = LetterAdapter { letter ->
val action =
LetterListFragmentDirections.actionLetterListFragmentToWordListFragment(letter = letter)
findNavController().navigate(action)
}
}
private fun setIcon(menuItem: MenuItem?) {
if (menuItem == null)
return
menuItem.icon =
if (isLinearLayoutManager)
ContextCompat.getDrawable(requireContext(), R.drawable.ic_grid_layout)
else ContextCompat.getDrawable(requireContext(), R.drawable.ic_linear_layout)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 0 | 0 | 1216263074df00c8de65056adc486504a9371b44 | 3,641 | words-app | Apache License 2.0 |
android/app/src/main/kotlin/com/alpondith/getx/getx_playground/MainActivity.kt | alpondith | 439,180,788 | false | {"HTML": 3942, "Dart": 1911, "Swift": 404, "Kotlin": 139, "Objective-C": 38} | package com.alpondith.getx.getx_playground
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | HTML | 0 | 1 | e0e762e1779699d514f6a1b476e10d6b74839c24 | 139 | getx_playground | MIT License |
app/src/main/java/com/android/roomdatabaserelationshipssample/entities/Student.kt | vengateshm | 319,062,206 | false | {"Kotlin": 10927, "PureBasic": 1901} | package com.android.roomdatabaserelationshipssample.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Student(
@PrimaryKey(autoGenerate = false)
val studentName: String,
val semester: Int,
val schoolName: String
) | 0 | Kotlin | 0 | 3 | 41dfc0834217aff7cb3f590b1ea49cc9a0587d0b | 269 | android_room_database_with_relationships | Apache License 2.0 |
app/src/main/java/com/dokidevs/pholder/gallery/AlbumFragment.kt | tingyik90 | 164,212,519 | false | null | package com.dokidevs.pholder.gallery
import com.dokidevs.dokilog.d
import com.dokidevs.pholder.PholderApplication.Companion.prefManager
import com.dokidevs.pholder.R
import com.dokidevs.pholder.data.PholderDatabase
import com.dokidevs.pholder.data.PholderDatabase.Companion.ALL_VIDEOS_FOLDER
import com.dokidevs.pholder.data.PholderTag
import com.dokidevs.pholder.data.fileTagDao
import com.dokidevs.pholder.data.folderTagDao
import com.dokidevs.pholder.utils.PrefManager.Companion.PREF_ARRAY_INCLUDED_FOLDER_PATHS
import com.dokidevs.pholder.utils.PrefManager.Companion.PREF_SHOW_EMPTY_FOLDERS
import java.io.File
/*--- AlbumFragment ---*/
class AlbumFragment : GalleryBaseFragment() {
/* companion object */
companion object {
/* tag */
const val FRAGMENT_CLASS = "AlbumFragment"
/* root */
val ALBUM_ROOT = File("/AlbumFragment")
}
// getFragmentClass
override fun getFragmentClass(): String {
return FRAGMENT_CLASS
}
// getDefaultRootFile
override fun getDefaultRootFile(): File {
return ALBUM_ROOT
}
// getEmptyViewMessage
override fun getEmptyViewMessage(): String {
// Request user to create folder directly in ALBUM_ROOT
return if (rootFile == ALBUM_ROOT) {
getString(R.string.galleryBaseFragment_emptyView_folder)
} else {
getString(R.string.galleryBaseFragment_emptyView_photo)
}
}
// getToolbarTitleName
override fun getToolbarTitleName(): String {
return when (rootFile) {
ALBUM_ROOT -> {
getString(R.string.toolbar_title_albumFragment)
}
else -> {
rootFile.name
}
}
}
// generateItems
override fun generateItems(): List<PholderTag>? {
val start = System.currentTimeMillis()
val items = when {
rootFile == ALBUM_ROOT -> {
// Use hashSet to ensure uniqueness
val folderPathSet = HashSet<String>()
// Get all folders with media, user created folders, included folder paths, starred folders
folderPathSet.addAll(folderTagDao.getDistinctFolderPaths())
folderPathSet.addAll(folderTagDao.getUserCreatedFolderPaths())
folderPathSet.addAll(folderTagDao.getStarredFolderPaths())
folderPathSet.addAll(prefManager.getStringArray(PREF_ARRAY_INCLUDED_FOLDER_PATHS))
// The db already removed excluded file paths, so the returned list is correct regardless of above paths
val folderTags = folderTagDao.get(folderPathSet.toList())
// Add 'All Videos' folder if does not exist
val allVideosFolderTag = folderTagDao.get(ALL_VIDEOS_FOLDER.absolutePath)
if (allVideosFolderTag != null && !folderTags.contains(allVideosFolderTag) && allVideosFolderTag.fileCount > 0) {
folderTags.add(allVideosFolderTag)
}
PholderDatabase.buildFolderFileItems(getApplicationContext(), folderTags, mutableListOf())
}
rootFile == ALL_VIDEOS_FOLDER -> {
val allVideoFileTags = fileTagDao.getAllVideos()
PholderDatabase.buildFolderFileItems(getApplicationContext(), mutableListOf(), allVideoFileTags)
}
rootFile.exists() -> {
val folderTags =
PholderDatabase.buildFolderItems(rootFile, prefManager.get(PREF_SHOW_EMPTY_FOLDERS, false))
val fileTags = fileTagDao.getChildren(rootFile.absolutePath)
PholderDatabase.buildFolderFileItems(getApplicationContext(), folderTags, fileTags)
}
else -> {
return null
}
}
d("${getFragmentTag()} - duration = ${System.currentTimeMillis() - start}, size = ${items.size}")
return items
}
} | 0 | Kotlin | 2 | 7 | ccb808bdc56088429c1fe20cab17af3b09636705 | 3,973 | Pholder | Apache License 2.0 |
app/src/main/java/com/pr0gramm/app/ui/dialogs/EditBookmarkDialog.kt | hmenke | 186,092,137 | true | {"Kotlin": 1197503, "Shell": 6712, "Prolog": 2951, "Python": 1124} | package com.pr0gramm.app.ui.dialogs
import android.app.Dialog
import android.os.Bundle
import android.widget.EditText
import androidx.core.os.bundleOf
import com.pr0gramm.app.R
import com.pr0gramm.app.model.bookmark.Bookmark
import com.pr0gramm.app.services.BookmarkService
import com.pr0gramm.app.ui.base.BaseDialogFragment
import com.pr0gramm.app.ui.base.bindView
import com.pr0gramm.app.ui.bottomSheet
import com.pr0gramm.app.util.di.instance
import com.pr0gramm.app.util.fragmentArgument
class EditBookmarkDialog : BaseDialogFragment("EditBookmarkDialog") {
private val bookmarkService: BookmarkService by instance()
private val bookmarkTitle by fragmentArgument<String>("Bookmark")
private val bookmarkTitleView: EditText by bindView(R.id.bookmark_name)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return bottomSheet(requireContext()) {
title(R.string.bookmark_editor_title)
layout(R.layout.bookmark_edit)
negative(R.string.delete) {
deleteClicked()
}
positive(R.string.okay) {
okayClicked()
}
}
}
private fun okayClicked() {
val newTitle = bookmarkTitleView.text.toString().take(64).trim()
if (newTitle != bookmarkTitle) {
renameTo(newTitle)
}
dismiss()
}
private fun renameTo(newTitle: String) {
val bookmark = bookmarkService.byTitle(bookmarkTitle)
if (bookmark != null) {
bookmarkService.rename(bookmark, newTitle)
}
}
private fun deleteClicked() {
val bookmark = bookmarkService.byTitle(bookmarkTitle)
if (bookmark != null) {
bookmarkService.delete(bookmark)
}
dismiss()
}
override suspend fun onDialogViewCreated() {
bookmarkTitleView.setText(bookmarkTitle)
}
companion object {
fun forBookmark(b: Bookmark): EditBookmarkDialog {
return EditBookmarkDialog().apply {
arguments = bundleOf("Bookmark" to b.title)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 7367051374f60fa2d4e5bbc5ddc800089983cd96 | 2,134 | Pr0 | MIT License |
android/src/main/java/io/mosip/tuvali/ble/peripheral/state/message/AdvertisementStartSuccessMessage.kt | mosip | 572,876,523 | false | {"Kotlin": 156258, "Swift": 66396, "Java": 11120, "TypeScript": 5017, "Ruby": 1353, "Objective-C": 550, "JavaScript": 77} | package io.mosip.tuvali.ble.peripheral.state.message
class AdvertisementStartSuccessMessage(): IMessage(PeripheralMessageTypes.ADV_START_SUCCESS) {
}
| 26 | Kotlin | 10 | 9 | 987b2d2512e57010c8a115b63b3b9093767c19ac | 151 | tuvali | MIT License |
server/src/main/kotlin/org/example/project/dao/DAOPetImpl.kt | ashutoshkailkhura | 715,660,759 | false | {"Kotlin": 186744, "Swift": 594} | //package org.example.project.dao
//
//class DAOPetImpl : DAOPet {
// override suspend fun addPet() {
// TODO("Not yet implemented")
// }
//
// override suspend fun getUserPets(userId: Int) {
// TODO("Not yet implemented")
// }
//
// override suspend fun getPetById(petId: Int) {
// TODO("Not yet implemented")
// }
//
// override suspend fun deletePet(petId: Int): Boolean {
// TODO("Not yet implemented")
// }
//} | 0 | Kotlin | 0 | 0 | b5cb1929876bedea4f68f04d3e60213a32e4994e | 467 | kmp-app-fullstack | The Unlicense |
shared/src/jvmMain/kotlin/io/github/ExpectedAPI.kt | mockative | 422,101,224 | false | {"Kotlin": 137014} | package io.github
actual interface ExpectedAPI {
actual fun expectedFunction(): String
}
| 26 | Kotlin | 10 | 262 | 9a4ced64d0a4dce3da9610d08959c7bcc0d544fd | 94 | mockative | MIT License |
app/src/main/java/star/iota/kisssub/ui/details/DetailsPresenter.kt | iota9star | 109,848,208 | false | null | /*
*
* * Copyright 2018. iota9star
* *
* * 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 star.iota.kisssub.ui.details
import com.lzy.okgo.model.Response
import org.jsoup.Jsoup
import star.iota.kisssub.KisssubUrl
import star.iota.kisssub.base.StringContract
import star.iota.kisssub.base.StringPresenter
class DetailsPresenter(view: StringContract.View<DetailsBean>) : StringPresenter<DetailsBean>(view) {
override fun deal(resp: Response<String>): DetailsBean? {
val doc = Jsoup.parse(resp.body())?.select("#btm > div.main > div.slayout > div > div.c2")
val bean = DetailsBean()
val details = doc?.select("div:nth-child(1) > div.intro")?.html()?.replace("<br>", "")
val tags = ArrayList<String>()
doc?.select("div:nth-child(4) > div > a")?.forEach {
tags.add(it.text())
}
val magnet = doc?.select("#magnet")?.attr("href")
val torrent = KisssubUrl.BASE + doc?.select("#download")?.attr("href")
val desc = doc?.select("div:nth-child(6) > h2 > span.right.text_normal")?.text()
doc?.select("div:nth-child(6) > div.torrent_files")?.select("img")?.remove()
val tree = doc?.select("div:nth-child(6) > div.torrent_files")?.html()
bean.desc = desc
bean.details = details
bean.tree = tree
bean.magnet = magnet
bean.tags = tags
bean.torrent = torrent
return bean
}
}
| 0 | Kotlin | 5 | 26 | edff44f5308acd660286096cf024cf996b1f29f2 | 2,012 | kisssub | Apache License 2.0 |
app/src/main/java/pt/ua/cm/n111763_114683_114715/androidproject/TetrisApplication.kt | Decathlannix | 581,174,094 | false | null | package pt.ua.cm.n111763_114683_114715.androidproject
import android.app.Application
import timber.log.Timber
class TetrisApplication: Application() {
override fun onCreate() {
super.onCreate()
// Initialize Timber library
Timber.plant(Timber.DebugTree())
}
} | 0 | Kotlin | 0 | 0 | af5807401ac58849412f9ab2361de88c004260d2 | 293 | android_project | MIT License |
app/src/main/kotlin/com/ttvnp/ttj_asset_android_client/presentation/ui/tracking/FireaseAnalytics.kt | ttvnp | 109,772,404 | false | null | package com.ttvnp.ttj_asset_android_client.presentation.ui.tracking
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import com.ttvnp.ttj_asset_android_client.domain.model.AssetType
class FirebaseAnalyticsHelper(val firebaseAnalytics: FirebaseAnalytics) {
fun logTutorialBeginEvent() {
val bundle = Bundle()
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_BEGIN, bundle)
}
fun logTutorialCompleteEvent() {
val bundle = Bundle()
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_COMPLETE, bundle)
}
fun logAssetSendEvent(assetType: AssetType, amount: Long) {
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, assetType.rawValue)
bundle.putString(FirebaseAnalytics.Param.VIRTUAL_CURRENCY_NAME, assetType.rawValue)
bundle.putLong(FirebaseAnalytics.Param.VALUE, amount)
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SPEND_VIRTUAL_CURRENCY, bundle)
}
fun setHasSetProfileImageUserPropertyOn() {
firebaseAnalytics.setUserProperty("has_set_profile_image", "1");
}
}
| 5 | null | 1 | 1 | 3a99c9d5b8362dbc5785c8849b8680405acb6a3a | 1,159 | ttj-asset-android-client | Apache License 1.1 |
src/main/kotlin/io/yazan/kego/kt/config/providers/KegoBaseUrlProvider.kt | Yazan98 | 260,540,090 | false | null | package io.yazan.kego.kt.config.providers
import io.yazan.kego.kt.config.components.KegoImagesUrlConfiguration
/**
* Name : Yazan98
* Date : 5/2/2020
* Time : 2:32 AM
* Project Name : IntelliJ IDEA
*/
abstract class KegoBaseUrlProvider : KegoProvider<KegoImagesUrlConfiguration>
| 0 | Kotlin | 0 | 0 | 5792243cf6a87134e0952bfd4f402e38dae9613d | 286 | Feature-Flag-Example | Apache License 2.0 |
src/test/kotlin/com/rdm/genetica/GeneticAApplicationTests.kt | RDMotta | 673,049,011 | false | {"Kotlin": 27695} | package com.rdm.genetica
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class GeneticAApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Kotlin | 0 | 1 | 517902110edd19fd332932666e126727ffc905db | 215 | GeneticA | MIT License |
app/src/main/java/com/prime/media/dialog/SleepTimer.kt | iZakirSheikh | 506,656,610 | false | null | @file:OptIn(ExperimentalTextApi::class)
package com.prime.media.dialog
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Slider
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.TimerOff
import androidx.compose.runtime.Composable
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.unit.dp
import com.prime.media.Material
import com.prime.media.R
import com.prime.media.core.ContentPadding
import com.prime.media.small2
import com.prime.media.surfaceColorAtElevation
import com.primex.core.OrientRed
import com.primex.core.textResource
import com.primex.material2.Dialog
import com.primex.material2.IconButton
import com.primex.material2.Label
import com.primex.material2.OutlinedButton
import com.primex.material2.TextButton
import kotlin.math.roundToInt
import kotlin.math.roundToLong
private const val TAG = "Timer"
@Composable
@NonRestartableComposable
private fun TopBar(
onRequestTimerOff: () -> Unit,
modifier: Modifier = Modifier,
) {
androidx.compose.material.TopAppBar(
title = { Label(text = textResource(R.string.sleep_timer_dialog_title), style = Material.typography.body1) },
backgroundColor = Material.colors.surfaceColorAtElevation(1.dp),
contentColor = Material.colors.onSurface,
modifier = modifier,
elevation = 0.dp,
actions = {
IconButton(imageVector = Icons.Outlined.TimerOff, onClick = onRequestTimerOff)
}
)
}
context(ColumnScope)
@Composable
private inline fun Layout(
crossinline onValueChange: (value: Long) -> Unit
) {
val haptic = LocalHapticFeedback.current
var value by remember { mutableFloatStateOf(10f) }
// Label
Label(
text = stringResource(R.string.sleep_timer_dialog_minute_s, value.roundToInt()),
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = ContentPadding.medium),
style = Material.typography.h6,
)
Slider(
value = value,
onValueChange = {
value = it
// make phone vibrate.
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
},
valueRange = 10f..100f,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(ContentPadding.normal),
steps = 7
)
// Buttons
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = ContentPadding.normal)
) {
// In case it is running; it will stop it.
TextButton(label = textResource(id = R.string.dismiss), onClick = { onValueChange(-2) })
// start the timer.
TextButton(
label = textResource(id = R.string.start),
onClick = { onValueChange((value.roundToInt() * 60 * 1_000L)) })
}
}
@Composable
@NonRestartableComposable
fun Timer(
expanded: Boolean,
onValueChange: (value: Long) -> Unit
) {
Dialog(
expanded = expanded,
onDismissRequest = { onValueChange(-2) }
) {
Surface(
shape = Material.shapes.small2,
content = {
Column {
// TopBar
TopBar(onRequestTimerOff = { onValueChange(-1) })
// Content
Layout(onValueChange = onValueChange)
}
}
)
}
} | 5 | null | 9 | 97 | a92a3d74451442b3dfb8d409c1177453c5d656a3 | 4,458 | Audiofy | Apache License 2.0 |
app/src/main/java/com/example/android/politicalpreparedness/representative/adapter/RepresentativeBindingAdapters.kt | phamngocduy09 | 845,399,793 | false | {"Kotlin": 43317} | package com.example.android.politicalpreparedness.representative.adapter
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.Spinner
import android.widget.TextView
import androidx.core.net.toUri
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.android.politicalpreparedness.R
import com.example.android.politicalpreparedness.election.VoterInfoFragmentArgs
import com.example.android.politicalpreparedness.network.models.VoterInfo
import com.example.android.politicalpreparedness.network.models.VoterInfoResponse
@BindingAdapter("profileImage")
fun fetchImage(view: ImageView, src: String?) {
src?.let {
val uri = src.toUri().buildUpon().scheme("https").build()
Glide.with(view.context)
.load(uri)
.apply(
RequestOptions()
.placeholder(R.drawable.loading_animation)
.error(R.drawable.ic_profile))
.circleCrop()
.into(view)
}
}
@BindingAdapter("electionInfoTitle")
fun bindElectionInfoTitleText(view: TextView, voterInfo: VoterInfo?) {
voterInfo?.run {
view.text = view.resources.getString(R.string.election_info_text, stateName)
}
}
@BindingAdapter("stateValue")
fun Spinner.setNewValue(value: String?) {
val adapter = toTypedAdapter<String>(this.adapter as ArrayAdapter<*>)
val position = when (adapter.getItem(0)) {
is String -> adapter.getPosition(value)
else -> this.selectedItemPosition
}
if (position >= 0) {
setSelection(position)
}
}
inline fun <reified T> toTypedAdapter(adapter: ArrayAdapter<*>): ArrayAdapter<T>{
return adapter as ArrayAdapter<T>
}
| 0 | Kotlin | 0 | 0 | e4a4eb638e166e1b87fcd7a1a2465fbbe62183f2 | 1,788 | Udacity-android-prj5 | Apache License 2.0 |
app/src/main/java/com/example/myapplication/onlinetest/model/data/DataModel.kt | kkosos | 603,139,490 | false | null | package com.example.myapplication.onlinetest.model.data
import android.util.Log
import kotlin.math.roundToInt
class DataModel {
private var _currencyRateMap = HashMap<String, Double>()
private var _currencyRateList:List<String> = kotlin.collections.ArrayList()
private var _currencyResultList: List<CurrencyPair> = kotlin.collections.ArrayList()
val currencyResultList: List<CurrencyPair>
get() = _currencyResultList
val currencyRateList: List<String>
get() = _currencyRateList
private var _selectedCurrency: String = "USD"
private var _selectedAmount:Double = 0.0
fun createCurrencyData(rateMap: HashMap<String, Double>) {
_currencyRateMap = rateMap
_currencyRateList = rateMap.keys.toList().sorted()
}
fun updateSelectedCurrency(target: String) {
if(_currencyRateMap.contains(target)) {
_selectedCurrency = target
generateExchangeRate()
} else {
Log.w(Log.WARN.toString(), "No such currency $target")
}
}
fun updateAmount(target: Double) {
_selectedAmount = target
generateExchangeRate()
}
private fun generateExchangeRate() {
val baseInUSD = _selectedAmount / _currencyRateMap[_selectedCurrency]!!
val resultList = kotlin.collections.ArrayList<CurrencyPair>()
_currencyRateList.forEach {currency ->
val number = baseInUSD * _currencyRateMap[currency]!!
resultList.add(CurrencyPair(currency, (number * 100000.0).roundToInt() / 100000.0))
}
_currencyResultList = resultList
}
} | 0 | Kotlin | 0 | 0 | 5c2ad80e98b6daca8593f664f366e841d69b8aee | 1,619 | AndroidSampleOne | MIT License |
app/src/main/java/com/rajchenbergstudios/hoygenda/ui/core/today/todayjentrieslist/TJEntriesListAdapter.kt | Davidhk2891 | 524,378,818 | false | null | package com.rajchenbergstudios.hoygenda.ui.core.today.todayjentrieslist
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.rajchenbergstudios.hoygenda.data.today.journalentry.JournalEntry
import com.rajchenbergstudios.hoygenda.databinding.SingleItemJournalEntryBinding
class TJEntriesListAdapter(private val listener: OnItemClickListener) : ListAdapter<JournalEntry, TJEntriesListAdapter.JEntriesListViewHolder>(
DiffCallback()
){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): JEntriesListViewHolder {
val binding = SingleItemJournalEntryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return JEntriesListViewHolder(binding)
}
override fun onBindViewHolder(holder: JEntriesListViewHolder, position: Int) {
val currentItem = getItem(position)
holder.bind(currentItem)
}
inner class JEntriesListViewHolder(private val binding: SingleItemJournalEntryBinding) : RecyclerView.ViewHolder(binding.root) {
init {
binding.apply {
root.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val jEntry = getItem(position)
listener.onItemClick(jEntry)
}
}
root.setOnLongClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val jEntry = getItem(position)
listener.onItemLongClick(jEntry)
}
return@setOnLongClickListener true
}
}
}
fun bind(journalEntry: JournalEntry){
binding.apply {
val title = "${journalEntry.createdTimeFormat} | "
itemJournalEntryTitleTextview.text = title
itemJournalEntryContentTextview.text = journalEntry.content
itemJournalEntryImportantImageview.isVisible = journalEntry.important
}
}
}
interface OnItemClickListener {
fun onItemClick(journalEntry: JournalEntry)
fun onItemLongClick(journalEntry: JournalEntry)
}
// No idea why areContentsTheSame function return expression gives error. Both .equals() and == are not liked by IDE
class DiffCallback : DiffUtil.ItemCallback<JournalEntry>() {
override fun areItemsTheSame(oldItem: JournalEntry, newItem: JournalEntry): Boolean
= oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: JournalEntry, newItem: JournalEntry): Boolean
= oldItem.equals(newItem)
}
} | 0 | Kotlin | 0 | 0 | 1154bbfb5865cb48a87497582b3149573c17efae | 2,951 | Rajchenberg_Studios-Hoytask | Apache License 2.0 |
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/photos/methods/PhotosGetAlbums.kt | Anton3 | 159,801,334 | true | {"Kotlin": 1382186} | @file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection")
package name.anton3.vkapi.generated.photos.methods
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import name.anton3.vkapi.generated.photos.objects.PhotoAlbumFull
import name.anton3.vkapi.method.UserServiceMethod
import name.anton3.vkapi.method.VkMethod
import name.anton3.vkapi.vktypes.VkList
/**
* [https://vk.com/dev/photos.getAlbums]
*
* Returns a list of a user's or community's photo albums.
*
* @property ownerId ID of the user or community that owns the albums.
* @property albumIds Album IDs.
* @property offset Offset needed to return a specific subset of albums.
* @property count Number of albums to return.
* @property needSystem '1' — to return system albums with negative IDs
* @property needCovers '1' — to return an additional 'thumb_src' field, '0' — (default)
* @property photoSizes '1' — to return photo sizes in a
*/
data class PhotosGetAlbums(
var ownerId: Long? = null,
var albumIds: List<Long>? = null,
var offset: Long? = null,
var count: Long? = null,
var needSystem: Boolean? = null,
var needCovers: Boolean? = null,
var photoSizes: Boolean? = null
) : VkMethod<VkList<PhotoAlbumFull>, UserServiceMethod>("photos.getAlbums", jacksonTypeRef())
| 2 | Kotlin | 0 | 8 | 773c89751c4382a42f556b6d3c247f83aabec625 | 1,308 | kotlin-vk-api | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/CodeCommit.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.CodeCommit: ImageVector
get() {
if (_codeCommit != null) {
return _codeCommit!!
}
_codeCommit = Builder(name = "CodeCommit", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(23.0f, 11.0f)
horizontalLineToRelative(-4.072f)
curveToRelative(-0.487f, -3.388f, -3.408f, -6.0f, -6.928f, -6.0f)
reflectiveCurveToRelative(-6.442f, 2.612f, -6.928f, 6.0f)
lineTo(1.0f, 11.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
reflectiveCurveToRelative(0.448f, 1.0f, 1.0f, 1.0f)
lineTo(5.072f, 13.0f)
curveToRelative(0.487f, 3.388f, 3.408f, 6.0f, 6.928f, 6.0f)
reflectiveCurveToRelative(6.441f, -2.612f, 6.928f, -6.0f)
horizontalLineToRelative(4.072f)
curveToRelative(0.553f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
reflectiveCurveToRelative(-0.447f, -1.0f, -1.0f, -1.0f)
close()
moveTo(12.0f, 17.0f)
curveToRelative(-2.757f, 0.0f, -5.0f, -2.243f, -5.0f, -5.0f)
reflectiveCurveToRelative(2.243f, -5.0f, 5.0f, -5.0f)
reflectiveCurveToRelative(5.0f, 2.243f, 5.0f, 5.0f)
reflectiveCurveToRelative(-2.243f, 5.0f, -5.0f, 5.0f)
close()
}
}
.build()
return _codeCommit!!
}
private var _codeCommit: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,399 | icons | MIT License |
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/routes/Standardfeil.kt | navikt | 487,246,438 | false | {"Kotlin": 1044388, "Shell": 1318, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.vedtak.routes
object Standardfeil {
fun fantIkkeFnr(): ErrorJson = ErrorJson(
"Fant ikke fødselsnummer",
"fant_ikke_fnr",
)
fun fantIkkeSak(): ErrorJson = ErrorJson(
"Fant ikke sak",
"fant_ikke_sak",
)
fun måVæreBeslutter(): ErrorJson = ErrorJson(
"Må ha beslutter-rolle.",
"må_ha_beslutter_rolle",
)
fun saksbehandlerOgBeslutterKanIkkeVæreLik(): ErrorJson = ErrorJson(
"Beslutter kan ikke være den samme som saksbehandler.",
"beslutter_og_saksbehandler_kan_ikke_være_lik",
)
}
| 2 | Kotlin | 0 | 1 | e5295a1543d080919ecbada5e796e59baa089fa7 | 608 | tiltakspenger-vedtak | MIT License |
src/main/kotlin/com/fgsoftwarestudio/baubles/api/IBaublesItemHandler.kt | fgsoftware-studio | 653,819,531 | false | null | package com.fgsoftwarestudio.baubles.api
import net.minecraft.entity.LivingEntity
import net.minecraft.item.ItemStack
import net.minecraftforge.items.IItemHandlerModifiable
interface IBaublesItemHandler : IItemHandlerModifiable {
val isEventBlocked: Boolean
fun isItemValidForSlot(slot: Int, stack: ItemStack?, player: LivingEntity?): Boolean
fun setEventBlock(blockEvent: Boolean)
fun isChanged(slot: Int): Boolean
fun setChanged(slot: Int, change: Boolean)
fun setPlayer(player: LivingEntity?)
}
| 0 | Kotlin | 0 | 0 | 552d15ad0f0fcfae6faabdb74a646bd9b4b7f2e5 | 525 | baubles | MIT License |
omisego-sdk/src/main/java/co/omisego/omisego/qrcode/scanner/OMGQRScannerContract.kt | tonefreqhz | 143,763,743 | true | {"Kotlin": 426024, "Shell": 229} | @file:Suppress("DEPRECATION")
package co.omisego.omisego.qrcode.scanner
/*
* OmiseGO
*
* Created by <NAME> on 4/4/2018 AD.
* Copyright © 2017-2018 OmiseGO. All rights reserved.
*/
import android.graphics.Rect
import android.hardware.Camera
import android.os.HandlerThread
import android.widget.ImageView
import co.omisego.omisego.OMGAPIClient
import co.omisego.omisego.constant.enums.ErrorCode
import co.omisego.omisego.custom.OMGCallback
import co.omisego.omisego.custom.camera.CameraWrapper
import co.omisego.omisego.custom.camera.ui.OMGCameraPreview
import co.omisego.omisego.custom.retrofit2.adapter.OMGCall
import co.omisego.omisego.model.APIError
import co.omisego.omisego.model.OMGResponse
import co.omisego.omisego.model.transaction.request.TransactionRequest
import co.omisego.omisego.qrcode.scanner.ui.OMGScannerUI
interface OMGQRScannerContract {
interface View : Camera.PreviewCallback {
/**
* Start stream the camera preview
*
* @param client The [OMGAPIClient] that used for verify the QR code with the eWallet backend
* @param callback The [Callback] used for delegate the scan result
*/
fun startCamera(client: OMGAPIClient, callback: Callback)
/**
* Stop the camera to stream the image preview
*/
fun stopCamera()
/* Read write zone */
/**
* Set the default color of QR frame border
*/
var borderColor: Int
/**
* Set the color of QR frame border when validating the QR code with the backend side
*/
var borderColorLoading: Int
/**
* Set the [HandlerThread] responsible for control the thread for [onPreviewFrame]
*/
var cameraHandlerThread: OMGQRScannerView.CameraHandlerThread?
/**
* A view that handle the preview image that streaming from the camera
*/
var cameraPreview: OMGCameraPreview?
/**
* A wrapper for [Camera] and the cameraId [Int]
*/
var cameraWrapper: CameraWrapper?
/**
* A debugging flag to see how the QR code processor actually see the preview image from the camera.
*/
var debugging: Boolean
/**
* A debugging image view for display the preview image from the camera
*/
var debugImageView: ImageView?
/**
* Set a loading view for display when validating the QR code with the backend side
*/
var loadingView: android.view.View?
/**
* A flag to indicate that the QR code is currently processing or not
*/
var isLoading: Boolean
/* Read only zone*/
/**
* A [View] for drawing the QR code frame, mask, and the hint text
*/
val omgScannerUI: OMGScannerUI
/**
* An orientation of the device
*/
val orientation: Int
}
interface Logic {
/**
* Keep failed QR payload that being sent to the server to prevent spamming
*/
val qrPayloadCache: MutableSet<String>
/**
* The [Callback] for retrieve the QR validation result
*/
var scanCallback: Callback?
/**
* Resize the frame to fit in the preview frame correctly
*
* @param cameraPreviewSize The width and height of the camera preview size
* @param previewSize The width and height of the preview layout
* @param qrFrame Represents the QR frame position and size
*
* @return The adjusted [Rect] with the correct ratio to the camera preview resolution
*/
fun adjustFrameInPreview(cameraPreviewSize: Pair<Int, Int>, previewSize: Pair<Int, Int>, qrFrame: Rect?): Rect?
/**
* Rotate the image based on the orientation of the raw image data
*
* @param data the raw image data from onPreviewFrame method
* @param size The size of the image (width to height)
* @param orientation the orientation of the image that return from the function [Rotation.getRotationCount]
* @return The correct image data for the current orientation of the device
*/
fun adjustRotation(data: ByteArray, size: Pair<Int, Int>, orientation: Int?): ByteArray
/**
* Handle logic when previewing a frame from the camera
*
* @param data the contents of the preview frame in the format defined by ImageFormat,
* which can be queried with getPreviewFormat(). If setPreviewFormat(int) is never called, the default will be the YCbCr_420_SP (NV21) format.
* @param camera the Camera service object
*/
fun onPreviewFrame(data: ByteArray, camera: Camera)
/**
* Cancel loading that verifying the QR code with the backend
*/
fun cancelLoading()
/**
* Verify if the given [formattedId] has already failed with code [ErrorCode.TRANSACTION_REQUEST_NOT_FOUND] yet
*
* @param formattedId The transaction formattedId which is created by EWallet backend
* @return true if the given [formattedId] has already failed with code [ErrorCode.TRANSACTION_REQUEST_NOT_FOUND], otherwise false.
*/
fun hasTransactionAlreadyFailed(formattedId: String): Boolean
interface QRVerifier {
/**
* The [OMGCall<TransactionRequest>] that will be assigned when call [requestTransaction], then will use later for cancel the request.
*/
var callable: OMGCall<TransactionRequest>?
/**
* The callback that will be used to get the result from the QR code verification API
*/
var callback: OMGCallback<TransactionRequest>?
/**
* Make request to the EWallet API to verify if the QR code has a valid transaction formattedId
*
* @param formattedId The transaction formattedId which is created by EWallet backend
* @param fail A lambda that will be invoked when the verification pass
* @param success A lambda that will be invoked when the verification fail
*/
fun requestTransaction(
formattedId: String,
fail: (response: OMGResponse<APIError>) -> Unit,
success: (response: OMGResponse<TransactionRequest>) -> Unit
)
/**
* Cancel the request to the EWallet API
*/
fun cancelRequest()
}
interface Rotation {
/**
* Rotate the image data depends on the device orientation
*
* @param data Raw image data from the camera that receiving from [Camera.PreviewCallback.onPreviewFrame]
* @param width Width of the image
* @param height Height of the image
* @param orientation The orientation of the image
*/
fun rotate(data: ByteArray, width: Int, height: Int, orientation: Int?): ByteArray
}
}
/**
* The callback that will receive events from the OMGQRScannerView
*/
interface Callback {
/**
* Called when the user tap on the screen. The request to the backend will be cancelled.
*
* @param view The QR scanner view
*/
fun scannerDidCancel(view: OMGQRScannerContract.View)
/**
* Called when a QR code was successfully decoded to a TransactionRequest object
*
* @param view The QR scanner view
* @param transactionRequest The transaction request decoded by the scanner
*/
fun scannerDidDecode(view: OMGQRScannerContract.View, transactionRequest: OMGResponse<TransactionRequest>)
/**
* Called when a QR code has been scanned but the scanner was not able to decode it as a TransactionRequest
*
* @param view The QR scanner view
* @param exception The error returned by the scanner
*/
fun scannerDidFailToDecode(view: OMGQRScannerContract.View, exception: OMGResponse<APIError>)
}
}
| 0 | Kotlin | 0 | 0 | a498f616d3e6178051cc55a92a562cb7d6c911fa | 8,259 | android-sdk-2 | Apache License 2.0 |
app/src/main/java/com/maliks/applocker/xtreme/data/database/callblocker/addtoblacklist/AddToBlackListDialog.kt | gamerz1990 | 873,653,054 | false | {"Kotlin": 357861, "Java": 1255} | package com.maliks.applocker.xtreme.data.database.callblocker.addtoblacklist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.lifecycle.Observer
import com.maliks.applocker.xtreme.R
import com.maliks.applocker.xtreme.databinding.DialogCallBlockerAddToBlacklistBinding
import com.maliks.applocker.xtreme.ui.BaseBottomSheetDialog
import com.maliks.applocker.xtreme.util.delegate.inflate
class AddToBlackListDialog : BaseBottomSheetDialog<AddToBlackListViewModel>() {
private val binding: DialogCallBlockerAddToBlacklistBinding by inflate(R.layout.dialog_call_blocker_add_to_blacklist)
override fun getViewModel(): Class<AddToBlackListViewModel> = AddToBlackListViewModel::class.java
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding.buttonBlock.setOnClickListener {
if (validateInputFields()) {
viewModel.blockNumber(
binding.editTextName.text.toString(),
binding.editTextPhoneNumber.text.toString()
)
}
}
binding.buttonCancel.setOnClickListener {
dismiss()
}
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.getViewStateLiveData()
.observe(viewLifecycleOwner, Observer {
dismiss()
})
}
private fun validateInputFields(): Boolean {
return !binding.editTextPhoneNumber.text.isNullOrEmpty()
}
companion object {
fun newInstance(): AppCompatDialogFragment = AddToBlackListDialog()
}
}
| 0 | Kotlin | 0 | 0 | db1181e64ce277c498bc52472010da1efcf4c52e | 1,848 | applocker | Apache License 2.0 |
gltf-parser/src/main/kotlin/com/dwursteisen/gltf/parser/material/MaterialParser.kt | minigdx | 242,223,166 | false | {"Kotlin": 84959, "Makefile": 165} | package com.dwursteisen.gltf.parser.material
import com.adrienben.tools.gltf.models.GltfAsset
import com.dwursteisen.gltf.parser.support.Dictionary
import com.dwursteisen.gltf.parser.support.isSupportedTexture
import com.dwursteisen.gltf.parser.support.source
import com.dwursteisen.minigdx.scene.api.common.Id
import com.dwursteisen.minigdx.scene.api.material.Material
import de.matthiasmann.twl.utils.PNGDecoder
import java.io.ByteArrayInputStream
import java.io.File
import java.util.Base64
class MaterialParser(
private val rootPath: File,
private val gltfAsset: GltfAsset,
private val ids: Dictionary
) {
fun materials(): Map<Id, Material> {
return gltfAsset.materials
// keep only materials using texture
.filter { m -> m.isSupportedTexture() }
.map { m ->
val (data, uri, isExternal) = if (m.source!!.bufferView != null) {
// Get data from the buffer
val buffer = m.source!!.bufferView!!
val data = buffer.buffer.data.copyOfRange(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
Triple(data, null, false)
} else {
// Get the data from the file if the texture is external.
val data = rootPath.parentFile.resolve(m.source!!.uri!!).readBytes()
Triple(data, m.source!!.uri!!, true)
}
// Read the PNG to know if some alpha are used in the texture.
val decoder = PNGDecoder(ByteArrayInputStream(data))
Material(
name = m.name ?: "",
id = ids.get(m),
data = if (!isExternal) {
Base64.getEncoder().encode(data)
} else {
ByteArray(0)
},
width = decoder.width,
height = decoder.height,
hasAlpha = decoder.hasAlpha(),
uri = uri,
isExternal = isExternal,
)
}.associateBy {
it.id
}
}
}
| 1 | Kotlin | 3 | 3 | 8e1748e6643bb08b446d0a797b81fc8e85a3097d | 2,199 | minigdx-glft-parser | MIT License |
app/src/main/java/id/dtprsty/movieme/ui/main/MainActivity.kt | dtprsty | 247,364,690 | false | null | package id.dtprsty.movieme.ui.main
import android.os.Bundle
import android.view.MenuItem
import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.commitNow
import com.google.android.material.bottomnavigation.BottomNavigationView
import id.dtprsty.movieme.R
import id.dtprsty.movieme.ui.favorite.FavoriteFragment
import id.dtprsty.movieme.ui.movie.MovieFragment
import id.dtprsty.movieme.ui.tv_show.TvShowFragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initBottomNavigation()
}
private fun initBottomNavigation() {
openFragment(MovieFragment.newInstance(), "movie")
navigation.setOnNavigationItemSelectedListener(object :
BottomNavigationView.OnNavigationItemSelectedListener {
override fun onNavigationItemSelected(@NonNull item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_movie -> {
openFragment(MovieFragment.newInstance(), "movie")
return true
}
R.id.menu_tvshow -> {
openFragment(TvShowFragment.newInstance(), "tv_show")
return true
}
R.id.menu_favorite -> {
openFragment(FavoriteFragment.newInstance(), "favorite")
return true
}
}
return false
}
})
}
private fun openFragment(fragment: Fragment, tag: String) =
supportFragmentManager.commitNow(allowStateLoss = true) {
replace(R.id.fl_container, fragment, tag)
}
}
| 0 | Kotlin | 2 | 2 | ff7496941e4a0c0f94d2898f01b7f9af86b13295 | 1,957 | MovieMe | MIT License |
extension/spring/src/test/kotlin/io/holixon/axon/projection/adhoc/dummy/events.kt | holixon | 701,266,989 | false | {"Kotlin": 74748} | package io.holixon.axon.projection.adhoc.dummy
import java.util.*
interface BankAccountEvent {
val bankAccountId: UUID
}
data class BankAccountCreatedEvent(
override val bankAccountId: UUID,
val owner: String,
) : BankAccountEvent
data class MoneyWithdrawnEvent(
override val bankAccountId: UUID,
val amountInEuroCent: Int
) : BankAccountEvent
data class MoneyDepositedEvent(
override val bankAccountId: UUID,
val amountInEuroCent: Int
) : BankAccountEvent
data class OwnerChangedEvent(
override val bankAccountId: UUID,
val owner: String
) : BankAccountEvent
data class BankAccountAggregate(
val bankAccountId: UUID,
val owner: String,
val amountInEuroCent: Int
)
| 1 | Kotlin | 0 | 4 | 90b58d1993c80c35513900708ea1b462f2b901a8 | 696 | axon-adhoc-projection | Apache License 2.0 |
app/src/main/java/com/example/tbilisi_parking_final_exm/domain/repository/parking/start_parking/StartParkingRepository.kt | Lasha-Ilashvili | 749,926,592 | false | {"Kotlin": 373909} | package com.example.tbilisi_parking_final_exm.domain.repository.parking.start_parking
import com.example.tbilisi_parking_final_exm.data.common.Resource
import com.example.tbilisi_parking_final_exm.domain.model.parking.start_parking.GetParkingIsStarted
import com.example.tbilisi_parking_final_exm.domain.model.parking.start_parking.GetStartParking
import kotlinx.coroutines.flow.Flow
interface StartParkingRepository {
suspend fun startParking( startParking: GetStartParking): Flow<Resource<GetParkingIsStarted>>
} | 0 | Kotlin | 1 | 0 | 20653c5077a4fa61e2c9616ddd986a82faf040dd | 521 | Tbilisi_Parking_FINAL_EXM | Apache License 2.0 |
app/src/main/java/com/tmdb/movie/ext/ViewModelExt.kt | sqsong66 | 703,818,964 | false | {"Kotlin": 899108} | package com.tmdb.movie.ext
import android.app.Activity
import android.content.ContextWrapper
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavBackStackEntry
import dagger.hilt.android.internal.lifecycle.HiltViewModelFactory
@Composable
inline fun <reified VM : ViewModel> hiltViewModelExt(
viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
},
noinline extrasProducer: (Bundle?) -> Bundle?
): VM {
val factory = createHiltViewModelFactory(viewModelStoreOwner, extrasProducer)
return viewModel(viewModelStoreOwner, factory = factory)
}
@Composable
fun createHiltViewModelFactory(
viewModelStoreOwner: ViewModelStoreOwner,
extrasProducer: (Bundle?) -> Bundle?
): ViewModelProvider.Factory? = when (viewModelStoreOwner) {
is NavBackStackEntry -> {
val navBackStackEntry = viewModelStoreOwner as NavBackStackEntry
val activity = LocalContext.current.let {
var ctx = it
while (ctx is ContextWrapper) {
if (ctx is Activity) {
return@let ctx
}
ctx = ctx.baseContext
}
throw IllegalStateException(
"Expected an activity context for creating a HiltViewModelFactory for a " +
"NavBackStackEntry but instead found: $ctx"
)
}
HiltViewModelFactory.createInternal(
activity,
navBackStackEntry,
extrasProducer(navBackStackEntry.arguments),
navBackStackEntry.defaultViewModelProviderFactory,
)
}
is ComponentActivity -> {
HiltViewModelFactory.createInternal(
viewModelStoreOwner,
viewModelStoreOwner,
extrasProducer(viewModelStoreOwner.intent?.extras),
SavedStateViewModelFactory(
viewModelStoreOwner.application,
viewModelStoreOwner,
extrasProducer(viewModelStoreOwner.intent?.extras)
)
)
}
else -> {
// Use the default factory provided by the ViewModelStoreOwner
// and assume it is an @AndroidEntryPoint annotated fragment
null
}
}
| 1 | Kotlin | 11 | 24 | 7dfc6aa197d1646773967f06eeef5a998bcda5a3 | 2,737 | TMDB-Movie | Apache License 2.0 |
app_sample_multimodule_lib0/src/main/java/com/joelzhu/lib/scanner/multimodule/ICommand.kt | JoelZhu | 567,595,477 | false | null | package com.joelzhu.lib.scanner.kotlin
/**
* [Description here].
*
* @author JoelZhu
* @since 2023-03-13
*/
interface ICommand {
fun execute(): String?
} | 0 | Kotlin | 0 | 1 | 194259415bb3d9687c7d74f234acfbd8329f5f3f | 163 | CompileScanner | MIT License |
app/src/test/java/jp/mydns/kokoichi0206/data/remote/SakamichiApiImplTest.kt | android-project-46group | 408,417,203 | false | null | package jp.mydns.kokoichi0206.data.remote
import com.squareup.moshi.JsonDataException
import jp.mydns.kokoichi0206.data.remote.dto.MemberDto
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import java.net.HttpURLConnection
class SakamichiApiImplTest {
private val mockWebServer = MockWebServer()
lateinit var api: SakamichiApi
@Before
fun setUp() {
api = createSakamichiApi(mockWebServer.url("/").toString())
}
@After
fun tearDown() {
mockWebServer.shutdown()
}
@Test
fun `get_members success`() = runBlocking {
// Arrange
val response = MockResponse()
.setBody("{\"members\":[{\"id\":0,\"name\":\"名前 です\",\"birthday\":\"12/26/1997\",\"height\":\"157.5cm\",\"blood_type\":\"Type O\",\"generation\":\"1st generation\",\"blog_url\":\"https://hinatazaka46.com/s/official/diary/member/list?ima=0000\\u0026ct=2\",\"img_url\":\"https://kokoichi0206.mydns.jp/imgs/hinata/namae.jpeg\"}]}")
.setResponseCode(HttpURLConnection.HTTP_OK)
mockWebServer.enqueue(response)
val expected = listOf(
MemberDto(
birthday = "12/26/1997",
blogUrl = "https://hinatazaka46.com/s/official/diary/member/list?ima=0000&ct=2",
bloodType = "Type O",
generation = "1st generation",
height = "157.5cm",
imgUrl = "https://kokoichi0206.mydns.jp/imgs/hinata/namae.jpeg",
userId = 0,
nameName = "名前 です",
)
)
// Act
val resp = api.getMembers(
groupName = "hinatazaka",
apiKey = "valid_api_key",
)
// Assert
assertNotNull(resp)
assertEquals(expected, resp.members)
val recordedRequest = mockWebServer.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/api/v1/members?gn=hinatazaka&key=valid_api_key", recordedRequest.path)
}
@Test(expected = JsonDataException::class)
fun `get_members with undecodable response should throw exception`() = runBlocking {
// Arrange
val response = MockResponse()
.setBody("{\"error\":\"Something unexpected happened.\"}")
.setResponseCode(HttpURLConnection.HTTP_OK)
mockWebServer.enqueue(response)
// Act
val resp = api.getMembers(
groupName = "hinatazaka",
apiKey = "valid_api_key",
)
// Assert
// Exception 'moshi.JsonDataException' is expected
// and this is checked in @Test annotation.
}
} | 15 | null | 0 | 2 | 05850671847dc7096228bdcc47692112c83ae581 | 2,845 | android | MIT License |
androidApp/src/main/java/jp/co/soramitsu/xnetworking/android/MainActivity.kt | soramitsu | 475,838,756 | false | {"Kotlin": 109437, "Swift": 339} | package jp.co.soramitsu.xnetworking.android
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import jp.co.soramitsu.xnetworking.basic.common.platform
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DepBuilder.build(applicationContext)
setContent {
MyApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
MainScreen()
}
}
}
}
}
@Composable
private fun MainScreen() {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
Button(
onClick = {
GlobalScope.launch {
try {
Log.e("foxxx", "r start btn 1")
val r = DepBuilder.networkService.getAssetsInfo()
Log.e("foxxx", "r = ${r}")
} catch (t: Throwable) {
Log.e("foxxx", "t= ${t.localizedMessage}")
}
}
},
content = {
Text(text = "btn1")
},
)
Spacer(modifier = Modifier.size(8.dp))
Button(
onClick = {
GlobalScope.launch {
Log.e("foxxx", "r start btn 2")
try {
val r = DepBuilder.networkService.getHistorySora(1) {
true
}!!
Log.e(
"foxxx",
"r = ${r.endReached} ${r.page} ${r.items.size} ${r.errorMessage}"
)
} catch (t: Throwable) {
Log.e("foxxx", "t= ${t.localizedMessage}")
}
}
},
content = {
Text(text = "btn2")
},
)
Spacer(modifier = Modifier.size(8.dp))
Button(
onClick = {
GlobalScope.launch {
Log.e("foxxx", "r start btn 3")
try {
val r = DepBuilder.networkService.getSoraConfig()
Log.e("foxxx", "r = $r")
} catch (t: Throwable) {
Log.e("foxxx", "t = ${t.localizedMessage}")
}
}
},
content = {
Text(text = "btn3")
},
)
}
}
@Composable
fun GreetingView(text: String) {
Text(text = text)
}
@Preview
@Composable
fun DefaultPreview() {
MyApplicationTheme {
GreetingView("Hello, Android!")
}
}
| 2 | Kotlin | 0 | 1 | 9048bf9bb1c547aa7c5c94ccda3e8d568f7b2738 | 3,556 | x-networking | Apache License 2.0 |
app/src/main/kotlin/org/jw/warehousecontrol/data/repository/BorrowedItemsRepositoryImpl.kt | anandacamara | 739,857,108 | false | {"Kotlin": 83107} | package org.jw.warehousecontrol.data.repository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.take
import org.jw.warehousecontrol.data.dao.BorrowedItemDao
import org.jw.warehousecontrol.data.dao.ItemDao
import org.jw.warehousecontrol.data.dao.VolunteerDao
import org.jw.warehousecontrol.data.model.*
import org.jw.warehousecontrol.data.model.ItemModel
import org.jw.warehousecontrol.data.model.VolunteerModel
import org.jw.warehousecontrol.data.model.toBorrowedItemModel
import org.jw.warehousecontrol.data.model.toEntity
import org.jw.warehousecontrol.domain.model.ItemEntity
import org.jw.warehousecontrol.domain.model.BorrowedItemsEntity
import org.jw.warehousecontrol.domain.model.VolunteerEntity
import org.jw.warehousecontrol.domain.repository.BorrowedItemsRepository
/**
* @author <NAME>
*/
internal class BorrowedItemsRepositoryImpl(
private val borrowedItemDao: BorrowedItemDao,
private val itemDao: ItemDao,
private val volunteerDao: VolunteerDao,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : BorrowedItemsRepository {
override suspend fun getBorrowedItems(): BorrowedItemsEntity {
val itemsDict = mutableMapOf<ItemEntity, MutableList<VolunteerEntity>>()
val volunteersDict = mutableMapOf<VolunteerEntity, MutableList<ItemEntity>>()
borrowedItemDao.getAllItems().flowOn(dispatcher).take(1).collect {
it.forEach { item ->
val itemEntity = item.toEntity()
if (itemsDict[itemEntity] == null) itemsDict[itemEntity] = mutableListOf()
item.volunteers.forEach { volunteer ->
val volunteerEntity = VolunteerEntity(name = volunteer)
if (volunteersDict[volunteerEntity] == null)
volunteersDict[volunteerEntity] = mutableListOf()
itemsDict[itemEntity]?.add(volunteerEntity)
volunteersDict[volunteerEntity]?.add(itemEntity)
}
}
}
return BorrowedItemsEntity(itemsDict, volunteersDict)
}
override suspend fun lendItems(vararg items: ItemEntity, to: VolunteerEntity) =
items.forEach { item ->
val itemModel = item.toBorrowedItemModel()
addItemOnDatabase(item.toModel())
borrowedItemDao.getItemById(item.id).flowOn(dispatcher).take(1).collect {
when (val savedItem = it) {
null -> {
itemModel.volunteers = listOf(to.name)
borrowedItemDao.insertItem(itemModel)
}
else -> {
itemModel.volunteers = savedItem.volunteers + to.name
borrowedItemDao.updateItem(itemModel)
}
}
}
}.also { addVolunteerOnDatabase(to.toModel()) }
override suspend fun returnItem(item: ItemEntity, from: VolunteerEntity) {
val itemModel = item.toBorrowedItemModel()
borrowedItemDao.getItemById(item.id).flowOn(dispatcher).take(1).collect {
val itemToBeDeleted = it?.volunteers?.indexOfFirst { name -> name == from.name }
it?.volunteers?.toMutableList()?.let { volunteers ->
itemToBeDeleted?.let { index -> volunteers.removeAt(index) }
itemModel.volunteers = volunteers
}
if (itemModel.volunteers.isEmpty()) borrowedItemDao.deleteItem(itemModel)
else borrowedItemDao.updateItem(itemModel)
}
}
private suspend fun addItemOnDatabase(item: ItemModel) {
itemDao.insertItem(item)
}
private suspend fun addVolunteerOnDatabase(volunteer: VolunteerModel) {
volunteerDao.insertVolunteer(volunteer)
}
} | 0 | Kotlin | 0 | 0 | f4f704cedb41cb4cc536fb7678fbb3371e44a05c | 3,886 | warehouse_control | MIT License |
app/src/dev/codewithdk/ktor/models/response/Response.kt | dineshktech | 537,748,354 | false | {"Kotlin": 57956, "FreeMarker": 197} | package dev.codewithdk.ktor.models.response
interface Response {
val status: State
val message: String
}
enum class State {
SUCCESS, NOT_FOUND, FAILED, UNAUTHORIZED, INVALID
}
| 7 | Kotlin | 0 | 3 | 07816803c6b28c75f84c5a25fa700efe8ce03035 | 192 | ktor-server-template | Apache License 2.0 |
app/src/main/java/com/progdeelite/dca/environment/Environment.kt | treslines | 408,171,722 | false | null | package com.progdeelite.dca.environment
// 1) Definindo os ambientes de desenvolvimento
// 2) Casos de uso, detalhando cada propriedade
// 3) Forcast próxima aula Configurações do Client (HttpClient)
// +--------------------------------------------------------------------+
// | DEFINICÃO DO AMBIENTE QUE SERA USADO EM SEUS CLIENTS E REQUISICÕES |
// +--------------------------------------------------------------------+
enum class Environment(
val host: String,
val port: String = "",
val useSSL: Boolean = true,
val certificatePinningHashes: List<String> = emptyList(),
) {
// +--------------------------------------------------------------------+
// | DEFINICÃO DOS AMBIENTES |
// +--------------------------------------------------------------------+
PROD(
host = "programadordeelite.com.br",
certificatePinningHashes = listOf(
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
)
),
STAGE(
host = "state.programadordeelite.com.br",
certificatePinningHashes = listOf(
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
)
),
DEV(
host = "dev.programadordeelite.com.br",
certificatePinningHashes = listOf(
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
)
),
TEST(
host = "test.programadordeelite.com.br",
certificatePinningHashes = listOf(
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
"sha256/rE/SEU_HASH_DE_PINNING",
)
),
// +--------------------------------------------------------------------+
// | AMBIENTES LOCAIS PARA DESENVOLVIMENTO (PRISM, DEMO, BACKEND_LOCAL) |
// +--------------------------------------------------------------------+
LOCAL_PRISM(
host = "localhost",
port = "4010",
useSSL = false,
),
LOCAL_BACKEND(
host = "localhost",
port = "8080",
useSSL = false,
),
DEMO(
host = "demo",
);
// +--------------------------------------------------------------------+
// | METODO AUXILIAR PARA SABER SE DEVEMOS USAR HEADERS ESPECIFICOS |
// +--------------------------------------------------------------------+
fun isBackendMocked(): Boolean = when (this) {
LOCAL_BACKEND -> true
else -> false
}
// +--------------------------------------------------------------------+
// | METODO AUXILIAR PARA SABER QUAL PROTOCOLO DEVEMO PREFIXAR |
// +--------------------------------------------------------------------+
private fun baseUrl(): String = "${if (useSSL) "https://" else "http://"}$host:$port"
// +--------------------------------------------------------------------+
// | MONTA A URL BASE DE CADA SERVIDOR OU ENDPOINT |
// +--------------------------------------------------------------------+
fun mobileBaseUrl(): String = when (this) {
LOCAL_PRISM -> baseUrl()
else -> "${baseUrl()}/mobile" // OU QUALQUER OUTRA COISA QUE SUA EMPRESA DEFINA
}
// +--------------------------------------------------------------------+
// | FORNECE A CREDENCIAIS DE AUTENTICACÃO USADAS NO AMBIENTES |
// +--------------------------------------------------------------------+
fun basicAuthentication(): BasicAuthentication? = when (this) {
// USE SUAS PROPRIAS CREDENCIAIS AQUI. APENAS PARA FINS DIDÁTICOS ASSIM
STAGE -> BasicAuthentication(username = "testUser", password = "<PASSWORD>")
DEV -> BasicAuthentication(username = "testUser", password = "<PASSWORD>")
else -> null
}
// +---------------------------------------------------------------------------------+
// | PARA SABER SE PRECISAMOS CONFIAR NO SERVIDOR BACKEND (DURANTE DESENVOLVIMENTO) |
// +---------------------------------------------------------------------------------+
fun ignoreServerTrust(): Boolean = when (this) {
TEST -> true
else -> false
}
// +-------------------------------------------------------------------+
// | PARA SABER SE PODEMOS DEBUGAR (DURANTE DESENVOLVIMENTO) |
// +-------------------------------------------------------------------+
fun hasDebugIdentifier(): Boolean = when (this) {
PROD -> false
else -> true
}
}
// +------------------------------------------------------------------+
// | CREDENDICAIS DE AUTENTICACÃO QUE USAREMOS NOS AMBIENTES |
// +------------------------------------------------------------------+
data class BasicAuthentication(val username: String, val password: String) | 0 | Kotlin | 5 | 23 | d3f3874288f72d6ccb9a1ce9722c7bb238c53565 | 4,982 | desafios_comuns_android | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/testbase/outputAssertions.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.testbase
import org.gradle.testkit.runner.BuildResult
import java.nio.file.Path
/**
* Asserts Gradle output contains [expectedSubString] string.
*/
fun BuildResult.assertOutputContains(
expectedSubString: String
) {
assert(output.contains(expectedSubString)) {
printBuildOutput()
"Build output does not contain \"$expectedSubString\""
}
}
/**
* Asserts Gradle output does not contain [notExpectedSubString] string.
*
* @param wrappingCharsCount amount of chars to include before and after [notExpectedSubString] occurrence
*/
fun BuildResult.assertOutputDoesNotContain(
notExpectedSubString: String,
wrappingCharsCount: Int = 100,
) {
assert(!output.contains(notExpectedSubString)) {
printBuildOutput()
// In case if notExpectedSubString is multiline string
val occurrences = mutableListOf<Pair<Int, Int>>()
var startIndex = output.indexOf(notExpectedSubString)
var endIndex = startIndex + notExpectedSubString.length
do {
occurrences.add(startIndex to endIndex)
startIndex = output.indexOf(notExpectedSubString, endIndex)
endIndex = startIndex + notExpectedSubString.length
} while (startIndex != -1)
val linesContainingSubString = occurrences.map { (startIndex, endIndex) ->
output.subSequence(
(startIndex - wrappingCharsCount).coerceAtLeast(0),
(endIndex + wrappingCharsCount).coerceAtMost(output.length)
)
}
"""
|
|===> Build output contains non-expected sub-string:
|'$notExpectedSubString'
|===> in following places:
|${linesContainingSubString.joinToString(separator = "\n|===> Next case:\n")}
|===> End of occurrences
|
""".trimMargin()
}
}
/**
* Assert build output contains one or more strings matching [expected] regex.
*/
fun BuildResult.assertOutputContains(
expected: Regex
) {
assert(output.contains(expected)) {
printBuildOutput()
"Build output does not contain any line matching '$expected' regex."
}
}
/**
* Asserts build output does not contain any lines matching [regexToCheck] regex.
*/
fun BuildResult.assertOutputDoesNotContain(
regexToCheck: Regex
) {
assert(!output.contains(regexToCheck)) {
printBuildOutput()
val matchedStrings = regexToCheck
.findAll(output)
.map { it.value }
.joinToString(prefix = " ", separator = "\n ")
"Build output contains following regex '$regexToCheck' matches:\n$matchedStrings"
}
}
/**
* Asserts build output contains exactly [expectedCount] of occurrences of [expected] string.
*/
fun BuildResult.assertOutputContainsExactlyTimes(
expected: String,
expectedCount: Int = 1
) {
val occurrenceCount = expected.toRegex(RegexOption.LITERAL).findAll(output).count()
assert(occurrenceCount == expectedCount) {
printBuildOutput()
"Build output contains different number of '$expected' string occurrences - $occurrenceCount then $expectedCount"
}
}
/**
* Assert build contains no warnings.
*/
fun BuildResult.assertNoBuildWarnings(
expectedWarnings: Set<String> = emptySet()
) {
val cleanedOutput = expectedWarnings.fold(output) { acc, s ->
acc.replace(s, "")
}
val warnings = cleanedOutput
.lineSequence()
.filter { it.trim().startsWith("w:") }
.toList()
assert(warnings.isEmpty()) {
printBuildOutput()
"Build contains following warnings:\n ${warnings.joinToString(separator = "\n")}"
}
}
fun BuildResult.assertIncrementalCompilation(
modifiedFiles: Set<Path> = emptySet(),
deletedFiles: Set<Path> = emptySet()
) {
val incrementalCompilationOptions = output
.lineSequence()
.filter { it.trim().startsWith("Options for KOTLIN DAEMON: IncrementalCompilationOptions(") }
.map {
it
.removePrefix("Options for KOTLIN DAEMON: IncrementalCompilationOptions(")
.removeSuffix(")")
}
.toList()
assert(incrementalCompilationOptions.isNotEmpty()) {
printBuildOutput()
"No incremental compilation options were found in the build"
}
val modifiedFilesPath = modifiedFiles.map { it.toAbsolutePath().toString() }
val deletedFilesPath = deletedFiles.map { it.toAbsolutePath().toString() }
val hasMatch = incrementalCompilationOptions
.firstOrNull {
val optionModifiedFiles = it
.substringAfter("modifiedFiles=[")
.substringBefore("]")
.split(",")
.filter(String::isNotEmpty)
val modifiedFilesFound = if (modifiedFilesPath.isEmpty()) {
optionModifiedFiles.isEmpty()
} else {
modifiedFilesPath.subtract(optionModifiedFiles).isEmpty()
}
val optionDeletedFiles = it
.substringAfter("deletedFiles=[")
.substringBefore("]")
.split(",")
.filter(String::isNotEmpty)
val deletedFilesFound = if (deletedFilesPath.isEmpty()) {
optionDeletedFiles.isEmpty()
} else {
deletedFilesPath.subtract(optionDeletedFiles).isEmpty()
}
modifiedFilesFound && deletedFilesFound
} != null
assert(hasMatch) {
printBuildOutput()
"""
|Expected incremental compilation options with:
|- modified files: ${modifiedFilesPath.joinToString()}
|- deleted files: ${deletedFilesPath.joinToString()}
|
|but none of following compilation options match:
|${incrementalCompilationOptions.joinToString(separator = "\n")}
""".trimMargin()
}
}
| 34 | null | 4903 | 39,894 | 0ad440f112f353cd2c72aa0a0619f3db2e50a483 | 6,140 | kotlin | Apache License 2.0 |
src/main/java/mutation/tool/operator/rpat/CSharpRPAT.kt | jcarlosadm | 212,240,193 | true | {"XML": 10, "Maven POM": 1, "Text": 1, "Ignore List": 1, "YAML": 1, "Markdown": 1, "JSON": 3, "Kotlin": 93, "Java": 5, "C#": 2, "Java Properties": 1} | package mutation.tool.operator.rpat
import mutation.tool.annotation.builder.CSharpAnnotationBuilder
import mutation.tool.annotation.finder.cSharpAnnotationFinder
import mutation.tool.context.Context
import mutation.tool.context.adapter.AnnotationAdapter
import mutation.tool.mutant.CSharpMutant
import mutation.tool.mutant.CSharpMutateVisitor
import mutation.tool.operator.CSharpOperator
import mutation.tool.operator.OperatorsEnum
import mutation.tool.util.Language
import mutation.tool.util.numOfAnnotationAttributes
import mutation.tool.util.xml.codeToDocument
import mutation.tool.util.xml.getAllTagNodes
import org.w3c.dom.Node
import java.io.File
class CSharpRPAT(context: Context, file: File) : CSharpOperator(context, file) {
override val mutateVisitor = CSharpMutateVisitor(this)
lateinit var map: Map<String, Map<String, List<Map<String, String>>>>
private lateinit var currentMutant:CSharpMutant
private lateinit var currentAnnotation: Node
private lateinit var currentAttr:String
private lateinit var currentAttrRep:String
private lateinit var currentAttrRepVal: String
override fun checkContext(): Boolean {
for (annotation in context.annotations){
var ok = false
var validKey = ""
map.keys.forEach { if (cSharpAnnotationFinder(annotation, it)) {ok = true; validKey = it} }
if (!ok) continue
if (numOfAnnotationAttributes(annotation.string) == 1 && map.getValue(validKey).containsKey(""))
return true
else if (numOfAnnotationAttributes(annotation.string) > 1){
if (annotation.genericPair == null) return false
for (pair in annotation.genericPair) {
// if present on map
if (!map.getValue(validKey).containsKey(pair.key)) continue
for (attrMap in map.getValue(validKey).getValue(pair.key)) {
var notContain = true
for (anotherPair in annotation.genericPair) {
if (anotherPair.key == attrMap.getValue("name")) {
notContain = false
break
}
}
if (notContain) return true
}
}
}
}
return false
}
override fun mutate(): List<CSharpMutant> {
val mutants = mutableListOf<CSharpMutant>()
for (annotation in context.annotations) {
var ok = false
var validKey = ""
map.keys.forEach { if (cSharpAnnotationFinder(annotation, it)) {ok = true; validKey = it} }
if (!ok) continue
if (numOfAnnotationAttributes(annotation.string) == 1 && map.getValue(validKey).containsKey("")) {
for (attrMap in map.getValue(validKey).getValue("")) {
val builder = CSharpAnnotationBuilder(annotation.string)
builder.build()
createMutant(builder.node!!, "", attrMap, mutants)
}
}
else if (numOfAnnotationAttributes(annotation.string) > 1) {
if (annotation.genericPair == null) continue
for (pair in annotation.genericPair) {
if (!map.getValue(validKey).contains(pair.key)) continue
for (attrMap in map.getValue(validKey).getValue(pair.key)) {
var notContain = true
for (anotherPair in annotation.genericPair) {
if (anotherPair.key == attrMap.getValue("name")) {
notContain = false
break
}
}
if (notContain) {
val builder = CSharpAnnotationBuilder(annotation.string)
builder.build()
createMutant(builder.node!!, pair.key, attrMap, mutants)
}
}
}
}
}
return mutants
}
private fun createMutant(
annotation: Node,
attr: String,
attrMap: Map<String, String>,
mutants: MutableList<CSharpMutant>
) {
currentAnnotation = annotation
currentMutant = CSharpMutant(OperatorsEnum.RPAT)
currentAttr = attr
currentAttrRep = attrMap.getValue("name")
currentAttrRepVal = attrMap.getValue("value")
currentMutant.rootNode = this.visit()
mutants += currentMutant
}
override fun visitClass(node: Node): Boolean = super.visitClass(node) && replacement(getAnnotations(node))
override fun visitMethod(node: Node): Boolean = super.visitMethod(node) && replacement(getAnnotations(node))
override fun visitParameter(node: Node): Boolean = super.visitParameter(node) && replacement(getAnnotations(node))
override fun visitProperty(node: Node): Boolean = super.visitProperty(node) && replacement(getAnnotations(node))
private fun replacement(annotations: List<Node>): Boolean {
for (annotation in annotations) {
val annotationAdapter = AnnotationAdapter(annotation)
if (annotationAdapter.name != AnnotationAdapter(currentAnnotation).name) continue
if (numOfAnnotationAttributes(annotation) > 1 && annotationAdapter.genericPair != null) {
for (pair in annotationAdapter.genericPair) {
if (pair.key == currentAttr){
val arguments = getAllTagNodes(annotation, "argument", emptyList())
val argument = arguments.find { it.textContent.contains("=") &&
it.textContent.split("=").first().trim() == currentAttr } ?: return false
val newAttr = annotation.ownerDocument.importNode(codeToDocument(
"$currentAttrRep=$currentAttrRepVal", Language.C_SHARP).firstChild,true)
val parent = argument.parentNode
parent.replaceChild(newAttr, argument)
break
}
}
} else {
val builder = CSharpAnnotationBuilder("[${annotationAdapter.name}(" +
"$currentAttrRep = $currentAttrRepVal)]")
builder.build()
val newAnnotation = annotation.ownerDocument.importNode(builder.node, true)
val parent = annotation.parentNode
parent.replaceChild(newAnnotation, annotation)
}
return true
}
return false
}
} | 0 | Kotlin | 0 | 0 | fce32936b61819b4791b04a7db7fefbe61e871c6 | 6,834 | mutation-tool-for-annotations | MIT License |
nomic-oozie/src/main/kotlin/nomic/oozie/OozieCoordinatorXml.kt | sn3d | 105,742,759 | false | null | /*
* Copyright 2017 <EMAIL>
*
* 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 nomic.oozie
import nomic.core.exception.WtfException
import org.w3c.dom.Document
import java.io.InputStream
import javax.xml.parsers.DocumentBuilderFactory
/**
* This class read the Ozzie coordinator XML and provide access to some
* values in this XML
*
* @author <EMAIL>
*/
class OozieCoordinatorXml {
private val doc: Document
/**
* constrcuct Oozie Coordinator class from XML [Document]
*/
constructor(doc: Document) {
this.doc = doc
}
/**
* parse [input] stream XML to Oozie Coordinator object
*/
constructor(input: InputStream) {
val factory = DocumentBuilderFactory.newInstance()
val builder = factory.newDocumentBuilder()
this.doc = builder.parse(input)
}
/**
* name from <coodrinator-app> root element
*/
val appName:String
get() = doc.documentElement.getAttribute("name") ?: throw WtfException()
} | 0 | Kotlin | 0 | 2 | 0f7bf3288eb135ae0279f570a9f2dd454bf59adb | 1,450 | nomic | Apache License 2.0 |
nomic-oozie/src/main/kotlin/nomic/oozie/OozieCoordinatorXml.kt | sn3d | 105,742,759 | false | null | /*
* Copyright 2017 <EMAIL>
*
* 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 nomic.oozie
import nomic.core.exception.WtfException
import org.w3c.dom.Document
import java.io.InputStream
import javax.xml.parsers.DocumentBuilderFactory
/**
* This class read the Ozzie coordinator XML and provide access to some
* values in this XML
*
* @author <EMAIL>
*/
class OozieCoordinatorXml {
private val doc: Document
/**
* constrcuct Oozie Coordinator class from XML [Document]
*/
constructor(doc: Document) {
this.doc = doc
}
/**
* parse [input] stream XML to Oozie Coordinator object
*/
constructor(input: InputStream) {
val factory = DocumentBuilderFactory.newInstance()
val builder = factory.newDocumentBuilder()
this.doc = builder.parse(input)
}
/**
* name from <coodrinator-app> root element
*/
val appName:String
get() = doc.documentElement.getAttribute("name") ?: throw WtfException()
} | 0 | Kotlin | 0 | 2 | 0f7bf3288eb135ae0279f570a9f2dd454bf59adb | 1,450 | nomic | Apache License 2.0 |
core/src/main/java/io/timeandspace/jpsg/PrimitiveTypeModifierPreProcessor.kt | TimeAndSpaceIO | 156,392,429 | false | null | /*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.timeandspace.jpsg
import io.timeandspace.jpsg.function.Predicate
import io.timeandspace.jpsg.function.UnaryOperator
open class PrimitiveTypeModifierPreProcessor(
private val keyword: String,
private val typeMapper: UnaryOperator<PrimitiveType>,
private val dimFilter: Predicate<String>) : TemplateProcessor() {
override fun priority(): Int {
return PRIORITY
}
override fun process(sb: StringBuilder, source: Context, target: Context, template: String) {
var template = template
val modifier = OptionProcessor.modifier(keyword)
for (e in source) {
val dim = e.key
if (!dimFilter.test(dim))
continue
if (e.value is PrimitiveType) {
val targetT = target.getOption(dim)
val sourceT = e.value as PrimitiveType
val kwDim = dim + "." + keyword
if (targetT is PrimitiveType && typeMapper.apply(targetT) !== targetT) {
val modP = OptionProcessor.prefixPattern(modifier, sourceT.standalone)
template = template.replace(modP.toRegex(), IntermediateOption.of(kwDim).standalone)
}
if (typeMapper.apply(sourceT) !== sourceT) {
template = typeMapper.apply(sourceT).intermediateReplace(template, kwDim)
}
}
}
// remove left modifier templates when for example target is object
template = template.replace(modifier.toRegex(), "")
postProcess(sb, source, target, template)
}
companion object {
@JvmStatic
val PRIORITY = OptionProcessor.PRIORITY + 10
}
}
| 3 | Java | 1 | 29 | b88de9f19058520e04eb204e46024b978b22f8d1 | 2,338 | java-primitive-specializations-generator | Apache License 2.0 |
peerdevicelist/src/main/java/jp/co/taosoftware/peerdevicelist/model/TransferData.kt | baobab2013 | 192,667,768 | false | null | /**
* Copyright 2019 Taosoftware Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.taosoftware.peerdevicelist.model
class TransferData {
var command: String? = null
var url: String? = null
var bytes: ByteArray? = null
constructor()
}
| 1 | null | 1 | 1 | fbc3e5bd95e27d18e8a1ead79b59260bd8e92bc7 | 783 | makesmileshutter | Apache License 2.0 |
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/presentation/validators/change/custom/search/CustomBlockProducersAdapter.kt | soramitsu | 278,060,397 | false | {"Kotlin": 5738459, "Java": 18796} | package jp.co.soramitsu.staking.impl.presentation.validators.change.custom.search
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import jp.co.soramitsu.common.list.PayloadGenerator
import jp.co.soramitsu.feature_staking_impl.databinding.ItemBlockProducerSearchBinding
class CustomBlockProducersAdapter(
private val itemHandler: ItemHandler
) : ListAdapter<SearchBlockProducerModel, BlockProducerViewHolder>(BlockProducerDiffCallback) {
interface ItemHandler {
fun blockProducerInfoClicked(blockProducerModel: SearchBlockProducerModel)
fun blockProducerClicked(blockProducerModel: SearchBlockProducerModel)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlockProducerViewHolder {
val binding = ItemBlockProducerSearchBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return BlockProducerViewHolder(binding, { itemHandler.blockProducerInfoClicked(getItem(it)) }, { itemHandler.blockProducerClicked(getItem(it)) })
}
override fun onBindViewHolder(holder: BlockProducerViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
class BlockProducerViewHolder(private val binding: ItemBlockProducerSearchBinding, infoClicked: (Int) -> Unit, selected: (Int) -> Unit) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.info.setOnClickListener { infoClicked(bindingAdapterPosition) }
binding.root.setOnClickListener { selected(bindingAdapterPosition) }
}
fun bind(item: SearchBlockProducerModel) {
binding.apply {
icon.setImageDrawable(item.image)
name.text = item.name
selectedIndicator.isVisible = item.selected
scoring.text = item.rewardsPercent
}
}
}
object BlockProducerDiffCallback : DiffUtil.ItemCallback<SearchBlockProducerModel>() {
override fun areItemsTheSame(
oldItem: SearchBlockProducerModel,
newItem: SearchBlockProducerModel
): Boolean {
return oldItem.address == newItem.address
}
override fun areContentsTheSame(
oldItem: SearchBlockProducerModel,
newItem: SearchBlockProducerModel
): Boolean {
return oldItem.name == newItem.name && oldItem.rewardsPercent == newItem.rewardsPercent && oldItem.selected == newItem.selected
}
override fun getChangePayload(
oldItem: SearchBlockProducerModel,
newItem: SearchBlockProducerModel
): Any {
return BlockProducerPayloadGenerator.diff(oldItem, newItem)
}
private object BlockProducerPayloadGenerator : PayloadGenerator<SearchBlockProducerModel>(
SearchBlockProducerModel::selected,
SearchBlockProducerModel::rewardsPercent
)
}
| 15 | Kotlin | 30 | 89 | 1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2 | 2,936 | fearless-Android | Apache License 2.0 |
tmp/arrays/youTrackTests/4391.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-33693
val map = mutableMapOf<String, String>()
inline fun <reified T> get(key: String): T? =
map[key]?.let {
when (T::class) {
String::class -> it as T
Int::class -> it.toInt() as T
Float::class -> it.toFloat() as T
Double::class -> it.toDouble() as T
else -> throw IllegalArgumentException("Not implemented for the given type.")
}
}
fun test() {
map["count"] = "1"
assert(getAsInt("count") == 1)
assert(getAsIntOptimal("count") == 1)
}
//inlined will all when branches, ~50 lines of bytecode
private fun getAsInt(key: String) = get<Int>(key)
//ideal result, ~10 lines of bytecode
private fun getAsIntOptimal(key: String) = map[key]?.toInt()
| 1 | null | 12 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 764 | bbfgradle | Apache License 2.0 |
modules/fbs-core/api/src/main/kotlin/de/thm/ii/fbs/model/v2/checker/excel/AnalysisResult.kt | thm-mni-ii | 145,119,531 | false | null | package de.thm.ii.fbs.model.v2.checker.excel
data class AnalysisResult(
private val errorCellResults: HashMap<Cell, CellResult> = HashMap(),
private val subtasks: HashMap<Int, MutableSet<Cell>> = HashMap()
) {
// should only be once if it shall be consistent
fun addCellResult(cell: Cell, isPropagated: Boolean = false) {
errorCellResults[cell] = CellResult(isPropagated)
}
fun getCellResult(cell: Cell): CellResult? {
return errorCellResults[cell]
}
fun addCellToSubtask(id: Int, cell: Cell) {
val set = subtasks[id] ?: HashSet()
set.add(cell)
subtasks[id] = set
}
fun getAllErrorCells(): Set<Cell> {
return errorCellResults.keys
}
fun getErrorCells(): Set<Cell> {
return errorCellResults.entries.filter { entry -> !entry.value.isPropagated }.map { entry -> entry.key }.toSet()
}
fun getPropagatedErrorCells(): Set<Cell> {
return errorCellResults.entries.filter { entry -> entry.value.isPropagated }.map { entry -> entry.key }.toSet()
}
}
| 239 | null | 9 | 19 | 73630e17e587a8bbf51e033817ef8f53a9f2499f | 1,071 | feedbacksystem | Apache License 2.0 |
idea/testData/codeInsight/expressionType/BlockBodyFunction.kt | JakeWharton | 99,388,807 | false | null | fun foo() {
val <caret>x = 1
}
// TYPE: val x = 1 -> <html>Int</html>
| 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 75 | kotlin | Apache License 2.0 |
epoxy-integrationtest/src/test/java/com/airbnb/epoxy/ModelViewInterfaceTest.kt | miladv33 | 152,602,423 | true | {"Java": 1552773, "Kotlin": 317033, "Ruby": 3134} | package com.airbnb.epoxy
import android.view.*
import com.airbnb.epoxy.integrationtest.*
import org.junit.*
import org.junit.runner.*
import org.robolectric.*
import org.robolectric.annotation.*
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(21))
class ModelViewInterfaceTest {
@Test
fun interfaceIsGeneratedForView() {
val model: InterfaceForViewModel_ = ViewWithInterfaceModel_()
model.text("")
}
@Test
fun generatedInterfaceIncludesBaseModelProps() {
val model: InterfaceForViewModel_ = ViewWithInterfaceModel_()
model.id(1)
.id("sfd")
.spanSizeOverride(null)
}
@Test
fun textPropMethodsAreOnInterface() {
val model: InterfaceForViewModel_ = ViewWithInterfaceModel_()
model.text("")
.text2("asdf")
.text2(3)
.text2(3, "arg")
}
@Test
fun multipleModelsDeclareInterface() {
val model1: InterfaceForViewModel_ = ViewWithInterfaceModel_()
val model2: InterfaceForViewModel_ = ViewWithInterface2Model_()
model1.text("")
.text2("")
.id(1)
model2.text("")
.text2("")
.id(1)
}
@Test
fun viewCanHaveMultipleInterfaces() {
val model = ViewWithInterfaceModel_()
val interface1 = model as InterfaceForViewModel_
val interface2 = model as InterfaceForView2Model_
interface1.text("")
interface2.listener(null)
}
@Test
fun nestedInterfaceWorks() {
val model = ViewWithInterfaceModel_() as ClassWithNestedInterface_NestedInterfaceModel_
model.listener( View.OnClickListener { })
}
} | 0 | Java | 0 | 1 | 9eb4fc658d6fef30ed23260ff10b9ec2ed1fbb70 | 1,782 | epoxy | Apache License 2.0 |
goblin-core/src/test/java/org/goblinframework/core/serialization/fst/FstSerializerTest.kt | xiaohaiz | 206,246,434 | false | null | package org.goblinframework.core.serialization.fst
import org.goblinframework.core.serialization.Serializer
import org.goblinframework.core.serialization.SerializerManager
import org.goblinframework.core.serialization.SerializerMode
import org.goblinframework.core.serialization.SerializerTest
import org.goblinframework.test.runner.GoblinTestRunner
import org.junit.runner.RunWith
import org.springframework.test.context.ContextConfiguration
@RunWith(GoblinTestRunner::class)
@ContextConfiguration("/UT.xml")
class FstSerializerTest : SerializerTest() {
override fun serializer(): Serializer {
return SerializerManager.INSTANCE.getSerializer(SerializerMode.FST)
}
} | 1 | null | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 677 | goblinframework | Apache License 2.0 |
android/src/main/kotlin/com/situm/situm_flutter_wayfinding/SitumMapPlatformView.kt | kerk12 | 578,338,490 | true | {"Markdown": 5, "YAML": 4, "Text": 1, "Ignore List": 6, "Dart": 12, "Gradle": 5, "XML": 14, "Java": 1, "Kotlin": 9, "JSON": 3, "INI": 2, "Ruby": 2, "Objective-C": 5, "OpenStep Property List": 4, "Swift": 3, "C": 1} | package com.situm.situm_flutter_wayfinding
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import es.situm.sdk.model.cartography.Building
import es.situm.sdk.model.cartography.Floor
import es.situm.sdk.model.cartography.Poi
import es.situm.wayfinding.OnPoiSelectionListener
import es.situm.wayfinding.SitumMapsLibrary
import es.situm.wayfinding.actions.ActionsCallback
import es.situm.wayfinding.navigation.Navigation
import es.situm.wayfinding.navigation.NavigationError
import es.situm.wayfinding.navigation.OnNavigationListener
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
class SitumMapPlatformView(
private val activity: AppCompatActivity,
messenger: BinaryMessenger,
id: Int
) : PlatformView,
MethodChannel.MethodCallHandler,
DefaultLifecycleObserver {
companion object {
const val TAG = "Situm>"
// Workaround to avoid WYF to be recreated with the flutter widget lifecycle.
@SuppressLint("StaticFieldLeak")
private var layout: View? = null
// WYF:
private var library: SitumMapsLibrary? = null
private lateinit var libraryLoader: SitumMapLibraryLoader
lateinit var loadSettings: FlutterLibrarySettings
const val ERROR_LIBRARY_NOT_LOADED = "ERROR_LIBRARY_NOT_LOADED"
const val ERROR_SELECT_POI = "ERROR_SELECT_POI"
}
private var methodChannel: MethodChannel
init {
libraryLoader = SitumMapLibraryLoader.fromActivity(activity)
activity.lifecycle.addObserver(this)
methodChannel = MethodChannel(messenger, "situm.com/flutter_wayfinding")
methodChannel.setMethodCallHandler(this)
}
override fun getView(): View? {
if (layout == null) {
val inflater = LayoutInflater.from(activity)
layout = inflater.inflate(R.layout.situm_flutter_map_view_layout, null, false)
}
return layout
}
override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
val arguments = (methodCall.arguments ?: emptyMap<String, Any>()) as Map<String, Any>
if (methodCall.method == "load") {
load(arguments, result)
} else {
// Check that the library was successfully loaded.
if (!verifyLibrary(result)) {
return
}
when (methodCall.method) {
// Add here all the library methods:
"unload" -> unload(result)
"selectPoi" -> selectPoi(arguments, result)
"startPositioning" -> startPositioning()
"stopPositioning" -> stopPositioning()
"stopNavigation" -> stopNavigation()
"filterPoisBy" -> filterPoisBy(arguments, result)
else -> result.notImplemented()
}
}
}
override fun dispose() {
Log.d(TAG, "PlatformView dispose() called.")
// TODO: this is causing problems with unload/load. A deeper analysis should be performed.
// Why the method call handler is not being re-established?
// methodChannel.setMethodCallHandler(null)
}
// Public methods (impl):
// Load WYF into the target view.
private fun load(arguments: Map<String, Any>, methodResult: MethodChannel.Result) {
loadSettings = FlutterLibrarySettings(arguments)
libraryLoader.load(loadSettings, object : SitumMapLibraryLoader.Callback {
override fun onSuccess(obtained: SitumMapsLibrary) {
library = obtained
methodResult.success("SUCCESS")
initCallbacks()
}
override fun onError(code: Int, message: String) {
methodResult.error(code.toString(), message, null)
}
})
}
private fun unload(methodResult: MethodChannel.Result?) {
Log.d(TAG, "PlatformView unload called!")
libraryLoader.unload()
// Ensure this layout does not have a parent:
if (layout?.parent != null) {
(layout?.parent as ViewGroup).removeView(layout)
}
layout = null
methodResult?.success("DONE")
}
private fun startPositioning() {
library?.startPositioning(loadSettings.buildingIdentifier)
}
private fun stopPositioning() {
library?.stopPositioning()
}
private fun stopNavigation() {
library?.stopNavigation()
}
// Select the given poi in the map.
private fun selectPoi(arguments: Map<String, Any>, methodResult: MethodChannel.Result) {
Log.d(TAG, "Android> Plugin selectPoi call.")
val buildingId = arguments["buildingId"] as String
val poiId = arguments["id"] as String
FlutterCommunicationManager.fetchPoi(
buildingId,
poiId,
object : FlutterCommunicationManager.Callback<Poi> {
override fun onSuccess(result: Poi) {
Log.d(TAG, "Android> Library selectPoi call.")
library?.selectPoi(result, object : ActionsCallback {
override fun onActionConcluded() {
Log.d(TAG, "Android> selectPoi success.")
methodResult.success(poiId)
}
})
}
override fun onError(message: String) {
Log.e(TAG, "Android> Library selectPoi error: $message.")
methodResult.error(ERROR_SELECT_POI, message, null)
}
})
}
// Filter poi categories
private fun filterPoisBy(arguments: Map<String, Any>, result: MethodChannel.Result) {
val categoryIdsFilter = arguments["categoryIdsFilter"] as List<String>
library?.filterPoisBy(categoryIdsFilter)
result.success("DONE")
}
// Callbacks
fun initCallbacks() {
// Listen for POI selection/deselection events.
library?.setOnPoiSelectionListener(object : OnPoiSelectionListener {
override fun onPoiSelected(poi: Poi, floor: Floor, building: Building) {
val arguments = mutableMapOf<String, String>(
"buildingId" to building.identifier,
"buildingName" to building.name,
"floorId" to floor.identifier,
"floorName" to floor.name,
"poiId" to poi.identifier,
"poiName" to poi.name,
"poiInfoHtml" to poi.infoHtml,
)
methodChannel.invokeMethod("onPoiSelected", arguments)
}
override fun onPoiDeselected(building: Building) {
val arguments = mutableMapOf(
"buildingId" to building.identifier,
"buildingName" to building.name,
)
methodChannel.invokeMethod("onPoiDeselected", arguments)
}
})
library?.setOnNavigationListener(object : OnNavigationListener {
override fun onNavigationError(navigation: Navigation, error: NavigationError) {
val arguments = mutableMapOf(
"error" to error.message,
"destinationId" to navigation.destination.identifier,
)
methodChannel.invokeMethod("onNavigationError", arguments)
}
override fun onNavigationFinished(navigation: Navigation) {
val arguments = mutableMapOf(
"destinationId" to navigation.destination.identifier,
)
methodChannel.invokeMethod("onNavigationFinished", arguments)
}
override fun onNavigationRequested(navigation: Navigation) {
val arguments = mutableMapOf(
"destinationId" to navigation.destination.identifier,
)
methodChannel.invokeMethod("onNavigationRequested", arguments)
}
override fun onNavigationStarted(navigation: Navigation) {
val arguments = mutableMapOf<String, Any?>(
"destinationId" to navigation.destination.identifier,
)
navigation.route?.let {
arguments += mutableMapOf<String, Any?>(
"routeDistance" to it.distance
)
}
methodChannel.invokeMethod("onNavigationStarted", arguments)
}
})
}
// Utils
private fun verifyLibrary(result: MethodChannel.Result): Boolean {
if (library == null) {
result.error(
ERROR_LIBRARY_NOT_LOADED, "SitumMapsLibrary not loaded.", null
)
return false
}
return true
}
// DefaultLifecycleObserver
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
owner.lifecycle.removeObserver(this)
unload(null)
}
} | 0 | Java | 0 | 0 | 8368b4a99dc7f6b78700242b76d14ac58ee9f511 | 9,408 | flutter-wayfinding | MIT License |
app/src/main/java/io/github/jixiaoyong/wanandroid/api/bean/CookieBean.kt | jixiaoyong | 122,834,572 | false | null | package io.github.jixiaoyong.wanandroid.api.bean
/**
* Created by jixiaoyong on 2018/3/8.
* email:<EMAIL>
*/
class CookieBean {
/**
* data : {"collectIds":[-1,-1,-1,-1,-1,-1,-1],"email":"","icon":"","id":,"password":"","type":0,"username":""}
* errorCode : 0
* errorMsg :
*/
var data: DataBean = DataBean()
var errorCode: Int = 0
var errorMsg: String = ""
class DataBean {
/**
* collectIds : [-1,-1,-1,-1,-1,-1,-1]
* email :
* icon :
* id :
* password :
* type : 0
* username :
*/
var email: String = ""
var icon: String = ""
var id: Int = 0
var password: String = ""
var type: Int = 0
var username: String = ""
var collectIds: List<Int>? = null
}
} | 1 | null | 6 | 24 | 4ffb6ce5434e6bd73606c43188955bdae37bdacd | 837 | WanAndroid | Apache License 2.0 |
goblin-example/goblin-example-transport/src/main/java/org/goblinframework/example/transport/server/Client.kt | xiaohaiz | 206,246,434 | false | null | package org.goblinframework.example.transport.server
import org.goblinframework.api.function.Block1
import org.goblinframework.bootstrap.core.StandaloneClient
import org.goblinframework.core.container.GoblinSpringContainer
import org.goblinframework.core.container.SpringContainer
import org.goblinframework.core.util.NetworkUtils
import org.goblinframework.transport.client.channel.TransportClientManager
import org.goblinframework.transport.client.flight.MessageFlightManager
import org.goblinframework.transport.client.setting.TransportClientSetting
@GoblinSpringContainer("/config/transport-client.xml")
class Client : StandaloneClient() {
override fun doExecute(container: SpringContainer?) {
val setting = TransportClientSetting.builder()
.name("goblinframework-example-transport-client")
.serverHost(NetworkUtils.getLocalAddress())
.serverPort(59766)
.autoReconnect(true)
.enableReceiveShutdown()
//.enableSendHeartbeat()
.applyHandlerSetting {
it.enableMessageFlight()
}
.enableDebugMode()
.build()
val client = TransportClientManager.INSTANCE.createConnection(setting)
client.connectFuture().awaitUninterruptibly()
if (client.available()) {
val flight = MessageFlightManager.INSTANCE.createMessageFlight(true)
.prepareRequest(Block1 {
it.writePayload("HELLO, WORLD!")
})
.sendRequest(client)
val reader = flight.uninterruptibly.responseReader()
val ret = reader.readPayload()
println(ret)
}
Thread.currentThread().join()
}
override fun doShutdown() {
TransportClientManager.INSTANCE.closeConnection("goblinframework-example-transport-client")
}
}
fun main(args: Array<String>) {
Client().bootstrap(args)
} | 1 | null | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 1,813 | goblinframework | Apache License 2.0 |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/feed/hot/HotView.kt | altaf933 | 122,962,254 | false | {"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Proguard": 1, "Kotlin": 485, "XML": 261, "Java": 4} | package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.hot
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.BaseEntryFeedView
interface HotView : BaseEntryFeedView | 1 | null | 1 | 1 | 0c2d9fc015a5bef5b258481e4233d04ab5705a49 | 202 | WykopMobilny | MIT License |
local/src/main/java/com/pechuro/bsuirschedule/local/entity/education/EducationFormCached.kt | Ilyshka991 | 147,244,674 | false | null | package com.pechuro.bsuirschedule.local.entity.education
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "education_form")
data class EducationFormCached(
@PrimaryKey
@ColumnInfo(name = "id")
val id: Long,
@ColumnInfo(name = "name")
val name: String
) | 1 | null | 1 | 8 | 8e07557025ed64784821fe31f5e02c53c976e5f4 | 337 | BsuirSchedule | Apache License 2.0 |
app/src/main/java/com/uiuang/cloudknowledge/ui/activity/SplashActivity.kt | uiuang | 284,432,922 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 217, "XML": 151, "Java": 7, "INI": 1, "Diff": 1} | package com.uiuang.cloudknowledge.ui.activity
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import com.uiuang.cloudknowledge.R
import com.uiuang.cloudknowledge.app.base.BaseActivity
import com.uiuang.cloudknowledge.databinding.ActivitySplashBinding
import com.uiuang.cloudknowledge.ext.loadUrl
import com.uiuang.cloudknowledge.utils.ColorUtil
import com.uiuang.cloudknowledge.utils.toast
import com.uiuang.cloudknowledge.viewmodel.state.SplashViewModel
import kotlinx.android.synthetic.main.activity_splash.*
import kotlinx.coroutines.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnNeverAskAgain
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.RuntimePermissions
@RuntimePermissions
class SplashActivity : BaseActivity<SplashViewModel, ActivitySplashBinding>(),
CoroutineScope by MainScope() {
override fun layoutId(): Int = R.layout.activity_splash
override fun initView(savedInstanceState: Bundle?) {
// 后台返回时可能启动这个页面 http://blog.csdn.net/jianiuqi/article/details/54091181
if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
finish()
return
}
imageView.loadUrl(this, ColorUtil.randomWallpaperUrl())
needPermissionWithPermissionCheck()
}
@NeedsPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
fun needPermission() {
toMain()
}
@OnNeverAskAgain(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
fun openPermission() {
toMain()
}
@OnPermissionDenied(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
fun deniedPermission() {
"拒绝权限部分功能将不能使用,请去设置打开权限".toast()
toMain()
}
@SuppressLint("NeedOnRequestPermissionsResult")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
private fun toMain() = launch {
delay(timeMillis = 2000L)
startActivity(Intent(this@SplashActivity, MainActivity::class.java))
overridePendingTransition(R.anim.screen_zoom_in, R.anim.screen_zoom_out)
finish()
}
override fun onDestroy() {
super.onDestroy()
cancel()
}
}
| 0 | Kotlin | 0 | 2 | 0a5d9e980f24abc6067392fc83fd930047b7d85e | 2,651 | CloudKnowledge | Apache License 2.0 |
app/src/main/java/com/robinkanatzar/qrreader/BarcodeScannerProcessor.kt | robinkanatzar | 288,663,798 | false | {"Java": 73364, "Kotlin": 21245} | package com.robinkanatzar.qrreader
import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat.getSystemService
import com.google.android.gms.tasks.Task
import com.google.mlkit.vision.barcode.Barcode
import com.google.mlkit.vision.barcode.BarcodeScanner
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage
class BarcodeScannerProcessor(private val context: Context) : VisionProcessorBase<List<Barcode>>(context) {
private val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
.build()
private val barcodeScanner: BarcodeScanner = BarcodeScanning.getClient(options)
override fun stop() {
super.stop()
barcodeScanner.close()
}
override fun detectInImage(image: InputImage): Task<List<Barcode>> {
return barcodeScanner.process(image)
}
override fun onSuccess(barcodes: List<Barcode>, graphicOverlay: GraphicOverlay) {
if (barcodes.isEmpty()) {
Log.v(MANUAL_TESTING_LOG, "No barcode has been detected")
}
for (i in barcodes.indices) {
val barcode = barcodes[i]
// TODO start wifi connection on success
when (barcode.valueType) {
Barcode.TYPE_WIFI -> {
val ssid = barcode.wifi!!.ssid
val password = barcode.wifi!!.password
val type = barcode.wifi!!.encryptionType
Log.d("RCK", "SSID = $ssid, password = $password, type = $type")
barcodeScanner.close()
val builder =
AlertDialog.Builder(context)
builder.setMessage("Do you want to connect to this wifi network?")
.setCancelable(false)
.setPositiveButton(
"Yes"
) { dialog, id ->
// TODO start wifi connection
checkIsCharging()
connectWifi(ssid, password, type)
dialog.dismiss()
}
.setNegativeButton(
"No"
) { dialog, id ->
// TODO restart barcode scanner
dialog.cancel()
}
val alert = builder.create()
alert.show()
}
/*Barcode.TYPE_URL -> {
val title = barcode.url!!.title
val url = barcode.url!!.url
}*/
}
//logExtrasForTesting(barcode)
}
}
private fun connectWifi(ssid: String?, password: String?, type: Int) {
val wifiManager = context.getSystemService(WIFI_SERVICE) as WifiManager
wifiManager.isWifiEnabled = true
val wifiConfig = WifiConfiguration()
wifiConfig.SSID = "\"" + ssid + "\""
wifiConfig.preSharedKey = "\""+ password +"\""
val netId = wifiManager.addNetwork(wifiConfig)
wifiManager.addNetwork(wifiConfig)
wifiManager.disconnect()
wifiManager.enableNetwork(netId, true)
wifiManager.reconnect()
}
private fun checkIsCharging() {
val batteryManager =
context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
Log.d("RCK", "isCharging? ${batteryManager.isCharging}")
}
override fun onFailure(e: Exception) {
Log.e(TAG, "Barcode detection failed $e")
}
companion object {
private const val TAG = "BarcodeProcessor"
private fun logExtrasForTesting(barcode: Barcode?) {
if (barcode != null) {
when (barcode.valueType) {
Barcode.TYPE_WIFI -> {
val ssid = barcode.wifi!!.ssid
val password = barcode.wifi!!.password
val type = barcode.wifi!!.encryptionType
Log.d("RCK", "SSID = $ssid, password = $password, type = $type")
// TODO exit scanning once this is found
}
Barcode.TYPE_URL -> {
val title = barcode.url!!.title
val url = barcode.url!!.url
// TODO open url, exit scanning
}
}
}
}
}
} | 1 | null | 1 | 1 | bf48f926c35b03a7028d5becd6884480fff5123b | 4,830 | qr-reader-android | Apache License 2.0 |
app/src/main/java/com/ulusoy/allaboutmaps/AppComponent.kt | ulusoyca | 263,270,190 | false | null | /*
* Copyright 2020 <NAME> (Ulus Oy Apps). All rights reserved.
*
* 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.ulusoy.hmscodelabs
import dagger.Component
import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import javax.inject.Singleton
/**
* Application component refers to application level modules only
*/
@Singleton
@Component(
modules = [
AndroidInjectionModule::class,
AppModule::class,
ContributeActivityModule::class,
ViewModelModule::class
]
)
interface AppComponent : AndroidInjector<HmsCodelabsApp> {
@Component.Factory
abstract class Factory : AndroidInjector.Factory<HmsCodelabsApp>
}
| 1 | Kotlin | 1 | 5 | 7bfe74beb007aa35f51d6554267f2ee90d6ab05a | 1,211 | AllAboutMaps | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/editor/enterHandler/SplitStringByEnterAddParentheses.after.kt | ingokegel | 72,937,917 | false | null | // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
val l = ("foo" +
"b<caret>ar").length() | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 87 | intellij-community | Apache License 2.0 |
app/src/main/java/com/hd/simplesplashscreen/demo/BaseActivity.kt | HelloHuDi | 119,490,011 | false | {"Java": 26331, "Kotlin": 3474} | package com.hd.simplesplashscreen.demo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
/**
* Created by hd on 2018/1/21 .
*
*/
abstract class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(android.view.Window.FEATURE_NO_TITLE)
window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
window.addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
}
| 1 | Java | 1 | 2 | 4aa97daf377373cf1d79de61cc0a0df68bb5cf4b | 561 | SimpleSplashScreen | Apache License 2.0 |
app/src/main/java/com/wavesplatform/wallet/v2/data/manager/base/BaseServiceManager.kt | wavesplatform | 98,419,999 | false | null | /*
* Created by <NAME> on 1/4/2019
* Copyright © 2019 Waves Platform. All rights reserved.
*/
package com.wavesplatform.wallet.v2.data.manager.base
import com.wavesplatform.sdk.WavesSdk
import com.wavesplatform.sdk.net.service.*
import com.wavesplatform.wallet.App
import com.wavesplatform.wallet.v2.util.PrefsUtil
import com.wavesplatform.wallet.v2.data.local.PreferencesHelper
import com.wavesplatform.wallet.v2.data.manager.GithubServiceManager
import com.wavesplatform.wallet.v2.data.manager.gateway.manager.CoinomatDataManager
import com.wavesplatform.wallet.v2.data.manager.gateway.manager.GatewayDataManager
import com.wavesplatform.wallet.v2.data.remote.CoinomatService
import com.wavesplatform.wallet.v2.data.remote.GatewayService
import com.wavesplatform.wallet.v2.data.remote.GithubService
import com.wavesplatform.wallet.v2.util.RxEventBus
import com.wavesplatform.wallet.v2.util.WavesWallet
import javax.inject.Inject
open class BaseServiceManager @Inject constructor() {
var nodeService: NodeService = WavesSdk.service().getNode()
var dataService: DataService = WavesSdk.service().getDataService()
var matcherService: MatcherService = WavesSdk.service().getMatcher()
var githubService: GithubService = GithubServiceManager.create()
var coinomatService: CoinomatService = CoinomatDataManager.create()
var gatewayService: GatewayService = GatewayDataManager.create()
var preferencesHelper: PreferencesHelper = PreferencesHelper(App.appContext)
var prefsUtil: PrefsUtil = PrefsUtil(App.appContext)
var rxEventBus: RxEventBus = RxEventBus()
fun getAddress(): String {
return WavesWallet.getAddress()
}
fun getPublicKeyStr(): String {
return WavesWallet.getPublicKeyStr()
}
fun getPrivateKey(): ByteArray {
return WavesWallet.getPrivateKey()
}
}
| 2 | null | 52 | 55 | 5f4106576dc4fe377a355d045f638e7469cd6abe | 1,850 | WavesWallet-android | MIT License |
sample/src/main/java/com/airbnb/mvrx/sample/features/helloworld/HelloWorldFragment.kt | littleGnAl | 167,345,526 | false | null | package com.airbnb.mvrx.sample.features.helloworld
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.airbnb.mvrx.BaseMvRxFragment
import com.airbnb.mvrx.sample.R
import com.airbnb.mvrx.sample.views.Marquee
class HelloWorldFragment : BaseMvRxFragment() {
private lateinit var marquee: Marquee
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_hello_world, container, false).apply {
findViewById<Toolbar>(R.id.toolbar).setupWithNavController(findNavController())
marquee = findViewById(R.id.marquee)
}
override fun invalidate() {
marquee.setTitle("Hello World")
}
} | 1 | null | 1 | 3 | 7ea6284530a0640f36d12508a669b4f4222902c3 | 953 | MvRx | Apache License 2.0 |
app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/ui/SettingActivity.kt | XiaoQiWen | 94,879,961 | false | null | package gorden.krefreshlayout.demo.ui
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import gorden.krefreshlayout.demo.R
import kotlinx.android.synthetic.main.activity_setting.*
class SettingActivity : AppCompatActivity() {
private var headerPosition = 0
private var pinContent = false
private var keepHeaderWhenRefresh = true
private var durationOffset = 200L
private var refreshTime = 2000L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setting)
btn_back.setOnClickListener {
finish()
}
headerPosition = intent.getIntExtra("header", 0)
pinContent = intent.getBooleanExtra("pincontent", false)
keepHeaderWhenRefresh = intent.getBooleanExtra("keepheader", true)
durationOffset = intent.getLongExtra("durationoffset", 200)
refreshTime = intent.getLongExtra("refreshtime", 2000)
spinner.setSelection(headerPosition)
togglePinContent.isChecked = pinContent
toggleKeepHeader.isChecked = keepHeaderWhenRefresh
edit_offset.setText(durationOffset.toString())
edit_refresh.setText(refreshTime.toString())
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
headerPosition = position
}
}
}
override fun finish() {
val data = Intent()
pinContent = togglePinContent.isChecked
keepHeaderWhenRefresh = toggleKeepHeader.isChecked
durationOffset = if (TextUtils.isEmpty(edit_offset.text)) 200 else edit_offset.text.toString().toLong()
refreshTime = if (TextUtils.isEmpty(edit_refresh.text)) 2000 else edit_refresh.text.toString().toLong()
data.putExtra("header", headerPosition)
data.putExtra("pincontent", pinContent)
data.putExtra("keepheader", keepHeaderWhenRefresh)
data.putExtra("durationoffset", durationOffset)
data.putExtra("refreshtime", refreshTime)
setResult(Activity.RESULT_OK, data)
super.finish()
}
}
| 2 | Kotlin | 37 | 219 | 510cd29710d10c3fee2e869ed9214ff17424abe4 | 2,476 | KRefreshLayout | Apache License 2.0 |
src/main/java/org/nirvana/kotlin/LambdaCode.kt | berialcheng | 170,461,260 | false | null | package org.nirvana.kotlin
class LambdaCode {
fun foo(){
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
}
} | 1 | null | 1 | 3 | b7f39aa93855ee57ecd325bc9c109a0000fc0ee0 | 319 | jvm-bytecode-insight | Apache License 2.0 |
seouling/src/main/java/mobile/seouling/com/application/data/vo/Schedule.kt | thisishoonlee | 208,585,721 | true | {"Java": 119376, "Kotlin": 104482} | package mobile.seouling.com.application.data.vo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
@Entity(tableName = "schedules")
data class Schedule(
@PrimaryKey @SerializedName("id")val id: Int,
@SerializedName("date")val date: String,
@SerializedName("morning")val morning: List<Spot>,
@SerializedName("after_noon")val afternoon: List<Spot>,
@SerializedName("night")val night: List<Spot>
) | 0 | null | 0 | 0 | 7c7cfbf3170856546d5b0b804a37b642c222214a | 495 | seouling-android | Apache License 2.0 |
app/src/main/java/me/cyber/nukleos/dagger/SensorStuffManagerModule.kt | cyber-punk-me | 141,065,829 | false | null | package me.cyber.nukleos.dagger
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module(includes = [ContextModule::class])
class SensorStuffManagerModule {
@Provides
@Singleton
fun provideSensorStuffManager()= PeripheryManager()
}
| 1 | Kotlin | 9 | 17 | 03fad246834e6c569e301b005037849bdfccb664 | 271 | nukleos | Apache License 2.0 |
request-filterer/request-filterer-store/src/main/java/com/duckduckgo/request/filterer/store/RequestFiltererFeatureToggleStore.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.request.filterer.store
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.duckduckgo.request.filterer.api.RequestFiltererFeatureName
interface RequestFiltererFeatureToggleStore {
fun deleteAll()
fun get(
featureName: RequestFiltererFeatureName,
defaultValue: Boolean,
): Boolean
fun getMinSupportedVersion(featureName: RequestFiltererFeatureName): Int
fun insert(toggle: RequestFiltererFeatureToggles)
}
class RealRequestFiltererFeatureToggleStore(private val context: Context) : RequestFiltererFeatureToggleStore {
private val preferences: SharedPreferences by lazy { context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE) }
override fun deleteAll() {
preferences.edit().clear().apply()
}
override fun get(featureName: RequestFiltererFeatureName, defaultValue: Boolean): Boolean {
return preferences.getBoolean(featureName.value, defaultValue)
}
override fun getMinSupportedVersion(featureName: RequestFiltererFeatureName): Int {
return preferences.getInt("${featureName.value}$MIN_SUPPORTED_VERSION", 0)
}
override fun insert(toggle: RequestFiltererFeatureToggles) {
preferences.edit {
putBoolean(toggle.featureName.value, toggle.enabled)
toggle.minSupportedVersion?.let {
putInt("${toggle.featureName.value}$MIN_SUPPORTED_VERSION", it)
}
}
}
companion object {
const val FILENAME = "com.duckduckgo.request.filterer.store.toggles"
const val MIN_SUPPORTED_VERSION = "MinSupportedVersion"
}
}
data class RequestFiltererFeatureToggles(
val featureName: RequestFiltererFeatureName,
val enabled: Boolean,
val minSupportedVersion: Int?,
)
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 1,844 | DuckDuckGo | Apache License 2.0 |
game-engine/src/main/kotlin/com/zenika/ageofdevsecops/domain/challenge/SecurityGroup.kt | zenika-open-source | 176,924,113 | false | null | package com.zenika.ageofdevsecops.domain.challenge
data class SecurityGroup(val id: String)
| 34 | Kotlin | 6 | 8 | be41076dd729649eff49633e20745fa917a544a4 | 93 | age-of-devsecops | Apache License 2.0 |
commons/src/main/java/com/hashone/commons/contactus/ContactUs.kt | hashonetech | 627,352,104 | false | {"Kotlin": 347496, "Java": 202116} | package com.hashone.commons.contactus
import android.app.Activity
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.FloatRange
import androidx.annotation.FontRes
import com.hashone.commons.R
import java.io.Serializable
open class ContactUs(val builder: Builder) : Serializable {
companion object {
inline fun build(
emailData: EmailData = EmailData("", ""),
appData: AppData,
purchases: Purchases,
extraContents: HashMap<String, String> = hashMapOf(),
exportToFile: Boolean = false,
showKeyboard: Boolean = false,
//TODO: Allow Media Pick
mediaBuilder: MediaBuilder = MediaBuilder(),
block: Builder.() -> Unit
) = Builder(
emailData,
appData,
purchases,
extraContents,
exportToFile,
showKeyboard,
mediaBuilder,
).apply(block).build()
fun open(activity: Activity, contactUs: ContactUs) {
ContactUsActivity.newIntent(context = activity, contactUs = contactUs)
.also { activity.startActivity(it) }
}
}
class Builder(
var emailData: EmailData,
var appData: AppData,
var purchases: Purchases,
var extraContents: HashMap<String, String> = hashMapOf(),
var exportToFile: Boolean = false,
var showKeyboard: Boolean = false,
//TODO: Allow Media Pick
var mediaBuilder: MediaBuilder = MediaBuilder()
) : Serializable {
//TODO: Screen
var screenBuilder = ScreenBuilder()
//TODO: Toolbar
var toolBarBuilder = ToolBarBuilder()
//TODO: Radio Buttons
var radioButtonBinding = RadioButtonBuilder()
//TODO: Message UI
var messageBuilder = MessageBuilder()
//TODO: Attachment UI
var attachmentBuilder = AttachmentBuilder()
//TODO: Action button
var actionButtonBuilder = ActionButtonBuilder()
fun build() = ContactUs(this)
}
class ScreenBuilder(
var isFullScreen: Boolean = false,
@ColorRes
var windowBackgroundColor: Int = R.color.white,
@ColorRes
var statusBarColor: Int = R.color.extra_extra_light_gray,
@ColorRes
var navigationBarColor: Int = R.color.extra_extra_light_gray,
) : Serializable
class ToolBarBuilder(
@ColorRes
var barColor: Int = R.color.extra_extra_light_gray,
@DrawableRes
var backIcon: Int = R.drawable.ic_back_contact_us,
var backIconDescription: String = "",
var title: String = "",
@ColorRes
var titleColor: Int = R.color.black,
@FontRes
var titleFont: Int = R.font.outfit_semi_bold,
@FloatRange
var titleSize: Float = 16F,
) : Serializable
class RadioButtonBuilder(
@ColorRes
var selectedColor: Int = R.color.black,
@ColorRes
var defaultColor: Int = R.color.black,
@FontRes
var textFont: Int = R.font.roboto_medium,
@FloatRange
var textSize: Float = 14F,
) : Serializable
class MessageBuilder(
@ColorRes
var backgroundColor: Int = R.color.extra_extra_light_gray,
@FloatRange
var backgroundRadius: Float = 8F,
var hint: String = "",
@ColorRes
var hintColor: Int = R.color.light_gray,
var message: String = "",
@ColorRes
var color: Int = R.color.black,
@FontRes
var font: Int = R.font.roboto_medium,
@FloatRange
var size: Float = 14F,
) : Serializable
class AttachmentBuilder(
@ColorRes
var cardBackgroundColor: Int = R.color.extra_extra_light_gray,
@FloatRange
var cardBackgroundRadius: Float = 8F,
@ColorRes
var backgroundColor: Int = R.color.white,
@FloatRange
var backgroundRadius: Float = 8F,
var title: String = "",
@ColorRes
var titleColor: Int = R.color.light_gray,
@FontRes
var titleFont: Int = R.font.roboto_medium,
@FloatRange
var titleSize: Float = 14F,
@DrawableRes
var addIcon: Int = R.drawable.ic_contact_us_add_attachment,
@DrawableRes
var deleteIcon: Int = R.drawable.ic_contact_us_img_delete,
) : Serializable
class ActionButtonBuilder(
@ColorRes
var backgroundInactiveColor: Int = R.color.light_gray,
@ColorRes
var backgroundColor: Int = R.color.black,
@FloatRange
var radius: Float = 30F,
var text: String = "",
@ColorRes
var textColor: Int = R.color.white,
@FontRes
var textFont: Int = R.font.outfit_bold,
@FloatRange
var textSize: Float = 16F,
) : Serializable
class EmailData(
var subject: String = "",
var email: String
): Serializable
class AppData(
var mPackage: String,
var name: String,
var appVersionData: AppVersionData,
var token: String = "",
var customerNumber: String = "",
var languageData: LanguageData = LanguageData(),
var countryData: CountryData = CountryData()
): Serializable
class CountryData(
var name: String = "",
var code: String = ""
): Serializable
class AppVersionData(
var name: String,
var code: String
): Serializable
class LanguageData(
var name: String = "",
var code: String = ""
): Serializable
class Purchases(
var isPremium: Boolean = false,
var title: String = "",
var orderId: String = "",
): Serializable
class MediaBuilder(
var allowPhotosOnly: Boolean = false,
var allowVideosOnly: Boolean = false,
var allowBoth: Boolean = true,
var maxFileSize: Long = 0L,
var messageBoxHeight: Double = 0.0,
var attachmentBoxHeight: Double = 0.0,
var optionItemsList: ArrayList<OptionItem> = arrayListOf()
) : Serializable
data class OptionItem(
val text: String = "",
val message: String = "",
val isChecked: Boolean = false
) : Serializable
} | 0 | Kotlin | 0 | 0 | b4be9603a39a230a8556287bc7496d4049201b33 | 6,346 | commons | Apache License 2.0 |
app/src/main/java/jp/gr/java_conf/miwax/troutoss/view/adapter/SnsTabAdapter.kt | tomoya0x00 | 88,883,321 | false | {"HTML": 454444, "Kotlin": 212305, "Java": 1172} | package jp.gr.java_conf.miwax.troutoss.view.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import io.realm.Realm
import jp.gr.java_conf.miwax.troutoss.model.MastodonHelper
import jp.gr.java_conf.miwax.troutoss.model.SnsTabRepository
import jp.gr.java_conf.miwax.troutoss.model.entity.AccountType
import jp.gr.java_conf.miwax.troutoss.model.entity.SnsTab
import jp.gr.java_conf.miwax.troutoss.view.fragment.DummyFragment
import jp.gr.java_conf.miwax.troutoss.view.fragment.MastodonNotificationsFragment
import jp.gr.java_conf.miwax.troutoss.view.fragment.MastodonTimelineFragment
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import timber.log.Timber
/**
* Created by <NAME> on 2017/05/01.
* SNSタブのアダプター
*/
class SnsTabAdapter(fm: FragmentManager?, val realm: Realm) : FragmentPagerAdapter(fm) {
private val helper = MastodonHelper()
private val repository = SnsTabRepository(helper)
private val tabs = repository.findAllSorted(realm)
private var tabMap = mutableMapOf<Int, TabPosHolder>()
init {
tabs.addChangeListener { _, _ ->
updateTabMap()
launch(UI) { notifyDataSetChanged() }
}
}
private data class TabPosHolder(val tabId: Int, var pos: Int, var gotPos: Int = pos)
override fun getItem(position: Int): Fragment {
if (tabs.isEmpty()) {
return DummyFragment()
}
val tab = tabs[position]
val fragment = when (tab.type) {
SnsTab.TabType.MASTODON_HOME -> {
MastodonTimelineFragment.newInstance(MastodonTimelineAdapter.Timeline.HOME, tab.accountUuid, tab.option)
}
SnsTab.TabType.MASTODON_FAVOURITES -> {
MastodonTimelineFragment.newInstance(MastodonTimelineAdapter.Timeline.FAVOURITES, tab.accountUuid, tab.option)
}
SnsTab.TabType.MASTODON_NOTIFICATIONS -> {
MastodonNotificationsFragment.newInstance(tab.accountUuid, tab.option)
}
SnsTab.TabType.MASTODON_LOCAL -> {
MastodonTimelineFragment.newInstance(MastodonTimelineAdapter.Timeline.LOCAL, tab.accountUuid, tab.option)
}
SnsTab.TabType.MASTODON_FEDERATED -> {
MastodonTimelineFragment.newInstance(MastodonTimelineAdapter.Timeline.FEDERATED, tab.accountUuid, tab.option)
}
else -> {
DummyFragment()
}
}
tabMap[fragment.hashCode()] = TabPosHolder(tab.hashCode(), position)
Timber.d("getItem tab pos: $position, fragmentHash: ${fragment.hashCode()}")
return fragment
}
override fun getPageTitle(position: Int): CharSequence {
if (tabs.isEmpty()) {
return ""
}
return repository.getTitleOf(tabs[position])
}
override fun getCount(): Int {
return tabs.count()
}
override fun getItemId(position: Int): Long {
val id = tabs[position].hashCode().toLong()
Timber.d("getItemId id: $id, pos: $position")
return id
}
override fun getItemPosition(fragment: Any): Int {
val pos = tabMap[fragment.hashCode()]?.let {
if (it.gotPos == it.pos) {
POSITION_UNCHANGED
} else {
it.gotPos = it.pos
it.pos
}
} ?: POSITION_NONE
Timber.d("getItemPosition fragmentHash: ${fragment.hashCode()}, pos: $pos")
return pos
}
fun getAccount(position: Int): Pair<AccountType, String> {
if (tabs.isEmpty()) {
return Pair(AccountType.UNKNOWN, "")
}
val tab = tabs[position]
return Pair(tab.type.accountType, tab.accountUuid)
}
fun findFragmentAt(viewPager: ViewPager, position: Int): Fragment {
val f = instantiateItem(viewPager, position) as Fragment
finishUpdate(viewPager)
return f
}
fun getSnsTabAt(position: Int): SnsTab = tabs[position]
private fun updateTabMap() {
val existTabIds = tabs.map { it.hashCode() }
val newTabMap = mutableMapOf<Int, TabPosHolder>()
for ((key, holder) in tabMap) {
if (existTabIds.contains(holder.tabId)) {
newTabMap[key] = TabPosHolder(holder.tabId, existTabIds.indexOf(holder.tabId), holder.gotPos)
}
}
tabMap = newTabMap
}
} | 68 | HTML | 1 | 7 | e9aa54ed32b2d70f029fcbcde5656b9886c0a712 | 4,582 | Troutoss | Apache License 2.0 |
sigstore-testkit/src/main/kotlin/dev/sigstore/testkit/BaseGradleTest.kt | sigstore | 460,184,708 | false | null | /*
* Copyright 2022 The Sigstore 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 dev.sigstore.testkit
import org.assertj.core.api.AbstractCharSequenceAssert
import org.assertj.core.api.SoftAssertions
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.internal.DefaultGradleRunner
import org.gradle.util.GradleVersion
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.io.CleanupMode
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.Arguments.arguments
import java.io.File
import java.nio.file.Path
open class BaseGradleTest {
enum class ConfigurationCache {
ON, OFF
}
protected val gradleRunner = GradleRunner.create().withPluginClasspath()
companion object {
val isCI = System.getenv().containsKey("CI") || System.getProperties().containsKey("CI")
val EXTRA_LOCAL_REPOS = System.getProperty("sigstore.test.local.maven.repo").split(File.pathSeparatorChar)
val SIGSTORE_JAVA_CURRENT_VERSION =
TestedSigstoreJava.LocallyBuiltVersion(
System.getProperty("sigstore.test.current.version")
)
@JvmStatic
fun gradleVersions() = listOf(
// Gradle 7.2 fails with "No service of type ObjectFactory available in default services"
// So we require Gradle 7.3+
"7.3",
"7.5.1",
"8.1",
"8.5",
).map { GradleVersion.version(it) }
@JvmStatic
fun gradleVersionAndSettings(): Iterable<TestedGradle> {
if (!isCI) {
// Execute a single combination only when running locally
return listOf(
TestedGradle(gradleVersions().first(), ConfigurationCache.ON)
)
}
return buildList {
addAll(
gradleVersions().map { TestedGradle(it, ConfigurationCache.ON) }
)
// Test the first and the last version without configuration cache
add(TestedGradle(gradleVersions().first(), ConfigurationCache.OFF))
add(TestedGradle(gradleVersions().last(), ConfigurationCache.OFF))
}
}
@JvmStatic
fun sigstoreJavaVersions(): Iterable<TestedSigstoreJava> {
return buildList {
add(SIGSTORE_JAVA_CURRENT_VERSION)
// For now, we test the plugins only with locally-built sigstore-java version
if (isCI && false) {
add(TestedSigstoreJava.Default)
// 0.3.0 is the minimal version that supports generating Sigstore Bundle
add(TestedSigstoreJava.Version("0.3.0"))
}
}
}
@JvmStatic
fun gradleAndSigstoreJavaVersions(): Iterable<TestedGradleAndSigstoreJava> {
val gradle = gradleVersionAndSettings()
val sigstore = sigstoreJavaVersions()
return gradle.flatMap { gradleVersion ->
sigstore.map { TestedGradleAndSigstoreJava(gradleVersion, it) }
}
}
}
@TempDir(cleanup = CleanupMode.ON_SUCCESS)
protected lateinit var projectDir: Path
fun Path.write(text: String) = this.toFile().writeText(text)
fun Path.read(): String = this.toFile().readText()
fun writeBuildGradle(@Language("Groovy") text: String) = projectDir.resolve("build.gradle").write(text)
fun writeSettingsGradle(@Language("Groovy") text: String) = projectDir.resolve("settings.gradle").write(text)
protected fun String.normalizeEol() = replace(Regex("[\r\n]+"), "\n")
protected fun declareRepositories(sigstoreJava: TestedSigstoreJava) =
"""
repositories {${
if (sigstoreJava is TestedSigstoreJava.Version) {
""
} else {
// We assume that the plugin defaults to the same version of the library, so we test both
// Default and LocallyBuiltVersion from locally staged repo
EXTRA_LOCAL_REPOS.joinToString("\n") {
"""
maven {
url = uri("${
File(it).toURI().toASCIIString().replace(Regex("""[\\"$]""")) { "\\" + it.value }
}")
}
""".trimIndent().prependIndent(" ")
}
}
}
mavenCentral()
}
""".trimIndent()
protected fun declareDependency(sigstoreJava: TestedSigstoreJava) =
"""
dependencies {
${
when (sigstoreJava) {
TestedSigstoreJava.Default -> ""
is TestedSigstoreJava.Version ->
"sigstoreClient(\"dev.sigstore:sigstore-java:${sigstoreJava.version}\")"
is TestedSigstoreJava.LocallyBuiltVersion ->
"sigstoreClient(\"dev.sigstore:sigstore-java:${sigstoreJava.version}\")"
}
}
}
""".trimIndent()
protected fun declareRepositoryAndDependency(sigstoreJava: TestedSigstoreJava) =
"""
${declareRepositories(sigstoreJava)}
${declareDependency(sigstoreJava)}
""".trimIndent()
protected fun createSettings(extra: String = "") {
projectDir.resolve("settings.gradle").write(
"""
rootProject.name = 'sample'
$extra
"""
)
}
protected fun prepare(gradleVersion: GradleVersion, vararg arguments: String) =
gradleRunner
.withGradleVersion(gradleVersion.version)
.withProjectDir(projectDir.toFile())
.apply {
this as DefaultGradleRunner
// See https://github.com/gradle/gradle/issues/10527
// Gradle does not provide API to configure heap size for testkit-based Gradle executions,
// so we resort to org.gradle.testkit.runner.internal.DefaultGradleRunner
System.getProperty("sigstore-java.test.org.gradle.jvmargs")?.let { jvmArgs ->
withJvmArguments(
jvmArgs.split(Regex("\\s+"))
.map { it.trim() }
.filter { it.isNotBlank() }
)
}
}
.withArguments(*arguments)
.forwardOutput()
protected fun enableConfigurationCache(
gradle: TestedGradle,
) {
if (gradle.configurationCache != ConfigurationCache.ON) {
return
}
// Gradle 6.5 expects values ON, OFF, WARN, so we add the option for 7.0 only
projectDir.resolve("gradle.properties").toFile().appendText(
"""
org.gradle.unsafe.configuration-cache=true
org.gradle.unsafe.configuration-cache-problems=fail
""".trimIndent()
)
}
protected fun assertSoftly(body: SoftAssertions.() -> Unit) =
SoftAssertions.assertSoftly(body)
protected fun <SELF : AbstractCharSequenceAssert<SELF, ACTUAL>, ACTUAL : CharSequence> AbstractCharSequenceAssert<SELF, ACTUAL>.basicSigstoreStructure() =
contains(
""""mediaType": "application/vnd.dev.sigstore.bundle+json;version\u003d0.2"""",
""""algorithm": "SHA2_256"""",
)
}
| 32 | null | 21 | 40 | cc82dd21b8bbb32624790efa0d169f093b348ef8 | 8,080 | sigstore-java | Apache License 2.0 |
support-ui/src/main/kotlin/co/anitrend/arch/ui/pager/SupportPageAdapter.kt | fossabot | 223,555,788 | true | {"Gradle": 14, "Java Properties": 3, "Markdown": 7, "YAML": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Proguard": 10, "Kotlin": 158, "XML": 78, "INI": 6, "JSON": 8, "Java": 1} | package co.anitrend.arch.ui.pager
import android.os.Bundle
import androidx.annotation.ArrayRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentStatePagerAdapter
import co.anitrend.arch.extension.empty
import co.anitrend.arch.extension.getStringList
import timber.log.Timber
import java.util.*
/**
* Constructor for {@link FragmentStatePagerAdapter}.
*
* If [FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT] is passed in, then only the current
* Fragment is in the [androidx.lifecycle.Lifecycle.State.RESUMED] state, while all other fragments are
* capped at [androidx.lifecycle.Lifecycle.State.STARTED].
*
* If [FragmentStatePagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT] is used, then all fragments are in the
* [androidx.lifecycle.Lifecycle.State.RESUMED] state and there will be callbacks to
* [androidx.fragment.app.Fragment.setUserVisibleHint].
*
* @param context fragment activity used to create fragment manager that will interact with this adapter
* @param defaultBehavior defaulted to [FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT]
*
* @since v0.9.X
*/
abstract class SupportPageAdapter(
protected val context: FragmentActivity,
defaultBehavior: Int = BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
): FragmentStatePagerAdapter(context.supportFragmentManager, defaultBehavior) {
val titles = ArrayList<String>()
val bundle = Bundle()
/**
* Sets the given array resources as standard strings titles
*
* @param titleRes array resource of which titles to use
*/
fun setPagerTitles(@ArrayRes titleRes: Int) {
if (titles.isNotEmpty())
titles.clear()
titles.addAll(context.getStringList(titleRes))
}
/**
* Return the number of views available.
*/
override fun getCount() = titles.size
/**
* Return the Fragment associated with a specified position.
*
* @param position
*/
abstract override fun getItem(position: Int): Fragment
/**
* This method may be called by the ViewPager to obtain a title string
* to describe the specified page. This method may return null
* indicating no title for this page. The default implementation returns
* null.
*
* @param position The position of the title requested
* @return A title for the requested page
*/
override fun getPageTitle(position: Int): CharSequence {
if (position <= titles.size)
return titles[position].toUpperCase(Locale.getDefault())
Timber.tag(TAG).w("Page title at position: $position doesn't have a corresponding title, returning empty string")
return String.empty()
}
companion object {
protected val TAG = SupportPageAdapter::class.java.simpleName
}
} | 0 | Kotlin | 0 | 0 | 50be1a136fc46fb0eaccc041ef40eca2f4c67771 | 2,858 | support-arch | Apache License 2.0 |
src/main/kotlin/com/wynnlab/listeners/ProjectileHitListener.kt | a7m444d | 357,584,316 | true | {"Kotlin": 113646, "Python": 43284} | package com.wynnlab.listeners
import org.bukkit.entity.Arrow
import org.bukkit.entity.Mob
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.ProjectileHitEvent
class ProjectileHitListener : Listener {
@EventHandler(priority = EventPriority.HIGHEST)
fun onProjectileHit(e: ProjectileHitEvent) {
val proj = e.entity
if (proj.shooter !is Player)
return
for (tag in proj.scoreboardTags) {
tags[tag]?.let {
if (e.hitEntity is Mob) (e.hitEntity as Mob).noDamageTicks = 0
if (proj is Arrow) proj.damage = 0.0
it(e)
}
}
}
val tags = hashMapOf<String, (ProjectileHitEvent) -> Unit>()
} | 0 | null | 0 | 0 | 1b71eb9e5c9664e7873a4422891425e569ea8981 | 832 | WynnLab | MIT License |
app/src/main/java/com/krossovochkin/fiberyunofficial/di/entitytypelist/EntityTypeListDomainModule.kt | krossovochkin | 221,648,261 | false | {"Kotlin": 493412, "Python": 2433, "Shell": 369} | /*
Copyright 2020 <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.krossovochkin.fiberyunofficial.di.entitytypelist
import com.krossovochkin.fiberyunofficial.entitytypelist.domain.EntityTypeListRepository
import com.krossovochkin.fiberyunofficial.entitytypelist.domain.GetEntityTypeListInteractor
import com.krossovochkin.fiberyunofficial.entitytypelist.domain.GetEntityTypeListInteractorImpl
import dagger.Module
import dagger.Provides
@Module
object EntityTypeListDomainModule {
@JvmStatic
@Provides
fun getEntityTypeListInteractor(
entityTypeListRepository: EntityTypeListRepository
): GetEntityTypeListInteractor {
return GetEntityTypeListInteractorImpl(
entityTypeListRepository
)
}
}
| 0 | Kotlin | 0 | 15 | 3568c445d83bdf332f1c6b96d9c137440c01cc25 | 1,279 | FiberyUnofficial | Apache License 2.0 |
src/main/kotlin/icu/windea/pls/core/ParadoxPreloadActivity.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.core
import com.intellij.openapi.application.*
import com.intellij.openapi.progress.*
import icu.windea.pls.*
/**
* IDE启动时执行。
*/
class ParadoxPreloadActivity : PreloadingActivity() {
override fun preload(indicator: ProgressIndicator) {
setInternalSettings()
}
private fun setInternalSettings() {
val internalSettings = getInternalSettings()
PlsProperties.debug.getBooleanProperty()?.let { internalSettings.debug = it }
PlsProperties.annotateUnresolvedKeyExpression.getBooleanProperty()?.let { internalSettings.annotateUnresolvedKeyExpression = it }
PlsProperties.annotateUnresolvedValueExpression.getBooleanProperty()?.let { internalSettings.annotateUnresolvedValueExpression = it }
}
private fun String.getBooleanProperty(): Boolean? {
return System.getProperty(this)?.toBoolean()
}
} | 1 | Kotlin | 1 | 7 | 037b9b4ba467ed49ea221b99efb0a26cd630bb67 | 834 | Paradox-Language-Support | MIT License |
app/src/main/java/com/example/nike/data/EmptyState.kt | SamTech0101 | 734,533,979 | false | {"Kotlin": 92515, "Java": 22121} | package com.example.nike.data
import androidx.annotation.StringRes
data class EmptyState(var mustShow:Boolean,@StringRes var messageResId: Int=0,var showActionButton:Boolean=false)
| 0 | Kotlin | 0 | 0 | b9bc7173d7ee92fa898f77a65dd2b2e3d2db545c | 183 | NikeSample | Apache License 2.0 |
croppylib/src/main/java/com/pearldrift/croppylib/main/StorageType.kt | pearldrift | 514,903,641 | false | null | package com.pearldrift.croppylib.main
enum class StorageType {
CACHE, EXTERNAL
} | 0 | Kotlin | 0 | 0 | 0fd6a5bda6fd3b60b6da05cb1d42010433210667 | 85 | image-croppy-kotlin-library | Apache License 2.0 |
src/main/kotlin/com/imma/persist/core/Where.kt | Indexical-Metrics-Measure-Advisory | 344,732,013 | false | {"XML": 2, "Gradle Kotlin DSL": 2, "INI": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 175, "Java": 3} | package com.imma.persist.core
import com.imma.persist.core.build.JointBuilder
@Suppress("EnumEntryName")
enum class JointType {
and, or
}
interface Condition
@Suppress("EnumEntryName")
enum class ExpressionOperator {
empty,
`not-empty`,
equals,
`not-equals`,
less,
`less-equals`,
more,
`more-equals`,
`in`,
`not-in`,
`has-text`,
`has-one`;
}
class Expression : Condition {
var left: Element? = null
var operator: ExpressionOperator? = null
var right: Element? = null
override fun toString(): String {
return "Expression(left=$left, operator=$operator, right=$right)"
}
}
abstract class Joint(val type: JointType) : Condition {
val parts: MutableList<Condition> = mutableListOf()
override fun toString(): String {
return "Joint(type=$type, parts=$parts)"
}
}
class And : Joint(JointType.and)
class Or : Joint(JointType.or)
fun where(block: JointBuilder.() -> Unit): Joint {
return where(JointType.and, block)
}
fun where(type: JointType, block: JointBuilder.() -> Unit): Joint {
val joint = if (type === JointType.and) And() else Or()
val builder = JointBuilder(joint)
builder.block()
return joint
}
typealias Where = Joint
| 0 | Kotlin | 0 | 1 | c42a959826e72ac8cea7a8390ccc7825f047a591 | 1,163 | watchmen-ktor | MIT License |
wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/FoundationDemos.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.integration.demos
import androidx.wear.compose.foundation.samples.CurvedAndNormalText
import androidx.wear.compose.foundation.samples.CurvedBottomLayout
import androidx.wear.compose.foundation.samples.CurvedBackground
import androidx.wear.compose.foundation.samples.CurvedFixedSize
import androidx.wear.compose.foundation.samples.CurvedFontWeight
import androidx.wear.compose.foundation.samples.CurvedFonts
import androidx.wear.compose.foundation.samples.CurvedRowAndColumn
import androidx.wear.compose.foundation.samples.CurvedWeight
import androidx.wear.compose.foundation.samples.ExpandableTextSample
import androidx.wear.compose.foundation.samples.ExpandableWithItemsSample
import androidx.wear.compose.foundation.samples.HierarchicalFocusCoordinatorSample
import androidx.wear.compose.foundation.samples.OversizeComposable
import androidx.wear.compose.foundation.samples.ScalingLazyColumnEdgeAnchoredAndAnimatedScrollTo
import androidx.wear.compose.foundation.samples.SimpleCurvedWorld
import androidx.wear.compose.foundation.samples.SimpleScalingLazyColumn
import androidx.wear.compose.foundation.samples.SimpleScalingLazyColumnWithContentPadding
import androidx.wear.compose.foundation.samples.SimpleScalingLazyColumnWithSnap
val WearFoundationDemos = DemoCategory(
"Foundation",
listOf(
DemoCategory(
"Expandables",
listOf(
ComposableDemo("Items in SLC") { ExpandableListItems() },
ComposableDemo("Expandable Text") { ExpandableText() },
ComposableDemo("Items Sample") { ExpandableWithItemsSample() },
ComposableDemo("Text Sample") { ExpandableTextSample() },
)
),
DemoCategory("CurvedLayout", listOf(
ComposableDemo("Curved Row") { CurvedWorldDemo() },
ComposableDemo("Curved Row and Column") { CurvedRowAndColumn() },
ComposableDemo("Curved Box") { CurvedBoxDemo() },
ComposableDemo("Simple") { SimpleCurvedWorld() },
ComposableDemo("Alignment") { CurvedRowAlignmentDemo() },
ComposableDemo("Curved Text") { BasicCurvedTextDemo() },
ComposableDemo("Curved and Normal Text") { CurvedAndNormalText() },
ComposableDemo("Fixed size") { CurvedFixedSize() },
ComposableDemo("Oversize composable") { OversizeComposable() },
ComposableDemo("Weights") { CurvedWeight() },
ComposableDemo("Ellipsis Demo") { CurvedEllipsis() },
ComposableDemo("Bottom layout") { CurvedBottomLayout() },
ComposableDemo("Curved layout direction") { CurvedLayoutDirection() },
ComposableDemo("Background") { CurvedBackground() },
ComposableDemo("Font Weight") { CurvedFontWeight() },
ComposableDemo("Fonts") { CurvedFonts() },
)),
ComposableDemo("Scrollable Column") { ScrollableColumnDemo() },
ComposableDemo("Scrollable Row") { ScrollableRowDemo() },
DemoCategory("Rotary Input", RotaryInputDemos),
ComposableDemo("Focus Sample") { HierarchicalFocusCoordinatorSample() },
DemoCategory("Scaling Lazy Column", listOf(
ComposableDemo(
"Defaults",
"Basic ScalingLazyColumn using default values"
) {
SimpleScalingLazyColumn()
},
ComposableDemo(
"With Content Padding",
"Basic ScalingLazyColumn with autoCentering disabled and explicit " +
"content padding of top = 20.dp, bottom = 20.dp"
) {
SimpleScalingLazyColumnWithContentPadding()
},
ComposableDemo(
"With Snap",
"Basic ScalingLazyColumn, center aligned with snap enabled"
) {
SimpleScalingLazyColumnWithSnap()
},
ComposableDemo(
"Edge Anchor",
"A ScalingLazyColumn with Edge (rather than center) item anchoring. " +
"If you click on an item there will be an animated scroll of the " +
"items edge to the center"
) {
ScalingLazyColumnEdgeAnchoredAndAnimatedScrollTo()
},
)
)
),
)
| 23 | null | 784 | 4,535 | ee02274ddff8d63df7435f944214d86fe5a60341 | 5,060 | androidx | Apache License 2.0 |
android/src/main/kotlin/com/linkdesk/flutter_beacon_plugin/events/BluetoothStateBroadcaster.kt | LinkDesk | 283,986,042 | true | {"Dart": 17527, "Kotlin": 16939, "Ruby": 4235, "Swift": 936, "Objective-C": 762} | package com.linkdesk.flutter_beacon_plugin.events
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import io.flutter.plugin.common.EventChannel
class BluetoothStateBroadcaster constructor(private val context: Context): EventChannel.StreamHandler, BroadcastReceiver() {
init {
Log.i("DAS", "ATTACH")
}
private var sink: EventChannel.EventSink? = null
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
context.registerReceiver(this, filter)
sink = events
}
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR)
val result = when (state) {
BluetoothAdapter.STATE_OFF -> "STATE_OFF"
BluetoothAdapter.STATE_TURNING_OFF -> "STATE_TURNING_OFF"
BluetoothAdapter.STATE_ON -> "STATE_ON"
BluetoothAdapter.STATE_TURNING_ON -> "STATE_TURNING_ON"
else -> return sink?.error("INVALID_STATE_RECEIVED", "Received unknown bluetooth state", state) ?: Unit
}
sink?.success(result)
}
}
override fun onCancel(arguments: Any?) {
context.unregisterReceiver(this)
}
}
| 0 | Dart | 0 | 0 | 468925121de3fdd00ad6f24bec119541c1288ca5 | 1,614 | simple_beacons_flutter | Apache License 2.0 |
carp.common/src/commonTest/kotlin/dk/cachet/carp/common/infrastructure/versioning/ApiJsonObjectMigrationBuilderTest.kt | cph-cachet | 116,270,288 | false | {"Kotlin": 1365001, "TypeScript": 46605} | package dk.cachet.carp.common.infrastructure.versioning
import dk.cachet.carp.common.infrastructure.serialization.createDefaultJSON
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.test.*
/**
* Tests for [ApiJsonObjectMigrationBuilder].
*/
class ApiJsonObjectMigrationBuilderTest
{
interface ToMigrate
@Serializable
@SerialName( "Migrate" )
class Migrate( val a: Int, val b: Int, val inner: MigrateInner ) : ToMigrate
@Serializable
class MigrateInner( val c: Int )
private val toMigrateSerializer = PolymorphicSerializer( ToMigrate::class )
private val json = createDefaultJSON(
SerializersModule {
polymorphic( ToMigrate::class )
{
subclass( Migrate::class )
}
}
)
@Test
fun ifType_succeeds()
{
val toMigrate: ToMigrate = Migrate( 42, 42, MigrateInner( 42 ) )
val toMigrateJson: JsonObject = json.encodeToJsonElement( toMigrateSerializer, toMigrate ).jsonObject
val toSet = JsonPrimitive( 0 )
val migrated = migrate( toMigrateJson ) {
ifType( "Migrate" ) {
json[ Migrate::a.name ] = toSet
}
ifType( "NoMatch" ) {
json[ Migrate::b.name ] = toSet
}
}
assertEquals( toSet, migrated[ Migrate::a.name ] )
assertNotEquals( toSet, migrated[ Migrate::b.name ] )
}
@Test
fun changeType_succeeds()
{
val toMigrate: ToMigrate = Migrate( 42, 42, MigrateInner( 42 ) )
val toMigrateJson: JsonObject = json.encodeToJsonElement( toMigrateSerializer, toMigrate ).jsonObject
val newTypeName = "Migrated"
val migrated = migrate( toMigrateJson ) {
changeType( newTypeName )
}
assertEquals( newTypeName, migrated[ "__type" ]?.jsonPrimitive?.content )
}
@Test
fun updateObject_succeeds()
{
val toMigrate = Migrate( 42, 42, MigrateInner( 42 ) )
val toMigrateJson = json.encodeToJsonElement( toMigrateSerializer, toMigrate ).jsonObject
val toSet = JsonPrimitive( 0 )
val migrated = migrate( toMigrateJson ) {
updateObject( Migrate::inner.name ) {
json[ MigrateInner::c.name ] = toSet
}
}
val inner = assertNotNull( migrated[ Migrate::inner.name ]?.jsonObject )
assertEquals( toSet, inner[ MigrateInner::c.name ] )
}
@Test
fun updateArray_succeeds()
{
val jsonArray = JsonArray( listOf( JsonPrimitive( 42 ) ) )
val arrayField = "array"
val jsonObject = JsonObject( mapOf( arrayField to jsonArray ) )
val migrated = migrate( jsonObject ) {
updateArray( arrayField ) { json.clear() }
}
val emptyArrayField = JsonObject( mapOf( arrayField to JsonArray( emptyList() ) ) )
assertEquals( emptyArrayField, migrated )
}
@Test
fun copyField_succeeds()
{
val toMigrate = Migrate( 42, 0, MigrateInner( 0 ) )
val toMigrateJson = json.encodeToJsonElement( toMigrateSerializer, toMigrate ).jsonObject
val migrated = migrate( toMigrateJson ) {
copyField( "a", "b" )
}
assertEquals( migrated[ Migrate::a.name ], migrated[ Migrate::b.name ] )
}
private fun migrate( json: JsonObject, migration: ApiJsonObjectMigrationBuilder.() -> Unit ): JsonObject =
ApiJsonObjectMigrationBuilder( json, 0, 1 ).apply( migration ).build()
}
| 93 | Kotlin | 3 | 21 | 7b6fa58bc97ab0c244b81897bc837def3b0d7daf | 3,589 | carp.core-kotlin | MIT License |
model/src/main/java/org/ligi/kithub/model/GithubBranchCommit.kt | komputing | 92,964,439 | false | {"Kotlin": 12622} | package org.ligi.kithub.model
data class GithubBranchCommit(val sha: String,
val url: String) | 6 | Kotlin | 2 | 6 | 64b29affbe1d3aadde5747e3ad39f6fc90518083 | 124 | Kithub | MIT License |
plugins/devkit/devkit-kotlin-tests/testData/inspections/statefulEp/Ext.kt | ingokegel | 72,937,917 | true | null | import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
class Ext {
val <warning descr="Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead">pe</warning>: PsiElement?
val <warning descr="Do not use PsiReference as a field in extension">r</warning>: PsiReference?
var <warning descr="Do not use Project as a field in extension">p</warning>: Project?
val pf: Project?
init {
pe = null
r = null
pf = null
p = pf
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 532 | intellij-community | Apache License 2.0 |
android/app/src/main/kotlin/com/example/forest_map/MainActivity.kt | Bioverse-Labs | 572,666,977 | false | {"Dart": 1131078, "JavaScript": 2291, "Ruby": 1355, "Java": 736, "Swift": 404, "Shell": 171, "Kotlin": 131, "Objective-C": 38} | package com.bioverselabs.forestmap
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | Dart | 1 | 2 | 4ae494bf980711f811b94600e769de8582e52505 | 131 | forest-map-app | MIT License |
src/main/kotlin/com/jetbrains/licensedetector/intellij/plugin/model/ProjectModule.kt | LOVECHEN | 364,047,288 | true | {"Kotlin": 594186, "Java": 4072} | package com.jetbrains.licensedetector.intellij.plugin.model
import com.intellij.openapi.module.Module
data class ProjectModule(
val name: String,
val nativeModule: Module,
val path: String
) | 0 | null | 0 | 0 | 9e6b7b21c9793fe1092c41ec356911d9e4351c50 | 204 | license-detector-plugin | Apache License 2.0 |
core/datastore/src/main/java/com/z1/core/datastore/repository/UserPreferencesRepository.kt | zero1code | 748,829,698 | false | {"Kotlin": 441569} | package com.z1.core.datastore.repository
import com.z1.comparaprecos.core.model.UserData
import kotlinx.coroutines.flow.Flow
interface UserPreferencesRepository {
val userData: Flow<UserData>
val listOfProdutoOrdenation: Flow<Long>
suspend fun putSelectedTheme(themeId: Long)
suspend fun putUseDynamicColor(useDynamicColor: Long)
suspend fun putDarkThemeMode(darkThemeMode: Long)
suspend fun putListOfProdutoOrdenation(ordenationId: Long)
suspend fun putOnboarded(onboarded: Boolean)
} | 0 | Kotlin | 0 | 0 | 2ada1d386ea6e42b37a6c86b145d3c35883d3856 | 516 | Compara-precos | Apache License 2.0 |
barcodeapp/src/main/java/de/alexander13oster/barcodeapp/MainActivity.kt | Alexander13Oster | 654,281,442 | false | {"Kotlin": 25215, "C++": 2722} | package de.alexander13oster.barcodeapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import de.alexander13oster.shared.model.Barcode
import de.alexander13oster.barcodeapp.ui.theme.QuantificatorTheme
import io.ktor.http.*
import io.ktor.serialization.gson.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.Inet4Address
import java.net.NetworkInterface
class MainActivity : ComponentActivity() {
private val _currentBarcode = MutableLiveData<Barcode?>(null)
private val currentBarcode: LiveData<Barcode?> = _currentBarcode
private val barcodeServer by lazy {
embeddedServer(factory = Netty, port = PORT, watchPaths = emptyList()) {
install(ContentNegotiation) {
gson {
setPrettyPrinting()
}
}
routing {
post(path = "barcode") {
val barcode = call.receive<Barcode>()
_currentBarcode.postValue(barcode)
call.respond(HttpStatusCode.OK)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
CoroutineScope(Dispatchers.IO).launch {
barcodeServer.start(wait = true)
}
setContent {
QuantificatorTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
val barcode: Barcode? by currentBarcode.observeAsState(initial = null)
if (barcode == null) Text("IP of the Server is ${getIpAddress()}")
barcode?.let {
BarcodeScreen(data = it.data, format = it.format)
}
}
}
}
}
override fun onDestroy() {
barcodeServer.stop(gracePeriodMillis = 1000, timeoutMillis = 2000)
super.onDestroy()
}
private fun getIpAddress() =
NetworkInterface.getNetworkInterfaces()
.asSequence()
.flatMap { networkInterface ->
networkInterface.inetAddresses
.asSequence()
.filter {
it.isLoopbackAddress.not() && it is Inet4Address
}
.map {
it.hostAddress
}
}.toList()
companion object {
private const val PORT = 8080
}
} | 0 | Kotlin | 0 | 1 | 6519196127c59331bd797183a739d681ebcdd9fc | 3,303 | CameraQuantificator | Creative Commons Attribution 4.0 International |
domain/src/main/java/com/jyproject/domain/features/cycle/GetCycleInfoUseCase.kt | JunYeong0314 | 778,833,940 | false | {"Kotlin": 158676} | package com.jyproject.domain.features.cycle
import javax.inject.Inject
class GetCycleInfoUseCase @Inject constructor(
private val cycleRepository: CycleRepository
) {
suspend operator fun invoke(
regionName: String
) = cycleRepository.getCycleInfo(regionName = regionName)
} | 0 | Kotlin | 0 | 0 | 2341a329320565d60cfae95a92fb5b5d49a7f42f | 296 | PlacePick | MIT License |
src/main/kotlin/jetbrains/buildServer/notification/slackNotifier/teamcity/ProjectManagerExtension.kt | JetBrains | 294,444,752 | false | {"Kotlin": 247902, "Java": 39261} |
package jetbrains.buildServer.notification.slackNotifier.teamcity
import jetbrains.buildServer.serverSide.BuildTypeSettings
import jetbrains.buildServer.serverSide.ProjectManager
fun ProjectManager.findBuildTypeSettingsByExternalId(buildTypeId: String): BuildTypeSettings? {
return when {
buildTypeId.startsWith("buildType:") -> {
findBuildTypeByExternalId(buildTypeId.substring("buildType:".length))
}
buildTypeId.startsWith("template:") -> {
findBuildTypeTemplateByExternalId(buildTypeId.substring("template:".length))
}
else -> null
}
} | 2 | Kotlin | 8 | 7 | 629c1bbae964f7106332439e83dd673ce583d917 | 616 | teamcity-slack-notifier | Apache License 2.0 |
tokenview-api/src/main/kotlin/io/mokuan/tokenview/api/bean/blockchain/btc/BlockHeaderBean.kt | squirrel-explorer | 680,471,556 | false | null | /**
* Bean for BlockHeaderInfo
*
* @copyright Copyright 2022 - 2023, mokuan.io
* @license MIT
*/
package io.mokuan.tokenview.api.bean.blockchain.btc
import com.google.gson.annotations.SerializedName
data class BlockHeaderBean(
val type: String = "",
val network: String = "",
@SerializedName(value = "blockNo", alternate = ["block_no"])
val blockNo: Long = -1,
@SerializedName(value = "blockTime", alternate = ["time"])
val blockTime: Long = -1,
@SerializedName(value = "blockSize", alternate = ["size"])
val blockSize: Int = -1,
@SerializedName(value = "blockHash", alternate = ["blockhash"])
val blockHash: String = "",
@SerializedName(value = "prevBlockHash", alternate = ["previous_blockhash"])
val prevBlockHash: String = "",
@SerializedName(value = "nextBlockHash", alternate = ["next_blockhash"])
val nextBlockHash: String = "",
val fee: String = "",
val reward: String = "",
val confirmations: Int = -1,
val miner: String = "",
val minerAlias: String = "",
@SerializedName(value = "miningDifficulty", alternate = ["mining_difficulty"])
val miningDifficulty: String = "",
@SerializedName(value = "merkleRoot", alternate = ["merkleroot"])
val merkleRoot: String = "",
@SerializedName(value = "sentValue", alternate = ["sent_value"])
val sentValue: String = "",
val txCnt: Int = -1,
val txs: List<BlockTransactionBean> = arrayListOf(),
) | 0 | Kotlin | 0 | 0 | 87f2e0f91b5ee3b82a893fa5660948fc6105de20 | 1,472 | tokenview-kotlin-api | MIT License |
src/main/kotlin/com.highthunder.kotlr/request/IncompleteRequestException.kt | Emamatcyber90 | 189,778,198 | true | {"Kotlin": 500099} | package com.highthunder.kotlr.request
import java.lang.Exception
/**
* IncompleteRequestException - TODO: Documentation
*
* @author highthunder
* @since 10/27/18
* @version 1.0.0
*/
class IncompleteRequestException : Exception {
constructor(message: String) : super(message)
constructor(cause: Throwable) : super(cause)
constructor(message: String, cause: Throwable) : super(message, cause)
}
| 0 | Kotlin | 0 | 0 | 5d7a671ac9fe68f061a52d19bf0ff7ef8e3dc7c8 | 413 | kotlr | MIT License |
packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/types/model/FlutterModelSchema.kt | aws-amplify | 253,571,453 | false | {"Dart": 7555050, "Kotlin": 376817, "Swift": 176193, "TypeScript": 116868, "Shell": 70670, "C++": 25950, "HTML": 24848, "CMake": 24438, "Objective-C": 19618, "Java": 18553, "Smithy": 18287, "Ruby": 12226, "JavaScript": 5524, "C": 3391, "Makefile": 2535, "CSS": 2472, "Dockerfile": 1550} | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.amplify.amplify_datastore.types.model
import com.amazonaws.amplify.amplify_datastore.util.cast
import com.amplifyframework.core.model.Model
import com.amplifyframework.core.model.ModelIndex
import com.amplifyframework.core.model.ModelSchema
import com.amplifyframework.core.model.SerializedModel
data class FlutterModelSchema(val map: Map<String, Any>) {
val name: String = map["name"] as String
private val pluralName: String? = map["pluralName"] as String?
private val authRules: List<FlutterAuthRule> = when (val rawAuthRules = map["authRules"]) {
is List<*> -> (rawAuthRules.cast<Map<String, Any>>()).map { FlutterAuthRule(it) }
else -> emptyList()
}
private val fields: Map<String, FlutterModelField> = when (val rawFields = map["fields"]) {
is Map<*, *> -> (rawFields.cast<String, Map<String, Any>>()).mapValues { FlutterModelField(it.value) }
else -> emptyMap()
}
private val associations: Map<String, FlutterModelAssociation> =
fields.filterKeys { key -> fields[key]?.getModelAssociation() != null }
.mapValues { it.value.getModelAssociation()!! }
// In amplify-android, primaryKey and indexes are categories as ModelIndex
private val indexes: Map<String, ModelIndex> = run {
val parsedIndexes = emptyMap<String, ModelIndex>().toMutableMap()
val rawIndexes = map["indexes"]
if (rawIndexes is List<*>) {
parsedIndexes.putAll(
(rawIndexes.cast<Map<String, Any>>()).associate {
(
it["name"] as String?
?: FlutterModelIndex.unnamedIndexKey
) to FlutterModelIndex(it).convertToNativeModelIndex()
}.toMap()
)
}
parsedIndexes
}
fun convertToNativeModelSchema(): ModelSchema {
return ModelSchema.builder()
.name(name)
.pluralName(pluralName)
.fields(fields.mapValues { it.value.convertToNativeModelField() })
.indexes(indexes)
.authRules(authRules.map { it.convertToNativeAuthRule() })
.associations(associations.mapValues { it.value.convertToNativeModelAssociation() })
.modelClass(SerializedModel::class.java)
.modelType(Model.Type.USER)
// to allow amplify-android correctly interpret custom primary key
// schema version needs to be >= 1
.version(1)
.build()
}
}
| 273 | Dart | 235 | 1,285 | f4faad6fd46f4f36531467b98a509d4373a91783 | 2,649 | amplify-flutter | Apache License 2.0 |
post-processing-tests/src/test/kotlin/com/casadetasha/kexp/sproute/processor/post/routes/BoringRequestRoutesTest.kt | Path-to-plunder | 427,878,747 | false | null | package com.casadetasha.kexp.sproute.processor.post.routes
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.casadetasha.kexp.sproute.processor.post.configuredTestApplication
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlin.test.Test
class BoringRequestRoutesTest {
@Test
fun `routes through with GET`() = configuredTestApplication {
val response = client.get("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring GET.")
}
@Test
fun `routes through with POST`() = configuredTestApplication {
val response = client.post("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring POST.")
}
@Test
fun `routes through with PUT`() = configuredTestApplication {
val response = client.put("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring PUT.")
}
@Test
fun `routes through with PATCH`() = configuredTestApplication {
val response = client.patch("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring PATCH.")
}
@Test
fun `routes through with DELETE`() = configuredTestApplication {
val response = client.delete("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring DELETE.")
}
@Test
fun `routes through with HEAD`() = configuredTestApplication {
val response = client.head("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring HEAD.")
}
@Test
fun `routes through with OPTIONS`() = configuredTestApplication {
val response = client.options("/boring_request_routes")
assertThat(response.bodyAsText()).isEqualTo("Boring OPTIONS.")
}
} | 0 | Kotlin | 0 | 1 | 3e75b3b053aac64c508568900f38b018b54b5e9e | 1,825 | Sproutes | Apache License 2.0 |
app/src/main/java/com/steleot/jetpackcompose/playground/PlaygroundApplication.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground
import android.app.Application
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.firebase.messaging.FirebaseMessaging
import com.steleot.jetpackcompose.playground.appwidget.PlaygroundGlanceAppWidgetReceiver
import com.steleot.jetpackcompose.playground.datastore.ProtoManager
import com.steleot.jetpackcompose.playground.helpers.InAppReviewHelper
import com.steleot.jetpackcompose.playground.utils.handleEnableSubscription
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
@HiltAndroidApp
class PlaygroundApplication : Application() {
private val scope = CoroutineScope(Dispatchers.Main)
@Inject
lateinit var inAppReviewHelper: InAppReviewHelper
@Inject
lateinit var firebaseAnalytics: FirebaseAnalytics
@Inject
lateinit var firebaseMessaging: FirebaseMessaging
@Inject
lateinit var firebaseCrashlytics: FirebaseCrashlytics
@Inject
lateinit var protoManager: ProtoManager
override fun onCreate() {
super.onCreate()
inAppReviewHelper.resetCounter()
scope.launch {
protoManager.isAnalyticsEnabled.collect { isEnabled ->
Timber.d("Analytics collection: $isEnabled")
firebaseAnalytics.setAnalyticsCollectionEnabled(isEnabled)
}
}
scope.launch {
protoManager.isMessagingEnabled.collect { isEnabled ->
Timber.d("Messaging: $isEnabled")
firebaseMessaging.handleEnableSubscription(isEnabled)
}
}
scope.launch {
protoManager.isCrashlyticsEnabled.collect { isEnabled ->
Timber.d("Crashlytics collection: $isEnabled")
firebaseCrashlytics.setCrashlyticsCollectionEnabled(isEnabled)
}
}
updateWidgets()
}
private fun updateWidgets() {
val intent = Intent(this, PlaygroundGlanceAppWidgetReceiver::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids: IntArray = AppWidgetManager.getInstance(this)
.getAppWidgetIds(ComponentName(this, PlaygroundGlanceAppWidgetReceiver::class.java))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(intent)
}
} | 1 | null | 46 | 346 | 0161d9c7bf2eee53270ba2227a61d71ba8292ad0 | 2,630 | Jetpack-Compose-Playground | Apache License 2.0 |
squery/src/androidTest/java/com/kishe/sizuha/kotlin/squery/DatabaseTest.kt | Sizuha | 155,130,786 | false | null | package com.kishe.sizuha.kotlin.squery
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import android.util.Log
import org.junit.runner.RunWith
import org.junit.Assert.*
import org.junit.Test
import java.text.SimpleDateFormat
import java.util.*
class SampleDB(context: Context, dbName: String, version: Int) : SQuery(context, dbName, version) {
override fun onCreate(db: SQLiteDatabase?) {
super.onCreate(db)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
}
}
@Table("user")
class User : ISQueryRow {
companion object {
val tableName = "user"
}
@Column("idx")
@PrimaryKey(autoInc = true)
var idx = 0
private set
@Column("l_name", notNull = true)
var lastName = ""
@Column("f_name", notNull = true)
var firstName = ""
@Column("birth", notNull = true)
@DateType("yyyyMMdd")
var birth: Int = 0
@Column("email")
var email: String? = null
@Column("reg_date", notNull = true)
@DateType
var registerDate: Date = Date()
}
@RunWith(AndroidJUnit4::class)
class DatabaseTest {
private fun getContext() = InstrumentationRegistry.getTargetContext()
private val dateTimeFmt = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
private fun openDB(): SQuery {
Config.enableDebugLog = true
return SampleDB(getContext(), "test-users.db", 1)
}
private fun releaseDB() {
openDB().use {
it.from(User.tableName).drop()
}
}
//-------------- Basic Test
@Test
@Throws(Exception::class)
fun createTableAndBasicTest() {
createTableAndInsert()
val row = findInsertedRow()
update(row)
deleteAll()
releaseDB()
}
@Throws(Exception::class)
private fun createTableAndInsert() {
openDB().use { db ->
db.from<User>().drop()
db.createTable(User())
val result = db.from<User>().insert(User().apply {
lastName = "Numakura"
firstName = "Manami"
birth = 19780415
})
assertTrue(result)
val count = db.from(User.tableName).count()
assertEquals(count, 1)
}
}
@Throws(Exception::class)
private fun findInsertedRow(): User {
openDB().use { db ->
return db.from(User.tableName).selectOne { User() }!!
}
}
@Throws(Exception::class)
private fun update(user: User) {
openDB().use { db ->
val result = db.from(User.tableName)
.update(ContentValues().apply {
put("idx", user.idx)
put("l_name", "沼倉")
put("f_name", "愛美")
put("birth", 19880415)
})
assertEquals(result, 1)
val count = db.from(User.tableName).where("birth=?", 19880415).count()
assertEquals(count, 1)
}
}
@Throws(Exception::class)
private fun deleteAll() {
openDB().use { db ->
db.from(User.tableName).delete()
val count = db.from(User.tableName).count()
assertEquals(count, 0)
}
}
//-------------- INSERT / UPDATE Test
class WrongUser : ISQueryRow {
@Column("idx")
var idx = 0
@Column("l_name")
var lastName = ""
@Column("f_name")
var firstName = ""
}
@Test
@Throws(Exception::class)
fun insertAndUpdateTest() {
openDB().use { db ->
db.from(User.tableName).create(User())
var result = false
//--- INSERT
// row 1
result = db.from(User.tableName).insert(User().apply {
lastName = "Test"
firstName = "User"
birth = 19990101
email = "<EMAIL>"
})
assertTrue(result)
// row 2
result = db.from(User.tableName).insert(User().apply {
lastName = "Test"
firstName = "User"
birth = 19990101
email = "<EMAIL>"
})
assertTrue(result)
// row 3
val regDateText = dateTimeFmt.format(dateTimeFmt.parse("1980-12-31 23:00:00"))
result = db.from(User.tableName).insert(User().apply {
lastName = "Test"
firstName = "User"
birth = 19990101
email = "<EMAIL>"
registerDate = dateTimeFmt.parse("1980-12-31 23:00:00")
})
assertTrue(result)
val rowCount = db.from(User.tableName).count()
// insert fail
result = db.from(User.tableName).insert(WrongUser().apply {
idx = 1
lastName = "ERROR"
firstName = "INSERT"
})
assertFalse(result)
var resCount = db.from(User.tableName).where("l_name=?", "Test").count()
assertEquals(resCount, rowCount)
resCount = db.from(User.tableName).where("reg_date=?", regDateText).count()
assertEquals(resCount, 1)
//--- UPDATE
resCount = db.from(User.tableName)
.where("l_name=?", "Test")
.update(ContentValues().apply {
put("l_name", "TEST")
}).toLong()
assertEquals(resCount, rowCount)
resCount = db.from(User.tableName)
.where("f_name=?", "User")
.update(ContentValues().apply {
put("f_name", "USER")
}).toLong()
assertEquals(resCount, rowCount)
}
releaseDB()
}
@Test
@Throws(Exception::class)
fun havingTest() {
openDB().use { db ->
db.createTable(User())
val sqlStr = db.from<User>()
.groupBy("l_name")
.having("1=1")
.makeQueryString(false, mutableListOf())
assert(sqlStr.equals("SELECT * FROM user GROUP BY `l_name` HAVING 1=1"))
}
releaseDB()
}
} | 0 | Kotlin | 0 | 0 | 1b2f3f23d3f375d0af3ea050a97c65b280a4ef3d | 6,441 | squery-android | The Unlicense |
app/src/main/java/zechs/zplex/utils/Constants.kt | itszechs | 381,082,348 | false | null | package zechs.zplex.utils
import zechs.zplex.BuildConfig
@Suppress("SpellCheckingInspection")
object Constants {
const val TMDB_API_URL = "https://api.themoviedb.org"
const val TMDB_IMAGE_PREFIX = "https://www.themoviedb.org/t/p"
const val TMDB_API_KEY = BuildConfig.TMDB_API_KEY
const val THEMOVIEDB_ID_REGEX = "(movie|tv)/(.*\\d)*"
const val SEARCH_DELAY_AMOUNT = 750L
} | 0 | Kotlin | 0 | 8 | 95cce5c6a0dd32b7e7a5940e87730148706a25ab | 397 | ZPlex | MIT License |
app/src/main/java/com/breezeiksindustries/features/NewQuotation/api/GetQuotListRegRepository.kt | DebashisINT | 863,536,151 | false | {"Kotlin": 15890094, "Java": 1030472} | package com.breezeiksindustries.features.NewQuotation.api
import com.breezeiksindustries.base.BaseResponse
import com.breezeiksindustries.features.NewQuotation.model.AddQuotRequestData
import com.breezeiksindustries.features.NewQuotation.model.EditQuotRequestData
import com.breezeiksindustries.features.NewQuotation.model.ViewDetailsQuotResponse
import com.breezeiksindustries.features.NewQuotation.model.ViewQuotResponse
import io.reactivex.Observable
class GetQuotListRegRepository(val apiService : GetQutoListApi) {
fun addQuot(shop: AddQuotRequestData): Observable<BaseResponse> {
return apiService.getAddQuot(shop)
}
fun viewQuot(shopId: String): Observable<ViewQuotResponse> {
return apiService.getQuotList(shopId)
}
fun viewDetailsQuot(quotId: String): Observable<ViewDetailsQuotResponse> {
return apiService.getQuotDetailsList(quotId)
}
fun viewDetailsDoc(docId: String): Observable<ViewDetailsQuotResponse> {
return apiService.getDocDetailsList(docId)
}
fun delQuot(quotId: String): Observable<BaseResponse>{
return apiService.QuotDel(quotId)
}
fun editQuot(shop: EditQuotRequestData): Observable<BaseResponse> {
return apiService.editQuot(shop)
}
} | 0 | Kotlin | 0 | 0 | 77cc3b80d20adbe55363e1825240b8e2c6a44cf3 | 1,265 | IKSIndustries | Apache License 2.0 |
src/commonMain/kotlin/com/dxc/ssi/agent/api/pluggable/wallet/Prover.kt | dxc-technology | 259,322,339 | false | {"Kotlin": 598967, "Objective-C": 537589, "Objective-C++": 442889, "C": 238203, "Ruby": 12614, "Shell": 7187, "Swift": 1114} | package com.dxc.ssi.agent.api.pluggable.wallet
import com.dxc.ssi.agent.api.pluggable.LedgerConnector
import com.dxc.ssi.agent.didcomm.model.common.RawData
import com.dxc.ssi.agent.didcomm.model.common.Thread
import com.dxc.ssi.agent.didcomm.model.issue.container.CredentialContainer
import com.dxc.ssi.agent.didcomm.model.issue.container.CredentialOfferContainer
import com.dxc.ssi.agent.didcomm.model.issue.data.*
import com.dxc.ssi.agent.didcomm.model.revokation.data.RevocationRegistryDefinition
import com.dxc.ssi.agent.didcomm.model.verify.container.PresentationRequestContainer
import com.dxc.ssi.agent.didcomm.model.verify.data.CredentialInfo
import com.dxc.ssi.agent.didcomm.model.verify.data.Presentation
import com.dxc.ssi.agent.didcomm.model.verify.data.PresentationRequest
import com.dxc.ssi.agent.didcomm.states.issue.CredentialIssuenceState
import com.dxc.ssi.agent.didcomm.states.verify.CredentialVerificationState
import com.dxc.ssi.agent.model.CredentialExchangeRecord
import com.dxc.ssi.agent.model.PresentationExchangeRecord
import com.dxc.ssi.agent.wallet.indy.model.revoke.RevocationState
import com.dxc.ssi.agent.wallet.indy.model.verify.RevocationRegistryEntry
/**
* This entity is able to receive credentials and create proofs about them.
* Has read-only access to public ledger.
*/
interface Prover {
/**
* Creates credential request
*
* @param proverDid [String] - prover's did
* @param credentialDefinition [CredentialDefinition]
* @param offer [CredentialOfferContainer] - credential offer
* @param masterSecretId [String]
*
* @return [CredentialRequestInfo] - credential request and all reliable data
*/
suspend fun createCredentialRequest(
proverDid: String,
credentialDefinition: CredentialDefinition,
credentialOffer: CredentialOffer,
masterSecretId: String
): CredentialRequestInfo
/**
* Stores credential exchange record in a wallet
*
* @param credentialExchangeRecord [CredentialExchangeRecord] - credentialExchangeRecord to store
*/
suspend fun storeCredentialExchangeRecord(credentialExchangeRecord: CredentialExchangeRecord)
/**
* Retrieves [CredentialExchangeRecord] from wallet
*
* @param thread [Thread]
* @return [CredentialExchangeRecord?]
*/
suspend fun getCredentialExchangeRecordByThread(thread: Thread): CredentialExchangeRecord?
/**
* Gets credential definition id from offer data
*
* @param offer [CredentialOfferContainer] - credential offer
*
* @return [CredentialDefinitionId] - id of credential definition
*/
//TODO: temporarily this function in WalletConnector, but logically it is some other layer of abstraction.But for now we consider that wallet is aware about of technology(indy) specifics on how to parse message
fun createCredentialDefinitionIdFromOffer(
credentialOffer: CredentialOffer
): CredentialDefinitionId
/**
* Stores credential in prover's wallet
*
* @param credentialInfo [CredentialInfo] - credential and all reliable data
* @param credentialRequest [CredentialRequestInfo] - credential request and all reliable data
* @param offerContainer [CredentialOfferContainer] - credential offer
* @param credentialDefinition [CredentialDefinition]
* @param revocationRegistryDefinition [RevocationRegistryDefinition] on [null]
*
* @return local UUID of the stored credential in the prover's wallet
*/
//TODO: fix javadoc above
suspend fun receiveCredential(
credential: Credential,
credentialRequestInfo: CredentialRequestInfo,
credentialDefinition: CredentialDefinition,
revocationRegistryDefinition: RevocationRegistryDefinition?
): String
/**
* Creates proof for provided proof request
*
* @param proofRequest [ProofRequest] - proof request created by verifier
* @param extraQuery Map [String] to Map [String] to [Any] - additional WQL query applied to Wallet's credential search
* @param provideSchema [SchemaProvider] - provide schema for each credential
* @param provideCredentialDefinition [CredentialDefinitionProvider] - provide credential definition for each credential
* @param masterSecretId [String]
* @param revocationStateProvider [RevocationStateProvider] or [null] - provide [RevocationState] for each credential
*
* @return [ProofInfo] - proof and all reliable data
*/
/* fun createProof(
proofRequest: ProofRequest,
provideSchema: SchemaProvider,
provideCredentialDefinition: CredentialDefinitionProvider,
masterSecretId: String,
extraQuery: Map<String, Map<String, Any>>?,
revocationStateProvider: RevocationStateProvider?
): ProofInfo
*/
/**
* Creates [RevocationState]
*
* @param revocationRegistryDefinition [RevocationRegistryDefinition]
* @param revocationRegistryEntry [RevocationRegistryEntry]
* @param credentialRevocationId [String]
* @param timestamp [Long]
*
* @return [RevocationState]
*/
suspend fun createRevocationState(
revocationRegistryDefinition: RevocationRegistryDefinition,
revocationRegistryEntry: RevocationRegistryEntry,
credentialRevocationId: String,
timestamp: Long
): RevocationState
/**
* Creates master secret by id
*
* @param id [String]
*/
suspend fun createMasterSecret(id: String)
fun extractCredentialRequestDataFromCredentialInfo(credentialRequestInfo: CredentialRequestInfo): RawData
fun buildCredentialObjectFromRawData(data: RawData): Credential
fun buildCredentialOfferObjectFromRawData(data: RawData): CredentialOffer
suspend fun removeCredentialExchangeRecordByThread(thread: Thread)
fun buildPresentationRequestObjectFromRawData(data: RawData): PresentationRequest
suspend fun createPresentation(
presentationRequest: PresentationRequest,
ledgerConnector: LedgerConnector,
): Presentation
fun extractPresentationDataFromPresentation(presentation: Presentation): RawData
suspend fun getParkedCredentialOffers(): Set<CredentialOfferContainer>
suspend fun findCredentialExchangeRecordsWithState(credentialIssuenceState: CredentialIssuenceState): Set<CredentialExchangeRecord>
suspend fun findPresentationExchangeRecordsWithState(credentialVerificationState: CredentialVerificationState): Set<PresentationExchangeRecord>
suspend fun getCredentialInfos(): Set<CredentialInfo>
suspend fun getCredentialInfo(localWalletCredId: String): CredentialInfo
suspend fun getParkedPresentationRequests(): Set<PresentationRequestContainer>
suspend fun getPresentationExchangeRecordByThread(thread: Thread): PresentationExchangeRecord?
suspend fun storePresentationExchangeRecord(presentationExchangeRecord: PresentationExchangeRecord)
} | 3 | Kotlin | 6 | 5 | 9bede83e0358b16d6dc9459ccc2fd85541027b6c | 7,003 | ssi-mobile-sdk | Apache License 2.0 |
android/src/main/kotlin/com/dooboolab/flutterinapppurchase/MethodResultWrapper.kt | dooboolab-community | 141,916,833 | false | {"Dart": 112087, "Kotlin": 51451, "Objective-C": 36724, "Ruby": 3029, "Java": 554} | package com.dooboolab.flutterinapppurchase
import android.os.Handler
import io.flutter.plugin.common.MethodChannel
import android.os.Looper
// MethodChannel.Result wrapper that responds on the platform thread.
class MethodResultWrapper internal constructor(
private val safeResult: MethodChannel.Result,
private val safeChannel: MethodChannel
) : MethodChannel.Result {
private val handler: Handler = Handler(Looper.getMainLooper())
private var exhausted: Boolean = false
override fun success(result: Any?) {
if (!exhausted) {
exhausted = true
handler.post { safeResult.success(result) }
}
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
if (!exhausted) {
exhausted = true
handler.post { safeResult.error(errorCode, errorMessage, errorDetails) }
}
}
override fun notImplemented() {
if (!exhausted) {
exhausted = true
handler.post { safeResult.notImplemented() }
}
}
fun invokeMethod(method: String?, arguments: Any?) {
handler.post { safeChannel.invokeMethod(method!!, arguments, null) }
}
} | 20 | Dart | 219 | 544 | e01ff816a05922ebb44d1f0fb344fc02f22ffbe5 | 1,213 | flutter_inapp_purchase | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/securityhub/StandardsControlPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.securityhub
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.securityhub.CfnStandard
@Generated
public fun buildStandardsControlProperty(initializer: @AwsCdkDsl
CfnStandard.StandardsControlProperty.Builder.() -> Unit): CfnStandard.StandardsControlProperty =
CfnStandard.StandardsControlProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e08d201715c6bd4914fdc443682badc2ccc74bea | 473 | aws-cdk-kt | Apache License 2.0 |
src/commonMain/kotlin/io/github/edmondantes/serialization/element/factory/structure/builder/AbstractComplexEncodingElementBuilder.kt | Simple-Kotlin-Project | 594,867,591 | false | {"Kotlin": 340720} | /*
* Copyright (c) 2023. <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 io.github.edmondantes.serialization.element.factory.structure.builder
import io.github.edmondantes.serialization.element.AnyEncodedElement
import io.github.edmondantes.serialization.element.ComplexElementBuilder
import io.github.edmondantes.serialization.element.ComplexEncodedElement
import io.github.edmondantes.serialization.element.DefaultEncodedElement
import io.github.edmondantes.serialization.element.EncodedElement
import io.github.edmondantes.serialization.element.EncodedElementType
import io.github.edmondantes.serialization.element.factory.simple.DefaultSimpleEncodedElementFactory
import io.github.edmondantes.serialization.element.factory.simple.SimpleEncodedElementFactory
import io.github.edmondantes.serialization.element.factory.structure.ComplexEncodedElementFactory
import io.github.edmondantes.serialization.element.factory.structure.DefaultComplexEncodedElementFactory
import io.github.edmondantes.serialization.util.tryGetElementDescriptor
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.descriptors.SerialDescriptor
public typealias IndexSupplier = (SerialDescriptor) -> Int
/**
* Abstract base implementation for [DefaultCollectionEncodingElementBuilder] and [DefaultStructureEncodingElementBuilder]
* @see DefaultCollectionEncodingElementBuilder
* @see DefaultStructureEncodingElementBuilder
*/
@OptIn(ExperimentalSerializationApi::class)
public abstract class AbstractComplexEncodingElementBuilder(
protected val descriptor: SerialDescriptor,
protected val typeForChildren: EncodedElementType,
protected val descriptorForChildren: SerialDescriptor? = null,
protected val parent: SerialDescriptor? = null,
protected val indexInParent: Int? = null,
) {
protected val structureValue: ComplexElementBuilder = mutableListOf()
protected val builder: DefaultEncodedElement.Builder<ComplexElementBuilder> =
DefaultEncodedElement.Builder<ComplexElementBuilder>()
.type(typeForChildren)
.descriptorName(descriptor)
.name(parent, indexInParent)
.value(structureValue)
protected fun <T> simpleInternal(
elementDescriptor: SerialDescriptor?,
indexSupplier: IndexSupplier,
): SimpleEncodedElementFactory<T> =
prepare(indexSupplier) { childDescriptor, index ->
DefaultSimpleEncodedElementFactory(
elementDescriptor ?: childDescriptor,
typeForChildren,
descriptorForChildren ?: descriptor,
index,
) {
structureValue.add(it)
}
}
protected fun <T> simpleInternal(
elementDescriptor: SerialDescriptor?,
block: SimpleEncodedElementFactory<T>.() -> EncodedElement<T>,
indexSupplier: IndexSupplier,
): Unit =
prepare(indexSupplier) { childDescriptor, index ->
val factory =
DefaultSimpleEncodedElementFactory<T>(
elementDescriptor ?: childDescriptor,
typeForChildren,
descriptorForChildren ?: descriptor,
index,
)
structureValue.add(factory.block() as AnyEncodedElement)
}
protected fun complexInternal(
elementDescriptor: SerialDescriptor?,
indexSupplier: IndexSupplier,
): ComplexEncodedElementFactory =
prepareComplex(elementDescriptor, indexSupplier) { childDescriptor, index ->
DefaultComplexEncodedElementFactory(
elementDescriptor ?: childDescriptor,
null,
descriptorForChildren ?: descriptor,
index,
) {
structureValue.add(it as AnyEncodedElement)
}
}
protected fun complexInternal(
elementDescriptor: SerialDescriptor?,
block: ComplexEncodedElementFactory.() -> ComplexEncodedElement,
indexSupplier: IndexSupplier,
): Unit =
prepareComplex(elementDescriptor, indexSupplier) { childDescriptor, index ->
val factory =
DefaultComplexEncodedElementFactory(
elementDescriptor ?: childDescriptor,
null,
descriptorForChildren ?: descriptor,
index,
)
structureValue.add(factory.block() as AnyEncodedElement)
}
protected fun contextualInternal(
elementDescriptor: SerialDescriptor?,
elementDescriptorForChildren: SerialDescriptor?,
indexSupplier: IndexSupplier,
): ComplexEncodedElementFactory =
prepareComplex(elementDescriptor, indexSupplier) { childDescriptor, index ->
DefaultComplexEncodedElementFactory(
elementDescriptor ?: childDescriptor,
elementDescriptorForChildren,
descriptorForChildren ?: descriptor,
index,
) {
structureValue.add(it as AnyEncodedElement)
}
}
protected fun contextualInternal(
elementDescriptor: SerialDescriptor?,
elementDescriptorForChildren: SerialDescriptor?,
block: ComplexEncodedElementFactory.() -> ComplexEncodedElement,
indexSupplier: IndexSupplier,
): Unit =
prepareComplex(elementDescriptor, indexSupplier) { childDescriptor, index ->
val factory =
DefaultComplexEncodedElementFactory(
elementDescriptor ?: childDescriptor,
elementDescriptorForChildren,
descriptorForChildren ?: descriptor,
index,
)
structureValue.add(factory.block() as AnyEncodedElement)
}
protected inline fun <T> prepare(
indexSupplier: IndexSupplier,
block: (SerialDescriptor?, Int) -> T,
): T {
val currDescriptorForChildren = descriptorForChildren ?: descriptor
val index = indexSupplier(currDescriptorForChildren)
return currDescriptorForChildren.run {
val childDescriptor = tryGetElementDescriptor(index)
block(childDescriptor, index)
}
}
protected inline fun <T> prepareComplex(
elementDescriptor: SerialDescriptor?,
indexSupplier: IndexSupplier,
block: (SerialDescriptor, Int) -> T,
): T =
prepare(indexSupplier) { childDescriptor, index ->
block(
elementDescriptor ?: childDescriptor ?: error("Can not find descriptor for element with index: $index"),
index,
)
}
}
| 0 | Kotlin | 0 | 1 | 1fc3993b94d93a5fc479af855320712f65179887 | 7,254 | simple-kotlinx-serialization-utils | Apache License 2.0 |
mobile_app1/module994/src/main/java/module994packageKt0/Foo81.kt | uber-common | 294,831,672 | false | null | package module994packageKt0;
annotation class Foo81Fancy
@Foo81Fancy
class Foo81 {
fun foo0(){
module994packageKt0.Foo80().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 233 | android-build-eval | Apache License 2.0 |
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/data/proxy/RealProxySyncService.kt | novasamatech | 415,834,480 | false | null | package io.novafoundation.nova.feature_account_impl.data.proxy
import android.util.Log
import io.novafoundation.nova.common.address.AccountIdKey
import io.novafoundation.nova.common.address.intoKey
import io.novafoundation.nova.common.utils.LOG_TAG
import io.novafoundation.nova.common.utils.coroutines.RootScope
import io.novafoundation.nova.common.utils.mapToSet
import io.novafoundation.nova.core_db.dao.MetaAccountDao
import io.novafoundation.nova.core_db.model.chain.account.MetaAccountLocal
import io.novafoundation.nova.core_db.model.chain.account.ProxyAccountLocal
import io.novafoundation.nova.feature_account_api.data.proxy.MetaAccountsUpdatesRegistry
import io.novafoundation.nova.feature_account_api.data.proxy.ProxySyncService
import io.novafoundation.nova.feature_account_api.data.repository.addAccount.addAccountWithSingleChange
import io.novafoundation.nova.feature_account_api.data.repository.addAccount.proxied.ProxiedAddAccountRepository
import io.novafoundation.nova.feature_account_api.domain.account.identity.Identity
import io.novafoundation.nova.feature_account_api.domain.account.identity.IdentityProvider
import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountRepository
import io.novafoundation.nova.feature_account_api.domain.model.LightMetaAccount
import io.novafoundation.nova.feature_account_api.domain.model.MetaAccount
import io.novafoundation.nova.feature_account_api.domain.model.requireAccountIdIn
import io.novafoundation.nova.feature_proxy_api.data.common.NestedProxiesGraphConstructor
import io.novafoundation.nova.feature_proxy_api.data.common.getAllAccountIds
import io.novafoundation.nova.feature_proxy_api.data.repository.GetProxyRepository
import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry
import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain
import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId
import io.novafoundation.nova.runtime.multiNetwork.enabledChains
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
private class CreateMetaAccountsResult(
val addedMetaIds: MutableList<Long> = mutableListOf(),
val alreadyExistedMetaIds: MutableList<Long> = mutableListOf(),
val shouldBeActivatedMetaIds: MutableList<Long> = mutableListOf()
) {
fun add(other: CreateMetaAccountsResult) {
addedMetaIds.addAll(other.addedMetaIds)
alreadyExistedMetaIds.addAll(other.alreadyExistedMetaIds)
shouldBeActivatedMetaIds.addAll(other.shouldBeActivatedMetaIds)
}
}
class RealProxySyncService(
private val chainRegistry: ChainRegistry,
private val getProxyRepository: GetProxyRepository,
private val accountRepository: AccountRepository,
private val accountDao: MetaAccountDao,
private val identityProvider: IdentityProvider,
private val metaAccountsUpdatesRegistry: MetaAccountsUpdatesRegistry,
private val proxiedAddAccountRepository: ProxiedAddAccountRepository,
private val rootScope: RootScope,
private val shouldSyncWatchOnlyProxies: Boolean
) : ProxySyncService {
override fun proxySyncTrigger(): Flow<*> {
return chainRegistry.currentChains
.map { chains ->
chains
.filter(Chain::supportProxy)
.map(Chain::id)
}.distinctUntilChanged()
}
override fun startSyncing() {
rootScope.launch(Dispatchers.Default) {
startSyncInternal()
}
}
override suspend fun startSyncingSuspend() {
startSyncInternal()
}
private suspend fun startSyncInternal() = runCatching {
val metaAccounts = getMetaAccounts()
if (metaAccounts.isEmpty()) return@runCatching
val supportedProxyChains = getSupportedProxyChains()
Log.d(LOG_TAG, "Starting syncing proxies in ${supportedProxyChains.size} chains")
supportedProxyChains.forEach { chain ->
syncChainProxies(chain, metaAccounts)
}
}.onFailure {
Log.e(LOG_TAG, "Failed to sync proxy delegators", it)
}
private suspend fun syncChainProxies(chain: Chain, allMetaAccounts: List<MetaAccount>) = runCatching {
Log.d(LOG_TAG, "Started syncing proxies for ${chain.name}")
val availableAccounts = chain.getAvailableMetaAccounts(allMetaAccounts)
val availableAccountIds = availableAccounts.mapToSet { it.requireAccountIdIn(chain).intoKey() }
val nodes = getProxyRepository.findAllProxiedsForAccounts(chain.id, availableAccountIds)
val proxiedAccountIds = NestedProxiesGraphConstructor.Node.getAllAccountIds(nodes)
val oldProxies = accountDao.getProxyAccounts(chain.id)
val identities = identityProvider.identitiesFor(proxiedAccountIds, chain.id)
val result = createMetaAccounts(chain, oldProxies, identities, availableAccounts, nodes)
val deactivatedMetaIds = result.findDeactivated(oldProxies)
accountDao.changeAccountsStatus(deactivatedMetaIds, MetaAccountLocal.Status.DEACTIVATED)
accountDao.changeAccountsStatus(result.shouldBeActivatedMetaIds, MetaAccountLocal.Status.ACTIVE)
val changedMetaIds = result.addedMetaIds + deactivatedMetaIds
metaAccountsUpdatesRegistry.addMetaIds(changedMetaIds)
}.onFailure {
Log.e(LOG_TAG, "Failed to sync proxy delegators in chain ${chain.name}", it)
}.onSuccess {
Log.d(LOG_TAG, "Finished syncing proxies for ${chain.name}")
}
private suspend fun createMetaAccounts(
chain: Chain,
oldProxies: List<ProxyAccountLocal>,
identities: Map<AccountIdKey, Identity?>,
maybeProxyMetaAccounts: List<MetaAccount>,
startNodes: List<NestedProxiesGraphConstructor.Node>
): CreateMetaAccountsResult {
val result = CreateMetaAccountsResult()
val accountIdToNode = startNodes.associateBy { it.accountId }
for (metaAccount in maybeProxyMetaAccounts) {
val proxyAccountId = metaAccount.requireAccountIdIn(chain).intoKey()
val startNode = accountIdToNode[proxyAccountId] ?: continue // skip adding proxieds for metaAccount if it's not in the tree
val nestedResult = recursivelyCreateMetaAccounts(chain.id, oldProxies, identities, metaAccount.id, startNode.nestedNodes)
result.add(nestedResult)
}
return result
}
private suspend fun recursivelyCreateMetaAccounts(
chainId: ChainId,
oldProxies: List<ProxyAccountLocal>,
identities: Map<AccountIdKey, Identity?>,
proxyMetaId: Long,
nestedNodes: List<NestedProxiesGraphConstructor.Node>
): CreateMetaAccountsResult {
val result = CreateMetaAccountsResult()
for (node in nestedNodes) {
val maybeExistedProxiedMetaId = node.getExistedProxiedMetaId(chainId, oldProxies, proxyMetaId)
val nextMetaId = if (maybeExistedProxiedMetaId == null) {
val addAccountResult = addProxiedAccount(chainId, node, proxyMetaId, identities)
result.addedMetaIds.add(addAccountResult.metaId)
addAccountResult.metaId
} else {
// An account may be deactivated but not deleted yet in case when we remove a proxy and then add it again
// To support this case we should track deactivated accounts and activate them again
val existedMetaAccount = accountRepository.getMetaAccount(maybeExistedProxiedMetaId)
if (existedMetaAccount.status == LightMetaAccount.Status.DEACTIVATED) {
result.shouldBeActivatedMetaIds.add(maybeExistedProxiedMetaId)
}
result.alreadyExistedMetaIds.add(maybeExistedProxiedMetaId)
maybeExistedProxiedMetaId
}
if (node.nestedNodes.isNotEmpty()) {
val nestedResult = recursivelyCreateMetaAccounts(chainId, oldProxies, identities, nextMetaId, node.nestedNodes)
result.add(nestedResult)
}
}
return result
}
private suspend fun addProxiedAccount(
chainId: ChainId,
node: NestedProxiesGraphConstructor.Node,
metaId: Long,
identities: Map<AccountIdKey, Identity?>
) = proxiedAddAccountRepository.addAccountWithSingleChange(
ProxiedAddAccountRepository.Payload(
chainId = chainId,
proxiedAccountId = node.accountId.value,
proxyType = node.permissionType,
proxyMetaId = metaId,
identity = identities[node.accountId]
)
)
private fun NestedProxiesGraphConstructor.Node.getExistedProxiedMetaId(
chainId: ChainId,
oldProxies: List<ProxyAccountLocal>,
proxyMetaId: Long
): Long? {
val oldIdentifiers = oldProxies.associateBy { it.identifier }
val identifier = ProxyAccountLocal.makeIdentifier(
proxyMetaId = proxyMetaId,
chainId = chainId,
proxiedAccountId = accountId.value,
proxyType = permissionType.name
)
return oldIdentifiers[identifier]?.proxiedMetaId
}
private suspend fun getMetaAccounts(): List<MetaAccount> {
return accountRepository.getActiveMetaAccounts()
.filter { it.isAllowedToSyncProxy(shouldSyncWatchOnlyProxies) }
}
private suspend fun getSupportedProxyChains(): List<Chain> {
return chainRegistry.enabledChains()
.filter { it.supportProxy }
}
private fun Chain.getAvailableMetaAccounts(metaAccounts: List<MetaAccount>): List<MetaAccount> {
return metaAccounts.filter { metaAccount -> metaAccount.hasAccountIn(chain = this) }
}
private suspend fun CreateMetaAccountsResult.findDeactivated(oldProxies: List<ProxyAccountLocal>): List<Long> {
val oldIds = oldProxies.map { it.proxiedMetaId }
val deactivated = oldIds - alreadyExistedMetaIds
val alreadyDeactivatedMetaIdsInCache = accountDao.getMetaAccountIdsByStatus(MetaAccountLocal.Status.DEACTIVATED)
return deactivated - alreadyDeactivatedMetaIdsInCache.toSet()
}
private suspend fun List<Long>.takeNotYetDeactivatedMetaAccounts(): List<Long> {
val alreadyDeactivatedMetaAccountIds = accountDao.getMetaAccountIdsByStatus(MetaAccountLocal.Status.DEACTIVATED)
return this - alreadyDeactivatedMetaAccountIds.toSet()
}
}
| 18 | null | 7 | 50 | 166755d1c3388a7afd9b592402489ea5ca26fdb8 | 10,555 | nova-wallet-android | Apache License 2.0 |
src/main/kotlin/ch/unibas/dmi/dbis/cottontail/sql/Context.kt | sauterl | 202,150,029 | true | {"Kotlin": 483171, "ANTLR": 12918} | package ch.unibas.dmi.dbis.cottontail.sql
import ch.unibas.dmi.dbis.cottontail.database.catalogue.Catalogue
import ch.unibas.dmi.dbis.cottontail.database.entity.Entity
import ch.unibas.dmi.dbis.cottontail.sql.metamodel.LiteralExpression
import ch.unibas.dmi.dbis.cottontail.sql.metamodel.NumberLiteralExpression
import ch.unibas.dmi.dbis.cottontail.sql.metamodel.StringLiteralExpression
import ch.unibas.dmi.dbis.cottontail.sql.metamodel.VectorLiteralExpression
/**
* A context class used for translating a raw CottonSQL query (string) into an executable, abstract syntax tree.
*
* @author <NAME>
* @version 1.0
*/
internal data class Context(val catalogue: Catalogue, val parameters: List<Any>, val default: String? = null) {
/**
* Fetches and returns the parameter bound for the given index.
*
* @param index The index of the parameter.
* @return LiteralExpression
*/
fun getBoundParameter(index: Int) : LiteralExpression {
try {
val value = this.parameters[index]
return when(value) {
is String -> StringLiteralExpression(value)
is FloatArray -> VectorLiteralExpression(value.toTypedArray())
is DoubleArray -> VectorLiteralExpression(value.toTypedArray())
is ByteArray -> VectorLiteralExpression(value.toTypedArray())
is ShortArray -> VectorLiteralExpression(value.toTypedArray())
is IntArray -> VectorLiteralExpression(value.toTypedArray())
is LongArray -> VectorLiteralExpression(value.toTypedArray())
is Float -> NumberLiteralExpression(value)
is Double -> NumberLiteralExpression(value)
is Byte -> NumberLiteralExpression(value)
is Short -> NumberLiteralExpression(value)
is Int -> NumberLiteralExpression(value)
is Long -> NumberLiteralExpression(value)
else -> throw QueryParsingException("Value for parameter binding '$index' is not supported.")
}
} catch (e: IndexOutOfBoundsException) {
throw QueryParsingException("No value for parameter binding '$index'; index is out of bounds!")
}
}
} | 0 | Kotlin | 0 | 0 | bc25f6be57b93f0658404025706204ff5f24f830 | 2,241 | cottontaildb | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.