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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
camera/src/main/java/com/pwj/camera1/MainActivity.kt | a-pwj | 255,207,003 | false | {"Gradle": 20, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 20, "Batchfile": 1, "Markdown": 5, "Proguard": 14, "XML": 252, "Java": 74, "INI": 13, "Kotlin": 133, "JSON": 2, "C++": 1, "CMake": 1, "C": 42, "Gradle Kotlin DSL": 1, "Groovy": 1} | package com.pwj.camera1
import android.os.Bundle
import android.os.Environment
import android.view.SurfaceHolder
import android.view.View
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
/**
* Author: pwj
* Date: 2020/3/26 9:34
* FileName: MainActivity
*/
class MainActivity : AppCompatActivity(){
private lateinit var mVideoRecorderUtils: VideoRecorderUtils
private lateinit var path: String
private lateinit var name: String
private var isRecording = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.activity_main)
mVideoRecorderUtils = VideoRecorderUtils()
mVideoRecorderUtils.create(mIdSvVideo, VideoRecorderUtils.WH_720X480)
path = Environment.getExternalStorageDirectory().absolutePath
mIdIvSnap.setOnClickListener { view: View? ->
if (!isRecording) {
mVideoRecorderUtils.startRecord(path, "Video")
} else {
mVideoRecorderUtils.stopRecord()
}
isRecording = !isRecording
}
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
mVideoRecorderUtils.stop()
}
override fun onDestroy() {
super.onDestroy()
mVideoRecorderUtils.destroy()
}
} | 0 | C | 0 | 0 | 6d6411916d1528b300c6c6ddf9932a10b41aa3fb | 1,603 | Record | Apache License 2.0 |
idea/testData/refactoring/rename/renameKotlinMethodWithEscapedName/after/RenameKotlinMethodWithEscapedName.kt | JakeWharton | 99,388,807 | false | null | package testing.rename
public open class C {
public fun second() = 1
public fun foo() = second()
}
| 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 109 | kotlin | Apache License 2.0 |
android/src/main/java/com/intervestlocationlibrary/IntervestLocationLibraryPackage.kt | chathurangakup | 570,876,105 | false | {"Java": 15785, "C++": 7321, "Objective-C++": 4460, "Ruby": 3050, "Objective-C": 2814, "JavaScript": 1832, "TypeScript": 1344, "Kotlin": 1340, "Starlark": 602, "Shell": 482, "Swift": 325, "CMake": 287, "C": 103} | package com.intervestlocationlibrary
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class IntervestLocationLibraryPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(IntervestLocationLibraryModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| 1 | null | 1 | 1 | 43545774666669db1b1e99bea1121f1dd0fa2e3d | 581 | react-native-native-module-location-library | MIT License |
wanandroid/src/main/java/com/lyl/wanandroid/http/Test.kt | laiyuling424 | 145,495,250 | false | null | package com.lyl.wanandroid.http
import com.lyl.wanandroid.ui.fragment.wechatpublic.WeChatPublicListBeanResponse
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
/**
* Create By: lyl
* Date: 2019-08-01 10:18
*/
public fun main() {
var api: Api = Proxy.newProxyInstance(Api::class.java.classLoader, arrayOf(Api::class.java), object : InvocationHandler {
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
// MyLog.Logd("method==$method")
println("method==$method")
return null
}
}) as Api
val weChatPublicList = api.getWeChatPublicList()
val call = ApiServer.getApiServer().getWeChatPublicListt()
call.enqueue(object : Callback<WeChatPublicListBeanResponse> {
override fun onResponse(call: Call<WeChatPublicListBeanResponse>, response: Response<WeChatPublicListBeanResponse>) {
println("onResponse")
}
override fun onFailure(call: Call<WeChatPublicListBeanResponse>, t: Throwable) {
println("onFailure")
}
})
Thread.sleep(4000)
println("end")
}
| 1 | null | 2 | 5 | 8c8d10aa48546f0a66f0a466990e3b2f886b011c | 1,255 | lylproject | MIT License |
core/src/com/t2wonderland/kurona/Models/CharacterFactory.kt | kemokemo | 65,126,666 | false | null | package com.t2wonderland.kurona.Models
import com.t2wonderland.kurona.Interfaces.ICharacterObject
import com.t2wonderland.kurona.Objects.Koma
import com.t2wonderland.kurona.Objects.Kurona
import com.t2wonderland.kurona.Objects.Shishimaru
internal class CharacterFactory(val selectedCharacter: CharacterSelect) {
fun createCharacter(): ICharacterObject {
// 設定に応じて実体を作る
if(selectedCharacter == CharacterSelect.Kurona){
var character = Kurona()
character.setInitialPosition(1f, 1f)
return character
}
else if (selectedCharacter == CharacterSelect.Koma){
var character = Koma()
character.setInitialPosition(1f, 1f)
return character
}
else if (selectedCharacter == CharacterSelect.Shishimaru){
var character = Shishimaru()
character.setInitialPosition(1f, 1f)
return character
}
else{
var character = Kurona()
character.setInitialPosition(1f, 1f)
return character
}
}
}
| 0 | Kotlin | 1 | 1 | 339fed233baaf5b46af4f26c33ed01a2015c1e94 | 1,092 | kuronan-dash-kotlin | Apache License 2.0 |
mimi-app/src/main/java/com/emogoth/android/phone/mimi/span/YoutubeLinkSpan.kt | Blatzar | 333,976,130 | true | {"Java Properties": 2, "YAML": 1, "Gradle": 4, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 3, "Ignore List": 2, "Proguard": 1, "Java": 128, "XML": 320, "Kotlin": 102, "HTML": 6, "SQL": 2} | package com.emogoth.android.phone.mimi.span
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.text.TextPaint
import android.view.View
import android.widget.Toast
import com.emogoth.android.phone.mimi.R
import com.emogoth.android.phone.mimi.util.MimiUtil
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class YoutubeLinkSpan(private val videoId: String, private val linkColor: Int) : LongClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = true
ds.color = linkColor
}
override fun onClick(widget: View) {
openLink(widget.context)
}
private fun showChoiceDialog(context: Context) {
val url = MimiUtil.https() + "youtube.com/watch?v=" + videoId
val handler = Handler(Looper.getMainLooper())
handler.post {
MaterialAlertDialogBuilder(context)
.setTitle(R.string.youtube_link)
.setItems(R.array.youtube_dialog_list) { dialog, which ->
if (which == 0) {
openLink(context)
} else {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(ClipData.newPlainText("youtube_link", url))
Toast.makeText(context, R.string.link_copied_to_clipboard, Toast.LENGTH_SHORT).show()
}
}
.setCancelable(true)
.show()
.setCanceledOnTouchOutside(true)
}
}
private fun openLink(context: Context) {
val url = MimiUtil.https() + "youtube.com/watch?v=" + videoId
val openIntent = Intent(Intent.ACTION_VIEW)
openIntent.data = Uri.parse(url)
context.startActivity(openIntent)
}
override fun onLongClick(v: View): Boolean {
showChoiceDialog(v.context)
return true
}
} | 0 | Java | 4 | 9 | fc1e4cd8d4f73360723b910be31907b970a5e5d1 | 2,233 | mimi-reader | Apache License 2.0 |
platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/ScrollingPosition.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.documentation.ide.ui
internal sealed class ScrollingPosition {
object Keep : ScrollingPosition()
object Reset : ScrollingPosition()
class Anchor(val anchor: String) : ScrollingPosition()
}
| 186 | null | 4323 | 13,182 | 26261477d6e3d430c5fa50c42b80ea8cfee45525 | 384 | intellij-community | Apache License 2.0 |
app/src/main/java/com/puutaro/commandclick/util/SharePreffrenceMethod.kt | puutaro | 596,852,758 | false | {"Kotlin": 1472142, "JavaScript": 147417, "HTML": 19619} | package com.puutaro.commandclick.util
import android.content.SharedPreferences
import com.puutaro.commandclick.common.variable.SharePrefferenceSetting
class SharePreffrenceMethod {
companion object {
fun getStringFromSharePreffrence(
sharedPref: SharedPreferences?,
sharePrefferenceSetting: SharePrefferenceSetting
): String {
val defaultStrValue = sharePrefferenceSetting.defalutStr
if(sharedPref == null) return defaultStrValue
return sharedPref.getString(
sharePrefferenceSetting.name,
defaultStrValue
) ?: defaultStrValue
}
fun putSharePreffrence (
sharedPref: SharedPreferences?,
sharedPrefKeyValeuMap: Map<String, String>
){
if(sharedPref == null) return
with(sharedPref.edit()) {
sharedPrefKeyValeuMap.forEach { currentKey, currentValue ->
putString(
currentKey,
currentValue
)
}
commit()
}
}
fun makeReadSharePreffernceMap(
startUpPref: SharedPreferences?
): Map<String, String> {
val sharedCurrentAppPath = getStringFromSharePreffrence(
startUpPref,
SharePrefferenceSetting.current_app_dir
)
val sharedCurrentShellFileName = getStringFromSharePreffrence(
startUpPref,
SharePrefferenceSetting.current_script_file_name
)
val sharedOnShortcut = getStringFromSharePreffrence(
startUpPref,
SharePrefferenceSetting.on_shortcut
)
return mapOf(
SharePrefferenceSetting.current_app_dir.name
to sharedCurrentAppPath,
SharePrefferenceSetting.current_script_file_name.name
to sharedCurrentShellFileName,
SharePrefferenceSetting.on_shortcut.name
to sharedOnShortcut,
)
}
fun getReadSharePreffernceMap(
readSharePreffernceMap: Map<String, String>,
sharePrefferenceSetting: SharePrefferenceSetting
): String {
return try {
readSharePreffernceMap.get(
sharePrefferenceSetting.name
) ?: sharePrefferenceSetting.defalutStr
} catch (e: Exception){
sharePrefferenceSetting.defalutStr
}
}
}
} | 2 | Kotlin | 3 | 54 | 000db311f5780b2861a2143f7985507b06cae5f1 | 2,646 | CommandClick | MIT License |
project/common/src/main/kotlin/ink/ptms/adyeshach/core/entity/type/AdySpellcasterIllager.kt | TabooLib | 284,936,010 | false | {"Kotlin": 1050024, "Java": 35966} | package ink.ptms.adyeshach.core.entity.type
import org.bukkit.entity.Spellcaster
/**
* @author sky
* @date 2020/8/4 23:15
*/
@Suppress("SpellCheckingInspection")
interface AdySpellcasterIllager : AdyRaider {
fun setSpell(spell: Spellcaster.Spell) {
setMetadata("spell", spell.ordinal)
}
fun getSpell(): Spellcaster.Spell {
return Spellcaster.Spell.values()[getMetadata("spell")]
}
} | 13 | Kotlin | 86 | 98 | ac7098b62db19308c9f14182e33181c079b9e561 | 421 | adyeshach | MIT License |
app/src/main/java/com/masterplus/notex/views/DisplayCheckListNoteFragment.kt | Ramazan713 | 458,716,624 | false | null | package com.masterplus.notex.views
import android.content.*
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.masterplus.notex.*
import com.masterplus.notex.adapters.CheckNoteAdapter
import com.masterplus.notex.databinding.FragmentDisplayCheckListNoteBinding
import com.masterplus.notex.designpatterns.state.CheckNoteEditorContext
import com.masterplus.notex.designpatterns.state.CheckNoteNullState
import com.masterplus.notex.designpatterns.strategy.RootNoteArchiveItem
import com.masterplus.notex.designpatterns.strategy.RootNoteDefaultItem
import com.masterplus.notex.designpatterns.strategy.RootNoteTrashItem
import com.masterplus.notex.enums.*
import com.masterplus.notex.models.ParameterNote
import com.masterplus.notex.models.ParameterRootNote
import com.masterplus.notex.models.copymove.CheckItemCopyMoveObject
import com.masterplus.notex.roomdb.models.UnitedNote
import com.masterplus.notex.utils.*
import com.masterplus.notex.viewmodels.CheckListNoteViewModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.masterplus.notex.models.ParameterAddCheckItem
import com.masterplus.notex.roomdb.entities.*
import com.masterplus.notex.viewmodels.items.AddCheckItemViewModel
import com.masterplus.notex.viewmodels.items.SetCopyMoveItemViewModel
import com.masterplus.notex.viewmodels.items.SetSelectColorItemViewModel
import com.masterplus.notex.views.view.CustomFragment
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
@AndroidEntryPoint
class DisplayCheckListNoteFragment @Inject constructor(private val imm: InputMethodManager,
private val showMessage: ShowMessage,
private val customAlerts: CustomAlerts,
private val customGetDialogs: CustomGetDialogs,
private val sharedPreferences: SharedPreferences
) : CustomFragment() {
private var _binding: FragmentDisplayCheckListNoteBinding?=null
private val binding get() = _binding!!
private lateinit var noteParameter: ParameterNote
private val viewModel: CheckListNoteViewModel by viewModels()
private val viewModelSelectColor: SetSelectColorItemViewModel by viewModels()
private val viewModelAddCheckItem: AddCheckItemViewModel by viewModels()
private val viewModelCopyMoveListener: SetCopyMoveItemViewModel by viewModels()
private lateinit var navController: NavController
private var lastSavedNote: UnitedNote = UnitedNote(Note(typeContent = NoteType.CheckList), arrayListOf())
private var note: UnitedNote = lastSavedNote
private var lastEditState:Boolean? = null
private val checkNoteAdapter=CheckNoteAdapter()
private lateinit var checkNoteContext:CheckNoteEditorContext
private lateinit var callback:ActionMode.Callback
private var actionMode:ActionMode? = null
private lateinit var itemTouchHelper:ItemTouchHelper
private var mInterstitialAd: InterstitialAd? = null
private var isAdCountAdded=false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean("isActionMode",actionMode!=null)
outState.putBoolean("isAdCountAdded",isAdCountAdded)
outState.putLong("noteId",note.note.uid)
noteParameter.sharedNote=null
viewModel.stateSelectedContentNotes.value=checkNoteAdapter.getSelectedItems().toMutableList()
viewModel.stateParameterNote=noteParameter.deepCopy()
super.onSaveInstanceState(outState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding= FragmentDisplayCheckListNoteBinding.inflate(layoutInflater,container,false)
setUpActionCallback()
binding.appbarCheckNote.setExpanded(false)
navController= Navigation.findNavController(requireActivity(),R.id.frames)
checkNoteContext= CheckNoteEditorContext(binding)
binding.recyclerCheckNote.adapter=checkNoteAdapter
binding.recyclerCheckNote.layoutManager=LinearLayoutManager(requireContext())
DisplayCheckListNoteFragmentArgs.fromBundle(requireArguments()).let { args->
var noteId:Long?=null
if(savedInstanceState!=null){
isAdCountAdded=savedInstanceState.getBoolean("isAdCountAdded",isAdCountAdded)
noteId=savedInstanceState.getLong("noteId")
}
noteParameter=viewModel.stateParameterNote?:args.noteParameter
adjustBackgroundColor(noteParameter.color)
noteParameter.sharedNote?.let { shared->
if(noteParameter.isEmptyNote){
binding.editTitleCheckNote.setText(shared.title?:"")
note.note.title=shared.title?:""
note.contents.addAll(shared.contentNotes)
noteParameter.sharedNote=null
}
}
val textFontSize=Utils.getFontSize(sharedPreferences).toFloat()
checkNoteAdapter.setInit(Utils.getColorIntWithAddition(noteParameter.color,requireContext())
,noteParameter.isEmptyNote,textFontSize,adapterListener)
setAddCheckNoteItemVisibility(false)
if(noteParameter.isEmptyNote){
checkNoteContext.setCurrentState(CheckNoteNullState(checkNoteContext))
note = lastSavedNote.deepCopy()
checkNoteAdapter.items=note.contents
binding.showReminderViewFromCheck.root.isGone=true
setEditState(true)
}else{
checkNoteContext.setCurrentState(noteParameter.noteKinds)
viewModel.signalToLoadCurrentNote(noteId?:noteParameter.parentId!!)
}
note.note.kindNote=noteParameter.noteKinds
requireActivity().invalidateOptionsMenu()
}
checkNoteContext.setNoteKindsListener {
note.note.kindNote=it
noteParameter.noteKinds=it
}
setObservers(savedInstanceState)
setBehaviourSelectItemBook()
setAddCheckNoteItemViews()
setItemTouchHelper()
checkAndLoadInterstitialAdd()
adjustNavigation()
return _binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.editTitleCheckNote.doOnTextChanged { text, start, before, count ->
note.note.title=text.toString().trim()
}
binding.showTagsCheckNote.setOnClickListener {
showSelectTagsDia()
}
binding.editTitleCheckNote.setKeyBackListener(object : (Boolean)->Unit{
override fun invoke(isActive: Boolean) {
if(noteParameter.noteKinds==NoteKinds.TRASH_KIND){
showMessage.showShort(getString(R.string.can_not_be_changed_text))
}else
setEditState(isActive)
}
})
}
private fun setObservers(savedInstanceState:Bundle?){
viewModel.note.observe(viewLifecycleOwner, Observer {
note=it
checkNoteAdapter.items=it.contents
loadDataWithCheckingSearchedText(it)
initLoading(it)
lastSavedNote=note.deepCopy()
adjustBackgroundColor(note.note.color)
noteParameter.parentId = noteParameter.parentId?:it.note.uid
if(savedInstanceState!=null){
if(savedInstanceState.getBoolean("isActionMode")){
setEditState(true)
val items=viewModel.stateSelectedContentNotes.value?: listOf()
checkNoteAdapter.setSelectedItems(items)
savedInstanceState.putBoolean("isActionMode",false)
}
}
if(noteParameter.isEmptyNote){
setTransNullToNote(it.note.uid)
noteParameter.isEmptyNote=false
}
})
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED){
launch {
viewModel.isRecoverNote.collect {
checkNoteContext.recoverNote()
viewModel.signalToLoadCurrentNote(note.note.uid)
requireActivity().invalidateOptionsMenu()
}
}
launch {
viewModel.isNoteSaved.collect {
showMessage.showLong(getString(R.string.saved_text))
lastSavedNote=note.deepCopy()
setShowDate(note.note.updateDate)
}
}
launch {
viewModelAddCheckItem.sentAddedCheckItem.collect {
val weight:Int=when{
it.isFirst->0
else->checkNoteAdapter.itemCount
}
val contentNote = ContentNote(note.note.uid,it.value,weight,false)
checkNoteAdapter.addItem(contentNote,weight)
}
}
launch {
viewModelAddCheckItem.sentEditedCheckItem.collect {
checkNoteAdapter.updateItem(it.newValue,it.pos)
}
}
launch {
viewModelCopyMoveListener.liveItem.collect {
if(it.isMove){
val items=checkNoteAdapter.getSelectedItems().toList()
note.contents.removeAll(items)
checkNoteAdapter.removeItems(items)
}
actionMode?.finish()
}
}
launch {
viewModelSelectColor.liveItem.collect {color->
adjustBackgroundColor(color)
note.note.color=color
viewModel.changeColor(color,note.note.uid)
}
}
}
}
}
private fun setTransNullToNote(noteId:Long){
checkNoteContext.transNullToNote(note.note.kindNote)
requireActivity().invalidateOptionsMenu()
when(noteParameter.noteFlags){
NoteFlags.DEFAULT_NOTE->{
noteParameter.parentId=noteId
}
NoteFlags.BOOK_FROM_NOTE->{
viewModel.setBookId(noteId,noteParameter.parentId?:0)
}
NoteFlags.TAG_FROM_NOTE->{
viewModel.setTagWithIds(noteParameter.parentId?:0,noteId)
}
}
}
private fun setEditState(isEdit:Boolean){
if(lastEditState==null || lastEditState!=isEdit){
lastEditState=isEdit
if(isEdit){
removeSearchedAffect()
actionMode=requireActivity().startActionMode(callback)
}else{
closeKeyboard()
binding.editTitleCheckNote.clearFocus()
actionMode?.finish()
viewModel.saveNote(note,lastSavedNote)
binding.editTitleCheckNote.setText(viewModel.checkAndSetDefaultTitleToNote(note))
}
binding.editTitleCheckNote.isCursorVisible=isEdit
checkNoteAdapter.setEdit(isEdit)
setAddCheckNoteItemVisibility(isEdit)
setIsAdCountAdded()
}
}
private fun initLoading(note:UnitedNote){
viewModel.getLiveReminder(note.note.uid).observe(viewLifecycleOwner, Observer { reminder->
setReminderViews(reminder)
})
viewModel.getLiveTags(note.note.uid).observe(viewLifecycleOwner, Observer {
setTagsAndVisibility(it.tags)
})
viewModel.getLiveBook(note.note.uid).observe(viewLifecycleOwner, Observer {
setBookText(it)
note.note.bookId=it?.bookId?:0L
})
setShowDate(note.note.updateDate)
}
private fun setBehaviourSelectItemBook(){
binding.selectBookFromCheckNote.root.setOnClickListener {
customGetDialogs.getSelectBookDia(note)
.show(childFragmentManager,"")
}
}
private fun loadDataWithCheckingSearchedText(note: UnitedNote){
val noteTitle=note.note.title
val searchText=noteParameter.searchText?:""
binding.editTitleCheckNote.setText(if(searchText!="") getHighLightedText(noteTitle,searchText) else noteTitle)
checkNoteAdapter.setSearchedText(searchText)
}
private fun removeSearchedAffect(){
if(noteParameter.searchText!=""){
binding.editTitleCheckNote.setText(note.note.title)
checkNoteAdapter.setSearchedText("")
noteParameter.searchText=""
}
}
private fun setIsAdCountAdded(){
if(!isAdCountAdded){
isAdCountAdded=true
MainActivity.SAVED_NOTE_COUNT++
checkAndLoadInterstitialAdd()
}
}
private fun checkAndLoadInterstitialAdd(){
if(!MainActivity.isPremiumActive&&mInterstitialAd==null&&
MainActivity.SAVED_NOTE_COUNT>=MainActivity.MAX_SAVED_NOTE_COUNT){
val adRequest = AdRequest.Builder().build()
InterstitialAd.load(requireContext(),getString(R.string.interstitialAdd_checkNote_id),adRequest,object :
InterstitialAdLoadCallback(){
override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
mInterstitialAd=null
}
override fun onAdLoaded(p0: InterstitialAd) {
super.onAdLoaded(p0)
mInterstitialAd=p0
MainActivity.SAVED_NOTE_COUNT-=MainActivity.SAVED_NOTE_COUNT
}
})
}
}
private fun adjustBackgroundColor(color:Int){
val colorInt=Utils.getColorUIMode(requireContext(),color)
val colorWithAddition = Utils.getColorIntWithAddition(colorInt,requireContext())
binding.nestedScrollDisplayCheckNote.setBackgroundColor(colorInt)
binding.appbarCheckNote.setBackgroundColor(colorInt)
binding.selectBookFromCheckNote.root.setCardBackgroundColor(colorWithAddition)
binding.addItemCheckList.root.setCardBackgroundColor(colorWithAddition)
binding.addItemCheckListBottom.root.setCardBackgroundColor(colorWithAddition)
checkNoteAdapter.setColor(colorWithAddition)
binding.showReminderViewFromCheck.root.setCardBackgroundColor(colorWithAddition)
Utils.changeToolBarColor(requireActivity(),colorInt)
}
private fun adjustBackgroundColor(color:String){
val colorInt:Int = Color.parseColor(color)
adjustBackgroundColor(colorInt)
}
private fun setFontSize(fontSize:Float?=null){
val size:Float=fontSize?:Utils.getFontSize(sharedPreferences).toFloat()
checkNoteAdapter.setTextSize(size)
}
private fun setBookText(book: Book?){
binding.selectBookFromCheckNote.textItemSelectBook.text = book?.name ?: getString(R.string.unselected_text)
}
private fun setReminderViews(reminder: Reminder?){
binding.showReminderViewFromCheck.let { reminderView->
if(reminder!=null){
val backgroundId=if(reminder.reminderType == ReminderTypes.NOT_REPEATED)R.drawable.ic_baseline_access_time_24
else R.drawable.ic_baseline_repeat_24
reminderView.viewReminderText.setCompoundDrawablesWithIntrinsicBounds(backgroundId,0,0,0)
reminderView.viewReminderText.text = Utils.getReminderSpanDateText(reminder)
}
reminderView.root.isVisible = reminder!=null
reminderView.root.setOnClickListener {
customGetDialogs.getSelectReminderDia(note.note.uid)
.show(childFragmentManager,"")
}
}
}
private val adapterListener = object:CheckNoteAdapter.CheckNoteAdapterListener{
override fun selectedMenuItem(menuItem: MenuItem, item: ContentNote, position: Int) {
when(menuItem.itemId){
R.id.edit_check_note_menu_item->{
customGetDialogs.getAddCheckNoteItemDia(ParameterAddCheckItem(true,item.text,position))
.show(childFragmentManager,"")
}
R.id.remove_check_note_menu_item->{
customAlerts.showDeleteContentItemsAlert(requireContext()){x,y->
viewModel.removeContentItem(item)
checkNoteAdapter.removeItem(position)
}
}
R.id.copyText_check_note_menu_item->{
val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText(item.text, item.text)
clipboard.setPrimaryClip(clip)
showMessage.showLong(getString(R.string.successfully_copied_text))
}
}
}
override fun editRequestItem(item: ContentNote, position: Int) {
customGetDialogs.getAddCheckNoteItemDia(ParameterAddCheckItem(true,item.text,position))
.show(childFragmentManager,"")
}
override fun selectedItemCount(count: Int) {
if(count>0&&(lastEditState==null || lastEditState==false))
setEditState(true)
actionMode?.invalidate()
}
override fun onStartDrag(viewHolder: RecyclerView.ViewHolder) {
itemTouchHelper.startDrag(viewHolder)
}
}
private fun setUpActionCallback(){
callback=object:ActionMode.Callback{
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
mode?.menuInflater?.inflate(R.menu.action_display_checklist_note_menu,menu)
menu?.findItem(R.id.check_list_save_act_menu_item)?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
menu?.findItem(R.id.check_list_selectAll_act_menu_item)?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
menu?.findItem(R.id.check_list_delete_act_menu_item)?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
val selectedSize=checkNoteAdapter.getSelectedItems().size
val isNotEmpty=selectedSize>0
menu?.findItem(R.id.check_list_delete_act_menu_item)?.isEnabled =isNotEmpty
menu?.findItem(R.id.check_list_copy_act_menu_item)?.isEnabled=isNotEmpty
menu?.findItem(R.id.check_list_move_act_menu_item)?.isEnabled=isNotEmpty
menu?.findItem(R.id.check_list_checkAllNone_act_menu_item)?.isEnabled=isNotEmpty
menu?.findItem(R.id.check_list_checkAll_act_menu_item)?.isEnabled=isNotEmpty
mode?.title=selectedSize.toString()
return true
}
override fun onActionItemClicked(p0: ActionMode?, p1: MenuItem?): Boolean {
when(p1?.itemId){
R.id.check_list_save_act_menu_item->{
actionMode?.finish()
}
R.id.check_list_delete_act_menu_item->{
customAlerts.showDeleteContentItemsAlert(requireContext()){x,y->
val selectedItems = checkNoteAdapter.getSelectedItems()
viewModel.removeContentItems(selectedItems.toList())
checkNoteAdapter.removeItems(selectedItems)
actionMode?.finish()
}
}
R.id.check_list_copy_act_menu_item->{
showCopyMoveDiaFragment(false)
}
R.id.check_list_move_act_menu_item->{
showCopyMoveDiaFragment(true)
}
R.id.check_list_checkAllNone_act_menu_item->{
checkNoteAdapter.setCheckSelectedItems(false)
}
R.id.check_list_checkAll_act_menu_item->{
checkNoteAdapter.setCheckSelectedItems(true)
}
R.id.check_list_selectAll_act_menu_item->{
checkNoteAdapter.selectAllItems()
}
}
return true
}
override fun onDestroyActionMode(p0: ActionMode?) {
actionMode=null
setEditState(false)
}
}
}
private fun showCopyMoveDiaFragment(isMove:Boolean){
val contentNotes = checkNoteAdapter.getSelectedItems()
val noteId=note.note.uid
val copyMoveObject=CheckItemCopyMoveObject(isMove,contentNotes,noteId,requireContext())
customGetDialogs.getCopyMoveDia(copyMoveObject)
.show(childFragmentManager,"")
}
private fun showSelectTagsDia(){
val noteIds=if(note.note.uid!=0L) listOf(note.note.uid)else listOf()
customGetDialogs.getSelectTagsDia(noteIds)
.show(childFragmentManager,"")
}
private fun setTagsAndVisibility(tags:List<Tag>){
binding.showTagsCheckNote.isGone = tags.isEmpty()
binding.showTagsCheckNote.showTags(tags)
}
private fun setShowDate(dateStr:String){
binding.showDateFromCheckNote.text=Utils.getInsideNoteDateFormat(dateStr)
}
private fun setAddCheckNoteItemViews(){
binding.addItemCheckList.imageTextText.let { textView ->
textView.gravity = Gravity.CENTER
textView.text = getText(R.string.add_text)
textView.typeface = Typeface.DEFAULT_BOLD
}
binding.addItemCheckList.imageTextImage.setImageDrawable(ContextCompat.getDrawable(requireContext(),R.drawable.ic_baseline_add_circle_24))
binding.addItemCheckList.root.setOnClickListener {
customGetDialogs.getAddCheckNoteItemDia(ParameterAddCheckItem(false,""))
.show(childFragmentManager,"")
}
binding.addItemCheckListBottom.imageTextText.let { textView ->
textView.gravity = Gravity.CENTER
textView.text = getText(R.string.add_text)
textView.typeface = Typeface.DEFAULT_BOLD
}
binding.addItemCheckListBottom.imageTextImage.setImageDrawable(ContextCompat.getDrawable(requireContext(),R.drawable.ic_baseline_add_circle_24))
binding.addItemCheckListBottom.root.setOnClickListener {
customGetDialogs.getAddCheckNoteItemDia(ParameterAddCheckItem(false,""))
.show(childFragmentManager,"")
}
}
private fun setAddCheckNoteItemVisibility(isEdit: Boolean){
binding.addItemCheckList.root.isVisible=isEdit
binding.addItemCheckListBottom.root.isVisible=isEdit
}
private fun navigateToAllNote(){
popBackCurrentNav()
val rootParameterNote= ParameterRootNote(null, RootNoteDefaultItem(), RootNoteFrom.DEFAULT_NOTE)
navController.navigate(MainNavDirections.actionGlobalNoteFragment(rootParameterNote))
}
private fun navigateToTrash(){
popBackCurrentNav()
val rootParameterNote= ParameterRootNote(null, RootNoteTrashItem(), RootNoteFrom.TRASH_FROM_NOTE)
navController.navigate(MainNavDirections.actionGlobalNoteFragment(rootParameterNote))
}
private fun navigateToArchive(){
popBackCurrentNav()
val rootParameterNote= ParameterRootNote(null, RootNoteArchiveItem(), RootNoteFrom.ARCHIVE_FROM_NOTE)
navController.navigate(MainNavDirections.actionGlobalNoteFragment(rootParameterNote))
}
private fun popBackCurrentNav(inclusive:Boolean=true){
navController.popBackStack(R.id.displayCheckListNoteFragment,inclusive)
}
private fun adjustNavigation(){
val navController= Navigation.findNavController(requireActivity(),R.id.frames)
val onBackPressedCallback=object: OnBackPressedCallback(true){
override fun handleOnBackPressed() {
popBackCurrentNav(false)
navController.navigateUp()
isEnabled=false
}
}
requireActivity().onBackPressedDispatcher.addCallback(onBackPressedCallback)
}
private fun setItemTouchHelper(){
itemTouchHelper=ItemTouchHelper(object:ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN,0){
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val destPos=viewHolder.bindingAdapterPosition
val targetPos=target.bindingAdapterPosition
checkNoteAdapter.swapItems(destPos,targetPos)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
})
itemTouchHelper.attachToRecyclerView(binding.recyclerCheckNote)
}
private fun closeKeyboard(){
imm.hideSoftInputFromWindow(requireActivity().currentFocus?.windowToken,0)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
checkNoteContext.setOnCreateMenu(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
checkNoteContext.setOnPrepareMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.display_note_color_menu_item->{
customGetDialogs.getSelectColorDia(note.note.color)
.show(childFragmentManager,"")
}
R.id.display_note_edit_menu_item->{
setEditState(true)
}
R.id.display_note_remove_menu_item->{
customAlerts.showDeleteNoteToTrashAlert(requireContext()){x,y->
viewModel.sendNoteToTrashWithNoteId(note.note.uid)
if(noteParameter.noteKinds==NoteKinds.ARCHIVE_KIND) navigateToArchive() else navigateToAllNote()
}
}
R.id.display_note_share_menu_item->{
val text=UtilsShareNote.transformContentNotesToText(note.contents,NoteType.CheckList)
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TITLE, note.note.title)
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
startActivity(shareIntent)
}
R.id.display_note_tag_menu_item->{
showSelectTagsDia()
}
R.id.display_note_set_reminder_menu_item->{
customGetDialogs.getSelectReminderDia(note.note.uid)
.show(childFragmentManager,"")
}
R.id.achieve_add_menu_item->{
note.note.kindNote=NoteKinds.ARCHIVE_KIND
viewModel.changeNoteKindsWithNoteId(note.note.uid,NoteKinds.ARCHIVE_KIND)
navigateToAllNote()
}
R.id.achieve_remove_menu_item->{
note.note.kindNote=NoteKinds.ALL_KIND
viewModel.changeNoteKindsWithNoteId(note.note.uid,NoteKinds.ALL_KIND)
navigateToArchive()
}
R.id.remove_notes_forever_act_trash_menu_item->{
customAlerts.showDeleteNoteForEverAlert(requireContext()){x,y->
viewModel.deleteNoteForEver(note.note.uid)
navigateToTrash()
}
}
R.id.restore_notes_act_trash_menu_item->{
customAlerts.showRestoreNoteAlert(requireContext()){x,y->
viewModel.recoverNote(note.note.uid)
}
}
R.id.check_list_remove_checked_notes_menu_item->{
customAlerts.showDeleteContentItemsAlert(requireContext()){x,y->
val items=checkNoteAdapter.items.filter { it.isCheck }
viewModel.removeContentItems(items.toList())
checkNoteAdapter.removeItems(items)
}
}
R.id.select_font_note_menu_item->{
customAlerts.showSelectFontSizeAlert(requireContext(),sharedPreferences) { pos: Int, textSize: Int ->
setFontSize(textSize.toFloat())
}
}
}
return super.onOptionsItemSelected(item)
}
override fun onPause() {
super.onPause()
viewModel.saveNote(note,lastSavedNote)
}
override fun onDestroyView() {
super.onDestroyView()
actionMode?.finish()
if(navController.currentDestination?.id!=R.id.displayCheckListNoteFragment)
viewModel.lastCheckNote(note)
_binding=null
if(!MainActivity.isPremiumActive)
mInterstitialAd?.show(requireActivity())
}
} | 0 | Kotlin | 0 | 0 | 886e40f402573bb2af517432bec48fa5628a5a0d | 30,740 | Note-X | Apache License 2.0 |
ggdsl-api/src/main/kotlin/org/jetbrains/kotlinx/ggdsl/dsl/kProp.kt | Kotlin | 502,039,936 | false | null | /*
* Copyright 2020-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.ggdsl.dsl
import org.jetbrains.kotlinx.dataframe.api.column
import org.jetbrains.kotlinx.dataframe.columns.ColumnReference
import org.jetbrains.kotlinx.ggdsl.ir.bindings.*
import org.jetbrains.kotlinx.ggdsl.ir.scale.NonPositionalScale
import org.jetbrains.kotlinx.ggdsl.ir.scale.NonPositionalUnspecifiedScale
import org.jetbrains.kotlinx.ggdsl.ir.scale.PositionalScale
import org.jetbrains.kotlinx.ggdsl.ir.scale.PositionalUnspecifiedScale
import kotlin.reflect.KProperty
import kotlin.reflect.typeOf
//TODO
@PublishedApi
internal inline fun <reified T> KProperty<T>.toColumnReference(): ColumnReference<T> =
column(this.name)
/**
* Maps the given [KProperty] (i.e. a column with the same name and type as the given property)
* to this non-scalable positional ("sub-positional") aesthetic attribute.
*
* @param property the mapped [KProperty].
*/
public inline operator fun <reified DomainType> NonScalablePositionalAes.invoke(
property: KProperty<DomainType>
) {
context.bindingCollector.mappings[this.name] =
NonScalablePositionalMapping(this.name, property.toColumnReference(), typeOf<DomainType>())
}
/**
* Maps the given [KProperty] (i.e. a column with the same name and type as the given property)
* to this positional aesthetic attribute with a default (i.e. without specifying the type and parameters;
* they will be defined automatically) scale.
*
* @param property the mapped [KProperty].
*/
public inline operator fun <reified DomainType> ScalablePositionalAes.invoke(
property: KProperty<DomainType>
): ScaledUnspecifiedDefaultPositionalMapping<DomainType> {
val mapping = ScaledUnspecifiedDefaultPositionalMapping<DomainType>(
this.name,
property.toColumnReference().scaled(),
typeOf<DomainType>()
)
context.bindingCollector.mappings[this.name] = mapping
return mapping
}
/**
* Maps the given [KProperty] (i.e. a column with the same name and type as the given property)
* to this non-positional aesthetic attribute with a default (i.e. without specifying the type and parameters;
* they will be defined automatically) scale.
*
* @param property the mapped [KProperty].
*/
public inline operator fun <reified DomainType, RangeType> ScalableNonPositionalAes<RangeType>.invoke(
property: KProperty<DomainType>
): ScaledUnspecifiedDefaultNonPositionalMapping<DomainType, RangeType> {
val mapping = ScaledUnspecifiedDefaultNonPositionalMapping<DomainType, RangeType>(
this.name,
property.toColumnReference().scaled(),
typeOf<DomainType>()
)
context.bindingCollector.mappings[this.name] = mapping
return mapping
}
/**
* Applies default (i.e. without specifying the type and parameters;
* they will be defined automatically; can be both used for positional and non-positional mappings) scale
* to this [KProperty] (i.e. a column with the same name and type as the given property).
*/
public inline fun <reified DomainType> KProperty<DomainType>.scaled()
: ColumnScaledUnspecifiedDefault<DomainType> =
ColumnScaledUnspecifiedDefault(this.toColumnReference())
/**
* Applies unspecified (i.e. without specifying the type and parameters;
* they will be defined automatically) positional scale to this [KProperty] (i.e. a column with the same
* name and type as the given property).
*
* @param DomainType type of domain.
* @param scale positional default scale.
* @return scaled source.
*/
public inline fun <reified DomainType> KProperty<DomainType>.scaled(scale: PositionalUnspecifiedScale):
ColumnScaledPositionalUnspecified<DomainType> =
ColumnScaledPositionalUnspecified(this.toColumnReference(), scale)
/**
* Applies unspecified (i.e. without specifying the type and parameters;
* they will be defined automatically) non-positional scale to this [KProperty] (i.e. a column with the same
* name and type as the given property).
*
* @param DomainType type of domain.
* @param scale non-positional default scale.
* @return scaled source.
*/
public inline fun <reified DomainType> KProperty<DomainType>.scaled(scale: NonPositionalUnspecifiedScale):
ColumnScaledNonPositionalUnspecified<DomainType> =
ColumnScaledNonPositionalUnspecified(this.toColumnReference(), scale)
/**
* Applies positional scale to this [KProperty] (i.e. a column with the same name
* and type as the given property).
*
* @param DomainType type of domain.
* @param scale positional scale.
* @return scaled source.
*/
public inline fun <reified DomainType> KProperty<DomainType>.scaled(
scale: PositionalScale<DomainType>
): ColumnScaledPositional<DomainType> = ColumnScaledPositional(this.toColumnReference(), scale)
/**
* Applies non-positional scale to this [KProperty] (i.e. a column with the same name
* and type as the given property).
*
* @param DomainType type of domain.
* @param scale non-positional scale.
* @return scaled source.
*/
public inline fun <reified DomainType, RangeType> KProperty<DomainType>.scaled(
scale: NonPositionalScale<DomainType, RangeType>
): ColumnScaledNonPositional<DomainType, RangeType> = ColumnScaledNonPositional(this.toColumnReference(), scale)
| 48 | Kotlin | 1 | 44 | 8a161098d0d946c28bde3cf3c7bea6a1eeba073c | 5,311 | ggdsl | Apache License 2.0 |
app/src/main/java/com/wcsm/confectionaryadmin/ui/view/InfoScreen.kt | WallaceMartinsTI | 835,736,123 | false | {"Kotlin": 410093} | package com.wcsm.confectionaryadmin.ui.view
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.wcsm.confectionaryadmin.R
import com.wcsm.confectionaryadmin.data.model.navigation.Screen
import com.wcsm.confectionaryadmin.ui.components.DialogConfirmDeleteUser
import com.wcsm.confectionaryadmin.ui.components.CustomLoading
import com.wcsm.confectionaryadmin.ui.components.DeleteButton
import com.wcsm.confectionaryadmin.ui.components.PrimaryButton
import com.wcsm.confectionaryadmin.ui.components.DialogSync
import com.wcsm.confectionaryadmin.ui.theme.AppBackgroundColor
import com.wcsm.confectionaryadmin.ui.theme.AppTitleGradientColor
import com.wcsm.confectionaryadmin.ui.theme.InterFontFamily
import com.wcsm.confectionaryadmin.ui.theme.PrimaryColor
import com.wcsm.confectionaryadmin.ui.util.showToastMessage
import com.wcsm.confectionaryadmin.ui.viewmodel.CustomersViewModel
import com.wcsm.confectionaryadmin.ui.viewmodel.InfoViewModel
import com.wcsm.confectionaryadmin.ui.viewmodel.LoginViewModel
import com.wcsm.confectionaryadmin.ui.viewmodel.OrdersViewModel
@Composable
fun InfoScreen(
paddingValues: PaddingValues,
externalNavController: NavController,
customersViewModel: CustomersViewModel,
ordersViewModel: OrdersViewModel,
loginViewModel: LoginViewModel,
infoViewModel: InfoViewModel = hiltViewModel()
) {
val context = LocalContext.current
val clipboardManager = LocalClipboardManager.current
val uriHandler = LocalUriHandler.current
val fetchedUser by infoViewModel.fetchedUser.collectAsState()
val isSyncSuccess by infoViewModel.isSyncSuccess.collectAsState()
val isSyncLoading by infoViewModel.isSyncLoading.collectAsState()
val isUserDeleted by infoViewModel.isUserDeleted.collectAsState()
val allUserDataDeleted by infoViewModel.allUserDataDeleted.collectAsState()
val confirmSyncDownDialogPreference by loginViewModel.showConfirmSyncDownDialog.collectAsState()
val isConnected by loginViewModel.isConnected.collectAsState()
var syncText by rememberSaveable { mutableStateOf("") }
var isSincronized by rememberSaveable { mutableStateOf(false) }
var showSyncDownConfirmDialog by remember { mutableStateOf(false) }
var isUserDataLoading by rememberSaveable { mutableStateOf(true) }
val isDeletingUserLoading by infoViewModel.isDeletingUserLoading.collectAsState()
var showDeleteUserDialog by remember { mutableStateOf(false) }
var showConfirmDeleteUserDialog by remember { mutableStateOf(false) }
var userName by rememberSaveable { mutableStateOf("") }
var userCustomers by rememberSaveable { mutableStateOf("") }
var userOrders by rememberSaveable { mutableStateOf("") }
var userSince by rememberSaveable { mutableStateOf("") }
val devEmail = "<EMAIL>"
val devLinkedin = "https://www.linkedin.com/in/wallace-martins-ti/"
LaunchedEffect(Unit) {
loginViewModel.checkConnection()
if(isConnected) {
infoViewModel.fetchUserData()
}
}
LaunchedEffect(fetchedUser) {
Log.i("#-# TESTE #-#", "fetchedUser: $fetchedUser")
if(fetchedUser != null) {
val name = fetchedUser!!.name
val customers = fetchedUser!!.customers
val orders = fetchedUser!!.orders
val since = fetchedUser!!.userSince
userName = createAnnotatedString("Nome: ",name).toString()
userCustomers = createAnnotatedString("Clientes: ", customers).toString()
userOrders = createAnnotatedString("Pedidos: ", orders).toString()
userSince = createAnnotatedString("Conta criada em: ", since).toString()
isUserDataLoading = false
}
}
LaunchedEffect(confirmSyncDownDialogPreference) {
loginViewModel.checkShowSyncDownConfirmDialog()
}
LaunchedEffect(allUserDataDeleted) {
if(allUserDataDeleted) {
infoViewModel.deleteUser()
}
}
LaunchedEffect(isUserDeleted) {
if(isUserDeleted) {
loginViewModel.clearLoggedUser()
externalNavController.navigate(Screen.Login.route)
}
}
LaunchedEffect(ordersViewModel.ordersWithCustomer, customersViewModel.customers) {
isSincronized = false
}
LaunchedEffect(isSyncSuccess) {
if(isSyncSuccess) {
showToastMessage(context, "Dados buscados da nuvem com sucesso!")
customersViewModel.getAllCustomers()
ordersViewModel.getAllOrders()
isSincronized = true
Log.i("#-# SYNC #-#", "Data fetched from Firestore to Room successfully")
}
}
LaunchedEffect(isSyncLoading) {
syncText = if(isSyncLoading) "SINCRONIZANDO..." else "BAIXAR DA NUVEM"
}
Column(
modifier = Modifier
.background(AppBackgroundColor)
.fillMaxSize()
.padding(paddingValues),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.screen_title_info_screen),
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 40.sp,
style = TextStyle(
brush = AppTitleGradientColor
),
modifier = Modifier.padding(top = 16.dp)
)
Spacer(modifier = Modifier.height(12.dp))
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp)
.verticalScroll(rememberScrollState())
.weight(1f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_user_info)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
if(isDeletingUserLoading) {
CustomLoading(size = 40.dp)
} else {
if(isUserDataLoading) {
CustomLoading(size = 40.dp)
} else {
Column {
Text(
text = userName,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
Text(
text = userCustomers,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
Text(
text = userOrders,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
Text(
text = userSince,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
HorizontalDivider(
color = Color.White, modifier = Modifier.padding(vertical = 8.dp)
)
DeleteButton(text = stringResource(id = R.string.btn_text_delete_user)) {
showDeleteUserDialog = true
}
}
}
}
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_about_app)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
Text(
text = stringResource(id = R.string.info_screen_about_app_description),
fontFamily = InterFontFamily,
fontSize = 18.sp,
textAlign = TextAlign.Justify
)
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_already_used_our_app)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
Text(
text = stringResource(id = R.string.info_screen_already_used_description),
fontFamily = InterFontFamily,
fontSize = 18.sp,
textAlign = TextAlign.Justify
)
Spacer(modifier = Modifier.height(4.dp))
PrimaryButton(
text = if(isSincronized) "ATUALIZADO" else syncText,
textColor = Color.White,
icon = Icons.Default.CloudSync
) {
loginViewModel.checkConnection()
if(!isSincronized) {
loginViewModel.checkShowSyncDownConfirmDialog()
if(confirmSyncDownDialogPreference != true) {
showSyncDownConfirmDialog = true
} else {
if (isConnected) {
loginViewModel.checkConnection()
infoViewModel.fetchUserCustomersAndOrders()
} else {
showToastMessage(context, "Sem conexão no momento")
}
}
}
}
}
if(showSyncDownConfirmDialog) {
DialogSync(
isSendingFromRoomToFirestore = false,
onDontShowAgain = {
loginViewModel.changeSyncDownConfirmDialogPreference(it)
},
onDismiss = { showSyncDownConfirmDialog = false }
) {
loginViewModel.checkConnection()
if (isConnected) {
loginViewModel.checkConnection()
infoViewModel.fetchUserCustomersAndOrders()
} else {
showToastMessage(context, "Sem conexão no momento")
}
}
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_about_me)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Image(
painter = painterResource(id = R.drawable.me),
contentDescription = null,
modifier = Modifier
.size(80.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Text(
text = "<NAME>\n25 Anos\nDesenvolvedor Android",
color = Color.White,
fontFamily = InterFontFamily,
fontWeight = FontWeight.SemiBold
)
}
HorizontalDivider(
color = Color.White,
modifier = Modifier.padding(vertical = 4.dp)
)
ContactContainer(
text = "COPIAR E-MAIL",
vectorIcon = Icons.Default.Email,
trailingIcon = Icons.Default.ContentCopy
) {
clipboardManager.setText(AnnotatedString(devEmail))
showToastMessage(context, "E-mail copiado!")
}
Spacer(modifier = Modifier.height(8.dp))
ContactContainer(
text = "ABRIR LINKEDIN",
painterIcon = painterResource(id = R.drawable.linkedin_icon),
trailingIcon = Icons.Default.OpenInBrowser
) {
uriHandler.openUri(devLinkedin)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
if(showDeleteUserDialog) {
DialogConfirmDeleteUser(
title = "Deletar Usuário",
message = "Deseja deletar sua conta de usuário?",
onConfirmText = "Deletar Usuário",
onDismiss = { showDeleteUserDialog = false }
) {
showConfirmDeleteUserDialog = true
}
}
if(showConfirmDeleteUserDialog) {
DialogConfirmDeleteUser(
title = "Confirmação Deletar Usuário",
message = "Tem certeza que deseja deletar sua conta de usuário?",
onConfirmText = "Confirmar e Deletar",
onDismiss = { showConfirmDeleteUserDialog = false }
) {
if(isConnected) {
infoViewModel.deleteAllUserData()
} else {
showToastMessage(context, "Sem conexão no momento, tente mais tarde.")
}
}
}
}
}
}
@Composable
private fun CustomTitle(text: String) {
Text(
text = text,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.SemiBold,
fontSize = 24.sp
)
}
@Composable
private fun CustomContainer(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Column(
modifier = modifier
.width(300.dp)
.border(1.dp, Color.White, RoundedCornerShape(15.dp))
.padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
content()
}
}
@Composable
private fun ContactContainer(
text: String,
vectorIcon: ImageVector? = null,
painterIcon: Painter? = null,
trailingIcon: ImageVector,
onClick: () -> Unit
) {
Row(
modifier = Modifier
.clip(RoundedCornerShape(15.dp))
.clickable { onClick() }
.fillMaxWidth()
.border(1.dp, PrimaryColor, RoundedCornerShape(15.dp))
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
if(vectorIcon != null) {
Icon(
imageVector = vectorIcon,
contentDescription = null,
tint = PrimaryColor
)
} else if(painterIcon != null) {
Icon(
painter = painterIcon,
contentDescription = null,
tint = PrimaryColor,
modifier = Modifier.size(20.dp)
)
}
Text(
text = text,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.SemiBold,
fontSize = 14.sp,
)
Icon(
imageVector = trailingIcon,
contentDescription = null,
tint = PrimaryColor
)
}
}
private fun createAnnotatedString(title: String, content: String): AnnotatedString {
return buildAnnotatedString {
append(title)
withStyle(
style = SpanStyle(color = Color.White, fontWeight = FontWeight.Normal)
) {
append(content)
}
}
} | 0 | Kotlin | 0 | 1 | 975edc2d7591ce648dd6062218465ff5069e1f8c | 19,933 | ConfectioneryAdmin | MIT License |
app/src/main/java/com/wcsm/confectionaryadmin/ui/view/InfoScreen.kt | WallaceMartinsTI | 835,736,123 | false | {"Kotlin": 410093} | package com.wcsm.confectionaryadmin.ui.view
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.wcsm.confectionaryadmin.R
import com.wcsm.confectionaryadmin.data.model.navigation.Screen
import com.wcsm.confectionaryadmin.ui.components.DialogConfirmDeleteUser
import com.wcsm.confectionaryadmin.ui.components.CustomLoading
import com.wcsm.confectionaryadmin.ui.components.DeleteButton
import com.wcsm.confectionaryadmin.ui.components.PrimaryButton
import com.wcsm.confectionaryadmin.ui.components.DialogSync
import com.wcsm.confectionaryadmin.ui.theme.AppBackgroundColor
import com.wcsm.confectionaryadmin.ui.theme.AppTitleGradientColor
import com.wcsm.confectionaryadmin.ui.theme.InterFontFamily
import com.wcsm.confectionaryadmin.ui.theme.PrimaryColor
import com.wcsm.confectionaryadmin.ui.util.showToastMessage
import com.wcsm.confectionaryadmin.ui.viewmodel.CustomersViewModel
import com.wcsm.confectionaryadmin.ui.viewmodel.InfoViewModel
import com.wcsm.confectionaryadmin.ui.viewmodel.LoginViewModel
import com.wcsm.confectionaryadmin.ui.viewmodel.OrdersViewModel
@Composable
fun InfoScreen(
paddingValues: PaddingValues,
externalNavController: NavController,
customersViewModel: CustomersViewModel,
ordersViewModel: OrdersViewModel,
loginViewModel: LoginViewModel,
infoViewModel: InfoViewModel = hiltViewModel()
) {
val context = LocalContext.current
val clipboardManager = LocalClipboardManager.current
val uriHandler = LocalUriHandler.current
val fetchedUser by infoViewModel.fetchedUser.collectAsState()
val isSyncSuccess by infoViewModel.isSyncSuccess.collectAsState()
val isSyncLoading by infoViewModel.isSyncLoading.collectAsState()
val isUserDeleted by infoViewModel.isUserDeleted.collectAsState()
val allUserDataDeleted by infoViewModel.allUserDataDeleted.collectAsState()
val confirmSyncDownDialogPreference by loginViewModel.showConfirmSyncDownDialog.collectAsState()
val isConnected by loginViewModel.isConnected.collectAsState()
var syncText by rememberSaveable { mutableStateOf("") }
var isSincronized by rememberSaveable { mutableStateOf(false) }
var showSyncDownConfirmDialog by remember { mutableStateOf(false) }
var isUserDataLoading by rememberSaveable { mutableStateOf(true) }
val isDeletingUserLoading by infoViewModel.isDeletingUserLoading.collectAsState()
var showDeleteUserDialog by remember { mutableStateOf(false) }
var showConfirmDeleteUserDialog by remember { mutableStateOf(false) }
var userName by rememberSaveable { mutableStateOf("") }
var userCustomers by rememberSaveable { mutableStateOf("") }
var userOrders by rememberSaveable { mutableStateOf("") }
var userSince by rememberSaveable { mutableStateOf("") }
val devEmail = "<EMAIL>"
val devLinkedin = "https://www.linkedin.com/in/wallace-martins-ti/"
LaunchedEffect(Unit) {
loginViewModel.checkConnection()
if(isConnected) {
infoViewModel.fetchUserData()
}
}
LaunchedEffect(fetchedUser) {
Log.i("#-# TESTE #-#", "fetchedUser: $fetchedUser")
if(fetchedUser != null) {
val name = fetchedUser!!.name
val customers = fetchedUser!!.customers
val orders = fetchedUser!!.orders
val since = fetchedUser!!.userSince
userName = createAnnotatedString("Nome: ",name).toString()
userCustomers = createAnnotatedString("Clientes: ", customers).toString()
userOrders = createAnnotatedString("Pedidos: ", orders).toString()
userSince = createAnnotatedString("Conta criada em: ", since).toString()
isUserDataLoading = false
}
}
LaunchedEffect(confirmSyncDownDialogPreference) {
loginViewModel.checkShowSyncDownConfirmDialog()
}
LaunchedEffect(allUserDataDeleted) {
if(allUserDataDeleted) {
infoViewModel.deleteUser()
}
}
LaunchedEffect(isUserDeleted) {
if(isUserDeleted) {
loginViewModel.clearLoggedUser()
externalNavController.navigate(Screen.Login.route)
}
}
LaunchedEffect(ordersViewModel.ordersWithCustomer, customersViewModel.customers) {
isSincronized = false
}
LaunchedEffect(isSyncSuccess) {
if(isSyncSuccess) {
showToastMessage(context, "Dados buscados da nuvem com sucesso!")
customersViewModel.getAllCustomers()
ordersViewModel.getAllOrders()
isSincronized = true
Log.i("#-# SYNC #-#", "Data fetched from Firestore to Room successfully")
}
}
LaunchedEffect(isSyncLoading) {
syncText = if(isSyncLoading) "SINCRONIZANDO..." else "BAIXAR DA NUVEM"
}
Column(
modifier = Modifier
.background(AppBackgroundColor)
.fillMaxSize()
.padding(paddingValues),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.screen_title_info_screen),
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 40.sp,
style = TextStyle(
brush = AppTitleGradientColor
),
modifier = Modifier.padding(top = 16.dp)
)
Spacer(modifier = Modifier.height(12.dp))
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp)
.verticalScroll(rememberScrollState())
.weight(1f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_user_info)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
if(isDeletingUserLoading) {
CustomLoading(size = 40.dp)
} else {
if(isUserDataLoading) {
CustomLoading(size = 40.dp)
} else {
Column {
Text(
text = userName,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
Text(
text = userCustomers,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
Text(
text = userOrders,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
Text(
text = userSince,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.Bold
)
HorizontalDivider(
color = Color.White, modifier = Modifier.padding(vertical = 8.dp)
)
DeleteButton(text = stringResource(id = R.string.btn_text_delete_user)) {
showDeleteUserDialog = true
}
}
}
}
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_about_app)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
Text(
text = stringResource(id = R.string.info_screen_about_app_description),
fontFamily = InterFontFamily,
fontSize = 18.sp,
textAlign = TextAlign.Justify
)
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_already_used_our_app)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
Text(
text = stringResource(id = R.string.info_screen_already_used_description),
fontFamily = InterFontFamily,
fontSize = 18.sp,
textAlign = TextAlign.Justify
)
Spacer(modifier = Modifier.height(4.dp))
PrimaryButton(
text = if(isSincronized) "ATUALIZADO" else syncText,
textColor = Color.White,
icon = Icons.Default.CloudSync
) {
loginViewModel.checkConnection()
if(!isSincronized) {
loginViewModel.checkShowSyncDownConfirmDialog()
if(confirmSyncDownDialogPreference != true) {
showSyncDownConfirmDialog = true
} else {
if (isConnected) {
loginViewModel.checkConnection()
infoViewModel.fetchUserCustomersAndOrders()
} else {
showToastMessage(context, "Sem conexão no momento")
}
}
}
}
}
if(showSyncDownConfirmDialog) {
DialogSync(
isSendingFromRoomToFirestore = false,
onDontShowAgain = {
loginViewModel.changeSyncDownConfirmDialogPreference(it)
},
onDismiss = { showSyncDownConfirmDialog = false }
) {
loginViewModel.checkConnection()
if (isConnected) {
loginViewModel.checkConnection()
infoViewModel.fetchUserCustomersAndOrders()
} else {
showToastMessage(context, "Sem conexão no momento")
}
}
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CustomTitle(
text = stringResource(id = R.string.info_screen_about_me)
)
Spacer(modifier = Modifier.height(4.dp))
CustomContainer {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Image(
painter = painterResource(id = R.drawable.me),
contentDescription = null,
modifier = Modifier
.size(80.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Text(
text = "<NAME>\n25 Anos\nDesenvolvedor Android",
color = Color.White,
fontFamily = InterFontFamily,
fontWeight = FontWeight.SemiBold
)
}
HorizontalDivider(
color = Color.White,
modifier = Modifier.padding(vertical = 4.dp)
)
ContactContainer(
text = "COPIAR E-MAIL",
vectorIcon = Icons.Default.Email,
trailingIcon = Icons.Default.ContentCopy
) {
clipboardManager.setText(AnnotatedString(devEmail))
showToastMessage(context, "E-mail copiado!")
}
Spacer(modifier = Modifier.height(8.dp))
ContactContainer(
text = "ABRIR LINKEDIN",
painterIcon = painterResource(id = R.drawable.linkedin_icon),
trailingIcon = Icons.Default.OpenInBrowser
) {
uriHandler.openUri(devLinkedin)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
if(showDeleteUserDialog) {
DialogConfirmDeleteUser(
title = "Deletar Usuário",
message = "Deseja deletar sua conta de usuário?",
onConfirmText = "Deletar Usuário",
onDismiss = { showDeleteUserDialog = false }
) {
showConfirmDeleteUserDialog = true
}
}
if(showConfirmDeleteUserDialog) {
DialogConfirmDeleteUser(
title = "Confirmação Deletar Usuário",
message = "Tem certeza que deseja deletar sua conta de usuário?",
onConfirmText = "Confirmar e Deletar",
onDismiss = { showConfirmDeleteUserDialog = false }
) {
if(isConnected) {
infoViewModel.deleteAllUserData()
} else {
showToastMessage(context, "Sem conexão no momento, tente mais tarde.")
}
}
}
}
}
}
@Composable
private fun CustomTitle(text: String) {
Text(
text = text,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.SemiBold,
fontSize = 24.sp
)
}
@Composable
private fun CustomContainer(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Column(
modifier = modifier
.width(300.dp)
.border(1.dp, Color.White, RoundedCornerShape(15.dp))
.padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
content()
}
}
@Composable
private fun ContactContainer(
text: String,
vectorIcon: ImageVector? = null,
painterIcon: Painter? = null,
trailingIcon: ImageVector,
onClick: () -> Unit
) {
Row(
modifier = Modifier
.clip(RoundedCornerShape(15.dp))
.clickable { onClick() }
.fillMaxWidth()
.border(1.dp, PrimaryColor, RoundedCornerShape(15.dp))
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
if(vectorIcon != null) {
Icon(
imageVector = vectorIcon,
contentDescription = null,
tint = PrimaryColor
)
} else if(painterIcon != null) {
Icon(
painter = painterIcon,
contentDescription = null,
tint = PrimaryColor,
modifier = Modifier.size(20.dp)
)
}
Text(
text = text,
color = PrimaryColor,
fontFamily = InterFontFamily,
fontWeight = FontWeight.SemiBold,
fontSize = 14.sp,
)
Icon(
imageVector = trailingIcon,
contentDescription = null,
tint = PrimaryColor
)
}
}
private fun createAnnotatedString(title: String, content: String): AnnotatedString {
return buildAnnotatedString {
append(title)
withStyle(
style = SpanStyle(color = Color.White, fontWeight = FontWeight.Normal)
) {
append(content)
}
}
} | 0 | Kotlin | 0 | 1 | 975edc2d7591ce648dd6062218465ff5069e1f8c | 19,933 | ConfectioneryAdmin | MIT License |
src/main/kotlin/io/kungfury/coworker/dbs/postgres/PgConnectionManager.kt | SecurityInsanity | 145,881,173 | false | {"XML": 1, "Maven POM": 4, "Markdown": 19, "Text": 1, "Ignore List": 1, "YAML": 4, "Shell": 6, "Kotlin": 35, "Java": 16, "SQL": 2, "HTML": 1} | package io.kungfury.coworker.dbs.postgres
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import io.kungfury.coworker.dbs.ConnectionManager
import io.kungfury.coworker.dbs.ConnectionType
import io.kungfury.coworker.dbs.Marginalia
import io.kungfury.coworker.dbs.TextSafety
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Metrics
import io.micrometer.core.instrument.Tag
import io.micrometer.core.instrument.Tags
import io.micrometer.core.instrument.Timer
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import org.postgresql.PGConnection
import org.slf4j.LoggerFactory
import java.io.IOException
import java.sql.Connection
import java.time.Duration
import java.time.Instant
import java.util.concurrent.TimeoutException
import java.util.function.Function
/**
* Manages a connection pool to postgres.
*/
class PgConnectionManager : ConnectionManager {
private val LOGGER = LoggerFactory.getLogger(PgConnectionManager::class.java)
private val connectionPool: HikariDataSource
private val timeoutLong: Long?
private var metricRegistry: MeterRegistry = Metrics.globalRegistry
private val queryTimer: Timer
/**
* A generic java compatible constructor for PgConnectionManager.
*
* @param configureSource
* A function that takes in a "HikariConfig" object, configures it, and returns a configured HikariConfig.
* @param timeout
* An optional timeout in ms. Defaults to 300000L.
* @param metricRegistry
* The metric registry to use.
*/
constructor(configureSource: Function<HikariConfig, HikariConfig>, timeout: Long?, metricRegistry: MeterRegistry? = null) {
val finalizedConfig = configureSource.apply(HikariConfig())
connectionPool = HikariDataSource(finalizedConfig)
timeoutLong = timeout
if (metricRegistry != null) {
this.metricRegistry = metricRegistry
}
queryTimer = this.metricRegistry.timer("coworker.pg.query_time", Tags.empty())
}
/**
* A PgConnectionManager constructor built specifically for kotlin.
*
* @param configureSource
* A block that takes a HikariConfig, configures it, and returns a configured HikariConfig.
*/
constructor(configureSource: (toConfigure: HikariConfig) -> HikariConfig) {
val finalizedConfig = configureSource(HikariConfig())
connectionPool = HikariDataSource(finalizedConfig)
timeoutLong = null
queryTimer = this.metricRegistry.timer("coworker.pg.query_time", Tags.empty())
}
/**
* A PgConnectionManager constructor built specifically for kotlin with timeout.
*
* @param configureSource
* A block that takes a HikariConfig, configures it, and returns a configured HikariConfig.
* @param timeout
* An optional timeout value.
*/
constructor(configureSource: (toConfigure: HikariConfig) -> HikariConfig, timeout: Long?) {
val finalizedConfig = configureSource(HikariConfig())
connectionPool = HikariDataSource(finalizedConfig)
timeoutLong = timeout
queryTimer = this.metricRegistry.timer("coworker.pg.query_time", Tags.empty())
}
/**
* A PgConnectionManager constructor built specifically for kotlin with timeout.
*
* @param configureSource
* A block that takes a HikariConfig, configures it, and returns a configured HikariConfig.
* @param timeout
* An optional timeout value.
* @param meterRegistry
* The metric registry to use
*/
constructor(configureSource: (toConfigure: HikariConfig) -> HikariConfig, timeout: Long?, meterRegistry: MeterRegistry?) {
val finalizedConfig = configureSource(HikariConfig())
connectionPool = HikariDataSource(finalizedConfig)
timeoutLong = timeout
if (meterRegistry != null) {
this.metricRegistry = meterRegistry
}
queryTimer = this.metricRegistry.timer("coworker.pg.query_time", Tags.empty())
}
override val TIMEOUT_MS
get() = if (timeoutLong == null) {
300000L
} else {
timeoutLong
}
override val CONNECTION_TYPE: ConnectionType = ConnectionType.POSTGRES
@Throws(TimeoutCancellationException::class, IOException::class, IllegalStateException::class)
override fun <T> executeTransaction(query: Function<Connection, T>, commitOnExit: Boolean): T {
return queryTimer.recordCallable {
runBlocking {
withTimeout(TIMEOUT_MS) {
CoroutineName("Coworker - ExecuteTransactionJava")
var result: T? = null
var error: Exception? = null
var conn: Connection? = null
try {
conn = connectionPool.connection
conn.autoCommit = false
result = query.apply(conn)
if (commitOnExit) {
conn.commit()
}
} catch (e: Exception) {
if (conn != null) {
conn.rollback()
error = e
}
} finally {
if (conn != null) {
conn.close()
}
}
if (!isActive) {
throw TimeoutException("Failed to complete in time!")
}
if (error != null) {
throw error
}
if (result == null) {
throw IllegalStateException("Result was null at the end of executeTransactionJava")
} else {
result
}
}
}
}
}
@Throws(TimeoutCancellationException::class, IOException::class, IllegalStateException::class)
override suspend fun <T> executeTransaction(query: suspend (Connection) -> T, commitOnExit: Boolean): T {
return withTimeout(TIMEOUT_MS) {
CoroutineName("Coworker - ExecuteTransaction")
val timeStart = Instant.now()
var result: T? = null
var error: Exception? = null
var conn: Connection? = null
try {
conn = connectionPool.connection
conn.autoCommit = false
result = query(conn)
if (commitOnExit) {
conn.commit()
}
} catch (e: Exception) {
if (conn != null) {
conn.rollback()
}
error = e
} finally {
if (conn != null) {
conn.close()
}
}
val timeEnd = Instant.now()
queryTimer.record(Duration.between(timeStart, timeEnd))
if (!isActive) {
throw TimeoutException("Failed to complete in time!")
}
if (error != null) {
throw error
}
if (result == null) {
throw IllegalStateException("Result was null at the end of executeTransaction")
} else {
result
}
}
}
@UseExperimental(ExperimentalCoroutinesApi::class)
override fun listenToChannel(channel: String, failureLimit: Short): ReceiveChannel<String> {
val failureGauge = this.metricRegistry.gauge("coworker.listen.failure_gauge", Tags.of(Tag.of("channel", channel)), 0)
return GlobalScope.produce {
CoroutineName("PostgresListen($channel)")
// So all in all this is subpar.
//
// Why is this subpar do you ask? Well because postgres keeps LISTEN/NOTIFY setup to one connection.
// Meaning there's no way to efficiently only use one connection from the thread pool whenever we need it.
// We always have to bogart one connection for LISTEN/NOTIFY.
//
// It's also subpar because there's no real way to know if we've got a transient failure, or if we need
// to reconnect to the db. Even if we were to enumerate all exception possibilities, differing architectures
// may mean something is "transient" while in someone elses architecture it isn't.
//
// So this method attempts to be "acceptable to failures". Everytime we get an error we'll increase a
// counter. If the counter hits failureLimit, we determine "this is a bad connection",
// and attempt to get a new one. If we fail to get a new connection the channel closes and you should reopen.
var raw_conn: Connection? = null
var conn: PGConnection?
var counter = 0
try {
raw_conn = connectionPool.connection
conn = raw_conn.unwrap(PGConnection::class.java)
// Ensure we only have a valid channel name, and not some rando sql injection.
val newChannel = TextSafety.EnforceStringPurity(channel)
if (newChannel != channel) {
throw IllegalStateException("invalid channel name!")
}
val statement = raw_conn.createStatement()
statement.execute(Marginalia.AddMarginalia("PgConnectionManager_listenToChannel", "LISTEN $newChannel"))
statement.close()
while (true) {
if (counter >= failureLimit) {
raw_conn = connectionPool.connection
conn = raw_conn.unwrap(PGConnection::class.java)
}
// Assert we have valid values.
raw_conn!!
conn!!
try {
// Execute a query to ensure we can connect to the backend.
val stmt = raw_conn.createStatement()
stmt.execute(Marginalia.AddMarginalia("PgConnectionManager_selectOnlineCheck", "SELECT 1"))
stmt.close()
conn.notifications?.forEach { pgNotification ->
if (pgNotification.name.equals(channel)) {
val param: String? = pgNotification.parameter
if (param != null) {
send(param)
}
}
}
if (counter > 0) {
failureGauge?.dec()
counter--
}
} catch (err: Exception) {
LOGGER.error("Failed to check for notification on connection!\n${err.message}\n" +
" ${err.stackTrace.joinToString("\n ")}")
failureGauge?.inc()
counter++
}
delay(500)
}
} catch (err: Exception) {
LOGGER.error("Failed to setup listen channel, or listen channel has thrown unknown exception.\n" +
"${err.message}\n ${err.stackTrace.joinToString("\n ")}")
} finally {
raw_conn?.close()
}
this.channel.close()
}
}
}
| 5 | Kotlin | 2 | 30 | 03a70e760294115a9f9fccf90d0cafede1a02319 | 11,709 | Coworker | MIT License |
plugins/kotlin/idea/tests/testData/inspectionsLocal/usePropertyAccessSyntax/dotQualifiedExpressions/propertyTypeIsMoreSpecific2.kt | JetBrains | 2,489,216 | false | null | // FIX: Use property access syntax
// IGNORE_K2
// Delete the ignore directive after fixing KTIJ-29110
abstract class KotlinClass : JavaInterface {
override fun getSomething(): String = ""
}
fun foo(k: KotlinClass, p: Any) {
if (p is String) {
k.<caret>setSomething(p)
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 294 | intellij-community | Apache License 2.0 |
src/main/kotlin/io/recursion/LetterCombinations.kt | jffiorillo | 138,075,067 | false | null | package io.recursion
// https://leetcode.com/explore/learn/card/recursion-ii/507/beyond-recursion/2905/
class LetterCombinations {
val map = mapOf(
'2' to listOf("a","b","c"),
'3' to listOf("d","e","f"),
'4' to listOf("g","h","i"),
'5' to listOf("j","k","l"),
'6' to listOf("m","n","o"),
'7' to listOf("p","q","r","s"),
'8' to listOf("t","u","v"),
'9' to listOf("w","x","y","z")
)
fun execute(digits:String) : List<String> = when(digits.length){
0 -> emptyList()
1 -> map.getValue(digits.first())
else -> {
map.getValue(digits.first()).flatMap { letter->
execute(digits.removePrefix(digits.first().toString())).map {
letter + it
}
}
}
}
}
fun main(){
val letterCombinations = LetterCombinations()
letterCombinations.execute("23").map { println(it) }
} | 1 | null | 1 | 1 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 869 | coding | MIT License |
src/test/kotlin/io/github/tobi/laa/spring/boot/embedded/redis/RedisStoreTest.kt | tobias-laa | 755,903,685 | false | {"Kotlin": 212961} | package io.github.tobi.laa.spring.boot.embedded.redis
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.context.ApplicationContext
@ExtendWith(MockKExtension::class)
@DisplayName("RedisStore tests")
internal class RedisStoreTest {
@MockK
private lateinit var context: ApplicationContext
@Test
@DisplayName("Unknown application context should yield null server")
fun unknownAppContext_serverIsNull() {
Assertions.assertThat(RedisStore.server(context)).isNull()
}
@Test
@DisplayName("Unknown application context should yield null client")
fun unknownAppContext_clientIsNull() {
Assertions.assertThat(RedisStore.client(context)).isNull()
}
} | 4 | Kotlin | 0 | 2 | d85c9b33dd87b1026894b177a7dac20cbb8fcb84 | 917 | spring-boot-embedded-redis | Apache License 2.0 |
app/src/main/java/com/github/htdangkhoa/demo/model/TodoModel.kt | htdangkhoa | 220,825,623 | false | null | package com.github.htdangkhoa.demo.model
import android.os.Parcelable
import androidx.recyclerview.widget.DiffUtil
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
data class TodoModel(
@SerializedName("completed")
val completed: Boolean = false,
@SerializedName("id")
val id: Int = 0,
@SerializedName("title")
val title: String = "",
@SerializedName("userId")
val userId: Int = 0
): Parcelable {
class DiffCallback(
private val oldList: MutableList<TodoModel>,
private val newList: MutableList<TodoModel>
): DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
oldList[oldItemPosition].id == newList[newItemPosition].id
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
oldList[oldItemPosition] == newList[newItemPosition]
}
} | 0 | Kotlin | 1 | 7 | 0a6ab25e19ddc8efdcf13421a5e3c39aedb39fe2 | 1,089 | kdux | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Wallet1.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Wallet1: ImageVector
get() {
if (_wallet1 != null) {
return _wallet1!!
}
_wallet1 = Builder(name = "Wallet1", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.9392f, 2.2118f)
lineTo(9.5292f, 7.8218f)
horizontalLineTo(7.1192f)
curveTo(6.7192f, 7.8218f, 6.3292f, 7.8518f, 5.9492f, 7.9318f)
lineTo(6.9492f, 5.5318f)
lineTo(6.9892f, 5.4418f)
lineTo(7.0492f, 5.2818f)
curveTo(7.0792f, 5.2118f, 7.0992f, 5.1518f, 7.1292f, 5.1018f)
curveTo(8.2892f, 2.4118f, 9.5892f, 1.5718f, 11.9392f, 2.2118f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.7311f, 8.0895f)
lineTo(18.7111f, 8.0795f)
curveTo(18.1111f, 7.9095f, 17.5011f, 7.8195f, 16.8811f, 7.8195f)
horizontalLineTo(10.6211f)
lineTo(12.8711f, 2.5895f)
lineTo(12.9011f, 2.5195f)
curveTo(13.0411f, 2.5695f, 13.1911f, 2.6395f, 13.3411f, 2.6895f)
lineTo(15.5511f, 3.6195f)
curveTo(16.7811f, 4.1295f, 17.6411f, 4.6595f, 18.1711f, 5.2995f)
curveTo(18.2611f, 5.4195f, 18.3411f, 5.5295f, 18.4211f, 5.6595f)
curveTo(18.5111f, 5.7995f, 18.5811f, 5.9395f, 18.6211f, 6.0895f)
curveTo(18.6611f, 6.1795f, 18.6911f, 6.2595f, 18.7111f, 6.3495f)
curveTo(18.8611f, 6.8595f, 18.8711f, 7.4395f, 18.7311f, 8.0895f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.5195f, 17.6581f)
horizontalLineTo(12.7695f)
curveTo(13.0695f, 17.6581f, 13.3195f, 17.3881f, 13.3195f, 17.0581f)
curveTo(13.3195f, 16.6381f, 13.1995f, 16.5781f, 12.9395f, 16.4781f)
lineTo(12.5195f, 16.3281f)
verticalLineTo(17.6581f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.2883f, 9.5203f)
curveTo(17.8383f, 9.3903f, 17.3683f, 9.3203f, 16.8783f, 9.3203f)
horizontalLineTo(7.1183f)
curveTo(6.4383f, 9.3203f, 5.7983f, 9.4503f, 5.1983f, 9.7103f)
curveTo(3.4583f, 10.4603f, 2.2383f, 12.1903f, 2.2383f, 14.2003f)
verticalLineTo(16.1503f)
curveTo(2.2383f, 16.3903f, 2.2583f, 16.6203f, 2.2883f, 16.8603f)
curveTo(2.5083f, 20.0403f, 4.2083f, 21.7403f, 7.3883f, 21.9503f)
curveTo(7.6183f, 21.9803f, 7.8483f, 22.0003f, 8.0983f, 22.0003f)
horizontalLineTo(15.8983f)
curveTo(19.5983f, 22.0003f, 21.5483f, 20.2403f, 21.7383f, 16.7403f)
curveTo(21.7483f, 16.5503f, 21.7583f, 16.3503f, 21.7583f, 16.1503f)
verticalLineTo(14.2003f)
curveTo(21.7583f, 11.9903f, 20.2883f, 10.1303f, 18.2883f, 9.5203f)
close()
moveTo(13.2783f, 15.5003f)
curveTo(13.7383f, 15.6603f, 14.3583f, 16.0003f, 14.3583f, 17.0603f)
curveTo(14.3583f, 17.9703f, 13.6483f, 18.7003f, 12.7683f, 18.7003f)
horizontalLineTo(12.5183f)
verticalLineTo(18.9203f)
curveTo(12.5183f, 19.2103f, 12.2883f, 19.4403f, 11.9983f, 19.4403f)
curveTo(11.7083f, 19.4403f, 11.4783f, 19.2103f, 11.4783f, 18.9203f)
verticalLineTo(18.7003f)
horizontalLineTo(11.3883f)
curveTo(10.4283f, 18.7003f, 9.6383f, 17.8903f, 9.6383f, 16.8903f)
curveTo(9.6383f, 16.6003f, 9.8683f, 16.3703f, 10.1583f, 16.3703f)
curveTo(10.4483f, 16.3703f, 10.6783f, 16.6003f, 10.6783f, 16.8903f)
curveTo(10.6783f, 17.3103f, 10.9983f, 17.6603f, 11.3883f, 17.6603f)
horizontalLineTo(11.4783f)
verticalLineTo(15.9703f)
lineTo(10.7183f, 15.7003f)
curveTo(10.2583f, 15.5403f, 9.6383f, 15.2003f, 9.6383f, 14.1403f)
curveTo(9.6383f, 13.2303f, 10.3483f, 12.5003f, 11.2283f, 12.5003f)
horizontalLineTo(11.4783f)
verticalLineTo(12.2803f)
curveTo(11.4783f, 11.9903f, 11.7083f, 11.7603f, 11.9983f, 11.7603f)
curveTo(12.2883f, 11.7603f, 12.5183f, 11.9903f, 12.5183f, 12.2803f)
verticalLineTo(12.5003f)
horizontalLineTo(12.6083f)
curveTo(13.5683f, 12.5003f, 14.3583f, 13.3103f, 14.3583f, 14.3103f)
curveTo(14.3583f, 14.6003f, 14.1283f, 14.8303f, 13.8383f, 14.8303f)
curveTo(13.5483f, 14.8303f, 13.3183f, 14.6003f, 13.3183f, 14.3103f)
curveTo(13.3183f, 13.8903f, 12.9983f, 13.5403f, 12.6083f, 13.5403f)
horizontalLineTo(12.5183f)
verticalLineTo(15.2303f)
lineTo(13.2783f, 15.5003f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.6797f, 14.1391f)
curveTo(10.6797f, 14.5591f, 10.7997f, 14.6191f, 11.0597f, 14.7191f)
lineTo(11.4797f, 14.8691f)
verticalLineTo(13.5391f)
horizontalLineTo(11.2297f)
curveTo(10.9197f, 13.5391f, 10.6797f, 13.8091f, 10.6797f, 14.1391f)
close()
}
}
.build()
return _wallet1!!
}
private var _wallet1: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 7,378 | VuesaxIcons | MIT License |
src/main/kotlin/com/virtuslab/timeevents/kafka/Serde.kt | jakubiec | 190,876,605 | false | null | package com.virtuslab.timeevents.kafka
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.virtuslab.timeevents.ScheduleCommand
import com.virtuslab.timeevents.TimeBasedEvent
import mu.KotlinLogging
import org.apache.kafka.common.serialization.Deserializer
import org.apache.kafka.common.serialization.Serde
import org.apache.kafka.common.serialization.Serializer
private val objectMapper = jacksonObjectMapper().registerModule(JavaTimeModule()).enableDefaultTyping()
private val logger = KotlinLogging.logger {}
object ScheduleCommandDeserializer : Deserializer<ScheduleCommand> {
override fun deserialize(topic: String, data: ByteArray): ScheduleCommand = objectMapper.readValue(data)
override fun close() = logger.info { "Closing ScheduleCommandDeserializer" }
override fun configure(configs: MutableMap<String, *>, isKey: Boolean) {}
}
object ScheduleCommandSerializer : Serializer<ScheduleCommand> {
override fun serialize(topic: String, data: ScheduleCommand): ByteArray = objectMapper.writeValueAsBytes(data)
override fun close() = logger.info { "Closing ScheduleCommandDeserializer" }
override fun configure(configs: MutableMap<String, *>, isKey: Boolean) {}
}
object TimeBasedEventSerde : Serde<TimeBasedEvent> {
override fun configure(configs: MutableMap<String, *>?, isKey: Boolean) {}
override fun deserializer(): Deserializer<TimeBasedEvent> = TimeBasedEventDeserializer
override fun close() {}
override fun serializer(): Serializer<TimeBasedEvent> = TimeBasedEventSerializer
}
object TimeBasedEventSerializer : Serializer<TimeBasedEvent> {
override fun serialize(topic: String, data: TimeBasedEvent): ByteArray = objectMapper.writeValueAsBytes(data)
override fun close() = logger.info { "Closing TimeBasedEventSerializer" }
override fun configure(configs: MutableMap<String, *>, isKey: Boolean) {}
}
object TimeBasedEventDeserializer : Deserializer<TimeBasedEvent> {
override fun deserialize(topic: String, data: ByteArray): TimeBasedEvent = objectMapper.readValue(data)
override fun close() = logger.info { "Closing TimeBasedEventDeserializer" }
override fun configure(configs: MutableMap<String, *>, isKey: Boolean) {}
} | 0 | Kotlin | 0 | 3 | 661cc0ad8aebd26cb8eb543328b8b351534c26a8 | 2,355 | time-based-events | Apache License 2.0 |
src/test/kotlin/com/charleskorn/okhttp/systemkeystore/ExtensionsTest.kt | charleskorn | 441,058,425 | false | {"Kotlin": 18675} | /*
Copyright 2017-2022 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.charleskorn.okhttp.systemkeystore
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.common.ExperimentalKotest
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.HeldCertificate
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import javax.net.ssl.SSLHandshakeException
// https://adambennett.dev/2021/09/mockwebserver-https/ is a very useful reference,
// as is https://github.com/square/okhttp/blob/master/okhttp-tls/README.md.
@ExperimentalKotest
class ExtensionsTest : FunSpec({
val now = ZonedDateTime.now(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_INSTANT).replace(":", ".")
fun requestShouldSucceed(url: HttpUrl) {
val client = OkHttpClient.Builder()
.useOperatingSystemCertificateTrustStore()
.build()
val request = Request.Builder()
.get()
.url(url)
.build()
client.newCall(request).execute().use { response ->
response.code shouldBe 200
}
}
fun requestShouldFailWithUntrustedCertificateError(url: HttpUrl) {
val client = OkHttpClient.Builder()
.useOperatingSystemCertificateTrustStore()
.build()
val request = Request.Builder()
.get()
.url(url)
.build()
val exception = shouldThrow<SSLHandshakeException> {
client.newCall(request).execute()
}
exception.message shouldBe "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"
}
context("connecting to a server that should be trusted by default") {
test("should be able to make requests") {
requestShouldSucceed("https://google.com".toHttpUrl())
}
}
context("connecting to a server that presents an untrusted certificate") {
val untrustedCertificate = TestCertificate("Untrusted certificate for okhttp-system-keystore tests running at $now")
val untrustedServer = autoClose(createServer(untrustedCertificate.heldCertificate))
test("should throw an exception") {
requestShouldFailWithUntrustedCertificateError(untrustedServer.url("/"))
}
}
context("when running on macOS").config(enabled = OperatingSystem.current == OperatingSystem.Mac) {
context("connecting to a server that presents a self-signed certificate trusted by the system trust store") {
val trustedCertificate = autoClose(MacKeychainTrustedCertificateContainer.createAndTrust("Trusted certificate for okhttp-system-keystore tests running at $now"))
val trustedServer = autoClose(createServer(trustedCertificate.heldCertificate))
val url = trustedServer.url("/")
test("should be able to make requests") {
requestShouldSucceed(url)
}
}
context("connecting to a server that presents a certificate signed by a CA trusted by the system trust store") {
val trustedCACertificate = autoClose(MacKeychainTrustedCertificateContainer.createAndTrust("Trusted CA certificate for okhttp-system-keystore tests running at $now", isCertificateAuthority = true))
val serverCertificateFromTrustedCA = TestCertificate("Server certificate signed by trusted CA certificate", signedBy = trustedCACertificate.certificate)
val serverUsingCertificateFromTrustedCA = autoClose(createServer(serverCertificateFromTrustedCA.heldCertificate))
val url = serverUsingCertificateFromTrustedCA.url("/")
test("should be able to make requests") {
requestShouldSucceed(url)
}
}
}
context("when running on Windows").config(enabled = OperatingSystem.current == OperatingSystem.Windows) {
context("connecting to a server that presents a self-signed certificate trusted by machine's trust store") {
val trustedCertificate = autoClose(WindowsTrustedCertificateContainer.createAndTrust("Machine-trusted certificate for okhttp-system-keystore tests running at $now"))
val trustedServer = autoClose(createServer(trustedCertificate.heldCertificate))
val url = trustedServer.url("/")
test("should be able to make requests") {
requestShouldSucceed(url)
}
}
context("connecting to a server that presents a certificate signed by a CA trusted by the machine's trust store") {
val trustedCACertificate = autoClose(WindowsTrustedCertificateContainer.createAndTrust("Machine-trusted CA certificate for okhttp-system-keystore tests running at $now", isCertificateAuthority = true))
val serverCertificateFromTrustedCA = TestCertificate("Server certificate signed by machine-trusted CA certificate", signedBy = trustedCACertificate.certificate)
val serverUsingCertificateFromTrustedCA = autoClose(createServer(serverCertificateFromTrustedCA.heldCertificate))
val url = serverUsingCertificateFromTrustedCA.url("/")
test("should be able to make requests") {
requestShouldSucceed(url)
}
}
}
})
private fun createServer(certificate: HeldCertificate): MockWebServer {
val serverCertificates = HandshakeCertificates.Builder()
.heldCertificate(certificate)
.build()
val server = MockWebServer()
server.useHttps(serverCertificates.sslSocketFactory(), false)
server.start()
server.enqueue(MockResponse().setResponseCode(200))
return server
}
| 1 | Kotlin | 1 | 27 | c1389ceb060e65fc743f60f13fcea3eb847e4369 | 6,559 | okhttp-system-keystore | Apache License 2.0 |
src/test/kotlin/ar/edu/unq/cucumber/registrodeusuario/RegistroDeUsuarioTest.kt | CristianGonzalez1980 | 320,041,280 | false | null | package ar.edu.unq.cucumber.registrodeusuario
import io.cucumber.junit.Cucumber
import io.cucumber.junit.CucumberOptions
import org.junit.runner.RunWith
@RunWith(Cucumber::class)
@CucumberOptions(features = ["src/test/resources/ar/edu/unq/cucumber/registrodeusuario.feature"])
class RegistroDeUsuarioTest
| 1 | Kotlin | 0 | 0 | 28553d578b6c6ec24c32759d604731bfbc40627a | 307 | exposicion-virtual | The Unlicense |
src/test/kotlin/ar/edu/unq/cucumber/registrodeusuario/RegistroDeUsuarioTest.kt | CristianGonzalez1980 | 320,041,280 | false | null | package ar.edu.unq.cucumber.registrodeusuario
import io.cucumber.junit.Cucumber
import io.cucumber.junit.CucumberOptions
import org.junit.runner.RunWith
@RunWith(Cucumber::class)
@CucumberOptions(features = ["src/test/resources/ar/edu/unq/cucumber/registrodeusuario.feature"])
class RegistroDeUsuarioTest
| 1 | Kotlin | 0 | 0 | 28553d578b6c6ec24c32759d604731bfbc40627a | 307 | exposicion-virtual | The Unlicense |
clck/app/src/main/java/com/example/primaryengine/framework/PixmapK.kt | MaximRybinsky | 351,463,250 | false | null | package com.example.primaryengine.framework
interface PixmapK {
var imageID : Int
fun dispose()
} | 0 | Kotlin | 0 | 0 | 3001a77afd2bf0a45423465f8d1f9a1f3c9081f7 | 106 | AppleClicker | MIT License |
src/main/kotlin/com/wutsi/flutter/sdui/enums/Axis.kt | wutsi | 415,658,640 | false | null | package com.wutsi.flutter.sdui.enums
enum class Axis {
Horizontal,
Vertical,
}
| 1 | Kotlin | 1 | 2 | 0e39b6120b9cb6e8acf35c5d4d86cf95e75ebfae | 88 | sdui-kotlin | MIT License |
sources-js/RDsl.kt | fluidsonic | 316,835,394 | false | null | package io.fluidsonic.react
@DslMarker
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.TYPEALIAS)
public annotation class RDsl
| 0 | Kotlin | 2 | 12 | 32e4e59d41d774eba10d48bbdbb40d89f14f972d | 223 | fluid-react | Apache License 2.0 |
sam-java-core/src/main/kotlin/software/elborai/api/services/blocking/intrafi/ExclusionService.kt | DefinitelyATestOrg | 787,029,081 | false | {"Kotlin": 13368521, "Shell": 3638, "Dockerfile": 366} | // File generated from our OpenAPI spec by Stainless.
@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102
package software.elborai.api.services.blocking.intrafi
import software.elborai.api.core.RequestOptions
import software.elborai.api.models.IntrafiExclusion
import software.elborai.api.models.IntrafiExclusionArchiveParams
import software.elborai.api.models.IntrafiExclusionCreateParams
import software.elborai.api.models.IntrafiExclusionListPage
import software.elborai.api.models.IntrafiExclusionListParams
import software.elborai.api.models.IntrafiExclusionRetrieveParams
interface ExclusionService {
/** Create an IntraFi Exclusion */
@JvmOverloads
fun create(
params: IntrafiExclusionCreateParams,
requestOptions: RequestOptions = RequestOptions.none()
): IntrafiExclusion
/** Get an IntraFi Exclusion */
@JvmOverloads
fun retrieve(
params: IntrafiExclusionRetrieveParams,
requestOptions: RequestOptions = RequestOptions.none()
): IntrafiExclusion
/** List IntraFi Exclusions. */
@JvmOverloads
fun list(
params: IntrafiExclusionListParams,
requestOptions: RequestOptions = RequestOptions.none()
): IntrafiExclusionListPage
/** Archive an IntraFi Exclusion */
@JvmOverloads
fun archive(
params: IntrafiExclusionArchiveParams,
requestOptions: RequestOptions = RequestOptions.none()
): IntrafiExclusion
}
| 1 | Kotlin | 0 | 0 | 896c77d132ececb8926a3b29f08ea09c98355ecd | 1,485 | sam-java | Apache License 2.0 |
app/src/main/java/com/example/wanAndroid/util/CacheDataUtil.kt | SaltedFish-Extreme | 458,692,555 | false | null | package com.example.wanAndroid.util
import android.content.Context
import android.os.Environment
import java.io.File
import java.math.BigDecimal
import java.math.RoundingMode
/**
* Created by 咸鱼至尊 on 2022/2/8
*
* desc: 缓存工具类
*/
object CacheDataUtil {
/** 获取缓存大小 */
fun getTotalCacheSize(context: Context): String {
var cacheSize: Long = getFolderSize(context.cacheDir)
if ((Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)) {
cacheSize += getFolderSize(context.externalCacheDir!!)
}
return getFormatSize(cacheSize.toDouble())
}
/** 清除缓存 */
fun clearAllCache(context: Context) {
deleteDir(context.cacheDir)
if ((Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)) {
deleteDir(context.externalCacheDir)
}
}
/** 删除文件夹 */
private fun deleteDir(dir: File?): Boolean {
if (dir == null) {
return false
}
if (!dir.isDirectory) {
return dir.delete()
}
val children: Array<out String> = dir.list() ?: return false
for (child: String in children) {
deleteDir(File(dir, child))
}
return false
}
/**
* 获取文件
*
* Context.getExternalFilesDir() -->
*
* SDCard/Android/data/你的应用的包名/files/目录, 一般放一些长时间保存的数据
*
* Context.getExternalCacheDir() -->
*
* SDCard/Android/data/你的应用包名/cache/目录, 一般存放临时缓存数据
*/
private fun getFolderSize(file: File): Long {
var size: Long = 0
try {
val list: Array<out File> = file.listFiles() ?: return 0
for (temp: File in list) {
// 如果下面还有文件
size += if (temp.isDirectory) {
getFolderSize(temp)
} else {
temp.length()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return size
}
/** 格式化单位 */
private fun getFormatSize(size: Double): String {
val kiloByte: Double = size / 1024
if (kiloByte < 1) {
// return size + "Byte";
return "0KB"
}
val megaByte: Double = kiloByte / 1024
if (megaByte < 1) {
return BigDecimal(kiloByte).setScale(2, RoundingMode.HALF_UP).toPlainString() + "KB"
}
val gigaByte: Double = megaByte / 1024
if (gigaByte < 1) {
return BigDecimal(megaByte).setScale(2, RoundingMode.HALF_UP).toPlainString() + "MB"
}
val teraBytes: Double = gigaByte / 1024
if (teraBytes < 1) {
return BigDecimal(gigaByte).setScale(2, RoundingMode.HALF_UP).toPlainString() + "GB"
}
return BigDecimal(teraBytes).setScale(2, RoundingMode.HALF_UP).toPlainString() + "TB"
}
} | 0 | null | 6 | 36 | 2ce81daeedee3f0df94dfc6b474f65356d6fd64a | 2,868 | WanAndroid | Apache License 2.0 |
JusAudio/app/src/main/java/com/curiolabs/jusaudio/repository/AudioDataRepository.kt | jusaudio | 229,417,104 | false | null | package com.curiolabs.jusaudio.repository
import android.util.Log
import com.curiolabs.jusaudio.content_providers.JusAudiosContentProvider
import com.curiolabs.jusaudio.persistence.JusAudioDatabase
import com.curiolabs.jusaudio.persistence.entities.JusAudios
import com.curiolabs.jusaudio.utility_classes.JusAudioConstants.QUERY_LIMIT
import com.curiolabs.jusaudio.utility_classes.JusAudioConstants.SEARCH_QUERY_TXT_MIN_LENGTH
private const val LOG_TAG = "AudioDataRepository"
class AudioDataRepository(
private val jusAudioContentProvider: JusAudiosContentProvider,
private val jusAudioDatabase: JusAudioDatabase
) {
//cache
private val myCollectionCache = ArrayList<JusAudios>()
private val recommendedAudiosCache = ArrayList<JusAudios>()
/********* getters *********/
fun findAudio(searchQuery: String, offset: Int = 0): ArrayList<JusAudios> {
Log.d(LOG_TAG, "findAudio() called")
var foundAudios = ArrayList<JusAudios>()
if (searchQuery.trim().length > SEARCH_QUERY_TXT_MIN_LENGTH) {
val localResults = jusAudioDatabase.jusAudiosFtsDao()
.findAudio(searchQuery = "*${searchQuery}*", offset = offset)
foundAudios.addAll(localResults)
if (foundAudios.isEmpty()) {
//fetch from server
Log.d(LOG_TAG, "fetching from server")
foundAudios =
jusAudioContentProvider.searchAudio(query = searchQuery, offset = offset)
if (foundAudios.isNotEmpty()) {
jusAudioDatabase.jusAudiosDao()
.insertAudios(foundAudios) //add to local database
}
}
}
return foundAudios
}
fun getRecommendedAudios(offset: Int = 0): ArrayList<JusAudios>? {
Log.d(LOG_TAG, "getRecommendedAudios() called")
if (recommendedAudiosCache.size <= offset) {
Log.d(LOG_TAG, "fetching from local db")
val recommendedAudios =
jusAudioDatabase.jusAudiosDao().getRecommendations(offset = offset)
if (recommendedAudios.isNotEmpty()) {
recommendedAudiosCache.addAll(recommendedAudios) //add to cache
} else {
Log.d(LOG_TAG, "fetching from server")
//poll the server
val recommendedAudiosFromServer =
jusAudioContentProvider.getRecommendations(offset = offset)
if (recommendedAudiosFromServer.isNotEmpty()) {
Log.d(LOG_TAG, "found in server")
jusAudioDatabase.jusAudiosDao()
.insertAudios(recommendedAudiosFromServer) //add to local database
recommendedAudiosCache.addAll(recommendedAudiosFromServer) //add to cache
}
}
}
return recommendedAudiosCache
}
fun getMyCollection(offset: Int = 0, limit : Int = QUERY_LIMIT): ArrayList<JusAudios>? {
Log.d(LOG_TAG, "getMyCollection() called offset $offset")
if (myCollectionCache.size <= offset) {
val audiosList = jusAudioDatabase.jusAudiosDao().getMyCollection(offset = offset, limit = limit)
if (audiosList.isNotEmpty()) {
Log.d(LOG_TAG, "found in local db " + audiosList.size.toString())
myCollectionCache.addAll(audiosList)
}
}
Log.d(LOG_TAG, "getMyCollection() returned cache size " + myCollectionCache.size.toString())
return myCollectionCache
}
/******** setters *************/
fun updateAudio(ogAudio: JusAudios, modifiedAudio: JusAudios) {
Log.d(LOG_TAG, "updateAudio() ${modifiedAudio.audioTitle}")
val posInCollection = myCollectionCache.indexOf(ogAudio)
if (posInCollection >= 0) {
myCollectionCache.removeAt(posInCollection)
}
if (modifiedAudio.audioIsInMyCollection) myCollectionCache.add(modifiedAudio)
val posInRecommendations = recommendedAudiosCache.indexOf(ogAudio)
if (posInRecommendations >= 0) recommendedAudiosCache[posInRecommendations] =
modifiedAudio
jusAudioDatabase.jusAudiosDao().updateAudio(modifiedAudio)
}
/************ deletions ************/
fun clearMyCollection() {
myCollectionCache.clear()
jusAudioDatabase.jusAudiosDao().clearMyCollection()
}
fun clearRecommendations() {
recommendedAudiosCache.clear()
jusAudioDatabase.jusAudiosDao().clearRecommendations()
}
fun clearFavorites() {
for (audio in myCollectionCache) {
if (audio.audioIsFavorite) {
myCollectionCache.removeAt(myCollectionCache.indexOf(audio))
audio.audioIsFavorite = false
myCollectionCache.add(audio)
}
}
jusAudioDatabase.jusAudiosDao().clearFavorites()
}
} | 0 | Kotlin | 0 | 0 | 23cd2a2ae1fd609e68f355a3e7484ed57234e7d6 | 4,964 | kotlin-android | MIT License |
recyct/src/main/java/me/showang/recyct/items/viewholder/LoadMoreViewHolder.kt | showang | 149,106,320 | false | null | package me.showang.recyct.items.viewholder
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
abstract class LoadMoreViewHolder(
@LayoutRes layout: Int,
inflater: LayoutInflater,
parent: ViewGroup
) : LegacyRecyctViewHolder(layout, inflater, parent) {
final override fun bind(data: Any, dataIndex: Int, itemIndex: Int) {
(data as? Boolean)?.let { bind(it, itemIndex) }
}
abstract fun bind(isLoadMoreFailed: Boolean, adapterIndex: Int)
} | 0 | Kotlin | 2 | 7 | 1fe543360d1779e355ecfd9656040e2c7e7a3378 | 524 | Recyct | MIT License |
src/test/kotlin/de/klg71/keycloakmigration/changeControl/actions/realm/DeleteRealmIntegTest.kt | mayope | 162,558,921 | false | null | package de.klg71.keycloakmigration.changeControl.actions.realm
import de.klg71.keycloakmigration.AbstractIntegrationTest
import de.klg71.keycloakmigration.keycloakapi.KeycloakApiException
import de.klg71.keycloakmigration.keycloakapi.KeycloakClient
import de.klg71.keycloakmigration.keycloakapi.realmExistsById
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
import org.koin.core.component.inject
class DeleteRealmIntegTest : AbstractIntegrationTest() {
val client by inject<KeycloakClient>()
@Test
fun testDeleteRealm() {
AddRealmAction("testRealm", id = "testRealm").executeIt()
DeleteRealmAction("testRealm").executeIt()
assertThat(client.realmExistsById("testRealm")).isFalse()
}
@Test
fun testDeleteRealmNotExisting() {
assertThatThrownBy {
DeleteRealmAction("testRealm").executeIt()
}.isInstanceOf(KeycloakApiException::class.java)
.hasMessage("Realm with id: testRealm does not exist!")
}
}
| 1 | null | 21 | 95 | 15730a5320247d515077532d37103e321123f578 | 1,079 | keycloakmigration | MIT License |
app/src/main/java/com/hulusimsek/cryptoapp/presentation/home_screen/CryptosEvent.kt | hulusimsek | 841,740,788 | false | {"Kotlin": 139992} | package com.hulusimsek.cryptoapp.presentation.home_screen
import com.hulusimsek.cryptoapp.data.database.entity.SearchQuery
sealed class CryptosEvent {
data class SelectSymbol(val symbol: String) : CryptosEvent()
data class SelectTab(val tabIndex: Int) : CryptosEvent()
data class SearchCrypto(val query: String) : CryptosEvent()
object Refresh : CryptosEvent()
object LoadCryptos : CryptosEvent()
object LoadSearchQuery : CryptosEvent()
object FilterList : CryptosEvent()
object ClearToastMessage : CryptosEvent()
data class SaveSearchQuery(val query: String) : CryptosEvent()
data class DeleteSearchQuery(val query: SearchQuery) : CryptosEvent()
} | 0 | Kotlin | 0 | 0 | b707bd905e9f9bd8566a6b544fa5be35208e7a85 | 690 | Cointograf | MIT License |
src/jsMain/kotlin/com/jeffpdavidson/kotwords/web/SnakeCharmerForm.kt | jpd236 | 143,651,464 | false | {"Kotlin": 4427111, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618} | package com.jeffpdavidson.kotwords.web
import com.jeffpdavidson.kotwords.KotwordsInternal
import com.jeffpdavidson.kotwords.model.Puzzle
import com.jeffpdavidson.kotwords.model.SnakeCharmer
import com.jeffpdavidson.kotwords.util.trimmedLines
import com.jeffpdavidson.kotwords.web.html.FormFields
import com.jeffpdavidson.kotwords.web.html.Html
import kotlinx.html.classes
@JsExport
@KotwordsInternal
class SnakeCharmerForm {
private val form = PuzzleFileForm("snake-charmer", ::createPuzzle)
private val answers: FormFields.TextBoxField = FormFields.TextBoxField("answers")
private val clues: FormFields.TextBoxField = FormFields.TextBoxField("clues")
private val gridShape: FormFields.TextBoxField = FormFields.TextBoxField("grid-shape")
init {
Html.renderPage {
form.render(this, bodyBlock = {
answers.render(this, "Answers") {
placeholder = "In sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored."
rows = "5"
}
clues.render(this, "Clues") {
placeholder = "One clue per row. Omit clue numbers."
rows = "10"
}
gridShape.render(this, "Grid shape", "Use '*' characters to represent white squares.") {
rows = "10"
classes = classes + "text-monospace"
+"""
| ************
| * *
| * *
| * *
| * **********
| * *
| * *
| * *
| * **********
| * *
| * *
| ********** *
| * *
| * *
| * *
|*********** *
|* *
|* *
|* *
|*************
""".trimMargin()
}
})
}
}
private suspend fun createPuzzle(): Puzzle {
val grid = gridShape.untrimmedValue.lines()
require(grid.isNotEmpty()) {
"Grid shape is required"
}
var y = 0
var x = grid[0].indexOfFirst { it == '*' }
require(x >= 0) {
"First row of grid must contain a white square ('*')"
}
val gridCoordinates = linkedSetOf<Pair<Int, Int>>()
do {
gridCoordinates += x to y
val nextPoint = listOf(x + 1 to y, x to y + 1, x - 1 to y, x to y - 1).find { (i, j) ->
j >= 0 && j < grid.size && i >= 0 && i < grid[j].length && !gridCoordinates.contains(i to j)
&& grid[j][i] == '*'
} ?: break
x = nextPoint.first
y = nextPoint.second
} while (true)
val snakeCharmer = SnakeCharmer(
title = form.title,
creator = form.creator,
copyright = form.copyright,
description = form.description,
answers = answers.value.uppercase().split("\\s+".toRegex()),
clues = clues.value.trimmedLines(),
gridCoordinates = gridCoordinates.toList()
)
return snakeCharmer.asPuzzle()
}
} | 8 | Kotlin | 6 | 25 | 79c9a262239f44cabcc912c9237610d9b8f39473 | 3,519 | kotwords | Apache License 2.0 |
src/main/java/com/example/niksen111/entity/Product.kt | Niksen111 | 864,485,807 | false | {"Kotlin": 9777, "Dockerfile": 134} | package com.example.niksen111.entity
import jakarta.persistence.*
import java.math.BigDecimal
@Entity
@Table(name = "products")
class Product(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@Column(nullable = false)
val name: String,
@Column(nullable = false, precision = 10, scale = 2)
val price: BigDecimal
) {
constructor() : this(0, "", BigDecimal.ZERO)
}
| 0 | Kotlin | 0 | 0 | 2aa2a626113d9142583aea3c479141ba38c2c07f | 451 | orm-demo | Apache License 2.0 |
window/window/src/main/java/androidx/window/layout/SafeWindowLayoutComponentProvider.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* 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.window.layout
import android.app.Activity
import android.content.Context
import android.graphics.Rect
import androidx.annotation.VisibleForTesting
import androidx.window.SafeWindowExtensionsProvider
import androidx.window.core.ConsumerAdapter
import androidx.window.core.ExtensionsUtil
import androidx.window.extensions.WindowExtensions
import androidx.window.extensions.WindowExtensionsProvider
import androidx.window.extensions.core.util.function.Consumer
import androidx.window.extensions.layout.WindowLayoutComponent
import androidx.window.reflection.ReflectionUtils.doesReturn
import androidx.window.reflection.ReflectionUtils.isPublic
import androidx.window.reflection.ReflectionUtils.validateReflection
import androidx.window.reflection.WindowExtensionsConstants.DISPLAY_FOLD_FEATURE_CLASS
import androidx.window.reflection.WindowExtensionsConstants.FOLDING_FEATURE_CLASS
import androidx.window.reflection.WindowExtensionsConstants.JAVA_CONSUMER
import androidx.window.reflection.WindowExtensionsConstants.SUPPORTED_WINDOW_FEATURES_CLASS
import androidx.window.reflection.WindowExtensionsConstants.WINDOW_CONSUMER
import androidx.window.reflection.WindowExtensionsConstants.WINDOW_LAYOUT_COMPONENT_CLASS
import java.lang.reflect.ParameterizedType
/**
* Reflection Guard for [WindowLayoutComponent]. This will go through the [WindowLayoutComponent]'s
* method by reflection and check each method's name and signature to see if the interface is what
* we required.
*/
internal class SafeWindowLayoutComponentProvider(
private val loader: ClassLoader,
private val consumerAdapter: ConsumerAdapter
) {
private val safeWindowExtensionsProvider = SafeWindowExtensionsProvider(loader)
val windowLayoutComponent: WindowLayoutComponent?
get() {
return if (canUseWindowLayoutComponent()) {
try {
WindowExtensionsProvider.getWindowExtensions().windowLayoutComponent
} catch (e: UnsupportedOperationException) {
null
}
} else {
null
}
}
private fun canUseWindowLayoutComponent(): Boolean {
if (!isWindowLayoutComponentAccessible()) {
return false
}
val vendorApiLevel = ExtensionsUtil.safeVendorApiLevel
return when {
vendorApiLevel < 1 -> false
vendorApiLevel == 1 -> hasValidVendorApiLevel1()
vendorApiLevel < 5 -> hasValidVendorApiLevel2()
else -> hasValidVendorApiLevel6()
}
}
@VisibleForTesting
internal fun isWindowLayoutComponentAccessible(): Boolean =
safeWindowExtensionsProvider.isWindowExtensionsValid() &&
isWindowLayoutProviderValid() &&
isFoldingFeatureValid()
/**
* [WindowExtensions.VENDOR_API_LEVEL_1] includes the following methods
* - [WindowLayoutComponent.addWindowLayoutInfoListener] with [Activity] and
* [java.util.function.Consumer]
* - [WindowLayoutComponent.removeWindowLayoutInfoListener] with [java.util.function.Consumer]
*/
@VisibleForTesting
internal fun hasValidVendorApiLevel1(): Boolean {
return isMethodWindowLayoutInfoListenerJavaConsumerValid()
}
/**
* [WindowExtensions.VENDOR_API_LEVEL_2] includes the following methods
* - [WindowLayoutComponent.addWindowLayoutInfoListener] with [Context] and [Consumer]
* - [WindowLayoutComponent.removeWindowLayoutInfoListener] with [Consumer]
*/
@VisibleForTesting
internal fun hasValidVendorApiLevel2(): Boolean {
return hasValidVendorApiLevel1() && isMethodWindowLayoutInfoListenerWindowConsumerValid()
}
@VisibleForTesting
internal fun hasValidVendorApiLevel6(): Boolean {
return hasValidVendorApiLevel2() &&
isDisplayFoldFeatureValid() &&
isSupportedWindowFeaturesValid() &&
isGetSupportedWindowFeaturesValid()
}
private fun isWindowLayoutProviderValid(): Boolean {
return validateReflection("WindowExtensions#getWindowLayoutComponent is not valid") {
val extensionsClass = safeWindowExtensionsProvider.windowExtensionsClass
val getWindowLayoutComponentMethod =
extensionsClass.getMethod("getWindowLayoutComponent")
val windowLayoutComponentClass = windowLayoutComponentClass
getWindowLayoutComponentMethod.isPublic &&
getWindowLayoutComponentMethod.doesReturn(windowLayoutComponentClass)
}
}
private fun isFoldingFeatureValid(): Boolean {
return validateReflection("FoldingFeature class is not valid") {
val foldingFeatureClass = foldingFeatureClass
val getBoundsMethod = foldingFeatureClass.getMethod("getBounds")
val getTypeMethod = foldingFeatureClass.getMethod("getType")
val getStateMethod = foldingFeatureClass.getMethod("getState")
getBoundsMethod.doesReturn(Rect::class) &&
getBoundsMethod.isPublic &&
getTypeMethod.doesReturn(Int::class) &&
getTypeMethod.isPublic &&
getStateMethod.doesReturn(Int::class) &&
getStateMethod.isPublic
}
}
private fun isMethodWindowLayoutInfoListenerJavaConsumerValid(): Boolean {
return validateReflection(
"WindowLayoutComponent#addWindowLayoutInfoListener(" +
"${Activity::class.java.name}, $JAVA_CONSUMER) is not valid"
) {
val consumerClass =
consumerAdapter.consumerClassOrNull() ?: return@validateReflection false
val windowLayoutComponent = windowLayoutComponentClass
val addListenerMethod =
windowLayoutComponent.getMethod(
"addWindowLayoutInfoListener",
Activity::class.java,
consumerClass
)
val removeListenerMethod =
windowLayoutComponent.getMethod("removeWindowLayoutInfoListener", consumerClass)
addListenerMethod.isPublic && removeListenerMethod.isPublic
}
}
private fun isMethodWindowLayoutInfoListenerWindowConsumerValid(): Boolean {
return validateReflection(
"WindowLayoutComponent#addWindowLayoutInfoListener" +
"(${Context::class.java.name}, $WINDOW_CONSUMER) is not valid"
) {
val windowLayoutComponent = windowLayoutComponentClass
val addListenerMethod =
windowLayoutComponent.getMethod(
"addWindowLayoutInfoListener",
Context::class.java,
Consumer::class.java
)
val removeListenerMethod =
windowLayoutComponent.getMethod(
"removeWindowLayoutInfoListener",
Consumer::class.java
)
addListenerMethod.isPublic && removeListenerMethod.isPublic
}
}
private fun isDisplayFoldFeatureValid(): Boolean {
return validateReflection("DisplayFoldFeature is not valid") {
val displayFoldFeatureClass = displayFoldFeatureClass
val getTypeMethod = displayFoldFeatureClass.getMethod("getType")
val hasPropertyMethod =
displayFoldFeatureClass.getMethod("hasProperty", Int::class.java)
val hasPropertiesMethod =
displayFoldFeatureClass.getMethod("hasProperties", IntArray::class.java)
getTypeMethod.isPublic &&
getTypeMethod.doesReturn(Int::class.java) &&
hasPropertyMethod.isPublic &&
hasPropertyMethod.doesReturn(Boolean::class.java) &&
hasPropertiesMethod.isPublic &&
hasPropertiesMethod.doesReturn(Boolean::class.java)
}
}
private fun isSupportedWindowFeaturesValid(): Boolean {
return validateReflection("SupportedWindowFeatures is not valid") {
val supportedWindowFeaturesClass = supportedWindowFeaturesClass
val getDisplayFoldFeaturesMethod =
supportedWindowFeaturesClass.getMethod("getDisplayFoldFeatures")
val returnTypeGeneric =
(getDisplayFoldFeaturesMethod.genericReturnType as ParameterizedType)
.actualTypeArguments[0]
as Class<*>
getDisplayFoldFeaturesMethod.isPublic &&
getDisplayFoldFeaturesMethod.doesReturn(List::class.java) &&
returnTypeGeneric == displayFoldFeatureClass
}
}
private fun isGetSupportedWindowFeaturesValid(): Boolean {
return validateReflection("WindowLayoutComponent#getSupportedWindowFeatures is not valid") {
val windowLayoutComponent = windowLayoutComponentClass
val getSupportedWindowFeaturesMethod =
windowLayoutComponent.getMethod("getSupportedWindowFeatures")
getSupportedWindowFeaturesMethod.isPublic &&
getSupportedWindowFeaturesMethod.doesReturn(supportedWindowFeaturesClass)
}
}
private val displayFoldFeatureClass: Class<*>
get() {
return loader.loadClass(DISPLAY_FOLD_FEATURE_CLASS)
}
private val supportedWindowFeaturesClass: Class<*>
get() {
return loader.loadClass(SUPPORTED_WINDOW_FEATURES_CLASS)
}
private val foldingFeatureClass: Class<*>
get() {
return loader.loadClass(FOLDING_FEATURE_CLASS)
}
private val windowLayoutComponentClass: Class<*>
get() {
return loader.loadClass(WINDOW_LAYOUT_COMPONENT_CLASS)
}
}
| 29 | Kotlin | 1011 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 10,398 | androidx | Apache License 2.0 |
trusteddevice/tests/unit/src/com/google/android/libraries/car/trusteddevice/storage/DatabaseMigrationTest.kt | google | 415,118,653 | false | {"Kotlin": 865761, "Java": 244253} | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trusteddevice.storage
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.testing.MigrationTestHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import java.io.IOException
import java.time.Clock
import org.junit.Test
import org.junit.runner.RunWith
private val DEFAULT_CAR_ID = "testId"
private val DEFAULT_HANDLE = "handle".toByteArray()
private val DEFAULT_TOKEN = "token".toByteArray()
private val CREDENTIALS_TABLE_NAME = "credentials"
private val UNLOCK_HISTORY_TABLE_NAME = "unlock_history"
@RunWith(AndroidJUnit4::class)
class DatabaseMigrationTest {
private val TEST_DB = "migration-test"
val helper: MigrationTestHelper =
MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
TrustedDeviceDatabase::class.java.canonicalName,
FrameworkSQLiteOpenHelperFactory()
)
@Test
@Throws(IOException::class)
fun testMigrate3To4() {
var database = helper.createDatabase(TEST_DB, 3)
var values = ContentValues()
values.put("carId", DEFAULT_CAR_ID)
values.put("token", DEFAULT_HANDLE)
values.put("handle", DEFAULT_TOKEN)
database.insert(CREDENTIALS_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values)
val now = Clock.systemUTC().instant()
values = ContentValues()
values.put("carId", DEFAULT_CAR_ID)
values.put("instant", now.getNano())
database.insert(UNLOCK_HISTORY_TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values)
database.close()
database = helper.runMigrationsAndValidate(TEST_DB, 4, true, DatabaseProvider.DB_MIGRATION_3_4)
database.close()
}
}
| 1 | Kotlin | 5 | 18 | 912fd5cff1f08577d679bfaff9fc0666b8093367 | 2,386 | android-auto-companion-android | Apache License 2.0 |
sample-library/src/commonTest/kotlin/sample/ComplexSerializationTests.kt | nosix | 162,433,160 | false | null | package sample
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlin.test.Test
import kotlin.test.assertEquals
class ComplexSerializationTests {
@Test
fun testComplexDate() {
val data = ComplexData(
ChildData(
BigDecimal("12345678901234567890123456789012345678901234567890"),
DateTime.now()
),
ChildData(
BigDecimal("12345678901234567890123456789012345678901234567890.09876543210987654321"),
DateTime.now()
)
)
val jsonData = format.encodeToString(data)
println(jsonData)
val decodedData: ComplexData = format.decodeFromString(jsonData)
assertEquals(data, decodedData)
}
}
| 0 | Kotlin | 0 | 0 | c70959712c1e64dab566b40f062b9056f9a64ef6 | 798 | kotlin-serialization-sample | MIT License |
sample-multiplatform/src/commonMain/kotlin/dev/shustoff/dikt/sample/CarModule.kt | sergeshustoff | 334,399,967 | false | null | package dev.shustoff.dikt.sample
import dev.shustoff.dikt.Create
import dev.shustoff.dikt.CreateSingle
import dev.shustoff.dikt.UseModules
@UseModules(EngineModule::class)
class CarModule(
val engineModule: EngineModule,
) {
@CreateSingle
fun owner(): CarOwner
@Create fun carUnknownModel(): Car
@Create fun car(model: String): Car
@Create fun getGarage(): Garage
} | 3 | Kotlin | 3 | 125 | dfb94e77bc283e92ab58f351b988228ed2aa2021 | 394 | dikt | MIT License |
app/src/main/java/com/apx6/chipmunk/app/ui/vms/SettingViewModel.kt | volt772 | 506,075,620 | false | {"Kotlin": 297434} | package com.apx6.chipmunk.app.ui.vms
import androidx.lifecycle.viewModelScope
import com.apx6.chipmunk.app.di.IoDispatcher
import com.apx6.chipmunk.app.ext.currMillis
import com.apx6.chipmunk.app.ui.base.BaseViewModel
import com.apx6.domain.State
import com.apx6.domain.constants.CmdSettingType
import com.apx6.domain.constants.CmdSettingValue
import com.apx6.domain.dto.CmdSetting
import com.apx6.domain.dto.CmdUser
import com.apx6.domain.repository.CheckListRepository
import com.apx6.domain.repository.SettingRepository
import com.apx6.domain.repository.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SettingViewModel @Inject constructor(
@IoDispatcher val ioDispatcher: CoroutineDispatcher,
private val userRepository: UserRepository,
private val checkListRepository: CheckListRepository,
private val settingRepository: SettingRepository
) : BaseViewModel() {
init {
getUser()
}
private val _checkListCount: MutableStateFlow<State<Int>> = MutableStateFlow(State.loading())
val checkListCount: StateFlow<State<Int>> = _checkListCount
private val _user: MutableSharedFlow<CmdUser?> = MutableSharedFlow()
val user: SharedFlow<CmdUser?> = _user
private val _userDeleted: MutableSharedFlow<Boolean> = MutableSharedFlow()
val userDeleted: SharedFlow<Boolean> = _userDeleted
private val _setting: MutableSharedFlow<CmdSetting?> = MutableSharedFlow()
val setting: SharedFlow<CmdSetting?> = _setting
private val _notiPosted: MutableSharedFlow<Boolean> = MutableSharedFlow()
val notiPosted: SharedFlow<Boolean> = _notiPosted
private fun getUser() {
viewModelScope.launch {
userRepository.getUser().collectLatest { _user.emit(it) }
}
}
fun getCheckListCount(uid: Int) {
viewModelScope.launch {
checkListRepository.getCheckListCount(uid)
.map { resource -> State.fromResource(resource) }
.collect { state -> _checkListCount.value = state }
}
}
fun deleteUser(user: CmdUser) {
viewModelScope.launch(ioDispatcher) {
val deleted = userRepository.delUser(user)
_userDeleted.emit(deleted)
}
}
fun fetchNotificationSetting(uid: Int) {
viewModelScope.launch(ioDispatcher) {
settingRepository.fetchSetting(uid, CmdSettingType.NOTIFICATION)
.collectLatest {
_setting.emit(it)
}
}
}
fun postNotificationSetting(uid: Int, csv: CmdSettingValue) {
val cs = CmdSetting(
uid = uid,
key = CmdSettingType.NOTIFICATION,
value = csv.value,
setDate = currMillis
)
viewModelScope.launch(ioDispatcher) {
val posted = settingRepository.postSetting(cs)
_notiPosted.emit(posted)
}
}
} | 0 | Kotlin | 0 | 0 | bd8b2a81a97e10c7dddc6a202c4316364b328ad2 | 3,297 | chipmunk | Apache License 2.0 |
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/MythicDrops.kt | MythicDrops | 10,021,467 | false | null | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 <NAME>
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.api
import com.tealcube.minecraft.bukkit.mythicdrops.api.enchantments.CustomEnchantmentRegistry
import com.tealcube.minecraft.bukkit.mythicdrops.api.errors.LoadingErrorManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItemManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGroupManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ProductionLine
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.strategies.DropStrategyManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.RelationManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.repair.RepairItemManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGemManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.cache.SocketGemCacheManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.combiners.SocketGemCombinerGuiFactory
import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.combiners.SocketGemCombinerManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.TierManager
/**
* Allows access to plugin data and utilities.
*/
interface MythicDrops {
val itemGroupManager: ItemGroupManager
val socketGemCacheManager: SocketGemCacheManager
val socketGemManager: SocketGemManager
val socketGemCombinerManager: SocketGemCombinerManager
val socketGemCombinerGuiFactory: SocketGemCombinerGuiFactory
val settingsManager: SettingsManager
val repairItemManager: RepairItemManager
val customItemManager: CustomItemManager
val relationManager: RelationManager
val tierManager: TierManager
val loadingErrorManager: LoadingErrorManager
val customEnchantmentRegistry: CustomEnchantmentRegistry
val dropStrategyManager: DropStrategyManager
val productionLine: ProductionLine
fun reloadSettings()
fun reloadTiers()
fun reloadCustomItems()
fun reloadNames()
fun reloadRepairCosts()
fun reloadItemGroups()
fun reloadSocketGemCombiners()
fun saveSocketGemCombiners()
fun reloadSocketGems()
fun reloadRelations()
}
| 63 | null | 44 | 38 | ba9dcc23ec2dd8f972f9c37ca15d9195f7cfe107 | 3,441 | MythicDrops | MIT License |
appbase/src/main/java/com/pthw/appbase/di/AppBaseModule.kt | PhyoThihaWin | 769,428,664 | false | {"Kotlin": 66269} | package com.pthw.appbase.di
import com.pthw.appbase.exceptionmapper.ExceptionHandler
import com.pthw.appbase.exceptionmapper.ExceptionHandlerImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
/**
* Created by P.T.H.W on 11/03/2024.
*/
@Module
@InstallIn(SingletonComponent::class)
abstract class BaseAppModule {
@Binds
@Singleton
abstract fun exceptionMapper(exceptionMapperImpl: ExceptionHandlerImpl): ExceptionHandler
} | 0 | Kotlin | 0 | 0 | 955c412cfb5d81a963afcd40782bd2b4a6d44fb7 | 541 | compose-rsa-biometric | Apache License 2.0 |
spesialist-selve/src/main/kotlin/no/nav/helse/modell/kommando/ForberedBehandlingAvGodkjenningsbehov.kt | navikt | 244,907,980 | false | {"Kotlin": 2818632, "PLpgSQL": 29687, "HTML": 1741, "Dockerfile": 258} | package no.nav.helse.modell.kommando
import no.nav.helse.modell.person.Person
import no.nav.helse.modell.vedtaksperiode.SpleisVedtaksperiode
import java.time.LocalDate
import java.util.UUID
internal class ForberedBehandlingAvGodkjenningsbehov(
private val person: Person,
private val spleisVedtaksperioder: List<SpleisVedtaksperiode>,
private val vedtaksperiodeId: UUID,
private val utbetalingId: UUID,
private val spleisBehandlingId: UUID,
private val tags: List<String>,
private val skjæringstidspunkt: LocalDate,
): Command {
override fun execute(context: CommandContext): Boolean {
person.mottaSpleisVedtaksperioder(spleisVedtaksperioder)
person.flyttEventuelleAvviksvarsler(vedtaksperiodeId, skjæringstidspunkt)
person.oppdaterPeriodeTilGodkjenning(vedtaksperiodeId, tags, spleisBehandlingId, utbetalingId)
return true
}
}
| 1 | Kotlin | 3 | 0 | 85cee4011126da24ec113b7f9a52baba808a107d | 898 | helse-spesialist | MIT License |
app/src/main/java/com/example/taskplanner/view/PlannerFragment.kt | kikichechka | 781,460,462 | false | {"Kotlin": 22209} | package com.example.taskplanner.view
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import com.example.diplomaproject.view.PlannerCalendarFragment
import com.example.taskplanner.view.adapter.VpAdapter
import com.example.taskplanner.R
import com.example.taskplanner.databinding.FragmentPlannerBinding
import com.google.android.material.tabs.TabLayoutMediator
class PlannerFragment : Fragment() {
private val listFragmentPlanner =
listOf(
PlannerListFragment.newInstance(),
PlannerCalendarFragment.newInstance()
)
private val tabIcons = listOf(
R.drawable.baseline_checklist_24,
R.drawable.baseline_calendar_month_24
)
private var _binding: FragmentPlannerBinding? = null
private val binding: FragmentPlannerBinding
get() {
return _binding!!
}
companion object {
fun newInstance() = PlannerFragment()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentPlannerBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
creatingVpAdapter()
}
private fun creatingVpAdapter() {
val vpAdapter = VpAdapter(this, listFragmentPlanner)
binding.containerViewPager2.adapter = vpAdapter
TabLayoutMediator(binding.tabLayout, binding.containerViewPager2) { tab, pos ->
tab.text = resources.getStringArray(R.array.list_name_fragment_for_planner)[pos]
tab.icon = ResourcesCompat.getDrawable(resources, tabIcons[pos], null)
}.attach()
binding.addNewTask.setOnClickListener {
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.container_main, AddNewNoteFragment.newInstance())
.addToBackStack("AddNewNoteFragment")
.commit()
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
} | 0 | Kotlin | 0 | 0 | 1bc5d277cc79e346399ab23da7abf67ea260c3c2 | 2,300 | Diploma | Apache License 2.0 |
app/src/main/java/com/adaldosso/spendykt/login/LoginActivityKt.kt | daldosso | 75,467,676 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "XML": 135, "JSON": 1, "Proguard": 1, "Java": 15, "Kotlin": 23} | package com.adaldosso.spendykt.login
//import android.arch.lifecycle.ViewModelProviders
/*
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.SignInButton
*/
//import kotlinx.android.synthetic.main.activity_user.*
import android.annotation.TargetApi
import android.app.LoaderManager.LoaderCallbacks
import android.content.Loader
import android.database.Cursor
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.support.v7.app.AppCompatActivity
import com.adaldosso.spendykt.R
import io.reactivex.disposables.CompositeDisposable
/**
* A login screen that offers login via email/password.
*/
class LoginActivityKt : AppCompatActivity(), LoaderCallbacks<Cursor> {
override fun onCreateLoader(p0: Int, p1: Bundle?): Loader<Cursor> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onLoadFinished(p0: Loader<Cursor>?, p1: Cursor?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onLoaderReset(p0: Loader<Cursor>?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private var mAuthTask: LoginActivity.UserLoginTask? = null
/*
private lateinit var viewModelFactory: ViewModelFactory
private lateinit var viewModel: UserViewModel
*/
private val disposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// Set up the login form.
populateAutoComplete()
/*
password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
attemptLogin()
return@OnEditorActionListener true
}
false
})
*/
/*
email_sign_in_button.setOnClickListener { attemptLogin() }
email_sign_up_button.setOnClickListener { attemptSignUp() }
*/
/*
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.client_id))
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
sign_in_button.setSize(SignInButton.SIZE_WIDE)
sign_in_button.setColorScheme(SignInButton.COLOR_LIGHT)
sign_in_button.setOnClickListener { googleSignIn() }
sign_in_button.visibility = GONE
viewModelFactory = Injection.provideViewModelFactory(this)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(UserViewModel::class.java)
setResult(RESULT_OK, Intent())
*/
}
override fun onStart() {
super.onStart()
/*
disposable.add(viewModel.userName()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ this.user_name.text = it },
{ error -> Log.e(TAG, "Unable to get username", error) }))
*/
}
override fun onStop() {
super.onStop()
disposable.clear()
}
// private lateinit var googleSignInClient: GoogleSignInClient
private val RC_SIGN_IN = 9001
private fun googleSignIn() {
/*
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
*/
}
private fun populateAutoComplete() {
if (!mayRequestContacts()) {
return
}
// loaderManager.initLoader(0, null, this)
}
private fun mayRequestContacts(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true
}
/*
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(email, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok
) { requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS) }
} else {
requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS)
}
*/
return false
}
/**
* Callback received when a permissions request has been completed.
*/
/*
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete()
}
}
}
*/
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private fun attemptLogin() {
if (mAuthTask != null) {
return
}
// Reset errors.
/*
email.error = null
password.error = null
*/
// Store values at the time of the login attempt.
/*
val emailStr = email.text.toString()
val passwordStr = password.text.toString()
var cancel = false
var focusView: View? = null
// Check for a valid password
if (TextUtils.isEmpty(passwordStr)) {
password.error = getString(R.string.error_field_required)
focusView = password
cancel = true
} else if (!isPasswordValid(passwordStr)) {
*/
/*
password.error = getString(R.string.error_invalid_password)
focusView = password
cancel = true
*//*
}
// Check for a valid email address.
if (TextUtils.isEmpty(emailStr)) {
email.error = getString(R.string.error_field_required)
focusView = email
cancel = true
} else if (!isEmailValid(emailStr)) {
email.error = getString(R.string.error_invalid_email)
focusView = email
cancel = true
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView?.requestFocus()
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true)
*/
/*
mAuthTask = UserLoginTask(emailStr, passwordStr)
mAuthTask!!.execute(null as Void?)
*//*
disposable.add(viewModel.login(emailStr, passwordStr)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
showMessage("Bentornato") { _, _ -> finish() }
showProgress(false)
},
{ error ->
run {
showMessage(error.message)
showProgress(false)
Log.e(TAG, "Unable to update username", error)
}
}
)
)
*/
}
}
private fun attemptSignUp() {
/*
val emailStr = email.text.toString()
val passwordStr = password.text.toString()
disposable.add(viewModel.signUp(emailStr, passwordStr)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
showMessage("Benvenuto") { _, _ -> finish() }
showProgress(false)
},
{ error -> Log.e(TAG, "Unable to update username", error)
}
)
)
*/
}
private fun isEmailValid(email: String): Boolean {
//TODO: Replace this with your own logic
return email.contains("@")
}
private fun isPasswordValid(password: String): Boolean {
//TODO: Replace this with your own logic
return password.length > 4
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private fun showProgress(show: Boolean) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
/*
login_form.visibility = if (show) View.GONE else View.VISIBLE
login_form.animate()
.setDuration(shortAnimTime)
.alpha((if (show) 0 else 1).toFloat())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
login_form.visibility = if (show) View.GONE else View.VISIBLE
}
})
*/
/*
login_progress.visibility = if (show) View.VISIBLE else View.GONE
login_progress.animate()
.setDuration(shortAnimTime)
.alpha((if (show) 1 else 0).toFloat())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
login_progress.visibility = if (show) View.VISIBLE else View.GONE
}
})
*/
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
// login_progress.visibility = if (show) View.VISIBLE else View.GONE
// login_form.visibility = if (show) View.GONE else View.VISIBLE
}
}
/*
override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> {
return CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?", arrayOf(ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE),
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC")
}
override fun onLoadFinished(cursorLoader: Loader<Cursor>, cursor: Cursor) {
val emails = ArrayList<String>()
cursor.moveToFirst()
while (!cursor.isAfterLast) {
emails.add(cursor.getString(ProfileQuery.ADDRESS))
cursor.moveToNext()
}
addEmailsToAutoComplete(emails)
}
override fun onLoaderReset(cursorLoader: Loader<Cursor>) {
}
*/
private fun addEmailsToAutoComplete(emailAddressCollection: List<String>) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
/*
val adapter = ArrayAdapter(this@LoginActivityKt,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection)
email.setAdapter(adapter)
*/
}
object ProfileQuery {
val PROJECTION = arrayOf(
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY)
val ADDRESS = 0
val IS_PRIMARY = 1
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
/*
inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : AsyncTask<Void, Void, Boolean>() {
override fun doInBackground(vararg params: Void): Boolean? {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000)
} catch (e: InterruptedException) {
return false
}
return DUMMY_CREDENTIALS
.map { it.split(":") }
.firstOrNull { it[0] == mEmail }
?.let {
// Account exists, return true if the password matches.
it[1] == mPassword
}
?: true
}
override fun onPostExecute(success: Boolean?) {
mAuthTask = null
showProgress(false)
if (success!!) {
finish()
} else {
password.error = getString(R.string.error_incorrect_password)
password.requestFocus()
}
}
override fun onCancelled() {
mAuthTask = null
showProgress(false)
}
}
companion object {
*/
/**
* Id to identity READ_CONTACTS permission request.
*//*
private val REQUEST_READ_CONTACTS = 0
*/
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*//*
private val DUMMY_CREDENTIALS = arrayOf("[email protected]:hello", "[email protected]:world")
private val TAG = UserActivity::class.java.simpleName
}
*/
//}
| 1 | null | 1 | 1 | c4caeb372ddb98a21b04bf5cee3852062d544c0e | 14,284 | SpendyKt | MIT License |
src/main/java/com/denisbelobrotski/eye_tracking_library/detector/EyeProcessor.kt | DenisBelobrotski | 354,017,403 | false | null | package by.swiftdrachen.eye_tracking_library.detector
import by.swiftdrachen.eye_tracking_library.abstraction.IEyeProcessor
import by.swiftdrachen.eye_tracking_library.abstraction.IEyeProcessorConfig
import by.swiftdrachen.eye_tracking_library.abstraction.IPointDetector
import by.swiftdrachen.eye_tracking_library.exception.EyeTrackerNotPreparedException
import by.swiftdrachen.eye_tracking_library.util.SessionFileManager
import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.core.Point
import org.opencv.core.Range
import org.opencv.imgproc.Imgproc
class EyeProcessor(
override val config: IEyeProcessorConfig,
override val eyePreciser: IPointDetector,
override val pupilDetector: IPointDetector) : IEyeProcessor {
private val processingImage = Mat()
private val hsvChannels: MutableList<Mat> = ArrayList(3)
private var mutableDetectedEyeCenter = Point()
private var mutableDetectedPupilCenter = Point()
override var sourceImage: Mat? = null
override var sessionFileManager: SessionFileManager? = null
override val detectedEyeCenter: Point
get() = mutableDetectedEyeCenter
override val detectedPupilCenter: Point
get() = mutableDetectedPupilCenter
override fun process() {
sessionFileManager?.addLog("EyeProcessor - process started")
if (sourceImage == null) {
throw EyeTrackerNotPreparedException("Source image cannot be null")
}
val sourceImage = this.sourceImage!!
val rowsCount = sourceImage.rows()
val colsCount = sourceImage.cols()
val topOffset = rowsCount * config.topOffsetPercentage / 100
val bottomOffset = rowsCount * config.bottomOffsetPercentage / 100
val rowsRange = Range(topOffset, rowsCount - bottomOffset)
val colsRange = Range(0, colsCount)
val cutImage = sourceImage.submat(rowsRange, colsRange)
sessionFileManager?.addLog("EyeProcessor - submat taken")
Imgproc.cvtColor(cutImage, processingImage, Imgproc.COLOR_RGB2HSV)
sessionFileManager?.addLog("EyeProcessor - RGB to HSV")
Core.split(processingImage, hsvChannels)
sessionFileManager?.addLog("EyeProcessor - HSV splitted")
val hue = hsvChannels[0]
val saturation = hsvChannels[1]
val value = hsvChannels[2]
sessionFileManager?.addLog("EyeProcessor - HSV splitted")
sessionFileManager?.saveMat(hue, "eye_hue", true)
sessionFileManager?.saveMat(saturation, "eye_saturation", true)
sessionFileManager?.saveMat(value, "eye_value", true)
sessionFileManager?.addLog("EyeProcessor - channels saved", true)
pupilDetector.processingImage = value
pupilDetector.detect()
mutableDetectedPupilCenter = pupilDetector.detectedPoint
mutableDetectedPupilCenter.y += topOffset
sessionFileManager?.addLog("EyeProcessor - pupil detection done")
eyePreciser.processingImage = saturation
eyePreciser.detect()
mutableDetectedEyeCenter = eyePreciser.detectedPoint
mutableDetectedEyeCenter.y += topOffset
sessionFileManager?.addLog("EyeProcessor - eye precision done")
hue.release()
saturation.release()
value.release()
hsvChannels.clear()
sessionFileManager?.addLog("EyeProcessor - memory cleared")
sessionFileManager?.addLog("EyeProcessor - process done")
}
}
| 0 | Kotlin | 0 | 1 | 7f7654914023a0f572abb79274081475edb724c5 | 3,470 | eye-tracking-library | MIT License |
core/src/main/kotlin/lemma/abstractions/Drawable.kt | kubeliv | 470,008,106 | false | null | package lemma.abstractions
import io.github.humbleui.skija.Canvas
interface Drawable {
fun draw(canvas: Canvas)
}
| 0 | Kotlin | 0 | 0 | f07d63cf6cba5c9647d37885852929f7e04cf435 | 118 | lemma | MIT License |
app/src/main/java/com/example/affirmations/DetailActivity.kt | xavierguillamonitb | 617,614,183 | false | null | package com.example.affirmations
import android.content.ActivityNotFoundException
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Mail
import androidx.compose.material.icons.filled.Phone
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.affirmations.ui.theme.CharactersViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.affirmations.model.Character
import com.example.affirmations.ui.theme.AffirmationsTheme
import com.example.affirmations.ui.theme.DetailViewModel
class DetailActivity: ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val characterId = intent.getIntExtra("id", 0)
setContent {
CharacterApp(characterId = characterId)
}
}
}
@Composable
fun CharacterApp(characterId: Int){
AffirmationsTheme{
DetailScreen(detailViewModel = DetailViewModel(characterId))
}
}
@Composable
fun DetailScreen(detailViewModel: DetailViewModel) {
val uiState by detailViewModel.uiState.collectAsState()
val context = LocalContext.current
Box {
Image(
painterResource(id = R.drawable.background), contentDescription = null,
modifier = Modifier
.fillMaxSize()
.alpha(0.5f),
contentScale = ContentScale.FillHeight
)
}
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
) {
Column() {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
Text(
text = stringResource(id = uiState.stringResourceId),
modifier = Modifier.padding(16.dp),
style = TextStyle(
fontSize = 24.sp
),
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
Image(
painter = painterResource(id = uiState.imageResourceId),
contentDescription = stringResource(
id = uiState.stringResourceId
),
modifier = Modifier
.size(100.dp)
.padding(8.dp)
.clip(CutCornerShape(20))
)
}
Text(
text = stringResource(id = uiState.descriptionId),
modifier = Modifier.padding(16.dp)
)
Image(
painter = painterResource(uiState.imageDetailResourceId),
contentDescription = "Background",
modifier = Modifier.fillMaxWidth(),
contentScale = ContentScale.FillWidth,
)
Row(
modifier = Modifier.fillMaxWidth()
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth(0.5f)
) {
Text(
text = "Card",
modifier = Modifier.padding(16.dp),
)
Image(
painter = painterResource(id = uiState.imageCardId),
contentDescription = stringResource(
id = uiState.stringResourceId
),
modifier = Modifier
.padding(8.dp)
.size(500.dp),
contentScale = ContentScale.FillHeight,
)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
) {
Text(
text = "Card",
modifier = Modifier.padding(16.dp),
)
Image(
painter = painterResource(id = uiState.imageModelId),
contentDescription = stringResource(
id = uiState.stringResourceId
),
modifier = Modifier
.padding(8.dp)
.size(500.dp),
contentScale = ContentScale.FillHeight,
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 15.dp),
horizontalArrangement = Arrangement.End
) {
IconButton(onClick = { context.sendMail(uiState.emailTo, uiState.email) }) {
Icon(
imageVector = Icons.Filled.Mail,
contentDescription = "Button Mail",
modifier = Modifier.padding(end = 30.dp)
)
}
IconButton(onClick = { context.dial(uiState.phone) }) {
Icon(
imageVector = Icons.Filled.Phone,
contentDescription = "ButtonPhone",
modifier = Modifier.padding(end = 30.dp)
)
}
}
}
}
}
fun Context.sendMail(to: String, subject: String) {
try {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "message/rfc822"
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(to))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
startActivity(Intent.createChooser(intent, ""))
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "No email client installed.", Toast.LENGTH_SHORT).show()
} catch (t: Throwable) {
Toast.makeText(this, "Nope", Toast.LENGTH_SHORT).show()
}
}
fun Context.dial(phone: String) {
try {
val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null))
startActivity(intent)
} catch (t: Throwable) {
}
}
@Preview
@Composable
fun si(){
DetailScreen(detailViewModel = DetailViewModel(3))
} | 0 | Kotlin | 0 | 0 | e8480a8fd683a6d6fb6e3e358b06312c286aef2c | 7,954 | M7-8_XaviGuillamon_ViewModel | Apache License 2.0 |
src/main/kotlin/commands/CommandRegistration.kt | enzosarmento | 854,270,944 | false | {"Kotlin": 8426} | package commands
import dev.kord.core.Kord
import dev.kord.rest.builder.interaction.string
suspend fun registerCommands(kord: Kord) {
kord.createGlobalApplicationCommands {
input("connect", "Conectar ao seu canal")
input("pause", "Pausa a música")
input("stop", "Para a música")
input("leave", "Sai do canal atual")
input("play", "Começa a tocar uma música") {
string("musica", "Qual a música que você quer tocar?")
}
input("skip", "Pula para a próxima música da fila")
}
} | 0 | Kotlin | 0 | 0 | db09708ff4f95bdf975d8a0a0b5724e59e8158b5 | 551 | px-bot | MIT License |
features/profile/src/commonMain/kotlin/com/mathroda/profile/settings/components/VersionItem.kt | MathRoda | 507,060,394 | false | null | package com.mathroda.profile.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filter
@Composable
fun VersionItem(
appVersion: String
) {
val title = "App Version"
val uriHandler = LocalUriHandler.current
var numberOfClicks by remember { mutableIntStateOf(0) }
val onClick: () -> Unit = {
if (++numberOfClicks == 7) {
uriHandler.openUri(EasterEggUrl)
}
}
LaunchedEffect(Unit) {
snapshotFlow { numberOfClicks }
.filter { it > 0 }
.collectLatest {
delay(1_000)
numberOfClicks = 0
}
}
Column(
modifier = Modifier
.clickable { onClick() }
.padding(horizontal = 8.dp)
.fillMaxWidth()
.height(48.dp),
verticalArrangement = Arrangement.Center,
) {
Text(
text = title,
style = MaterialTheme.typography.body2,
)
Text(
text = appVersion,
style = MaterialTheme.typography.caption,
)
}
}
private const val EasterEggUrl = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" | 0 | null | 41 | 297 | cf303ba50bad35a816253bee5b27beee5ea364b8 | 2,049 | DashCoin | Apache License 2.0 |
agp-7.1.0-alpha01/tools/base/wizard/template-impl/src/com/android/tools/idea/wizard/template/impl/fragments/blankFragment/src/app_package/blankFragmentKt.kt | jomof | 502,039,754 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.wizard.template.impl.fragments.blankFragment.src.app_package
import com.android.tools.idea.wizard.template.getMaterialComponentName
import com.android.tools.idea.wizard.template.escapeKotlinIdentifier
import com.android.tools.idea.wizard.template.renderIf
fun blankFragmentKt(
applicationPackage: String?,
className: String,
fragmentName: String,
packageName: String,
useAndroidX: Boolean
): String {
val applicationPackageBlock = renderIf(applicationPackage != null) { "import ${applicationPackage}.R" }
return """
package ${escapeKotlinIdentifier(packageName)}
import android.os.Bundle
import ${getMaterialComponentName("android.support.v4.app.Fragment", useAndroidX)}
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
$applicationPackageBlock
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [${className}.newInstance] factory method to
* create an instance of this fragment.
*/
class ${className} : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.${fragmentName}, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ${className}.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic fun newInstance(param1: String, param2: String) =
${className}().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
"""
}
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 3,172 | CppBuildCacheWorkInProgress | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsalertsapi/validator/CreateAlertDateValidator.kt | ministryofjustice | 750,461,021 | false | {"Kotlin": 693597, "Shell": 1834, "Mermaid": 1398, "Dockerfile": 1372} | package uk.gov.justice.digital.hmpps.hmppsalertsapi.validator
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import uk.gov.justice.digital.hmpps.hmppsalertsapi.model.request.CreateAlert
class CreateAlertDateValidator : ConstraintValidator<DateComparison, CreateAlert> {
override fun isValid(value: CreateAlert, context: ConstraintValidatorContext?): Boolean {
return if (value.activeFrom != null && value.activeTo != null) {
value.activeFrom!!.isBefore(value.activeTo)
} else {
true
}
}
}
| 4 | Kotlin | 0 | 0 | b06f88b3f8c9d6dfd78eef03b25dc77535dc856d | 571 | hmpps-alerts-api | MIT License |
idea/tests/testData/inspectionsLocal/simpleRedundantLet/extensionWithNullableReceiverCall2.kt | JetBrains | 278,369,660 | false | null | // WITH_STDLIB
// PROBLEM: none
class Optional<out T>(val value: T)
val Any?.foo get() = println("foo: $this")
fun main() {
val b: Optional<Any?>? = Optional(null)
b?.let<caret> { it.value.foo }
}
| 1 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 207 | intellij-kotlin | Apache License 2.0 |
src/main/kotlin/com/healthmetrix/labres/LabResApplication.kt | labres | 255,649,801 | false | null | package com.healthmetrix.labres
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
@SpringBootApplication
@ConfigurationPropertiesScan
@EnableConfigurationProperties
class LabResApplication
fun main(args: Array<String>) {
runApplication<LabResApplication>(*args)
}
| 1 | Kotlin | 0 | 0 | 5df188bed713e9dcfab5f1dd36e16fda43c4167d | 496 | server | MIT License |
src/main/java/com/kotlinspirit/number/FloatRule.kt | tiksem | 494,746,133 | false | {"Kotlin": 465350, "HTML": 2017} | package com.kotlinspirit.number
import com.kotlinspirit.core.*
import com.kotlinspirit.core.createComplete
import com.kotlinspirit.core.createStepResult
import com.kotlinspirit.repeat.RuleWithDefaultRepeat
class FloatRule(name: String? = null) : BaseFloatRule<Float>(
name = name,
invalidFloatErrorCode = ParseCode.INVALID_FLOAT
) {
override fun String.getValue(): Float {
// TODO: Optimize
return when {
isNan() -> Float.NaN
isNegativeInfinity() -> Float.NEGATIVE_INFINITY
isPositiveInfinity() -> Float.POSITIVE_INFINITY
else -> toFloat()
}
}
override fun clone(): FloatRule {
return this
}
override fun name(name: String): FloatRule {
return FloatRule(name)
}
override val defaultDebugName: String
get() = "float"
} | 0 | Kotlin | 0 | 2 | 783fdb0655608e8260c0e0a368a99af468f08d29 | 854 | KotlinSpirit | MIT License |
integration-test/src/test/java/gsonpath/extension/TestUtil.kt | LachlanMcKee | 84,700,968 | false | null | package gsonpath.extension
import com.google.gson.GsonBuilder
import com.google.gson.JsonParseException
import gsonpath.GsonPath
import gsonpath.TestGsonTypeFactory
import org.junit.Assert
object TestUtil {
fun <T> executeFromJson(clazz: Class<T>, jsonString: String): T =
GsonBuilder()
.registerTypeAdapterFactory(GsonPath.createTypeAdapterFactory(TestGsonTypeFactory::class.java))
.create()
.fromJson(jsonString, clazz)
fun expectException(clazz: Class<*>, jsonString: String, message: String) {
val exception: JsonParseException? =
try {
executeFromJson(clazz, jsonString)
null
} catch (e: JsonParseException) {
e
}
if (exception != null) {
Assert.assertEquals(message, exception.message)
return
}
Assert.fail("Expected exception was not thrown.")
}
}
| 1 | Kotlin | 1 | 8 | edeb2bb93ee4811559500b9788bdf8bbc1073d6d | 958 | gsonpath-extensions | MIT License |
navigation/navigation-runtime-lint/src/test/java/androidx/navigation/runtime/lint/Stub.kt | androidx | 256,589,781 | false | {"Kotlin": 109239658, "Java": 66148038, "C++": 9132145, "AIDL": 624766, "Python": 320425, "Shell": 190703, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* Copyright 2024 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.navigation.runtime.lint
import androidx.navigation.lint.common.bytecodeStub
import androidx.navigation.lint.common.kotlinAndBytecodeStub
internal val NAV_CONTROLLER =
bytecodeStub(
"NavController.kt",
"androidx/navigation",
0xe2eb4ee4,
"""
package androidx.navigation
import kotlin.reflect.KClass
open class NavController {
fun navigate(resId: Int) {}
fun navigate(route: String) {}
fun <T : Any> navigate(route: T) {}
inline fun <reified T: Any> popBackStack(
inclusive: Boolean,
saveState: Boolean = false
) {}
fun <T : Any> popBackStack(
route: T,
inclusive: Boolean,
saveState: Boolean = false
) {}
}
inline fun NavController.createGraph(
startDestination: Any,
route: KClass<*>? = null,
): NavGraph { return NavGraph() }
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJOBijgMuQSTsxLKcrPTKnQy0ssy0xPLMnM
zxPi90ssc87PKynKz8lJLfIuEeIECnjkF5d4l3CJc/HCtZSkFpcIsYWkgiSU
GLQYABRWGrdkAAAA
""",
"""
androidx/navigation/NavController.class:
H4sIAAAAAAAA/41VW1MjRRQ+PZPLMAQYss<KEY>
fAB9You/4/iohDIVwPy/6dF9DeMIAAA=
""",
"""
androidx/navigation/NavControllerKt.class:
<KEY>"""
)
internal val NAV_DESTINATION =
bytecodeStub(
"NavDestination.kt",
"androidx/navigation",
0x89e4229a,
"""
package androidx.navigation
open class NavDestination
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJOBijgMuQSTsxLKcrPTKnQy0ssy0xPLMnM
zxPi90ssc87PKynKz8lJLfIuEeIECnjkF5d4l3CJcnEn5+fqpVYk5hbkpAqx
haSChJUYtBgAOMX57WIAAAA=
""",
"""
androidx/navigation/NavDestination.class:
H<KEY>
"""
)
internal val NAV_GRAPH =
bytecodeStub(
"NavGraph.kt",
"androidx/navigation",
0x54a108f5,
"""
package androidx.navigation
open class NavGraph: NavDestination() {
fun <T : Any> setStartDestination(startDestRoute: T) {}
}
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJOBijgMuQSTsxLKcrPTKnQy0ssy0xPLMnM
<KEY>
haSChJUYtBgAOMX57WIAAAA=
""",
"""
androidx/navigation/NavGraph.class:
H4sIAAAAAAAA/31SXU8TQRQ9s2232wVpAUGo4<KEY>
"""
)
internal val NAV_HOST =
bytecodeStub(
"NavHost.kt",
"androidx/navigation",
0x5ce5aeda,
"""
package androidx.navigation
import kotlin.reflect.KClass
interface NavHost
inline fun NavHost.createGraph(
startDestination: Any,
route: KClass<*>? = null,
): NavGraph { return NavGraph() }
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJOBijgMuQSTsxLKcrPTKnQy0ssy0xPLMnM
zxPi90ssc87PKynKz8lJLfIuEeIECnjkF5d4l3CJcnEn5+fqpVYk5hbkpAqx
haSChJUYtBgAOMX57WIAAAA=
""",
"""
androidx/navigation/NavHost.class:
H4sIAAAAAAAA/32OzUoDMRSFz81of8a/qVqoiK9g2uLOlZviQFVQcDOrtBNL
Ot<KEY>ZZBeCQenR1YLcIOPwEAAA==
""",
"""
androidx/navigation/NavHostKt.class:
<KEY>
"""
)
internal val TEST_NAV_HOST =
bytecodeStub(
"TestNavHost.kt",
"androidx/navigation",
0x2f602e26,
"""
package androidx.navigation
class TestNavHost: NavHost
""",
"""
META-INF/main.kotlin_module:
H<KEY>OMX57WIAAAA=
""",
"""
androidx/navigation/TestNavHost.class:
H4sIAAAAAAAA/4VRTUtCQRQ99z01fVmpfWlW0q5a9EzaFUEFkWAGJW5cjb5H
Teo8cEZp<KEY>"""
)
internal val NAVIGATION_STUBS =
arrayOf(NAV_CONTROLLER, NAV_DESTINATION, NAV_GRAPH, NAV_HOST, TEST_NAV_HOST)
internal val TEST_CODE =
kotlinAndBytecodeStub(
"Test.kt",
"androidx/test",
0xef517b0b,
"""
package androidx.test
val classInstanceRef = TestClass()
val classInstanceWithArgRef = TestClassWithArg(15)
val innerClassInstanceRef = Outer.InnerClass(15)
object TestGraph
object TestObject
class TestClass
class TestClassWithArg(val arg: Int)
object Outer {
data object InnerObject
data class InnerClass (
val innerArg: Int,
)
}
interface TestInterface
class InterfaceChildClass(val arg: Boolean): TestInterface
object InterfaceChildObject: TestInterface
abstract class TestAbstract
class AbstractChildClass(val arg: Boolean): TestAbstract()
object AbstractChildObject: TestAbstract()
// classes with companion object to simulate classes marked with @Serializable
class TestClassComp { companion object }
class TestClassWithArgComp(val arg: Int) { companion object }
object OuterComp {
data object InnerObject
data class InnerClassComp (
val innerArg: Int,
) { companion object }
}
class InterfaceChildClassComp(val arg: Boolean): TestInterface { companion object }
abstract class TestAbstractComp { companion object }
class AbstractChildClassComp(val arg: Boolean): TestAbstractComp() { companion object }
object AbstractChildObjectComp: TestAbstractComp()
""",
"""
META-INF/main.kotlin_module:
<KEY>GL<KEY>
""",
"""
androidx/test/AbstractChildClass.class:
<KEY>hQcKvsJDBVchUKj/BOsI9uW0AgAA
""",
"""
androidx/test/AbstractChildClassComp$Companion.class:
H<KEY>mnhcLHyAVvFLkwfUWz+G18d6Hxt9bOIGpbjZp5m3j8EMGmgSbxAY3DEo/wZN
V6SgDwMAAA==
""",
"""
androidx/test/AbstractChildClassComp.class:
<KEY>
""",
"""
androidx/test/AbstractChildObject.class:
<KEY>
""",
"""
androidx/test/AbstractChildObjectComp.class:
<KEY>
""",
"""
androidx/test/InterfaceChildClass.class:
<KEY>
""",
"""
androidx/test/InterfaceChildClassComp$Companion.class:
<KEY>s<KEY>
YBIDAAA=
""",
"""
androidx/test/InterfaceChildClassComp.class:
<KEY>
""",
"""
androidx/test/InterfaceChildObject.class:
H<KEY>
""",
"""
androidx/test/Outer$InnerClass.class:
H4sIAAAAAAAA/4VU308cVRT+7sz+mB0WmOVXKay0yorL0nYAW62FVgFFBpel
QkOs+HLZvcLAMoMzs6S+GJ76JzTRFxNjfOKhTRSMTQy2b/5NxnjuznS3LgSS
mXvOPXPOd757zrnz979//AngJlYZhrhT8Vy78sgMhB+Yy7VAeDnLcYQ3V+W+
nwRjMLb5Pjer3Nk0lze2RTlIQmVITNuOHdxjiOWt0TUGNT+6lkYcSR0xaAya
LVFmvE0GZqWhoy0FBWnyD7Zsn+Fq8fzUUwxtmyKwGiiUwGLQy+7unusIJ5gg
qLK79y3DMDG4GG246Hqb5<KEY>
""",
"""
androidx/test/Outer$InnerObject.class:
H<KEY>5<KEY>
""",
"""
androidx/test/Outer.class:
<KEY>
""",
"""
androidx/test/OuterComp$InnerClassComp$Companion.class:
<KEY>
""",
"""
androidx/test/OuterComp$InnerClassComp.class:
<KEY>Py<KEY>
""",
"""
androidx/test/OuterComp$InnerObject.class:
<KEY>
""",
"""
androidx/test/OuterComp.class:
<KEY>
""",
"""
androidx/test/TestAbstract.class:
<KEY>
""",
"""
androidx/test/TestAbstractComp$Companion.class:
<KEY>
""",
"""
androidx/test/TestAbstractComp.class:
<KEY>zA/4OwMAAA==
""",
"""
androidx/test/TestClass.class:
<KEY>
""",
"""
androidx/test/TestClassComp$Companion.class:
<KEY>
""",
"""
androidx/test/TestClassComp.class:
<KEY>
""",
"""
androidx/test/TestClassWithArg.class:
<KEY>
""",
"""
androidx/test/TestClassWithArgComp$Companion.class:
<KEY>4QkDAAA=
""",
"""
androidx/test/TestClassWithArgComp.class:
H4sIAAAAAAAA/41SW08TQRT+ZnvZ7VpkqYgFvCAXLRXZQnwSQoI1xk1KTZDU
GJ<KEY>
""",
"""
androidx/test/TestGraph.class:
<KEY>
""",
"""
androidx/test/TestInterface.class:
<KEY>
""",
"""
androidx/test/TestKt.class:
<KEY>
""",
"""
androidx/test/TestObject.class:
<KEY>
"""
)
.bytecode
| 27 | Kotlin | 992 | 5,270 | c2be9e019eb2fc7a1c9f1a5b8d244db7046246d0 | 8,049 | androidx | Apache License 2.0 |
template/app/src/commonMain/kotlin/kotli/app/presentation/passcode/ui/forgot/ForgotPasscodeDialog.kt | kotlitecture | 790,159,970 | false | {"Kotlin": 545071, "Swift": 543, "JavaScript": 313, "HTML": 234} | package kotli.app.presentation.passcode.ui.forgot
import androidx.compose.runtime.Composable
import org.jetbrains.compose.resources.stringResource
import shared.design.component.AppAlertDialog
import shared.presentation.store.DataState
import shared.presentation.viewmodel.provideViewModel
import template.app.generated.resources.Res
import template.app.generated.resources.passcode_forgot_message
import template.app.generated.resources.passcode_forgot_no
import template.app.generated.resources.passcode_forgot_title
import template.app.generated.resources.passcode_forgot_yes
@Composable
fun ForgotPasscodeDialog(state: DataState<Boolean>) {
if (state.asStateValue() != true) return
val viewModel: ForgotPasscodeViewModel = provideViewModel()
AppAlertDialog(
onDismissRequest = { state.set(false) },
title = stringResource(Res.string.passcode_forgot_title),
text = stringResource(Res.string.passcode_forgot_message),
confirmLabel = stringResource(Res.string.passcode_forgot_yes),
dismissLabel = stringResource(Res.string.passcode_forgot_no),
confirmAction = { viewModel.onConfirm(state) },
dismissAction = { state.set(false) }
)
} | 2 | Kotlin | 3 | 55 | 0ea8aa724e156259d5d5c9c8a423513c61b5156b | 1,209 | template-multiplatform-compose | MIT License |
src/main/kotlin/ro/sek1/RESTful/model/request/index/IndexDeleteVoteRequest.kt | vSEK1RO | 789,349,322 | false | {"Kotlin": 41819, "Dockerfile": 125} | package ro.sek1.RESTful.model.request.index
import com.fasterxml.jackson.annotation.JsonProperty
data class IndexDeleteVoteRequest(
@JsonProperty("list_ids")
var list_ids: MutableList<Long>
)
| 0 | Kotlin | 0 | 0 | ceaa3e7e685723c4bc978dd6f8aeaac7cb4bf6a8 | 201 | RESTful | MIT License |
lib_net/src/main/java/com/hzsoft/lib/net/utils/RequestBodyUtil.kt | zhouhuandev | 346,678,456 | false | null | package com.hzsoft.lib.net.utils
import com.hzsoft.lib.domain.base.BaseBean
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
/**
* Retrofit转换请求工具类
* @author zhouhuan
* @time 2021/6/25 21:05
*/
object RequestBodyUtil {
@JvmStatic
fun createRequestBody(params: Map<*, *>): RequestBody {
return params.toJson()
.toRequestBody("application/json; charset=utf-8".toMediaType())
}
@JvmStatic
fun <T : BaseBean> createRequestBody(bean: T): RequestBody {
return bean.toJson()
.toRequestBody("application/json; charset=utf-8".toMediaType())
}
@JvmStatic
fun <T : BaseBean> createRequestBody(list: List<T>): RequestBody {
return list.toJson()
.toRequestBody("application/json; charset=utf-8".toMediaType())
}
@JvmStatic
fun <T> createRequestBodyNew(list: List<T>): RequestBody {
return list.toJson()
.toRequestBody("application/json; charset=utf-8".toMediaType())
}
@JvmStatic
fun <T> createFieldMap(bean: T): Map<String, Any>? {
return GsonUtils.mapFromJson(bean?.toJson())
}
} | 0 | null | 53 | 242 | 75e30d9a1463c63b964f848a0ae1977d29d1442d | 1,202 | BaseDemo | Apache License 2.0 |
dialogspinner/src/main/java/com/github/mhdwajeeh/dialogspinner/DialogSpinnerPopup.kt | mhdwajeeh95 | 249,400,326 | false | null | package com.github.mhdwajeeh.dialogspinner
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.Window
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.mhdwajeeh.dialogspinner.R
import kotlinx.android.synthetic.main.dialog_spinner_popup.*
class DialogSpinnerPopup(
context: Context,
var selectionMode: Int,
dataSet: MutableList<String>,
selectionList: List<Int>,
var itemSelectionListener: ItemSelectionListener?
) : Dialog(context), ItemSelectionListener {
var recyclerAdapter: DialogSpinnerRecyclerAdapter? = null
init {
recyclerAdapter =
DialogSpinnerRecyclerAdapter(selectionMode, dataSet, selectionList.toMutableSet(), this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.dialog_spinner_popup)
recycler_view.layoutManager = LinearLayoutManager(context)
recycler_view.adapter = recyclerAdapter
search_clear_btn.setOnClickListener { search_et.setText("") }
ok_btn.visibility =
if (selectionMode == DialogSpinner.SELECTION_MODE_SINGLE) View.GONE else View.VISIBLE
ok_btn.setOnClickListener { dismiss() }
search_et.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
recyclerAdapter?.searchQuery = s?.toString() ?: ""
}
})
}
override fun onItemSelection(items: List<Int>) {
if (selectionMode == DialogSpinner.SELECTION_MODE_SINGLE)
this.dismiss()
this.itemSelectionListener?.onItemSelection(items)
}
fun getSelection(): List<Int> {
return recyclerAdapter?.getSelection() ?: listOf()
}
} | 0 | Kotlin | 0 | 0 | 7355a63adb04b5de6f775c1f9c4acb99b0636b45 | 2,183 | DialogSpinner | Apache License 2.0 |
src/test/kotlin/com/igorwojda/string/hasrepeatedcharacter/challenge.kt | ExpensiveBelly | 308,111,738 | true | {"Kotlin": 244479} | package com.igorwojda.string.hasrepeatedcharacter
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
private fun hasRepeatedChar(str: String): Boolean {
return str.groupingBy { it }.eachCount().count { it.value > 1 } > 0
}
private class Test {
@Test
fun `"abc" don't have repeated character`() {
hasRepeatedChar("abc") shouldBeEqualTo false
}
@Test
fun `"aabc" has repeated character`() {
hasRepeatedChar("aabc") shouldBeEqualTo true
}
@Test
fun `"aabcc" has repeated character`() {
hasRepeatedChar("aabcc") shouldBeEqualTo true
}
}
| 1 | Kotlin | 0 | 0 | f08e5bc1ccf5e1c686e228c7377edff12fd1b35f | 627 | kotlin-coding-puzzle-1 | MIT License |
app/src/main/java/com/example/disneycharactersapp/ui/home/HomeViewModel.kt | sahinkaradeniz | 609,536,462 | false | null | package com.example.disneycharactersapp.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.disneycharactersapp.R
import com.example.disneycharactersapp.data.NetworkResponse
import com.example.disneycharactersapp.domain.DisneyCharactersEntity
import com.example.disneycharactersapp.domain.mapper.allcharacter.DisneyCharacterListMapper
import com.example.disneycharactersapp.domain.usecase.getallcharacter.GetDisneyUseCase
import com.example.disneycharactersapp.domain.usecase.searchcharacter.GetSearchCharacterUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val getSearchCharacterUseCase: GetSearchCharacterUseCase,
private val disneyCharacterMapper:DisneyCharacterListMapper<DisneyCharactersEntity,HomeUiData>,
private val getDisneyUseCase:GetDisneyUseCase
) : ViewModel() {
private val _disneyHomeUiState=MutableLiveData<HomeUiState>()
val disneyHomeUiState:LiveData<HomeUiState> get() = _disneyHomeUiState
var allDisneyCharacters: List<HomeUiData>? = null
fun searchDisneyCharacters(name: String) {
getSearchCharacterUseCase(nameText = name).onEach {
when (it) {
is NetworkResponse.Error -> {
_disneyHomeUiState.value = HomeUiState.Error(R.string.eror)
}
NetworkResponse.Loading -> {
_disneyHomeUiState.postValue(HomeUiState.Loading)
}
is NetworkResponse.Success -> {
_disneyHomeUiState.postValue(HomeUiState.Success(disneyCharacterMapper.map(it.result)))
}
}
}.launchIn(viewModelScope)
}
fun getDisneyCharacters(){
getDisneyUseCase().onEach {
when (it) {
is NetworkResponse.Error -> {
_disneyHomeUiState.value = HomeUiState.Error(R.string.eror)
}
is NetworkResponse.Loading -> {
_disneyHomeUiState.value = HomeUiState.Loading
}
is NetworkResponse.Success -> {
val data = disneyCharacterMapper.map(it.result)
_disneyHomeUiState.value = HomeUiState.Success(data)
allDisneyCharacters = data
}
}
}.launchIn(viewModelScope)
}
} | 0 | Kotlin | 0 | 2 | a5134ef29da949929365f0b622b77d0cc489e952 | 2,613 | DisneyCharactersApp | MIT License |
app/src/main/java/com/example/disneycharactersapp/ui/home/HomeViewModel.kt | sahinkaradeniz | 609,536,462 | false | null | package com.example.disneycharactersapp.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.disneycharactersapp.R
import com.example.disneycharactersapp.data.NetworkResponse
import com.example.disneycharactersapp.domain.DisneyCharactersEntity
import com.example.disneycharactersapp.domain.mapper.allcharacter.DisneyCharacterListMapper
import com.example.disneycharactersapp.domain.usecase.getallcharacter.GetDisneyUseCase
import com.example.disneycharactersapp.domain.usecase.searchcharacter.GetSearchCharacterUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val getSearchCharacterUseCase: GetSearchCharacterUseCase,
private val disneyCharacterMapper:DisneyCharacterListMapper<DisneyCharactersEntity,HomeUiData>,
private val getDisneyUseCase:GetDisneyUseCase
) : ViewModel() {
private val _disneyHomeUiState=MutableLiveData<HomeUiState>()
val disneyHomeUiState:LiveData<HomeUiState> get() = _disneyHomeUiState
var allDisneyCharacters: List<HomeUiData>? = null
fun searchDisneyCharacters(name: String) {
getSearchCharacterUseCase(nameText = name).onEach {
when (it) {
is NetworkResponse.Error -> {
_disneyHomeUiState.value = HomeUiState.Error(R.string.eror)
}
NetworkResponse.Loading -> {
_disneyHomeUiState.postValue(HomeUiState.Loading)
}
is NetworkResponse.Success -> {
_disneyHomeUiState.postValue(HomeUiState.Success(disneyCharacterMapper.map(it.result)))
}
}
}.launchIn(viewModelScope)
}
fun getDisneyCharacters(){
getDisneyUseCase().onEach {
when (it) {
is NetworkResponse.Error -> {
_disneyHomeUiState.value = HomeUiState.Error(R.string.eror)
}
is NetworkResponse.Loading -> {
_disneyHomeUiState.value = HomeUiState.Loading
}
is NetworkResponse.Success -> {
val data = disneyCharacterMapper.map(it.result)
_disneyHomeUiState.value = HomeUiState.Success(data)
allDisneyCharacters = data
}
}
}.launchIn(viewModelScope)
}
} | 0 | Kotlin | 0 | 2 | a5134ef29da949929365f0b622b77d0cc489e952 | 2,613 | DisneyCharactersApp | MIT License |
app/src/main/java/com/sport/common/callback/RequestLifecycle.kt | bizehao | 175,768,952 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "CMake": 1, "Proguard": 1, "Kotlin": 64, "XML": 58, "Java": 175, "C++": 287, "C": 16, "Objective-C": 2, "JSON": 2, "Maven POM": 1} | package com.sport.common.callback
/**
* User: bizehao
* Date: 2019-03-08
* Time: 下午4:26
* Description: 在Activity或Fragment中进行网络请求所需要经历的生命周期函数。
*/
interface RequestLifecycle {
fun startLoading()
fun loadFinished()
fun loadFailed(msg: String?)
} | 1 | null | 1 | 1 | e34473639641d8dac5939f9c953c8139cbfcb803 | 262 | sport | MIT License |
app/src/main/java/com/example/chooseownapi_codepathunit5project/MainActivity.kt | ASCRoy22 | 622,133,399 | false | null | package com.example.chooseownapi_codepathunit5project
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.codepath.asynchttpclient.AsyncHttpClient
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler
import okhttp3.Headers
class MainActivity : AppCompatActivity() {
var imgUrl=""
var pokemon="charizard"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("petImageURL", "pet image URL set")
var button=findViewById<Button>(R.id.button)
var image=findViewById<ImageView>(R.id.pic)
getNextImage(button,image)
}
private fun getNextImage(button: Button, imageView: ImageView) {
button.setOnClickListener {
getPokemon()
Glide.with(this)
.load(imgUrl)
.fitCenter()
.into(imageView)
}
}
private fun getPokemon() {
var search:EditText=findViewById<EditText>(R.id.search)
var species:TextView=findViewById<TextView>(R.id.species)
var weight:TextView=findViewById<TextView>(R.id.weight)
val client = AsyncHttpClient()
var speciesString=""
var weightString=""
pokemon=search.getText().toString()
client["https://pokeapi.co/api/v2/pokemon/${pokemon}", object : JsonHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Headers, json: JSON) {
// Access a JSON array response with `json.jsonArray`
//Log.d("DEBUG ARRAY", json.jsonArray.toString())
// Access a JSON object response with `json.jsonObject`
Log.d("Dog", "response successful")
Log.d("DEBUG OBJECT", json.jsonObject.toString())
imgUrl=json.jsonObject.getJSONObject("sprites").getString("back_default")
speciesString=json.jsonObject.getJSONArray("types").getJSONObject(0).getJSONObject("type").getString("name")
weightString=json.jsonObject.getString("weight")
species.setText("Type: "+speciesString)
weight.setText("Weight: "+weightString)
}
override fun onFailure(
statusCode: Int,
headers: Headers?,
response: String,
throwable: Throwable?
) {
}
}]
}
} | 0 | Kotlin | 0 | 0 | b198d5993828dcf98ebf5f8709b541990aa6c0f4 | 2,671 | ChooseOwnAPI_CodepathUnit5Project | Apache License 2.0 |
data/src/commonMain/kotlin/tech/alexib/yaba/data/settings/AppSettings.kt | ruffCode | 377,878,114 | false | null | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.alexib.yaba.data.settings
import co.touchlab.stately.ensureNeverFrozen
import com.russhwolf.settings.coroutines.FlowSettings
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
interface AppSettings {
fun theme(): Flow<Theme>
suspend fun setTheme(theme: Theme)
class Impl(
private val flowSettings: FlowSettings,
) : AppSettings {
override fun theme(): Flow<Theme> =
flowSettings.getStringFlow(THEME_KEY, Theme.SYSTEM.name).map {
Theme.valueOf(it)
}.distinctUntilChanged()
override suspend fun setTheme(theme: Theme) {
flowSettings.putString(THEME_KEY, theme.name)
}
companion object {
const val THEME_KEY = "app_theme"
}
init {
ensureNeverFrozen()
}
}
}
enum class Theme(val displayName: String) {
DARK("Dark"),
LIGHT("Light"),
SYSTEM("System default")
}
| 9 | Kotlin | 1 | 6 | ca86e5a60d0fcc2accfd6c12da07a334558cce0e | 1,609 | yaba-kmm | Apache License 2.0 |
app/src/main/java/dev/kadirkid/pagingtest/ui/CharacterCard.kt | kadirkid | 732,869,570 | false | {"Kotlin": 35953} | /**
* Copyright (c) 2023 <NAME>
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package dev.kadirkid.pagingtest.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import dev.kadirkid.pagingtest.character.model.Character
@Composable
internal fun CharacterCard(character: Character, modifier: Modifier = Modifier) {
Card(
modifier = modifier.heightIn(max = 200.dp),
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
character.image.ImageContent()
character.InfoContent()
}
}
}
@Composable
private fun String.ImageContent(modifier: Modifier = Modifier) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(this)
.build(),
contentDescription = "Character Image",
modifier = modifier
.width(170.dp)
.fillMaxHeight()
.size(96.dp),
)
}
@Composable
private fun Character.InfoContent(modifier: Modifier = Modifier) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.Start,
modifier = modifier
.fillMaxSize()
.background(color = Color.Black.copy(alpha = 0.2f))
.padding(16.dp),
) {
Text(text = name, fontSize = 24.sp)
status.Content()
origin?.let {
val text = buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.DarkGray)) {
append("Place of origin: ")
}
append(it.name)
}
Text(text = text, modifier = Modifier.padding(top = 16.dp))
}
}
}
@Composable
private fun Character.Status.Content(modifier: Modifier = Modifier) {
val color = when (this) {
Character.Status.ALIVE -> Color.Green
Character.Status.DEAD -> Color.Red
Character.Status.UNKNOWN -> Color.Yellow
}
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Canvas(modifier = modifier) {
drawCircle(color = color, radius = 4.dp.toPx())
}
Text(text = " - ")
Text(text = name)
}
}
| 0 | Kotlin | 0 | 0 | f4201ab31c2f845eb7f86d60d10e0f8fecdcc8be | 3,440 | Pagingtest | MIT License |
app/src/main/java/com/example/barcodetest/network/RetrofitInstance.kt | Zahermah | 205,928,665 | false | null | package com.example.barcodetest.network
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
const val BASE_URL = "https://api.upcitemdb.com/prod/"
class RetrofitInstance {
fun getRetrofitInstance(): Retrofit {
var retrofit: Retrofit =
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit
}
} | 0 | Kotlin | 0 | 0 | 7ab06da4053acf612e5b63c22172acabfa0a2c15 | 467 | Barcode | Apache License 2.0 |
android/app/src/main/java/com/btsplusplus/fowallet/ActivityLaunch.kt | GLIBX | 203,500,915 | false | null | package com.btsplusplus.fowallet
import android.content.Intent
import android.graphics.Color.TRANSPARENT
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.View
import bitshares.*
import bitshares.serializer.T_Base
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.answers.Answers
import com.flurry.android.FlurryAgent
import com.fowallet.walletcore.bts.ChainObjectManager
import com.fowallet.walletcore.bts.WalletManager
import io.fabric.sdk.android.Fabric
import org.json.JSONObject
import java.util.*
class ActivityLaunch : BtsppActivity() {
private var _appNativeVersion: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 初始化 Fabric
Fabric.with(this, Crashlytics(), Answers())
// 初始化Flurry
FlurryAgent.Builder().withLogEnabled(true).build(this, "H45RRHMWCPMKZNNKR5SR")
// 初始化启动界面
setFullScreen()
// 初始化石墨烯对象序列化类
T_Base.registerAllType()
// 初始化参数
val dm = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(dm)
Utils.screen_width = dm.widthPixels.toFloat()
Utils.screen_height = dm.heightPixels.toFloat()
OrgUtils.initDir(this.applicationContext)
AppCacheManager.sharedAppCacheManager().initload()
// 统计设备信息
val accountName = WalletManager.sharedWalletManager().getWalletAccountName()
if (accountName != null && accountName != "") {
Crashlytics.setUserName(accountName)
FlurryAgent.setUserId(accountName)
}
// 初始化配置
_appNativeVersion = Utils.appVersionName(this)
initCustomConfig()
// 启动日志
btsppLogCustom("event_app_start", jsonObjectfromKVS("ver", _appNativeVersion))
// 初始化完毕后启动。
startInit(true)
}
/**
* start init graphene network & app
*/
private fun startInit(first_init: Boolean) {
val waitPromise = asyncWait()
checkUpdate().then {
val pVersionConfig = it as? JSONObject
SettingManager.sharedSettingManager().serverConfig = pVersionConfig
return@then Promise.all(waitPromise, asyncInitBitshares()).then {
_onLoadVersionJsonFinish(pVersionConfig)
return@then null
}
}.catch {
if (first_init) {
showToast(resources.getString(R.string.tip_network_error))
}
// auto restart
OrgUtils.asyncWait(1000).then {
startInit(false)
}
}
}
/**
* Version加载完毕
*/
private fun _onLoadVersionJsonFinish(pConfig: JSONObject?) {
if (pConfig != null) {
val pNewestVersion = pConfig.optString("version", "")
if (pNewestVersion != "") {
val ret = Utils.compareVersion(pNewestVersion, _appNativeVersion)
if (ret > 0) {
// 有更新
var message = pConfig.optString(resources.getString(R.string.launchTipVersionKey), "")
if (message == "") {
message = String.format(resources.getString(R.string.launchTipDefaultNewVersion), pNewestVersion)
}
_showAppUpdateWindow(message, pConfig.getString("appURL"), pConfig.getString("force").toInt() != 0)
return
}
}
}
// 没更新则直接启动
_enterToMain()
}
/**
* 提示app更新
*/
private fun _showAppUpdateWindow(message: String, url: String, forceUpdate: Boolean) {
var btn_cancel: String? = null
if (!forceUpdate) {
btn_cancel = resources.getString(R.string.kRemindMeLatter)
}
UtilsAlert.showMessageConfirm(this, resources.getString(R.string.kWarmTips), message, btn_ok = resources.getString(R.string.kUpgradeNow), btn_cancel = btn_cancel).then {
// 进入APP
_enterToMain()
// 立即升级:打开下载。
if (it != null && it as Boolean) {
openURL(url)
}
}
}
/**
* 进入主界面
*/
private fun _enterToMain() {
var homeClass: Class<*> = ActivityIndexMarkets::class.java
if (!BuildConfig.kAppModuleEnableTabMarket) {
homeClass = ActivityIndexCollateral::class.java
}
if (!BuildConfig.kAppModuleEnableTabDebt) {
homeClass = ActivityIndexServices::class.java
}
val intent = Intent()
intent.setClass(this, homeClass)
startActivity(intent)
}
/**
* 检测更新
*/
private fun checkUpdate(): Promise {
if (BuildConfig.kAppCheckUpdate) {
val p = Promise()
val version_url = "https://btspp.io/app/android/${BuildConfig.kAppChannelID}_$_appNativeVersion/version.json?t=${Date().time}"
OrgUtils.asyncJsonGet(version_url).then {
p.resolve(it as? JSONObject)
return@then null
}.catch {
p.resolve(null)
}
return p
} else {
return Promise._resolve(null)
}
}
/**
* 强制等待
*/
private fun asyncWait(): Promise {
return OrgUtils.asyncWait(2000)
}
/**
* 初始化BTS网络,APP启动时候执行一次。
*/
private fun asyncInitBitshares(): Promise {
val p = Promise()
val connMgr = GrapheneConnectionManager.sharedGrapheneConnectionManager()
val chainMgr = ChainObjectManager.sharedChainObjectManager()
// 初始化链接
connMgr.Start(resources.getString(R.string.serverWssLangKey)).then { success ->
// 初始化网络相关数据
chainMgr.grapheneNetworkInit().then { data ->
// 初始化逻辑相关数据
val walletMgr = WalletManager.sharedWalletManager()
val promise_map = JSONObject().apply {
put("kInitTickerData", chainMgr.marketsInitAllTickerData())
put("kInitGlobalProperties", connMgr.last_connection().async_exec_db("get_global_properties"))
put("kInitFeeAssetInfo", chainMgr.queryFeeAssetListDynamicInfo()) // 查询手续费兑换比例、手续费池等信息
// 每次启动都刷新当前账号信息
if (walletMgr.isWalletExist()) {
put("kInitFullUserData", chainMgr.queryFullAccountInfo(walletMgr.getWalletInfo().getString("kAccountName")))
}
// 初始化OTC数据
put("kQueryConfig", OtcManager.sharedOtcManager().queryConfig())
}
return@then Promise.map(promise_map).then {
// 更新全局属性
val data_hash = it as JSONObject
chainMgr.updateObjectGlobalProperties(data_hash.getJSONObject("kInitGlobalProperties"))
// 更新帐号完整数据
val full_account_data = data_hash.optJSONObject("kInitFullUserData")
if (full_account_data != null) {
AppCacheManager.sharedAppCacheManager().updateWalletAccountInfo(full_account_data)
}
// 初始化完成之后:启动计划调度任务
ScheduleManager.sharedScheduleManager().startTimer()
ScheduleManager.sharedScheduleManager().autoRefreshTickerScheduleByMergedMarketInfos()
// 初始化完成
p.resolve(true)
return@then null
}
}.catch {
p.reject(resources.getString(R.string.tip_network_error))
}
return@then null
}.catch {
p.reject(resources.getString(R.string.tip_network_error))
}
return p
}
fun setFullScreen() {
val dector_view: View = window.decorView
val option: Int = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
dector_view.systemUiVisibility = option
window.navigationBarColor = TRANSPARENT
}
/**
* 初始化自定义启动设置 : (启动仅执行一次)
*/
private fun initCustomConfig() {
// 初始化缓存
ChainObjectManager.sharedChainObjectManager().initAll(this)
}
}
| 1 | null | 1 | 1 | e9a5df578c4a09f798eb696866e163bf17975ba1 | 8,329 | bitshares-mobile-app | MIT License |
app/src/main/java/ru/rznnike/eyehealthmanager/app/ui/fragment/acuity/instruction/AcuityInstructionFragment.kt | RznNike | 207,148,781 | false | {"Kotlin": 539909} | package ru.rznnike.eyehealthmanager.app.ui.fragment.acuity.instruction
import android.os.Bundle
import android.view.View
import by.kirich1409.viewbindingdelegate.viewBinding
import moxy.presenter.InjectPresenter
import moxy.presenter.ProvidePresenter
import ru.rznnike.eyehealthmanager.R
import ru.rznnike.eyehealthmanager.app.global.ui.fragment.BaseFragment
import ru.rznnike.eyehealthmanager.app.presentation.acuity.instruction.AcuityInstructionPresenter
import ru.rznnike.eyehealthmanager.app.presentation.acuity.instruction.AcuityInstructionView
import ru.rznnike.eyehealthmanager.app.utils.extensions.addSystemWindowInsetToPadding
import ru.rznnike.eyehealthmanager.app.utils.extensions.getIntArg
import ru.rznnike.eyehealthmanager.databinding.FragmentAcuityInstructionBinding
import ru.rznnike.eyehealthmanager.domain.model.enums.DayPart
class AcuityInstructionFragment : BaseFragment(R.layout.fragment_acuity_instruction),
AcuityInstructionView {
@InjectPresenter
lateinit var presenter: AcuityInstructionPresenter
@ProvidePresenter
fun providePresenter() = AcuityInstructionPresenter(
dayPart = DayPart[getIntArg(DAY_PART)]
)
private val binding by viewBinding(FragmentAcuityInstructionBinding::bind)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
layoutToolbarContainer.addSystemWindowInsetToPadding(top = true)
layoutControls.addSystemWindowInsetToPadding(bottom = true)
}
initToolbar()
initOnClickListeners()
}
private fun initToolbar() = binding.toolbar.apply {
textViewToolbarHeader.setText(R.string.instruction)
buttonToolbarLeft.setImageResource(R.drawable.ic_back)
buttonToolbarLeft.setOnClickListener {
onBackPressed()
}
}
private fun initOnClickListeners() = binding.apply {
buttonStartTest.setOnClickListener {
presenter.onStart()
}
}
companion object {
const val DAY_PART = "DAY_PART"
}
}
| 0 | Kotlin | 0 | 0 | 6f319237d56f99a836fe3481efd32908e28c3d56 | 2,114 | EyeHealthManager | MIT License |
meistercharts-commons/src/commonMain/kotlin/com/meistercharts/annotations/Zoomed.kt | Neckar-IT | 599,079,962 | false | {"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114} | package com.meistercharts.annotations
import it.neckar.open.unit.other.px
/**
* Marked values represent window values in pixels with zoom but *without* translation
* This is *not* the window (missing the translation).
*
* Values are useful to calculate lengths for relative movements/calculations
*
*/
@Retention(AnnotationRetention.SOURCE)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.TYPE_PARAMETER,
AnnotationTarget.PROPERTY,
AnnotationTarget.FIELD,
AnnotationTarget.LOCAL_VARIABLE,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.TYPE,
AnnotationTarget.EXPRESSION,
AnnotationTarget.FILE,
AnnotationTarget.TYPEALIAS
)
@MustBeDocumented
@px
annotation class Zoomed
| 3 | Kotlin | 3 | 5 | ed849503e845b9d603598e8d379f6525a7a92ee2 | 873 | meistercharts | Apache License 2.0 |
app/src/main/java/org/queiroz/themoviedb/api/NetworkRequest.kt | queiroz | 237,280,338 | false | {"Kotlin": 67194} | package org.queiroz.themoviedb.api
import com.google.gson.JsonSyntaxException
import org.json.JSONException
import org.json.JSONObject
import org.queiroz.themoviedb.util.Resource
import retrofit2.HttpException
import timber.log.Timber
import java.io.IOException
suspend inline fun <T> networkRequest(block: () -> T): Resource<T> {
var response = Resource.error<T>("Something went wrong")
try {
response = Resource.success(block())
} catch (e: IOException) {
response = Resource.error("No network connectivity")
Timber.d(e)
} catch (e: HttpException) {
Timber.e(getStatusMessage(e))
} catch (e: JsonSyntaxException) {
Timber.e(e)
} catch (e: Exception) {
Timber.e(e)
}
return response
}
fun getStatusMessage(e: HttpException): String {
var message = ""
try {
e.response()?.errorBody()?.string()?.let {
val jObjError = JSONObject(it)
message = jObjError.getString("status_message")
}
} catch (e: JSONException) { }
return message
}
| 0 | Kotlin | 0 | 0 | 9e00020ee260523afe52f5721655caead2ec5b66 | 1,070 | themoviedb | Apache License 2.0 |
data/RF03502/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF03502"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 4
78 to 80
}
value = "#589efc"
}
color {
location {
8 to 11
71 to 74
}
value = "#78b590"
}
color {
location {
13 to 15
66 to 68
}
value = "#6fd1eb"
}
color {
location {
17 to 20
61 to 64
}
value = "#481d19"
}
color {
location {
23 to 27
54 to 58
}
value = "#049849"
}
color {
location {
29 to 34
48 to 53
}
value = "#7177cd"
}
color {
location {
5 to 7
75 to 77
}
value = "#f8418b"
}
color {
location {
12 to 12
69 to 70
}
value = "#74a6f4"
}
color {
location {
16 to 16
65 to 65
}
value = "#8524fe"
}
color {
location {
21 to 22
59 to 60
}
value = "#956487"
}
color {
location {
28 to 28
54 to 53
}
value = "#453ac5"
}
color {
location {
35 to 47
}
value = "#4d1382"
}
color {
location {
1 to 1
}
value = "#af2b17"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 2,107 | Rfam-for-RNArtist | MIT License |
app/src/test/java/com/movietrivia/filmfacts/domain/GetMovieImageUseCaseTest.kt | jlynchsd | 631,418,923 | false | {"Kotlin": 524037} | package com.movietrivia.filmfacts.domain
import com.movietrivia.filmfacts.api.DiscoverMovie
import com.movietrivia.filmfacts.api.DiscoverMovieResponse
import com.movietrivia.filmfacts.model.CalendarProvider
import com.movietrivia.filmfacts.model.FilmFactsRepository
import com.movietrivia.filmfacts.model.RecentPromptsRepository
import com.movietrivia.filmfacts.model.UiTextPrompt
import com.movietrivia.filmfacts.model.UserDataRepository
import com.movietrivia.filmfacts.model.UserSettings
import io.mockk.clearAllMocks
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.runTest
import okio.IOException
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class GetMovieImageUseCaseTest {
private lateinit var filmFactsRepository: FilmFactsRepository
private lateinit var recentPromptsRepository: RecentPromptsRepository
private lateinit var userDataRepository: UserDataRepository
private lateinit var userSettingsFlow: MutableSharedFlow<UserSettings>
@Before
fun setup() {
filmFactsRepository = mockk(relaxed = true)
recentPromptsRepository = mockk(relaxed = true)
userDataRepository = mockk(relaxed = true)
mockkStatic(::preloadImages)
coEvery {
preloadImages(any(), *anyVararg())
} returns true
userSettingsFlow = MutableSharedFlow(replay = 1)
userSettingsFlow.tryEmit(UserSettings())
every {
userDataRepository.userSettings
} returns userSettingsFlow
mockkStatic(::getMovieDateRange)
every {
getMovieDateRange(any(), any())
} returns mockk()
coEvery {
filmFactsRepository.getMovies(dateRange = any(), order = any(), includeGenres = any())
} returns DiscoverMovieResponse(
0,
listOf(
DiscoverMovie(0, "foo", "fooPath", emptyList(), "", "en", 5f, 10, 5f),
DiscoverMovie(0, "bar", "barPath", emptyList(), "", "en", 5f, 10, 5f),
DiscoverMovie(0, "fizz", "fizzPath", emptyList(), "", "en", 5f, 10, 5f),
DiscoverMovie(0, "buzz", "buzzPath", emptyList(), "", "en", 5f, 10, 5f)
),
1,
4
)
mockkStatic(::getMovieImage)
coEvery {
getMovieImage(any(), any())
} returns mockk(relaxed = true)
coEvery {
filmFactsRepository.getImageUrl(any(), any())
} returns "fooPath"
}
@After
fun teardown() {
clearAllMocks()
}
@Test
fun `When unable to get user settings returns null`() = runTest {
val useCase = getUseCase(testScheduler)
every {
userDataRepository.userSettings
} returns emptyFlow()
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When getting user settings throws exception returns null`() = runTest {
val useCase = getUseCase(testScheduler)
every {
userDataRepository.userSettings
} returns kotlinx.coroutines.flow.flow {
throw IOException()
}
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When unable to get movies response returns null`() = runTest {
val useCase = getUseCase(testScheduler)
coEvery {
filmFactsRepository.getMovies(dateRange = any(), order = any(), includeGenres = any())
} returns null
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When movie results are empty returns null`() = runTest {
val useCase = getUseCase(testScheduler)
coEvery {
filmFactsRepository.getMovies(dateRange = any(), order = any(), includeGenres = any())
} returns DiscoverMovieResponse(0, emptyList(), 1, 0)
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When too few movie results returns null`() = runTest {
val useCase = getUseCase(testScheduler)
coEvery {
filmFactsRepository.getMovies(dateRange = any(), order = any(), includeGenres = any())
} returns DiscoverMovieResponse(
0,
listOf(mockk(relaxed = true), mockk(relaxed = true), mockk(relaxed = true)),
1,
3
)
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When too few movie results after filtering returns null`() = runTest {
val useCase = getUseCase(testScheduler)
every {
recentPromptsRepository.isRecentMovie(any())
} returns true
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When unable to get movie images returns null`() = runTest {
val useCase = getUseCase(testScheduler)
coEvery {
getMovieImage(any(), any())
} returns null
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When unable to preload images returns null`() = runTest {
val useCase = getUseCase(testScheduler)
coEvery {
preloadImages(any(), *anyVararg())
} returns false
Assert.assertNull(useCase.invoke(null))
}
@Test
fun `When able to load movie image and data returns prompt`() = runTest {
val useCase = getUseCase(testScheduler)
Assert.assertTrue(useCase.invoke(null) is UiTextPrompt)
}
@Test
fun `When unable to load image url returns prompt with empty path`() = runTest {
val useCase = getUseCase(testScheduler)
coEvery {
filmFactsRepository.getImageUrl(any(), any())
} returns null
val prompt = useCase.invoke(null) as UiTextPrompt
Assert.assertEquals("", prompt.images.first().imagePath)
}
private fun getUseCase(testScheduler: TestCoroutineScheduler) =
GetMovieImageUseCase(
mockk(),
filmFactsRepository,
recentPromptsRepository,
userDataRepository,
CalendarProvider(),
StandardTestDispatcher(testScheduler)
)
} | 0 | Kotlin | 0 | 0 | 9a6c9ae5bc2f7a743c9399a64d0c9edf5c7e0d84 | 6,348 | FilmFacts | Apache License 2.0 |
shared/data/note/src/commonMain/kotlin/little/goose/data/note/NoteRepositoryImpl.kt | MReP1 | 525,822,587 | false | null | package little.goose.data.note
import kotlinx.coroutines.flow.Flow
import little.goose.data.note.bean.Note
import little.goose.data.note.bean.NoteContentBlock
import little.goose.data.note.bean.NoteWithContent
import little.goose.data.note.local.NoteDatabase
class NoteRepositoryImpl(
private val dataBase: NoteDatabase
) : NoteRepository {
override val deleteNoteIdListFlow: Flow<List<Long>> = dataBase.deleteNoteIdListFlow
override fun getNoteFlow(noteId: Long): Flow<Note> {
return dataBase.getNoteFlow(noteId)
}
override suspend fun insertOrReplaceNote(note: Note): Long {
return dataBase.insertOrReplaceNote(note)
}
override fun getNoteWithContentFlow(noteId: Long): Flow<NoteWithContent> {
return dataBase.getNoteWithContentFlow(noteId)
}
override suspend fun deleteNoteAndItsBlocks(noteId: Long) {
return dataBase.deleteNoteAndItsBlocks(noteId)
}
override suspend fun deleteNoteAndItsBlocksList(noteIds: List<Long>) {
return dataBase.deleteNoteAndItsBlocksList(noteIds)
}
override suspend fun deleteBlock(id: Long) {
return dataBase.deleteBlock(id)
}
override suspend fun deleteBlockWithNoteId(noteId: Long) {
return dataBase.deleteBlockWithNoteId(noteId)
}
override suspend fun insertOrReplaceNoteContentBlock(noteContentBlock: NoteContentBlock): Long {
return dataBase.insertOrReplaceNoteContentBlock(noteContentBlock)
}
override suspend fun insertOrReplaceNoteContentBlocks(noteContentBlocks: List<NoteContentBlock>) {
return dataBase.insertOrReplaceNoteContentBlocks(noteContentBlocks)
}
override fun getNoteWithContentFlow(): Flow<List<NoteWithContent>> {
return dataBase.getNoteWithContentFlow()
}
override fun getNoteWithContentFlowByKeyword(keyword: String): Flow<List<NoteWithContent>> {
return dataBase.getNoteWithContentFlowByKeyword(keyword)
}
} | 1 | null | 29 | 110 | ed7bc878de42e0355abaf7a815e7287a4633915d | 1,962 | LittleGooseOffice | MIT License |
core/src/com/yopox/ld47/entities/Boss.kt | yopox | 300,811,828 | false | null | package com.yopox.ld47.entities
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.math.Vector2
import com.yopox.ld47.Levels
import com.yopox.ld47.Resources
import com.yopox.ld47.screens.Screen
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class Boss(texture: Texture, var lives: Int = 3) : Orbital(texture) {
var willCross = false
var justUpdated = false
private data class Starting(val leftOrbit: Boolean, val angle: Double, val pos: Vector2)
init {
setOriginCenter()
forward = false
movement = Companion.Movement.LINEAR
radius = Screen.HEIGHT
val startingPos = arrayOf(
Starting(true, 4 * PI / 5, Vector2(
Screen.WIDTH / 2 + cos(4 * PI / 5).toFloat() * radius - 32f,
Screen.HEIGHT / 2 + sin(4 * PI / 5).toFloat() * radius
)),
Starting(false, PI / 5, Vector2(
Screen.WIDTH / 2 + cos(PI / 5).toFloat() * radius + 32f,
Screen.HEIGHT / 2 + sin(PI / 5).toFloat() * radius
))).random()
leftOrbit = startingPos.leftOrbit
acceleration = 1.5f * Levels.selected.minSpeed
x = startingPos.pos.x
y = startingPos.pos.y
linearAngle = (startingPos.angle - PI).normalize
angle = (linearAngle + if (leftOrbit) PI / 2 else -PI / 2).normalize
}
override fun shouldCross(): Boolean = willCross
override fun update() {
if (lives > 0)
super.update()
else {
applyAcceleration()
updateInvulnerability()
x += speed * cos(angle + PI / 2).toFloat()
y += speed * sin(angle + PI / 2).toFloat()
if (x - width > Screen.WIDTH || x + width < 0 || y - width > Screen.HEIGHT || y + width < 0) {
toDestroy = true
}
}
if (leftOrbit && orbitalX < LEFT_FOCAL.x || !leftOrbit && orbitalX > RIGHT_FOCAL.x) {
if (!justUpdated) {
justUpdated = true
willCross = !willCross
}
} else {
justUpdated = false
}
}
override fun hit(collision: Companion.Collision, otherOrbital: Orbital?) {
lives -= 1
triggerHit()
if (lives == 0) acceleration += 5f
}
} | 0 | Kotlin | 1 | 4 | 19867902caed4d99e0939eda0bcf19c22eabae6d | 2,385 | LD47 | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/paypaytest/currencyconversionapp/data/repository/CurrencyAppRepositoryImp.kt | deepdelvadiya | 753,472,003 | false | {"Kotlin": 72443} | package com.paypaytest.currencyconversionapp.data.repository
import android.util.Log
import com.paypaytest.currencyconversionapp.common.DispatcherProvider
import com.paypaytest.currencyconversionapp.data.database.dao.CountryDao
import com.paypaytest.currencyconversionapp.data.database.dao.RateDao
import com.paypaytest.currencyconversionapp.data.remote.OpenExchangeRatesApis
import com.paypaytest.currencyconversionapp.domain.model.CountryModel
import com.paypaytest.currencyconversionapp.domain.model.RateModel
import com.paypaytest.currencyconversionapp.domain.model.toCountryModel
import com.paypaytest.currencyconversionapp.domain.model.toRateModel
import com.paypaytest.currencyconversionapp.domain.repository.CurrencyAppRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import java.util.concurrent.CancellationException
import javax.inject.Inject
import kotlin.math.log
class CurrencyAppRepositoryImp @Inject constructor(
private val openExchangeRatesApis: OpenExchangeRatesApis,
private val countryDao: CountryDao,
private val rateDao: RateDao,
private val dispatcherProvider: DispatcherProvider
) : CurrencyAppRepository {
override fun getCurrencies(): Flow<List<CountryModel>> {
return countryDao.getCurrencies().map { it?.codeEntity?.map { it.toCountryModel() } ?: emptyList() }
}
override fun getRates(): Flow<List<RateModel>> {
return rateDao.getCountryRates().map { it?.rates?.map { it.toRateModel() } ?: emptyList() }
}
override suspend fun syncWith(apiId: String): Boolean {
return withContext(dispatcherProvider.io) {
try {
val countryCodeResponse = openExchangeRatesApis.getCurrencies(apiId)
val ratesResponse = openExchangeRatesApis.getLatestCurrenciesValue(apiId)
if (ratesResponse.isSuccessful && countryCodeResponse.isSuccessful) {
val countryCode = countryCodeResponse.body()
val rates = ratesResponse.body()
if (rates != null && countryCode != null) {
Log.d("DEEP", "syncWith: Completed ")
Log.d("DEEP", "syncWith: $countryCode. and $rates")
rateDao.insertRates(rates)
countryDao.insertCurrencies(countryCode)
true
} else {
false
}
} else {
false
}
} catch (exception: Exception) {
if (exception is CancellationException) {
throw exception
}
Log.i("DEEP", "syncWith: ${exception.localizedMessage}")
false
}
}
}
} | 0 | Kotlin | 0 | 0 | 3d8eecadc1963879bea43ba0236bcc7b58494d42 | 2,993 | Currency-Conversion-App | Apache License 2.0 |
domene/src/main/kotlin/no/nav/tiltakspenger/saksbehandling/domene/vilkår/SkalErstatteVilkår.kt | navikt | 487,246,438 | false | {"Kotlin": 681488, "Shell": 1309, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.saksbehandling.domene.vilkår
/**
* TODO jah: Skal erstatte Vilkår.kt. Men vi tar det iterativt.
*/
interface SkalErstatteVilkår {
val lovreferanse: Lovreferanse
}
| 7 | Kotlin | 0 | 1 | e125e2953c16c4bb2c99e6d36075c553b51ed794 | 199 | tiltakspenger-vedtak | MIT License |
jps/jps-plugin/testData/incremental/pureKotlin/sealedClassesWithExpectActual/Actual2.kt | JetBrains | 3,432,266 | false | null | package test
actual class ExpectClass2 {
actual fun doSmth() = ""
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 72 | kotlin | Apache License 2.0 |
app/src/main/java/me/taolin/app/gank/ui/category/CategoryContract.kt | taolin2107 | 125,477,908 | false | null | package me.taolin.app.gank.ui.category
import me.taolin.app.gank.base.BasePresenter
import me.taolin.app.gank.base.BaseView
import me.taolin.app.gank.data.entity.Gank
/**
* @author taolin
* @version v1.0
* @date 2018/03/15
* @description
*/
interface CategoryContract {
interface View : BaseView<Presenter> {
fun refreshList(list: List<Gank>)
fun loadedMoreData(list: List<Gank>)
}
interface Presenter : BasePresenter<View> {
fun loadCategoryData(category: String)
fun loadMoreCategoryData(category: String)
}
} | 0 | Kotlin | 0 | 0 | 643397660a7ae4ef41b078511ff3ad61743e8060 | 572 | Gank | The Unlicense |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/simpleProject/src/deploy/kotlin/kotlinSrc.kt | JakeWharton | 99,388,807 | false | null | package demo
import com.google.common.primitives.Ints
import com.google.common.base.Joiner
class ExampleSource(param : Int) {
val property = param
fun f() : String? {
return "Hello World"
}
}
| 179 | null | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 206 | kotlin | Apache License 2.0 |
app/src/main/java/com/worksmobile/study/coroutinestudy_seongheon/data/ImageRepository.kt | works-android-study | 541,963,500 | false | {"Kotlin": 48921} | package com.worksmobile.study.coroutinestudy_seongheon.data
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.worksmobile.study.coroutinestudy_seongheon.api.SearchService
import com.worksmobile.study.coroutinestudy_seongheon.entity.BookmarkItem
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class ImageRepository @Inject constructor(
private val service: SearchService,
private val imageDao: BookmarkDAO
) {
fun searchImages(query: String): Flow<PagingData<Item>> {
return Pager(
config = PagingConfig(
pageSize = SearchDataSource.defaultDisplay,
enablePlaceholders = true
),
pagingSourceFactory = {
SearchDataSource(query, service)
}
).flow
}
fun selectBookmarkImage(): Flow<PagingData<Item>> {
return Pager(
config = PagingConfig(
pageSize = SearchDataSource.defaultDisplay,
enablePlaceholders = true
),
pagingSourceFactory = {
BookmarkDataSource(imageDao)
}
).flow
}
fun insertBookmarkImage(item: Item) = imageDao.insertBookmarkTime(BookmarkItem(item = item))
fun deleteBookmarkImage(item: Item) = imageDao.deleteBookmarkTime(BookmarkItem(item = item))
}
| 7 | Kotlin | 0 | 0 | 299d0befb15ca974f93b26e682bf41e12a9a2381 | 1,396 | CoroutineStudy_SeongHeon | MIT License |
app/src/main/kotlin/com/konkuk/boost/presentation/adapters/listeners/OnItemEventListener.kt | sys09270883 | 323,874,439 | false | null | package com.konkuk.boost.presentation.adapters.listeners
import androidx.constraintlayout.widget.ConstraintLayout
interface OnItemEventListener<in T> {
fun onItemClick(item: T)
fun isItemClicked(item: T): Boolean
}
interface OnFaqEventListener<T> : OnItemEventListener<T> {
fun onItemClick(item: T, linkLayout: ConstraintLayout)
}
| 0 | Kotlin | 1 | 19 | 266d8db5f42a3d1cd897eb421450777ac9e18276 | 346 | ku-boost-android | MIT License |
app/src/main/java/com/honegroupp/familyRegister/utility/searchUtil/ListViewAdapter.kt | BeginnerRudy | 199,853,686 | false | null | package com.honegroupp.familyRegister.utility.searchUtil
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.honegroupp.familyRegister.R
import com.honegroupp.familyRegister.model.Item
import com.squareup.picasso.Picasso
/**
* ListViewAdapter is an adapter to deal with data with listView
* */
class ListViewAdapter(
val items: ArrayList<Item>,
val mActivity: AppCompatActivity
) : BaseAdapter() {
private val nameList: ArrayList<String> = ArrayList()
private val dateList: ArrayList<String> = ArrayList()
private val imageURLList: ArrayList<String> = ArrayList()
/**
* the function is used to get the items' total number
* */
override fun getCount(): Int {
return items.size
}
/**
* the function is used to get the item object by its position in list
* */
override fun getItem(position: Int): Item {
return items[position]
}
/**
* the function is used to get item id by its position
* */
override fun getItemId(position: Int): Long {
return position.toLong()
}
/**
* the function is used to present UI view for listView with necessary data
* */
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup
): View? {
val layout: View = View.inflate(mActivity, R.layout.item_listview, null)
val picture: ImageView = layout.findViewById(R.id.picture)
val name: TextView = layout.findViewById(R.id.search_name)
val date: TextView = layout.findViewById(R.id.search_date)
for (item in items) {
imageURLList.add(item.imageURLs[0])
nameList.add(item.itemName)
dateList.add(item.date)
}
//set image to imageView
Picasso.get()
.load(imageURLList[position])
.placeholder(R.mipmap.loading_jewellery)
.fit()
.centerCrop()
.into(picture)
name.text = nameList[position]
date.text = dateList[position]
return layout
}
} | 6 | Kotlin | 2 | 2 | 81f41ddfc348ffab46760b335707b3a9a0e5e913 | 2,237 | BeginnerRudy-COMP30022-IT-Project | MIT License |
app/src/main/java/com/aibb/android/base/example/lazy/fragment/LazyMvpFragment2.kt | aibingbing | 289,698,382 | false | null | package com.aibb.android.base.example.lazy.fragment
import com.aibb.android.base.example.network.presenter.NetworkServiceTestPresenter
import com.aibb.android.base.mvp.annotation.MvpPresenterInject
import com.aibb.android.base.mvp.annotation.MvpPresenterVariable
@MvpPresenterInject(values = [NetworkServiceTestPresenter::class])
class LazyMvpFragment2 : LazyMvpFragment1(){
@MvpPresenterVariable
override lateinit var mNetworkServicePresenter: NetworkServiceTestPresenter
} | 0 | Kotlin | 0 | 0 | 6cc08b75cc1ee504591035a09815de16b4a7a0db | 484 | AndroidBaseComponent | Apache License 2.0 |
sociallogintest/src/main/java/com/github/windsekirun/sociallogintest/MainActivity.kt | WindSekirun | 108,518,077 | false | null | package com.github.windsekirun.sociallogintest
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import pyxis.uzuki.live.richutilskt.utils.getKeyHash
import pyxis.uzuki.live.sociallogin.impl.OnResponseListener
import pyxis.uzuki.live.sociallogin.kakao.KakaoLogin
class MainActivity : AppCompatActivity() {
private lateinit var kakaoLogin: KakaoLogin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(MainActivity::class.java.simpleName, "KeyHash: ${getKeyHash()}," +
" apiKey: ${getString(R.string.kakao_api_key)}")
btnLogin.setOnClickListener {
if (::kakaoLogin.isInitialized) {
kakaoLogin.onLogin()
}
}
kakaoLogin = KakaoLogin(this, OnResponseListener { _, result, resultMap ->
val typeStr = "type: ${result?.name}"
val resultMapStr = toMapString(resultMap)
Log.d(MainActivity::class.java.simpleName, resultMapStr);
txtResult.text = "$typeStr \n $resultMapStr"
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (::kakaoLogin.isInitialized) {
kakaoLogin.onActivityResult(requestCode, resultCode, data)
}
}
override fun onDestroy() {
super.onDestroy()
if (::kakaoLogin.isInitialized) {
kakaoLogin.onDestroy()
}
}
@JvmOverloads
fun <K, V> toMapString(map: Map<K, V>, delimiter: CharSequence = "\n"): String {
val builder = StringBuilder()
val lists = map.entries.toList()
(0 until lists.size)
.map { lists[it] }
.forEach { builder.append("[${it.key}] -> [${it.value}]$delimiter") }
return builder.toString()
}
}
| 0 | null | 5 | 10 | 10dd126dcb8a7a15b7bcbdf1fe9ead67547e02c3 | 2,066 | SocialLogin | Apache License 2.0 |
friends/friends_domain/src/main/java/com/beomsu317/friends_domain/use_case/DeleteFriendUseCase.kt | beomsu317 | 485,776,806 | false | null | package com.beomsu317.friends_domain.use_case
import com.beomsu317.core.common.Resource
import com.beomsu317.friends_domain.repository.FriendsRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.lang.Exception
class DeleteFriendUseCase(
private val repository: FriendsRepository
) {
suspend operator fun invoke(friendId: String): Flow<Resource<Unit>> = flow {
try {
emit(Resource.Loading<Unit>())
repository.deleteUserFriendById(friendId = friendId)
emit(Resource.Success<Unit>(data = Unit))
} catch (e: Exception) {
emit(Resource.Error<Unit>(e.localizedMessage))
}
}
} | 0 | Kotlin | 0 | 0 | 4ff38347196aaebb75d2729d62289bc717f14370 | 698 | private-chat-app | Apache License 2.0 |
domain/src/main/java/com/gauvain/seigneur/domain/model/AlbumPaginedModel.kt | GauvainSeigneur | 267,048,711 | false | null | package com.gauvain.seigneur.domain.model
data class AlbumPaginedModel(
val albums: List<AlbumModel>,
val next: Int?,
val prev: Int?
)
| 0 | Kotlin | 0 | 0 | 5cd5d9ec1a9aefe7150ec631032467210fd18d80 | 148 | ShinyAlbums | Apache License 2.0 |
shared/java/top/fpsmaster/event/events/EventJoinServer.kt | FPSMasterTeam | 816,161,662 | false | {"Java": 620089, "Kotlin": 396547, "GLSL": 2647} | package top.fpsmaster.event.events
import top.fpsmaster.event.Event
class EventJoinServer(val serverId: String) : Event {
var cancel: Boolean = false
} | 14 | Java | 34 | 97 | 34a00cc1834e80badd0df6f5d17ae027163d0ce9 | 157 | FPSMaster | MIT License |
tokisaki-core/src/main/kotlin/io/micro/core/auth/RandomLoginCode.kt | spcookie | 730,690,607 | false | {"Kotlin": 192200, "Java": 17009} | package io.micro.core.auth
import kotlinx.coroutines.sync.Mutex
import kotlin.random.Random
object RandomLoginCode {
class Code(
val value: String,
private val isSpecial: Boolean,
private val special: MutableList<String>
) {
fun back() {
if (isSpecial) {
special.add(value)
}
}
}
private val special = mutableListOf(
"1111", "3691", "8889", "7776", "6666",
"5555", "4444", "3333", "2222", "1010",
"8887", "1319", "9998", "7778", "6669",
"5556", "4445", "3334", "2223", "1011",
"1315", "5208", "8886", "1689", "7779",
"9997", "6668", "5557", "4446", "3335"
)
private val mutex = Mutex()
private val random = Random(0)
fun hire(): Code {
return if (mutex.tryLock()) {
val code = if (special.isNotEmpty()) {
Code(special.removeFirst(), true, special)
} else {
Code(random(), false, special)
}
mutex.unlock()
code
} else {
Code(random(), false, special)
}
}
private fun random() = random.nextInt(10000, 99999).toString()
} | 0 | Kotlin | 0 | 0 | f9e34417c08d52727c8458f1a315f811c86c2c5d | 1,223 | Tokisaki | Apache License 2.0 |
app/src/main/java/com/sucho/playground/ui/activity/main/MainActivity.kt | suchoX | 375,678,376 | false | null | package com.sucho.playground.ui.activity.main
import android.os.Bundle
import android.view.View
import com.sucho.playground.R
import com.sucho.playground.ui.base.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : BaseActivity<MainViewModel>() {
override fun getViewModelClass(): Class<MainViewModel> = MainViewModel::class.java
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
} | 0 | Kotlin | 0 | 1 | 1b6b1b49ab54763ba96e1837d38ac79fb59b7771 | 751 | PlaygroundAndroid | MIT License |
src/main/java/test/ECNUTest.kt | YZune | 232,583,513 | false | {"Kotlin": 426459, "Java": 45879} | package test
import main.java.parser.ECNUParser
import parser.AHNUParser
import java.io.File
fun main() {
val source = File("/Users/user/Desktop/test.html")
.readText()
ECNUParser(source).apply {
generateCourseList()
saveCourse()
}
} | 1 | Kotlin | 135 | 146 | 2029c2688d2080e91b1a21c745889fa75e8fa539 | 271 | CourseAdapter | MIT License |
android/src/main/java/com/reactnativefreeotp/FreeOtpModule.kt | osamaqarem | 276,801,859 | false | {"Swift": 29731, "Java": 23367, "Ruby": 5892, "Objective-C": 4846, "Kotlin": 2310, "JavaScript": 1927, "Starlark": 602, "TypeScript": 507} | package com.reactnativefreeotp
import android.util.Log
import com.facebook.react.bridge.*
import com.reactnativefreeotp.core.Token
import com.reactnativefreeotp.core.TokenCode
class FreeOtpModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return "FreeOtp"
}
@ReactMethod
fun getTokenPair(totpUrl: String, promise: Promise) {
try {
val token = Token(totpUrl)
val codes: TokenCode = token.generateCodes()
val now: Long = System.currentTimeMillis()
val state: Long = codes.getmUntil() - now
val remainingSeconds = (state / 1000).toInt()
val stateNext: Long = codes.getmNext().getmUntil() - now
val remainingSecondsNext = (stateNext / 1000).toInt()
// debugLogTokenPair(codes, remainingSeconds, remainingSecondsNext)
val resultMap = Arguments.createMap()
resultMap.putString(
"tokenOne", codes.getmCode()
)
resultMap.putString(
"tokenTwo", codes.getmNext().getmCode()
)
resultMap.putString(
"tokenOneExpires", remainingSeconds.toString()
)
resultMap.putString(
"tokenTwoExpires", remainingSecondsNext.toString()
)
promise.resolve(resultMap)
} catch (e: Token.TokenUriInvalidException) {
e.printStackTrace()
promise.reject("Error", "RN-FreeOtp: Invalid URL: " + e.message)
}
}
fun debugLogTokenPair(codes: TokenCode, remainingSeconds: Int, remainingSecondsNext: Int) {
Log.d("time", "[ " +
"${codes.getmCode()} ${remainingSeconds}, " +
"${codes.getmNext().getmCode()} ${remainingSecondsNext}" +
" ]")
}
}
| 0 | Swift | 2 | 7 | d28cdd3d167692663ad5c39155b039849313648b | 1,691 | react-native-freeotp | MIT License |
app/src/main/java/com/example/novelfever/ui/screen/home/HomeViewModel.kt | yukinpb | 822,620,915 | false | {"Kotlin": 94472} | package com.example.novelfever.ui.screen.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.novelfever.core.model.Book
import com.example.novelfever.core.model.Genre
import com.example.novelfever.ui.repository.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
data class HomeScreenState(
val isLoading: Boolean = false,
val isError: Boolean = false,
val isRefreshing: Boolean = false,
val isLoadMore: Boolean = false,
val genres: List<Genre> = emptyList(),
val genreSelected: Int = 0,
val books: List<BookDisplay> = listOf()
)
data class BookDisplay(
val genre: Genre,
val books: List<Book>,
val currentPage: Int
)
sealed class HomeScreenEvent {
data object LoadGenre : HomeScreenEvent()
data class LoadBook(val index: Int, val page: Int) : HomeScreenEvent()
data object RefreshData : HomeScreenEvent()
}
@HiltViewModel
class HomeViewModel @Inject constructor(
private val repository: BookRepository
) : ViewModel() {
private val _state = MutableStateFlow(HomeScreenState())
val state: StateFlow<HomeScreenState> = _state
init {
handleEvent(HomeScreenEvent.LoadGenre)
}
fun handleEvent(event: HomeScreenEvent) {
when (event) {
is HomeScreenEvent.LoadGenre -> loadGenre()
is HomeScreenEvent.LoadBook -> loadBook(event.index, event.page)
is HomeScreenEvent.RefreshData -> {
}
}
}
private fun loadGenre() {
viewModelScope.launch {
_state.value = HomeScreenState(isLoading = true)
try {
val genres = repository.getGenre()
_state.value = _state.value.copy(genres = genres, isLoading = false)
} catch (e: Exception) {
_state.value = _state.value.copy(isError = true, isLoading = false)
}
}
}
private fun loadBook(index: Int, page: Int) {
viewModelScope.launch {
if (page == 1) {
_state.value = _state.value.copy(isLoading = true)
} else {
_state.value = _state.value.copy(isLoadMore = true)
}
try {
val genre = _state.value.genres[index]
val bookResponse = repository.getBook(genre.url, page)
if (bookResponse.isEmpty()) {
_state.value = _state.value.copy(isError = true)
return@launch
}
val updatedBooks = _state.value.books.toMutableList()
val bookDisplayIndex = updatedBooks.indexOfFirst { it.genre == genre }
if (bookDisplayIndex != -1) {
val currentBooks = updatedBooks[bookDisplayIndex].books.toMutableList()
currentBooks.addAll(bookResponse)
updatedBooks[bookDisplayIndex] = updatedBooks[bookDisplayIndex].copy(
books = currentBooks,
currentPage = page
)
} else {
updatedBooks.add(BookDisplay(genre, bookResponse, page))
}
_state.value = _state.value.copy(
books = updatedBooks,
isLoading = false,
isLoadMore = false
)
} catch (e: Exception) {
_state.value =
_state.value.copy(isError = true, isLoading = false, isLoadMore = false)
}
}
}
} | 0 | Kotlin | 0 | 0 | dd50e27ce154c0dc1157dbce92545a63e13dbcac | 3,726 | NovelFever | MIT License |
picture_library/src/main/java/com/luck/picture/lib/camera/CheckPermission.kt | MoustafaShahin | 365,029,122 | false | null | package com.luck.picture.lib.camera
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
/**
* =====================================
* 作 者: 陈嘉桐
* 版 本:1.1.4
* 创建日期:2017/6/8
* 描 述:
* =====================================
*/
object CheckPermission {
const val STATE_RECORDING = -1
const val STATE_NO_PERMISSION = -2
const val STATE_SUCCESS = 1//检测是否可以获取录音结果//6.0以下机型都会返回此状态,故使用时需要判断bulid版本
//检测是否在录音中
//检测是否可以进入初始化状态
/**
* 用于检测是否具有录音权限
*
* @return
*/
val recordState: Int
get() {
val minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
var audioRecord: AudioRecord? = AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, minBuffer * 100)
val point = ShortArray(minBuffer)
var readSize = 0
try {
audioRecord!!.startRecording() //检测是否可以进入初始化状态
} catch (e: Exception) {
if (audioRecord != null) {
audioRecord.release()
audioRecord = null
}
return STATE_NO_PERMISSION
}
return if (audioRecord.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
//6.0以下机型都会返回此状态,故使用时需要判断bulid版本
//检测是否在录音中
if (audioRecord != null) {
audioRecord.stop()
audioRecord.release()
audioRecord = null
}
STATE_RECORDING
} else {
//检测是否可以获取录音结果
readSize = audioRecord.read(point, 0, point.size)
if (readSize <= 0) {
if (audioRecord != null) {
audioRecord.stop()
audioRecord.release()
audioRecord = null
}
STATE_NO_PERMISSION
} else {
if (audioRecord != null) {
audioRecord.stop()
audioRecord.release()
audioRecord = null
}
STATE_SUCCESS
}
}
}
} | 0 | Kotlin | 0 | 0 | 6cc5ff6a5c86c491a852304c58ce979ed42d6225 | 2,366 | InsGallery | Apache License 2.0 |
app/src/main/java/com/khaled/mlbarcodescanner/base/BaseBindingFragment.kt | ngochai4404 | 497,193,942 | false | {"Kotlin": 27662, "Java": 9856} | package com.khaled.mlbarcodescanner.model
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
abstract class BaseBindingFragment<B : ViewDataBinding, T : BaseViewModel> :
BaseFragment() {
lateinit var binding: B
lateinit var viewModel: T
// lateinit var mainViewModel: MainViewModel
protected abstract fun getViewModel(): Class<T>
abstract val layoutId: Int
protected abstract fun onCreatedView(view: View?, savedInstanceState: Bundle?)
protected abstract fun onPermissionGranted()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, layoutId, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(this).get(getViewModel())
// mainViewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
onCreatedView(view, savedInstanceState)
}
} | 0 | Kotlin | 0 | 0 | d0559ce2d739990846e7dfe4dd8f25d5345c1602 | 1,314 | barcode | Apache License 2.0 |
flux-standard-action/src/main/java/com/github/grehynds/redux/fsa/Action.kt | greghynds | 136,754,633 | false | {"Kotlin": 9466} | package com.github.grehynds.redux.fsa
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
/**
* From the reduxjs docs:
* Actions are payloads of information that send data from your application to your store.
*
* Based on Flux Standard Action - https://github.com/redux-utilities/flux-standard-action
*/
data class Action(
val type: String = "",
val payload: Any? = null,
val error: Boolean = false
) {
fun isOfType(vararg type: String): Boolean = type.contains(this.type)
companion object {
val EMPTY = Action("NONE")
}
}
@ExperimentalContracts
fun Any.isOfType(type: String): Boolean {
contract {
returns(true) implies (this@isOfType is Action)
}
return this is Action && isOfType(type)
} | 0 | Kotlin | 0 | 1 | 37917faa9be23c2fa7f06d4e315edacf33cf2082 | 779 | redux-kt | Apache License 2.0 |
exvi-core/src/commonMain/kotlin/com/camackenzie/exvi/core/api/AcceptFriendRequest.kt | CallumMackenzie | 450,285,154 | false | {"Kotlin": 123790} | /*
* Copyright (c) Callum Mackenzie 2022.
*/
package com.camackenzie.exvi.core.api
import com.camackenzie.exvi.core.util.EncodedStringCache
import kotlinx.serialization.Serializable
/**
* Response type: NoneResult
*/
@Serializable
@Suppress("unused")
data class AcceptFriendRequest(
override val username: EncodedStringCache,
override val accessKey: EncodedStringCache,
val toAccept: Array<EncodedStringCache>,
) : GenericDataRequest(), ValidatedUserRequest {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as AcceptFriendRequest
if (username != other.username) return false
if (accessKey != other.accessKey) return false
if (!toAccept.contentEquals(other.toAccept)) return false
return true
}
override fun hashCode(): Int {
var result = username.hashCode()
result = 31 * result + accessKey.hashCode()
result = 31 * result + toAccept.contentHashCode()
return result
}
} | 0 | Kotlin | 0 | 0 | e949347d9ada0a1f958002918a5b970f3c9d2194 | 1,094 | exvi-core | Apache License 2.0 |
src/main/kotlin/de/flapdoodle/kfx/extensions/CssExtensions.kt | flapdoodle-oss | 451,526,335 | false | {"Kotlin": 812480, "Java": 154205, "CSS": 39842, "Shell": 297} | /*
* Copyright (C) 2022
* <NAME> <<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 de.flapdoodle.kfx.extensions
import javafx.scene.Node
import javafx.scene.Parent
fun Node.cssClassName(vararg name: String) {
styleClass.addAll(name)
}
fun Parent.bindCss(name: String) {
cssClassName(name)
val resource = javaClass.getResource("${javaClass.simpleName}.css")
require(resource!=null) { "could not bind css to ${javaClass.simpleName}.css" }
stylesheets += resource.toExternalForm()
} | 0 | Kotlin | 1 | 0 | c908ca0c885de23d05923a2e4ce60dfef50956cc | 1,030 | de.flapdoodle.kfx | Apache License 2.0 |
app/src/main/java/com/dluvian/nozzle/data/preferences/ISettingsPreferences.kt | dluvian | 645,936,540 | false | {"Kotlin": 679778} | package com.dluvian.nozzle.data.preferences
interface ISettingsPreferences : ISettingsPreferenceStates {
fun showProfilePictures(): Boolean
fun setShowProfilePictures(bool: Boolean)
fun setDarkMode(isDarkMode: Boolean)
}
| 13 | Kotlin | 3 | 35 | 30ffd7b88fdb612afd80e422a0bfe92a74733338 | 234 | Nozzle | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.