content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.score.vact.di.appointment_details import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.appointment_details.AppointmentDetailsViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class AppointmentDetailsViewModelModule { @Binds @IntoMap @ViewModelKey(AppointmentDetailsViewModel::class) abstract fun bindAppointmentDetailsModule(appointmentDetailsViewModel: AppointmentDetailsViewModel): ViewModel }
vact/app/src/main/java/com/score/vact/di/appointment_details/AppointmentDetailsViewModelModule.kt
59828016
package com.score.vact.di.survey import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class SurveyScope
vact/app/src/main/java/com/score/vact/di/survey/SurveyScope.kt
527053003
package com.score.vact.di.survey import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.survey.SurveyViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class SurveyViewModelModule { @Binds @IntoMap @ViewModelKey(SurveyViewModel::class) abstract fun bindSurveyViewModelModule(surveyViewModel: SurveyViewModel):ViewModel }
vact/app/src/main/java/com/score/vact/di/survey/SurveyViewModelModule.kt
999423868
package com.score.vact.di import android.app.Application import com.score.vact.VACTApp import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import javax.inject.Singleton @Singleton @Component( modules = [ AndroidInjectionModule::class, ActivityBuildersModule::class, AppModule::class, ViewModelFactoryModule::class] ) interface AppComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } fun inject(vactApp: VACTApp) }
vact/app/src/main/java/com/score/vact/di/AppComponent.kt
4044722112
/* * Copyright (C) 2018 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.score.vact.di import androidx.lifecycle.ViewModel import dagger.MapKey import kotlin.reflect.KClass @MustBeDocumented @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER ) @Retention(AnnotationRetention.RUNTIME) @MapKey annotation class ViewModelKey(val value: KClass<out ViewModel>)
vact/app/src/main/java/com/score/vact/di/ViewModelKey.kt
806491955
package com.score.vact.di.login import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.login.LoginViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class LoginViewModelModule { @Binds @IntoMap @ViewModelKey(LoginViewModel::class) abstract fun bindLoginViewModel(loginViewModel: LoginViewModel):ViewModel }
vact/app/src/main/java/com/score/vact/di/login/LoginViewModelModule.kt
1084525292
package com.score.vact.di.login import java.lang.annotation.Documented import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import javax.inject.Scope @Scope @Documented @Retention(RetentionPolicy.RUNTIME) annotation class LoginScope
vact/app/src/main/java/com/score/vact/di/login/LoginScope.kt
4237833290
package com.score.vact.di.appointment_booking import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.appointment_booking.AccompaniedPersonViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class AccompaniedPersonViewModelModule { @Binds @IntoMap @ViewModelKey(AccompaniedPersonViewModel::class) abstract fun bindAccompaniedPersonViewModelMoldue(accompaniedPersonViewModel: AccompaniedPersonViewModel):ViewModel }
vact/app/src/main/java/com/score/vact/di/appointment_booking/AccompaniedPersonViewModelModule.kt
3338701362
package com.score.vact.di.appointment_booking import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class AppointmentBookingScope
vact/app/src/main/java/com/score/vact/di/appointment_booking/AppointmentBookingScope.kt
2449348038
package com.score.vact.di.appointment_booking import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.appointment_booking.AppointmentBookingViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class AppointmentBookingViewModelModule { @Binds @IntoMap @ViewModelKey(AppointmentBookingViewModel::class) abstract fun bindBookAppointmentModule(appointmentBookingViewModel: AppointmentBookingViewModel): ViewModel }
vact/app/src/main/java/com/score/vact/di/appointment_booking/AppointmentBookingViewModelModule.kt
578079559
package com.score.vact.util import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.animation.DecelerateInterpolator import android.widget.Scroller import androidx.viewpager.widget.ViewPager class NonSwipeableViewPager : ViewPager { constructor(context: Context?) : super(context!!) { setMyScroller() } constructor(context: Context?, attrs: AttributeSet?) : super( context!!, attrs ) { setMyScroller() } override fun onInterceptTouchEvent(event: MotionEvent): Boolean { // Never allow swiping to switch between pages return false } override fun onTouchEvent(event: MotionEvent): Boolean { // Never allow swiping to switch between pages return false } //down one is added for smooth scrolling private fun setMyScroller() { try { val viewpager: Class<*> = ViewPager::class.java val scroller = viewpager.getDeclaredField("mScroller") scroller.isAccessible = true scroller[this] = MyScroller(context) } catch (e: Exception) { e.printStackTrace() } } inner class MyScroller(context: Context?) : Scroller(context, DecelerateInterpolator()) { override fun startScroll( startX: Int, startY: Int, dx: Int, dy: Int, duration: Int ) { super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/) } } }
vact/app/src/main/java/com/score/vact/util/NonSwipeableViewPager.kt
4264385400
package com.score.vact.util import androidx.fragment.app.Fragment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.observe import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * A lazy property that gets cleaned up when the fragment's view is destroyed. * * Accessing this variable while the fragment's view is destroyed will throw NPE. */ class AutoClearedValue<T : Any>(val fragment: Fragment) : ReadWriteProperty<Fragment, T> { private var _value: T? = null init { fragment.lifecycle.addObserver(object: DefaultLifecycleObserver { override fun onCreate(owner: LifecycleOwner) { fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner -> viewLifecycleOwner?.lifecycle?.addObserver(object: DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { _value = null } }) } } }) } override fun getValue(thisRef: Fragment, property: KProperty<*>): T { return _value ?: throw IllegalStateException( "should never call auto-cleared-value get when it might not be available" ) } override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) { _value = value } } /** * Creates an [AutoClearedValue] associated with this fragment. */ fun <T : Any> Fragment.autoCleared() = AutoClearedValue<T>(this)
vact/app/src/main/java/com/score/vact/util/AutoClearedValue.kt
123625122
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.util import androidx.lifecycle.LiveData import com.score.vact.api.ApiResponse import retrofit2.Call import retrofit2.CallAdapter import retrofit2.Callback import retrofit2.Response import java.lang.reflect.Type import java.util.concurrent.atomic.AtomicBoolean /** * A Retrofit adapter that converts the Call into a LiveData of ApiResponse. * @param <R> </R> */ class LiveDataCallAdapter<R>(private val responseType: Type) : CallAdapter<R, LiveData<ApiResponse<R>>> { override fun responseType() = responseType override fun adapt(call: Call<R>): LiveData<ApiResponse<R>> { return object : LiveData<ApiResponse<R>>() { private var started = AtomicBoolean(false) override fun onActive() { super.onActive() if (started.compareAndSet(false, true)) { call.enqueue(object : Callback<R> { override fun onResponse(call: Call<R>, response: Response<R>) { postValue(ApiResponse.create(response)) } override fun onFailure(call: Call<R>, throwable: Throwable) { postValue(ApiResponse.create(throwable)) } }) } } } } }
vact/app/src/main/java/com/score/vact/util/LiveDataCallAdapter.kt
144562585
package com.score.vact.util import androidx.lifecycle.LiveData import com.score.vact.api.ApiResponse import retrofit2.CallAdapter import retrofit2.CallAdapter.Factory import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class LiveDataCallAdapterFactory : Factory() { override fun get( returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit ): CallAdapter<*, *>? { if (Factory.getRawType(returnType) != LiveData::class.java) { return null } val observableType = Factory.getParameterUpperBound(0, returnType as ParameterizedType) val rawObservableType = Factory.getRawType(observableType) if (rawObservableType != ApiResponse::class.java) { throw IllegalArgumentException("type must be a resource") } if (observableType !is ParameterizedType) { throw IllegalArgumentException("resource must be parameterized") } val bodyType = Factory.getParameterUpperBound(0, observableType) return LiveDataCallAdapter<Any>(bodyType) } }
vact/app/src/main/java/com/score/vact/util/LiveDataCallAdapterFactory.kt
1883026582
package com.score.vact import android.app.Activity import android.app.Application import com.score.vact.di.AppInjector import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import timber.log.Timber import javax.inject.Inject class VACTApp : Application(), HasActivityInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } AppInjector.init(this) } override fun activityInjector() = dispatchingAndroidInjector }
vact/app/src/main/java/com/score/vact/VACTApp.kt
2956447969
package com.score.vact.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.ContextCompat import androidx.viewpager.widget.PagerAdapter import com.google.android.material.button.MaterialButton import com.score.vact.R import com.score.vact.model.QuestionData import com.score.vact.vo.Answer import kotlinx.coroutines.Job class SurveyAdapter( private val mContext: Context, private val questions: List<QuestionData>, private val onAnswer: ((questionId: Int, answer: Answer) -> Job) ) : PagerAdapter() { override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } override fun instantiateItem(container: ViewGroup, position: Int): Any { val question = questions[position] val layout = LayoutInflater.from(mContext).inflate(R.layout.question_layout, container, false) val tv = layout.findViewById<TextView>(R.id.tvQuestion) val btnNo = layout.findViewById<MaterialButton>(R.id.btnNo) btnNo.tag = position val btnYes = layout.findViewById<MaterialButton>(R.id.btnYes) btnYes.tag = position val btnNotSure = layout.findViewById<MaterialButton>(R.id.btnNotSure) btnNotSure.tag = position tv.text = question.question if (question.answer == Answer.Yes) { btnYes.backgroundTintList = ContextCompat.getColorStateList(mContext, R.color.colorPrimary); btnYes.setTextColor(ContextCompat.getColor(mContext, R.color.ghostWhite)) btnNo.backgroundTintList = ContextCompat.getColorStateList(mContext, android.R.color.white); btnNo.setTextColor(ContextCompat.getColor(mContext, R.color.divider)) btnNotSure.setTextColor(ContextCompat.getColor(mContext, R.color.divider)) } else if (question.answer == Answer.No) { btnNo.backgroundTintList = ContextCompat.getColorStateList(mContext, R.color.colorPrimary); btnNo.setTextColor(ContextCompat.getColor(mContext, R.color.ghostWhite)) btnYes.backgroundTintList = ContextCompat.getColorStateList(mContext, android.R.color.white); btnYes.setTextColor(ContextCompat.getColor(mContext, R.color.divider)) btnNotSure.setTextColor(ContextCompat.getColor(mContext, R.color.divider)) } else if (question.answer == Answer.NOT_AWARE) { btnYes.backgroundTintList = ContextCompat.getColorStateList(mContext, android.R.color.white); btnYes.setTextColor(ContextCompat.getColor(mContext, R.color.divider)) btnNo.backgroundTintList = ContextCompat.getColorStateList(mContext, android.R.color.white); btnNo.setTextColor(ContextCompat.getColor(mContext, R.color.divider)) btnNotSure.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary)) } btnYes.setOnClickListener { onAnswer.invoke(question.id, Answer.Yes) } btnNo.setOnClickListener { onAnswer.invoke(question.id, Answer.No) } btnNotSure.setOnClickListener { onAnswer.invoke(question.id, Answer.NOT_AWARE) } container.addView(layout) return layout } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun getCount(): Int { return questions.size } override fun getItemPosition(`object`: Any): Int { return POSITION_NONE } interface AnswerListener { fun onAnswer(position: Int, answer: Boolean) } }
vact/app/src/main/java/com/score/vact/adapter/SurveyAdapter.kt
9369291
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.adapter.appointment_booking import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import android.view.LayoutInflater import android.view.ViewGroup import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.databinding.AccompaniedPersonRowBinding import com.score.vact.model.appointment_booking.AccompaniedPersonData import com.score.vact.ui.common.DataBoundListAdapter /** * A RecyclerView adapter for [Repo] class. */ class AccompaniedPersonListAdapter( appExecutors: AppExecutors, private val removeCallback: ((AccompaniedPersonData) -> Unit)? ) : DataBoundListAdapter<AccompaniedPersonData, AccompaniedPersonRowBinding>( appExecutors = appExecutors, diffCallback = object : DiffUtil.ItemCallback<AccompaniedPersonData>() { override fun areItemsTheSame( oldItem: AccompaniedPersonData, newItem: AccompaniedPersonData ): Boolean { return oldItem.number == newItem.number && oldItem.name == newItem.name } override fun areContentsTheSame( oldItem: AccompaniedPersonData, newItem: AccompaniedPersonData ): Boolean { return oldItem == newItem } } ) { override fun createBinding(parent: ViewGroup): AccompaniedPersonRowBinding { val binding = DataBindingUtil.inflate<AccompaniedPersonRowBinding>( LayoutInflater.from(parent.context), R.layout.accompanied_person_row, parent, false ) binding.imgDelete.setOnClickListener { binding.person?.let { removeCallback?.invoke(it) } } return binding } override fun bind(binding: AccompaniedPersonRowBinding, item: AccompaniedPersonData) { binding.person = item } }
vact/app/src/main/java/com/score/vact/adapter/appointment_booking/AccompaniedPersonListAdapter.kt
160146149
package com.score.vact.adapter.appointment_booking import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.databinding.BelongingsRowBinding import com.score.vact.model.appointment_booking.AccompaniedPersonData import com.score.vact.model.appointment_booking.BelongingsData import com.score.vact.ui.common.DataBoundListAdapter class BelongingsAdapter( appExecutors: AppExecutors, private val onCheckCallback: ((BelongingsData) -> Unit)? ) : DataBoundListAdapter<BelongingsData, BelongingsRowBinding>( appExecutors = appExecutors, diffCallback = object : DiffUtil.ItemCallback<BelongingsData>() { override fun areItemsTheSame( oldItem: BelongingsData, newItem: BelongingsData ): Boolean { return oldItem.id == newItem.id && oldItem.isSelected == newItem.isSelected } override fun areContentsTheSame( oldItem: BelongingsData, newItem: BelongingsData ): Boolean { return oldItem == newItem } }) { override fun createBinding(parent: ViewGroup): BelongingsRowBinding { val binding = DataBindingUtil.inflate<BelongingsRowBinding>( LayoutInflater.from(parent.context), R.layout.belongings_row, parent, false ) binding.checkbox.setOnCheckedChangeListener { _, b -> binding.belongingItem?.let { val updatedItem = it.copy(isSelected = b) onCheckCallback?.invoke(updatedItem) } } return binding } override fun bind(binding: BelongingsRowBinding, item: BelongingsData) { binding.belongingItem = item } }
vact/app/src/main/java/com/score/vact/adapter/appointment_booking/BelongingsAdapter.kt
3803377043
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.adapter.appointment_booking import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import android.view.LayoutInflater import android.view.ViewGroup import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.databinding.AccompaniedDetailsRowBinding import com.score.vact.databinding.AccompaniedPersonRowBinding import com.score.vact.model.appointment.AccompaniedBy import com.score.vact.model.appointment_booking.AccompaniedPersonData import com.score.vact.ui.common.DataBoundListAdapter import com.score.vact.ui.common.DataBoundViewHolder /** * A RecyclerView adapter for [Repo] class. */ class AccompaniedDetailsListAdapter( appExecutors: AppExecutors ) : DataBoundListAdapter<AccompaniedBy, AccompaniedDetailsRowBinding>( appExecutors = appExecutors, diffCallback = object : DiffUtil.ItemCallback<AccompaniedBy>() { override fun areItemsTheSame( oldItem: AccompaniedBy, newItem: AccompaniedBy ): Boolean { return oldItem.number == newItem.number && oldItem.name == newItem.name } override fun areContentsTheSame( oldItem: AccompaniedBy, newItem: AccompaniedBy ): Boolean { return oldItem == newItem } } ) { override fun createBinding(parent: ViewGroup): AccompaniedDetailsRowBinding { val binding = DataBindingUtil.inflate<AccompaniedDetailsRowBinding>( LayoutInflater.from(parent.context), R.layout.accompanied_details_row, parent, false ) return binding } override fun onBindViewHolder( holder: DataBoundViewHolder<AccompaniedDetailsRowBinding>, position: Int ) { super.onBindViewHolder(holder, position) holder.binding.tvSlNo.text = "${position+1}" } override fun bind(binding: AccompaniedDetailsRowBinding, item: AccompaniedBy) { binding.person = item } }
vact/app/src/main/java/com/score/vact/adapter/appointment_booking/AccompaniedDetailsListAdapter.kt
392467512
package com.score.vact.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.databinding.AppointmentsRowBinding import com.score.vact.model.appointment.AppointmentData import com.score.vact.ui.appointment_list.Action import com.score.vact.ui.common.DataBoundListAdapter class AppointmentListAdapter( val appExecutors: AppExecutors, private val onClick: ((AppointmentData) -> Unit)?, private val onActionClick:((Int,Action) ->Unit)? ) : DataBoundListAdapter<AppointmentData, AppointmentsRowBinding>( appExecutors = appExecutors, diffCallback = object : DiffUtil.ItemCallback<AppointmentData>() { override fun areItemsTheSame( oldItem: AppointmentData, newItem: AppointmentData ): Boolean { return oldItem.id == newItem.id || oldItem.status == newItem.status } override fun areContentsTheSame( oldItem: AppointmentData, newItem: AppointmentData ): Boolean { return oldItem == newItem } } ) { override fun createBinding(parent: ViewGroup): AppointmentsRowBinding { val binding = DataBindingUtil.inflate<AppointmentsRowBinding>( LayoutInflater.from(parent.context), R.layout.appointments_row, parent, false ) binding.root.setOnClickListener { binding.appointment?.let { onClick?.invoke(it) } } binding.btnReject.setOnClickListener{ binding.appointment?.let { onActionClick?.invoke(it.id,Action.REJECT) } } binding.btnModify.setOnClickListener{ binding.appointment?.let { onActionClick?.invoke(it.id,Action.MODIFY) } } binding.btnApprove.setOnClickListener{ binding.appointment?.let { onActionClick?.invoke(it.id,Action.APPROVE) } } return binding } override fun bind(binding: AppointmentsRowBinding, item: AppointmentData) { binding.appointment = item } }
vact/app/src/main/java/com/score/vact/adapter/AppointmentListAdapter.kt
2342576538
package com.score.vact.binding import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.util.Patterns import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.CenterCrop import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestOptions import com.google.android.material.textfield.TextInputLayout import com.score.vact.R import com.score.vact.vo.Status /** * Data Binding adapters specific to the app. */ object BindingAdapters { @JvmStatic @BindingAdapter("visibleGone") fun showHide(view: View, show: Boolean) { view.visibility = if (show) View.VISIBLE else View.GONE } @JvmStatic @BindingAdapter( value = ["app:imageUrl", "app:placeHolder", "app:error", "circular"], requireAll = false ) fun loadImage( imageView: ImageView, url: String?, holderDrawable: Drawable, errorDrawable: Drawable, circular: String? ) { if (url.isNullOrEmpty()) { imageView.setImageDrawable(holderDrawable) } else { var requestOptions = RequestOptions() if (circular != null) { requestOptions = requestOptions.transforms(CenterCrop(), RoundedCorners(200)) } Glide.with(imageView.context) .load(url) .centerCrop() .placeholder(holderDrawable) .error(errorDrawable) .apply(requestOptions) .into(imageView) } } @JvmStatic @BindingAdapter(value = ["validateField", "errorMessage"], requireAll = false) fun checkEmpty(view: TextInputLayout, text: String, errorMessage: String?) { view.error = if (text.isEmpty()) if (errorMessage.isNullOrEmpty()) "Field cannot be empty" else errorMessage else "" view.isErrorEnabled = text.isEmpty() } @JvmStatic @BindingAdapter("validateEmail") fun checkValidEmail(view: TextInputLayout, enteredEmail: String) { var errorMessage = "" var hasError = false if (enteredEmail.isEmpty()) { errorMessage = "Please enter email Id" hasError = true } else if (!Patterns.EMAIL_ADDRESS.matcher(enteredEmail).matches()) { errorMessage = "Invalid Email Id" hasError = true } view.error = errorMessage view.isErrorEnabled = hasError } @JvmStatic @BindingAdapter("showVehicleInfo") fun showVehicleInfo(view: View, selectedVehicleType: Int) { val selectedType = selectedVehicleType == R.id.rdPersonal if (selectedType) { view.visibility = View.VISIBLE } else { view.visibility = View.GONE } } @JvmStatic @BindingAdapter("isEnabled") fun isEnabled(view: View, isEnabled: Boolean) { view.isClickable = isEnabled if (isEnabled) { view.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(view.context,R.color.colorPrimary)) }else{ view.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(view.context,R.color.divider)) } } @JvmStatic @BindingAdapter("arrayFormattedText") fun arrayFormattedText(view:TextView,text:List<String>?){ if(!text.isNullOrEmpty()) { val formatted1 = text.toString().replace("[", "") val formattedText = formatted1.replace("]", "") view.text = formattedText }else{ view.text = "" } } @JvmStatic @BindingAdapter(value = ["status","errorDrawable","successDrawable"]) fun applyStatusOnImage(view:ImageView,status:Status?,errorDrawable: Drawable,successDrawable: Drawable){ status?.let { if(status ==Status.LOADING){ view.visibility = View.INVISIBLE }else{ view.visibility = View.VISIBLE } if(status== Status.SUCCESS){ view.setImageDrawable(successDrawable) }else if(status == Status.ERROR){ view.setImageDrawable(errorDrawable) } } } }
vact/app/src/main/java/com/score/vact/binding/BindingAdapters.kt
1363153235
package com.score.vact.model data class UserData (val id:Int, val name:String, val image:String, val type:String,val isAdmin:Int)
vact/app/src/main/java/com/score/vact/model/UserData.kt
1009527713
package com.score.vact.model.appointment import androidx.room.Embedded import androidx.room.Relation data class AppointmentDetailsData( @Embedded val appointmentData: AppointmentData, @Relation(parentColumn = "id", entityColumn = "id") val detailsData: DetailsData? )
vact/app/src/main/java/com/score/vact/model/appointment/AppointmentDetailsData.kt
540381682
package com.score.vact.model.appointment data class AccompaniedBy( val name: String, val number: String )
vact/app/src/main/java/com/score/vact/model/appointment/AccompaniedBy.kt
3943097732
package com.score.vact.model.appointment import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "appointment_details") data class DetailsData( @PrimaryKey val id: Int, @SerializedName("accompanied_by") val accompaniedBy: List<AccompaniedBy>, val belongings: List<String>, val department: String, val designation: String, val purpose: String, @SerializedName("report_to") val reportTo: String )
vact/app/src/main/java/com/score/vact/model/appointment/DetailsData.kt
1438101259
package com.score.vact.model.appointment import androidx.lifecycle.LiveData import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "appointments") data class AppointmentData( @PrimaryKey var id:Int, @SerializedName("image_url") var profileImage: String, var name: String, var number: String, var email: String, var address: String, var date: String, var time: String, var status: Int )
vact/app/src/main/java/com/score/vact/model/appointment/AppointmentData.kt
3414114663
package com.score.vact.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class CityData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/CityData.kt
2490054128
package com.score.vact.model import android.os.Parcel import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class IDProofData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ):Parcelable{ constructor(parcel: Parcel) : this( parcel.readString()?:"", parcel.readString()?:"" ) { } override fun toString(): String { return name } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(name) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<IDProofData> { override fun createFromParcel(parcel: Parcel): IDProofData { return IDProofData(parcel) } override fun newArray(size: Int): Array<IDProofData?> { return arrayOfNulls(size) } } }
vact/app/src/main/java/com/score/vact/model/IDProofData.kt
510001680
package com.score.vact.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "country_master") data class CountryData( @PrimaryKey @ColumnInfo(name = "id") @SerializedName("ID") val id: String, @ColumnInfo(name = "name") @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/CountryData.kt
562543694
package com.score.vact.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.score.vact.vo.Answer @Entity(tableName = "survey") data class QuestionData( @PrimaryKey val id: Int, val question: String, var answer:Answer=Answer.NA)
vact/app/src/main/java/com/score/vact/model/QuestionData.kt
3447265876
package com.score.vact.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class StateData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/StateData.kt
2648097795
package com.score.vact.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class DistrictData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/DistrictData.kt
1656223824
package com.score.vact.model.appointment_booking import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class DepartmentData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/appointment_booking/DepartmentData.kt
1885198436
package com.score.vact.model.appointment_booking import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class EmployeeData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/appointment_booking/EmployeeData.kt
2622856981
package com.score.vact.model.appointment_booking import java.io.Serializable data class AccompaniedPersonData( var name: String, var doy: String, var gender: String, var number: String, var email: String, var address: String, var docTypeId: String, var docId: String ) : Serializable
vact/app/src/main/java/com/score/vact/model/appointment_booking/AccompaniedPersonData.kt
2743986436
package com.score.vact.model.appointment_booking import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName data class CompanyData( @SerializedName("ID") val id: String, @SerializedName("NAME") val name: String ){ override fun toString(): String { return name } }
vact/app/src/main/java/com/score/vact/model/appointment_booking/CompanyData.kt
1688342230
package com.score.vact.model.appointment_booking import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "belongings_master") data class BelongingsData( @PrimaryKey @SerializedName("ID") val id: Int, @SerializedName("NAME") val name: String, var isSelected: Boolean = false)
vact/app/src/main/java/com/score/vact/model/appointment_booking/BelongingsData.kt
2644416920
package com.score.vact import android.os.Handler import android.os.Looper import java.util.concurrent.Executor import java.util.concurrent.Executors import javax.inject.Inject import javax.inject.Singleton /** * Global executor pools for the whole application. * * Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind * webservice requests). */ @Singleton open class AppExecutors( private val diskIO: Executor, private val networkIO: Executor, private val mainThread: Executor ) { @Inject constructor() : this( Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), MainThreadExecutor() ) fun diskIO(): Executor { return diskIO } fun networkIO(): Executor { return networkIO } fun mainThread(): Executor { return mainThread } private class MainThreadExecutor : Executor { private val mainThreadHandler = Handler(Looper.getMainLooper()) override fun execute(command: Runnable) { mainThreadHandler.post(command) } } }
vact/app/src/main/java/com/score/vact/AppExecutors.kt
691819629
package com.score.vact.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.score.vact.model.QuestionData @Dao interface SurveyDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertQuestions(questions:List<QuestionData>) @Query("select * from survey") fun getSurveyQuestions():LiveData<List<QuestionData>> }
vact/app/src/main/java/com/score/vact/db/SurveyDao.kt
705531432
package com.score.vact.db import androidx.room.TypeConverter import com.google.gson.Gson import com.score.vact.model.appointment.AccompaniedBy class AccompaniedByDataConverter { @TypeConverter fun listToJson(value: List<AccompaniedBy>) = Gson().toJson(value) @TypeConverter fun jsonToList(value: String) = Gson().fromJson(value, Array<AccompaniedBy>::class.java).toList() }
vact/app/src/main/java/com/score/vact/db/AccompaniedByDataConverter.kt
3030651951
package com.score.vact.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.score.vact.model.appointment.AppointmentData import com.score.vact.model.appointment.AppointmentDetailsData import com.score.vact.model.appointment.DetailsData import com.score.vact.model.appointment_booking.BelongingsData @Dao interface AppointmentDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAppointments(appointments: List<AppointmentData>) @Query("select * from appointments where date =:date") fun getAppointments(date: String): LiveData<List<AppointmentData>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertDetails(detailsData: DetailsData) @Query("select * from appointments where id =:appointmentId") fun getAppointmentDetails(appointmentId: Int): LiveData<AppointmentDetailsData> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertBelongings(belongings:List<BelongingsData>) @Query("select * from belongings_master") fun getBelongings():LiveData<List<BelongingsData>> }
vact/app/src/main/java/com/score/vact/db/AppointmentDao.kt
3776359741
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.db import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.score.vact.model.appointment.AppointmentData import com.score.vact.model.CountryData import com.score.vact.model.QuestionData import com.score.vact.model.appointment.DetailsData import com.score.vact.model.appointment_booking.BelongingsData /** * Main database description. */ @Database( entities = [CountryData::class, AppointmentData::class, DetailsData::class, BelongingsData::class,QuestionData::class], version = 1, exportSchema = false ) @TypeConverters(StringListConverter::class, AccompaniedByDataConverter::class, AnswerConverter::class) abstract class AppDb : RoomDatabase() { abstract fun registrationFormData(): RegistrationFormDao abstract fun appointmentDao(): AppointmentDao abstract fun surveyDao():SurveyDao }
vact/app/src/main/java/com/score/vact/db/AppDb.kt
4258553228
package com.score.vact.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.score.vact.model.CountryData import kotlinx.coroutines.Deferred @Dao interface RegistrationFormDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertCountries(countries:List<CountryData>) @Query("select * from country_master") fun getCountries():LiveData<List<CountryData>> }
vact/app/src/main/java/com/score/vact/db/RegistrationFormDao.kt
2262497384
package com.score.vact.db import androidx.room.TypeConverter class StringListConverter { @TypeConverter fun fromString(stringListString: String): List<String> { return stringListString.split(",").map { it } } @TypeConverter fun toString(stringList: List<String>): String { return stringList.joinToString(separator = ",") } }
vact/app/src/main/java/com/score/vact/db/StringListConverter.kt
2344293188
package com.score.vact.db import androidx.room.TypeConverter import com.score.vact.vo.Answer class AnswerConverter { @TypeConverter fun toHealth(value: String) = enumValueOf<Answer>(value) @TypeConverter fun fromHealth(value: Answer) = value.name }
vact/app/src/main/java/com/score/vact/db/AnswerConverter.kt
1689477308
package com.score.vact.api import androidx.lifecycle.LiveData import com.score.vact.model.CountryData import kotlinx.coroutines.Deferred import retrofit2.http.* interface AppService { @GET("Appointment/CheckLogin") fun loginAsync( @Query("UserName") username: String, @Query("Password") password: String ): Deferred<String> @GET("Appointment/GetCountry") fun getCountries(): Deferred<String> @GET("Appointment/GetState") fun getStates(@Query("CountryId") countryId: String): Deferred<String> @GET("Appointment/GetDistrict") fun getDistricts(@Query("StateId") stateId: String): Deferred<String> @GET("Appointment/GetCity") fun getCities(@Query("DistrictId") districtId: String): Deferred<String> @GET("Appointment/GetIdentityType") fun getIdProofList(): Deferred<String> @GET("Appointment/GetCompanyMaster") fun getCompanies(): Deferred<String> @GET("Appointment/GetDepartment") fun getDepartments(@Query("CompanyId") companyId: String): Deferred<String> @GET("Appointment/GetEmployee") fun getEmployees( @Query("CompanyId") companyId: String, @Query("DepartmentId") departmentId: String ): Deferred<String> @GET("Appointment/SendOTP") fun verifyPhoneNumber(@Query("strMobileno") number: String): Deferred<String> @GET("Appointment/CheckOTP") fun verifyOTP( @Query("MobileNo") number: String, @Query("OTP") otp: String ): Deferred<String> @GET("Appointment/GetBelongingMaster") fun getBelongings(): Deferred<String> @POST("Appointment/SaveVisitor") fun registerVisitor(@Query("VisitorDetails") requestParam: String): Deferred<String> @POST() fun getSurveyQuestions(): Deferred<String> @GET("Appointment/CheckAvailability") fun checkAppointmentAvailability( @Query("CompanyId") companyId: String, // @Query("") departmentId: String, @Query("EmployeeId") employeeId: String, @Query("AppointmentDate") date: String, @Query("AppointmentTime") time: String ): Deferred<String> }
vact/app/src/main/java/com/score/vact/api/AppService.kt
2710453090
package com.score.vact.api import retrofit2.Response import timber.log.Timber import java.util.regex.Pattern /** * Common class used by API responses. * @param <T> the type of the response object </T> */ @Suppress("unused") // T is used in extending classes sealed class ApiResponse<T> { companion object { fun <T> create(error: Throwable): ApiErrorResponse<T> { return ApiErrorResponse(error.message ?: "unknown error") } fun <T> create(response: Response<T>): ApiResponse<T> { return if (response.isSuccessful) { val body = response.body() if (body == null || response.code() == 204) { ApiEmptyResponse() } else { ApiSuccessResponse( body = body, linkHeader = response.headers()?.get("link") ) } } else { val msg = response.errorBody()?.string() val errorMsg = if (msg.isNullOrEmpty()) { response.message() } else { msg } ApiErrorResponse(errorMsg ?: "unknown error") } } } } /** * separate class for HTTP 204 responses so that we can make ApiSuccessResponse's body non-null. */ class ApiEmptyResponse<T> : ApiResponse<T>() data class ApiSuccessResponse<T>( val body: T, val links: Map<String, String> ) : ApiResponse<T>() { constructor(body: T, linkHeader: String?) : this( body = body, links = linkHeader?.extractLinks() ?: emptyMap() ) val nextPage: Int? by lazy(LazyThreadSafetyMode.NONE) { links[NEXT_LINK]?.let { next -> val matcher = PAGE_PATTERN.matcher(next) if (!matcher.find() || matcher.groupCount() != 1) { null } else { try { Integer.parseInt(matcher.group(1)) } catch (ex: NumberFormatException) { Timber.w("cannot parse next page from %s", next) null } } } } companion object { private val LINK_PATTERN = Pattern.compile("<([^>]*)>[\\s]*;[\\s]*rel=\"([a-zA-Z0-9]+)\"") private val PAGE_PATTERN = Pattern.compile("\\bpage=(\\d+)") private const val NEXT_LINK = "next" private fun String.extractLinks(): Map<String, String> { val links = mutableMapOf<String, String>() val matcher = LINK_PATTERN.matcher(this) while (matcher.find()) { val count = matcher.groupCount() if (count == 2) { links[matcher.group(2)] = matcher.group(1) } } return links } } } data class ApiErrorResponse<T>(val errorMessage: String) : ApiResponse<T>()
vact/app/src/main/java/com/score/vact/api/ApiResponse.kt
2083160087
package com.example.gdsc_card2 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.gdsc_card2", appContext.packageName) } }
NoobCoder/app/src/androidTest/java/com/example/gdsc_card2/ExampleInstrumentedTest.kt
2814522978
package com.example.gdsc_card2 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
NoobCoder/app/src/test/java/com/example/gdsc_card2/ExampleUnitTest.kt
3246230390
package com.example.gdsc_card2.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val Purple1 = Color(0xFFc9bef4)
NoobCoder/app/src/main/java/com/example/gdsc_card2/ui/theme/Color.kt
3100383303
package com.example.gdsc_card2.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun GDSC_card2Theme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
NoobCoder/app/src/main/java/com/example/gdsc_card2/ui/theme/Theme.kt
2330482814
package com.example.gdsc_card2.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
NoobCoder/app/src/main/java/com/example/gdsc_card2/ui/theme/Type.kt
2416442936
package com.example.gdsc_card2 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column 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.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.Blue import androidx.compose.ui.graphics.Color.Companion.Red import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.gdsc_card2.ui.theme.GDSC_card2Theme import com.example.gdsc_card2.ui.theme.Purple1 import com.example.gdsc_card2.ui.theme.Purple80 class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GDSC_card2Theme { MyScreen() } } } } @Composable fun MyScreen() { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ){ Card( modifier = Modifier .fillMaxWidth() .padding(26.dp) .height(250.dp), backgroundColor = Blue, elevation = 10.dp, shape = RoundedCornerShape(20.dp) ){ Column { MyRow1() MyRow2() } } } } @Composable fun MyRow1(){ Row(modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text( text ="HI \nGDSC ", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = Color.Black,) Spacer(modifier = Modifier.padding(16.dp)) Image(painter = painterResource(id = R.drawable.gdsc_logo), contentDescription ="GDSC Logo" ) } } @Composable fun MyRow2(){ Row( verticalAlignment = Alignment.Bottom ){ Image(painter = painterResource(id = R.drawable.android_logo), contentDescription ="Android Logo") Spacer(modifier = Modifier.padding(16.dp)) Text( text = "Attendace\nLagwade\nPls", fontSize = 15.sp, color = Color.White,) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { GDSC_card2Theme { MyScreen() } }
NoobCoder/app/src/main/java/com/example/gdsc_card2/MainActivity.kt
3369435719
package wow.app.core import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("wow.app.core.test", appContext.packageName) } }
MeloPlayer/core/src/androidTest/java/wow/app/core/ExampleInstrumentedTest.kt
3210154375
package wow.app.core import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MeloPlayer/core/src/test/java/wow/app/core/ExampleUnitTest.kt
3559268067
package meloplayer.core.prefs import android.content.Context import androidx.compose.runtime.Composable import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import meloplayer.core.startup.applicationContextGlobal private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") interface Preference<T> { fun setValue(value: T) val key: String val defaultValue: T val observableValue: Flow<T> val value: T get() = runBlocking { observableValue.firstOrNull() ?: defaultValue } @Composable fun asState() = observableValue.collectAsStateWithLifecycle(initialValue = value) } /** * Handle default values carefully, just like in enumPreference */ fun <T, BackingT> customPreference( backingPref: Preference<BackingT>, defaultValue: T, serialize: (T) -> BackingT, deserialize: (BackingT) -> T ) = object : Preference<T> { override val key = backingPref.key override val defaultValue = defaultValue override val observableValue: Flow<T> get() = backingPref.observableValue.map(deserialize) override fun setValue(value: T) { backingPref.setValue(serialize(value)) } } inline fun <reified T : Enum<T>> enumPreference( key: String, defaultValue: T ) = customPreference( backingPref = IntPreference(key, Int.MAX_VALUE), defaultValue, serialize = { it.ordinal }, deserialize = { if (it == Int.MAX_VALUE) { defaultValue } else { enumValues<T>().getOrNull(it) ?: defaultValue } } ) class IntPreference( override val key: String, override val defaultValue: Int ) : Preference<Int> { private val backingKey = intPreferencesKey(key) override fun setValue(value: Int) { runBlocking { applicationContextGlobal.dataStore.edit { prefs -> prefs[backingKey] = value } } } override val observableValue: Flow<Int> get() = applicationContextGlobal.dataStore.data.map { pref -> pref[backingKey] ?: defaultValue } } class BooleanPreference( override val key: String, override val defaultValue: Boolean ) : Preference<Boolean> { private val backingKey = booleanPreferencesKey(key) override fun setValue(value: Boolean) { runBlocking { applicationContextGlobal.dataStore.edit { prefs -> prefs[backingKey] = value } } } override val observableValue: Flow<Boolean> get() = applicationContextGlobal.dataStore.data.map { pref -> pref[backingKey] ?: defaultValue } } class LongPreference( override val key: String, override val defaultValue: Long ) : Preference<Long> { private val backingKey = longPreferencesKey(key) override fun setValue(value: Long) { runBlocking { applicationContextGlobal.dataStore.edit { prefs -> prefs[backingKey] = value } } } override val observableValue: Flow<Long> get() = applicationContextGlobal.dataStore.data.map { pref -> pref[backingKey] ?: defaultValue } } class StringPreference( override val key: String, override val defaultValue: String ) : Preference<String> { private val backingKey = stringPreferencesKey(key) override fun setValue(value: String) { runBlocking { applicationContextGlobal.dataStore.edit { prefs -> prefs[backingKey] = value } } } override val observableValue: Flow<String> get() = applicationContextGlobal.dataStore.data.map { pref -> pref[backingKey] ?: defaultValue } }
MeloPlayer/core/src/main/java/meloplayer/core/prefs/Preference.kt
945159770
package meloplayer.core.ui import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import com.materialkolor.dynamicColorScheme enum class DarkThemeType { Dark, Black } enum class ThemeConfig { FollowSystem, Light, Dark } sealed interface ColorSchemeType { data object Dynamic : ColorSchemeType class WithSeed(val seed: Color = Color.Blue) : ColorSchemeType } val DefaultThemeSeed = Color(0xFF8F00FF) @Composable fun AppTheme( colorSchemeType: ColorSchemeType = ColorSchemeType.Dynamic, themeConfig: ThemeConfig = ThemeConfig.FollowSystem, darkThemeType: DarkThemeType = DarkThemeType.Dark, content: @Composable () -> Unit ) { val context = LocalContext.current val isDarkTheme = themeConfig == ThemeConfig.Dark || (themeConfig == ThemeConfig.FollowSystem && isSystemInDarkTheme()) val colorScheme = remember(colorSchemeType, isDarkTheme, darkThemeType) { val scheme = when (colorSchemeType) { ColorSchemeType.Dynamic -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (isDarkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } else { dynamicColorScheme(DefaultThemeSeed, isDarkTheme) } } is ColorSchemeType.WithSeed -> { dynamicColorScheme(colorSchemeType.seed, isDarkTheme) } } scheme.copy( background = if (isDarkTheme && darkThemeType == DarkThemeType.Black) Color.Black else scheme.background, surface = if (isDarkTheme && darkThemeType == DarkThemeType.Black) Color.Black else scheme.surface ) } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = Color.Transparent.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !isDarkTheme } } MaterialTheme( colorScheme = colorScheme, content = content ) }
MeloPlayer/core/src/main/java/meloplayer/core/ui/AppTheme.kt
219709762
package meloplayer.core.ui.components import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope 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.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ripple.rememberRipple import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp /** * Base composable for a group of multiple tabs, to be used as primary or secondary navigation utility. * Is actually only a wrapped [Row] * * @param modifier The [Modifier] to apply to the container * @param tabs The content, preferably multiple [TabItem]s or [CustomTabItem]s */ @Composable fun NavigationBarTabs( modifier: Modifier = Modifier, tabs: @Composable RowScope.() -> Unit ) { Row( modifier = Modifier .fillMaxWidth() .then(modifier), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { tabs() } } /** * Composable for a one-ui style [TabItem], to be used in a [NavigationBarTabs] row. * Note: For proper usage, every [TabItem] should have a weight of 1, to be applied via [Modifier.weight()] * * @param modifier The [Modifier] to be applied to the container * @param colors The [TabsColors] to apply * @param onClick The callback invoked when the [TabItem] is clicked * @param text The text to be shown on the tab * @param selected Whether this tab is selected or not * @param interactionSource The [MutableInteractionSource] */ @Composable fun TabItem( modifier: Modifier = Modifier, colors: TabsColors = tabsColors(), onClick: () -> Unit, enabled: Boolean = true, text: String, selected: Boolean, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { Column( modifier = modifier .clip(TabsDefaults.itemShape) .clickable( interactionSource = interactionSource, indication = rememberRipple( color = colors.itemRipple ), role = Role.Tab, onClick = onClick, enabled = enabled ) .minimumInteractiveComponentSize() .padding(TabsDefaults.itemPadding), verticalArrangement = Arrangement.spacedBy( TabsDefaults.itemIndicatorSpacing, alignment = Alignment.CenterVertically ), horizontalAlignment = Alignment.CenterHorizontally ) { var textWidth by remember { mutableIntStateOf(0) } Text( modifier = Modifier //We need to measure the width of the text at runtime .onGloballyPositioned { textWidth = it.size.width }, text = text, color = colors.itemIndicator, style = if (selected) MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold) else MaterialTheme.typography.bodyLarge ) Box( modifier = Modifier .width(with(LocalDensity.current) { textWidth.toDp() }) .height(TabsDefaults.itemIndicatorHeight) ) { Canvas( modifier = Modifier.fillMaxSize() ) { drawLine( color = if (selected) colors.itemIndicator else Color.Transparent, start = Offset( x = 0F, y = size.height / 2F ), end = Offset( x = size.width, y = size.height / 2F ), strokeWidth = TabsDefaults.itemIndicatorHeight.toPx(), cap = StrokeCap.Round ) } } } } @Composable fun CustomTabItem( modifier: Modifier = Modifier, colors: TabsColors = tabsColors(), onClick: () -> Unit, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { Box( modifier = modifier .height(TabsDefaults.customButtonHeight) .clip(TabsDefaults.itemShape) .clickable( interactionSource = interactionSource, indication = rememberRipple( color = colors.itemRipple ), role = Role.Tab, onClick = onClick, enabled = enabled ), contentAlignment = Alignment.Center ) { content() } } /** * Contains the colors needed to constructs a [TabItem] */ data class TabsColors( val itemRipple: Color, val itemIndicator: Color ) @Composable fun tabsColors( itemRipple: Color = MaterialTheme.colorScheme.onSurface, itemIndicator: Color = MaterialTheme.colorScheme.primary, ): TabsColors = TabsColors( itemRipple = itemRipple, itemIndicator = itemIndicator ) object TabsDefaults { val itemIndicatorHeight = 2.dp val itemIndicatorSpacing = 1.dp val itemShape = RoundedCornerShape( size = 26.dp ) val itemSubShape = RoundedCornerShape( size = 23.dp ) val itemPadding = PaddingValues( start = 10.dp, end = 10.dp, top = 14.dp, bottom = 14.dp - itemIndicatorSpacing - itemIndicatorHeight ) val itemSubPadding = PaddingValues( all = 8.dp ) val customButtonHeight = 43.dp }
MeloPlayer/core/src/main/java/meloplayer/core/ui/components/NavigationBar.kt
939381699
package meloplayer.core.ui.components import android.view.Gravity import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ProvideTextStyle import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalView import androidx.compose.ui.semantics.paneTitle import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogWindowProvider @Composable fun BaseDialog( modifier: Modifier = Modifier, backgroundColor: Color = MaterialTheme.colorScheme.surfaceVariant, properties: DialogProperties = DialogProperties( dismissOnClickOutside = true, usePlatformDefaultWidth = false ), onDismissRequest: () -> Unit, padding: PaddingValues = BaseDialogDefaults.contentPadding, minWidth: Dp = 280.dp, paneTitle: String = "Dialog", content: @Composable ColumnScope.() -> Unit, ) { Dialog( onDismissRequest = onDismissRequest, properties = properties, ) { (LocalView.current.parent as? DialogWindowProvider)?.window?.run { setDimAmount(BaseDialogDefaults.dimAmount) setGravity(Gravity.BOTTOM) } Box( modifier = modifier .widthIn(min = minWidth) .padding(BaseDialogDefaults.dialogMargins) .semantics { this.paneTitle = paneTitle } ) { Column( modifier = Modifier .clip(BaseDialogDefaults.shape) .shadow(elevation = BaseDialogDefaults.elevation) .background( color = backgroundColor, shape = BaseDialogDefaults.shape ) .padding(padding), ) { content() } } } } @Composable fun AlertDialog( modifier: Modifier = Modifier, onDismissRequest: () -> Unit, title: (@Composable () -> Unit)? = null, body: (@Composable () -> Unit)? = null, buttonBar: (@Composable () -> Unit)? = null ) { BaseDialog( modifier = modifier, onDismissRequest = onDismissRequest ) { Column( verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start ) { ProvideTextStyle(MaterialTheme.typography.titleLarge) { title?.let { it() } } if (title != null && body != null) { Spacer( modifier = Modifier .height(8.dp) ) } ProvideTextStyle(MaterialTheme.typography.bodyLarge) { body?.let { it() } } if (buttonBar != null) { Spacer( modifier = Modifier .height(26.dp) ) } Row { buttonBar?.let { it() } } } } } object BaseDialogDefaults { val contentPadding = PaddingValues( all = 24.dp ) val dialogMargins = PaddingValues( bottom = 12.dp, start = 12.dp, end = 12.dp ) val shape = RoundedCornerShape( size = 26.dp ) const val dimAmount = 0.65F val elevation = 1.dp }
MeloPlayer/core/src/main/java/meloplayer/core/ui/components/Dialog.kt
3452263032
package meloplayer.core.ui.components import androidx.compose.ui.tooling.preview.Preview @Preview( name = "small font", group = "font scales", fontScale = 0.5f, showBackground = true, showSystemUi = true ) @Preview( name = "large font", group = "font scales", fontScale = 2f, showBackground = true, showSystemUi = true ) annotation class FontScalePreviews @Preview( name = "mobile device", group = "devices", showSystemUi = true, device = "spec:id=reference_phone,shape=Normal,width=411,height=891,unit=dp,dpi=420" ) @Preview( name = "tablet device", group = "devices", showBackground = true, showSystemUi = true, device = "spec:id=reference_tablet,shape=Normal,width=1280,height=800,unit=dp,dpi=240" ) @Preview( name = "desktop device", group = "devices", showBackground = true, showSystemUi = true, device = "spec:id=reference_desktop,shape=Normal,width=1920,height=1080,unit=dp,dpi=160" ) annotation class DevicesPreviews
MeloPlayer/core/src/main/java/meloplayer/core/ui/components/Preview.kt
3192272760
package meloplayer.core.ui.components.sheet import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.anchoredDraggable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset import kotlin.math.roundToInt @OptIn(ExperimentalFoundationApi::class) @Composable fun PlayerSheetScaffold( sheetState: PlayerSheetState, fullPlayerContent: @Composable ColumnScope.() -> Unit, miniPlayerContent: @Composable () -> Unit, navBarContent: @Composable () -> Unit, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit ) { var layoutHeight by remember { mutableIntStateOf(0) } var miniPlayerHeight by remember { mutableIntStateOf(0) } var tabBarHeight by remember { mutableIntStateOf(0) } /** * No padding applied, content composables have to handle system bars padding */ Box( modifier = modifier .fillMaxSize() .onSizeChanged { layoutHeight = it.height if (layoutHeight > 0 && miniPlayerHeight > 0) { sheetState.updateAnchors(layoutHeight, miniPlayerHeight) } } ) { Column(modifier = Modifier.fillMaxSize()) { content() } val alpha = remember(sheetState.sheetExpansionRatio) { derivedStateOf { if (sheetState.sheetExpansionRatio >= 0.5f) { 0f } else { 1 - sheetState.sheetExpansionRatio * 2f } } } Box( modifier = Modifier .fillMaxSize() .align(Alignment.BottomCenter) .offset { val yOffset = sheetState .requireOffset() .roundToInt() IntOffset(x = 0, y = yOffset) } .anchoredDraggable( state = sheetState.draggableState, orientation = Orientation.Vertical ) ) { AnimatedVisibility( visible = sheetState.targetValue == PlayerSheetStateType.FullPlayer || alpha.value < 0.5f, enter = fadeIn(), exit = fadeOut() ) { Column( modifier = Modifier .fillMaxSize() .graphicsLayer { this.alpha = if (sheetState.targetValue == PlayerSheetStateType.FullPlayer) 1f else (0.5f - alpha.value) * 2 } ) { fullPlayerContent() } } AnimatedVisibility( visible = sheetState.targetValue == PlayerSheetStateType.MiniPlayer, enter = fadeIn(), exit = fadeOut() ) { val density = LocalDensity.current Column( modifier = Modifier .onSizeChanged { miniPlayerHeight = it.height if (layoutHeight > 0 && miniPlayerHeight > 0) { sheetState.updateAnchors(layoutHeight, miniPlayerHeight) } } .navigationBarsPadding() .padding(bottom = with(density) { tabBarHeight.toDp() }) .fillMaxWidth() .graphicsLayer { this.alpha = alpha.value } ) { miniPlayerContent() } } } AnimatedVisibility( visible = sheetState.targetValue == PlayerSheetStateType.MiniPlayer, modifier = Modifier.align(Alignment.BottomCenter), enter = fadeIn(), exit = fadeOut() ) { Column( modifier = Modifier .onSizeChanged { tabBarHeight = it.height } .offset { val yOffset = ((1 - alpha.value) * tabBarHeight).roundToInt() IntOffset(x = 0, y = yOffset) } .graphicsLayer { this.alpha = alpha.value } ) { navBarContent() } } } }
MeloPlayer/core/src/main/java/meloplayer/core/ui/components/sheet/PlayerSheetScaffold.kt
1453604354
package meloplayer.core.ui.components.sheet import androidx.compose.animation.core.AnimationConstants import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.AnchoredDraggableState import androidx.compose.foundation.gestures.DraggableAnchors import androidx.compose.foundation.gestures.animateTo import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp enum class PlayerSheetStateType { MiniPlayer, FullPlayer } @Composable fun rememberPlayerSheetState(): PlayerSheetState { val density = LocalDensity.current return rememberSaveable( saver = PlayerSheetState.Saver( density = density ), init = { PlayerSheetState(PlayerSheetStateType.MiniPlayer, density) } ) } @OptIn(ExperimentalFoundationApi::class) @Stable class PlayerSheetState( initialValue: PlayerSheetStateType, density: Density, ) { val draggableState = AnchoredDraggableState( initialValue = initialValue, animationSpec = tween(easing = FastOutSlowInEasing, durationMillis = (AnimationConstants.DefaultDurationMillis * 1.5).toInt()), positionalThreshold = { distance: Float -> distance * 0.5f }, velocityThreshold = { with(density) { 125.dp.toPx() } }, confirmValueChange = { true } ) ///////////////////////PUBLIC val currentValue: PlayerSheetStateType get() = draggableState.currentValue val targetValue: PlayerSheetStateType get() = draggableState.targetValue val sheetExpansionRatio: Float get() { val miniPlayerPos = draggableState.anchors.positionOf(PlayerSheetStateType.MiniPlayer) val fullPlayerPos = draggableState.anchors.positionOf(PlayerSheetStateType.FullPlayer) val currentPos = requireOffset() return (currentPos - miniPlayerPos) / (fullPlayerPos - miniPlayerPos) } suspend fun expandToFullPlayer() { draggableState.animateTo(PlayerSheetStateType.FullPlayer, draggableState.lastVelocity) } suspend fun shrinkToMiniPlayer() { draggableState.animateTo(PlayerSheetStateType.MiniPlayer, draggableState.lastVelocity) } fun requireOffset() = if (draggableState.offset.isNaN()) 0f else draggableState.offset /** * @param maxPossibleFullPlayerHeightPx full player will take the maximum amount of height * possible, this is that height * @param miniPlayerHeightPx miniPlayer will only take limited height, this is that value */ fun updateAnchors(maxPossibleFullPlayerHeightPx: Int, miniPlayerHeightPx: Int) { val newAnchors = DraggableAnchors { PlayerSheetStateType.MiniPlayer at maxPossibleFullPlayerHeightPx - miniPlayerHeightPx.toFloat() PlayerSheetStateType.FullPlayer at 0f } draggableState.updateAnchors(newAnchors) } ////////////////////////PUBLIC END companion object { fun Saver( density: Density ): Saver<PlayerSheetState, PlayerSheetStateType> = Saver( save = { it.currentValue }, restore = { PlayerSheetState( initialValue = it, density = density ) } ) } }
MeloPlayer/core/src/main/java/meloplayer/core/ui/components/sheet/PlayerSheetState.kt
3114738886
package meloplayer.core.startup import android.content.Context import android.util.Log import androidx.startup.Initializer private var appContext: Context? = null val applicationContextGlobal get() = appContext!! internal class ApplicationContextInitializer : Initializer<Context> { override fun create(context: Context): Context { context.applicationContext.also { appContext = it } Log.i("ApplicationContextInitializer", "init done") return context.applicationContext } override fun dependencies(): List<Class<out Initializer<*>>> = emptyList() }
MeloPlayer/core/src/main/java/meloplayer/core/startup/ApplicationContextInitializer.kt
1882143026
package meloplayer.app import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("meloplayer.app", appContext.packageName) } }
MeloPlayer/app/src/androidTest/java/meloplayer/app/ExampleInstrumentedTest.kt
1838665627
package meloplayer.app import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MeloPlayer/app/src/test/java/meloplayer/app/ExampleUnitTest.kt
2797665889
package meloplayer.app.prefs import androidx.compose.ui.graphics.Color import meloplayer.core.prefs.BooleanPreference import meloplayer.core.prefs.LongPreference import meloplayer.core.prefs.customPreference import meloplayer.core.prefs.enumPreference import meloplayer.core.ui.DarkThemeType import meloplayer.core.ui.DefaultThemeSeed import meloplayer.core.ui.ThemeConfig object PreferenceManager { val themeConfig = enumPreference( key = "theme_config", defaultValue = ThemeConfig.FollowSystem ) val darkThemeType = enumPreference( key = "dark_theme_type", defaultValue = DarkThemeType.Dark ) val followSystemColors = BooleanPreference(key = "follow_system_colors", defaultValue = true) val colorSchemeSeed = customPreference( backingPref = LongPreference("color_scheme_type", 0), defaultValue = DefaultThemeSeed, serialize = { color -> color.value.toLong() }, deserialize = { if (it == 0L) DefaultThemeSeed else Color(it.toULong()) } ) }
MeloPlayer/app/src/main/java/meloplayer/app/prefs/PreferenceManager.kt
2379472154
package meloplayer.app.ui import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import kotlin.math.absoluteValue /** * */ @OptIn(ExperimentalFoundationApi::class) fun PagerState.pageOffsetCoerced(page: Int) = ((currentPage - page) + currentPageOffsetFraction).absoluteValue.coerceIn(0f, 1f) @OptIn(ExperimentalFoundationApi::class) fun calculateScale(pagerState: PagerState, page: Int): Float { val distanceFromCenter = pagerState.pageOffsetCoerced(page) val offset = 0.4f // Adjust for desired scale difference return 1f - (distanceFromCenter * offset) } @OptIn(ExperimentalFoundationApi::class) @Composable fun NowPlayingPanel( playItemAtIndex: (Int) -> Unit, playingQueue: List<Painter>, currentItemIndex: Int, modifier: Modifier = Modifier ) { val pagerState = rememberPagerState(pageCount = { playingQueue.size }, initialPage = currentItemIndex) LaunchedEffect(pagerState.currentPage) { if (pagerState.currentPage != currentItemIndex) { playItemAtIndex(pagerState.currentPage) } } HorizontalPager( modifier = modifier, state = pagerState, contentPadding = PaddingValues(start = 16.dp, end = 16.dp), ) { page -> val scaleFactor = calculateScale(pagerState, page) Box( Modifier .padding(horizontal = 16.dp), contentAlignment = Alignment.Center, ) { // AsyncImage( // targetStateSong // .createArtworkImageRequest(context.symphony) // .build(), // null, // contentScale = ContentScale.Crop, // filterQuality = FilterQuality.High, // modifier = Modifier // .fillMaxSize() // .clip(RoundedCornerShape(12.dp)) // ) Image( painter = playingQueue[page], contentDescription = null, modifier = Modifier .fillMaxWidth() .scale(scaleFactor.also { println("$it") }) .aspectRatio(1f), ) } } }
MeloPlayer/app/src/main/java/meloplayer/app/ui/NowPlayingPanel.kt
3490217764
package meloplayer.app.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column 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.navigationBarsPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Face import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import meloplayer.app.R import meloplayer.core.ui.components.NavigationBarTabs import meloplayer.core.ui.components.TabItem import meloplayer.core.ui.components.sheet.PlayerSheetScaffold import meloplayer.core.ui.components.sheet.rememberPlayerSheetState enum class TabScreen { Dashboard, Budget, Stats, More } @Composable fun RootScreen(){ val sheetState = rememberPlayerSheetState() PlayerSheetScaffold( sheetState = sheetState, fullPlayerContent = { Column( modifier = Modifier .weight(1f) .fillMaxWidth() .systemBarsPadding() .background(color = MaterialTheme.colorScheme.background) ) { val queue = remember { listOf( R.drawable.app_icon, R.drawable.app_icon_monochrome, R.drawable.app_icon, R.drawable.app_icon_monochrome, R.drawable.app_icon, R.drawable.app_icon_monochrome, R.drawable.app_icon, R.drawable.app_icon_monochrome, ) } val itemIndex = remember { mutableIntStateOf(0) } NowPlayingPanel( playItemAtIndex = { itemIndex.intValue = it }, playingQueue = queue.map { painterResource(id = it) }, currentItemIndex = itemIndex.intValue ) } }, miniPlayerContent = { Row( modifier = Modifier .fillMaxWidth() .systemBarsPadding() ) { Icon(imageVector = Icons.Default.Face, contentDescription = null) Spacer(modifier = Modifier.size(16.dp)) Text(text = "Something in the way", style = MaterialTheme.typography.titleMedium) } }, navBarContent = { val selectedItem = remember { mutableStateOf(TabScreen.Dashboard) } NavigationBarTabs( modifier = Modifier .selectableGroup() .navigationBarsPadding() ) { val tabs = remember { TabScreen.entries.toList() } tabs.forEach { tabScreen -> TabItem( onClick = { selectedItem.value = tabScreen }, selected = selectedItem.value == tabScreen, text = when (tabScreen) { TabScreen.Dashboard -> "For you" TabScreen.Budget -> "Songs" TabScreen.More -> "Albums" TabScreen.Stats -> "Folders" } ) } IconButton(onClick = { }) { Icon( imageVector = Icons.Default.Menu, contentDescription = "TODO", tint = MaterialTheme.colorScheme.primary ) } } }, content = { Column( modifier = Modifier .fillMaxSize() .systemBarsPadding() //.background(androidx.compose.ui.graphics.Color.Yellow) ) { Text(text = "Yellow is main content") val scope = rememberCoroutineScope() Button(onClick = { scope.launch { sheetState.expandToFullPlayer() } }) { Text(text = "Expand") } Button(onClick = { scope.launch { sheetState.shrinkToMiniPlayer() } }) { Text(text = "Shrink") } } } ) }
MeloPlayer/app/src/main/java/meloplayer/app/ui/RootScreen.kt
2371509800
package meloplayer.app import android.graphics.Color import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column 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.navigationBarsPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Face import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import kotlinx.coroutines.launch import meloplayer.app.prefs.PreferenceManager import meloplayer.app.ui.NowPlayingPanel import meloplayer.core.ui.AppTheme import meloplayer.core.ui.ColorSchemeType import meloplayer.core.ui.components.NavigationBarTabs import meloplayer.core.ui.components.TabItem import meloplayer.core.ui.components.sheet.PlayerSheetScaffold import meloplayer.core.ui.components.sheet.rememberPlayerSheetState class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { installSplashScreen() super.onCreate(savedInstanceState) enableEdgeToEdge( statusBarStyle = SystemBarStyle.light( Color.TRANSPARENT, Color.TRANSPARENT ), navigationBarStyle = SystemBarStyle.light( Color.TRANSPARENT, Color.TRANSPARENT ) ) setContent { val followSystemColor = PreferenceManager.followSystemColors.asState() val seedColor = PreferenceManager.colorSchemeSeed.asState() val theme = PreferenceManager.themeConfig.asState() val darkThemeType = PreferenceManager.darkThemeType.asState() AppTheme( colorSchemeType = if (followSystemColor.value) { ColorSchemeType.Dynamic } else { ColorSchemeType.WithSeed(seedColor.value) }, themeConfig = theme.value, darkThemeType = darkThemeType.value ) { Surface( modifier = Modifier .fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val state = rememberPlayerSheetState() PlayerSheetScaffold( sheetState = state, fullPlayerContent = { Surface( modifier = Modifier.fillMaxSize(), color = androidx.compose.ui.graphics.Color.Green ) { } }, miniPlayerContent = { Surface(modifier = Modifier.height(100.dp).fillMaxWidth(), color = androidx.compose.ui.graphics.Color.Red) { } }, navBarContent = { Surface(modifier = Modifier.height(100.dp).fillMaxWidth(), color = androidx.compose.ui.graphics.Color.Blue) { } }) { } } } } } }
MeloPlayer/app/src/main/java/meloplayer/app/MainActivity.kt
4211418864
package bz.micro.tehuur import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("bz.micro.tehuur", appContext.packageName) } }
tehuur1/app/src/androidTest/java/bz/micro/tehuur/ExampleInstrumentedTest.kt
3923559988
package bz.micro.tehuur import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
tehuur1/app/src/test/java/bz/micro/tehuur/ExampleUnitTest.kt
1290523924
package bz.micro.tehuur.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
tehuur1/app/src/main/java/bz/micro/tehuur/ui/theme/Color.kt
2047024304
package bz.micro.tehuur.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun TehuurTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
tehuur1/app/src/main/java/bz/micro/tehuur/ui/theme/Theme.kt
2258035098
package bz.micro.tehuur.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) , bodyMedium = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
tehuur1/app/src/main/java/bz/micro/tehuur/ui/theme/Type.kt
1017488535
package bz.micro.tehuur import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import bz.micro.tehuur.models.TeModel import bz.micro.tehuur.modules.NavGraph import bz.micro.tehuur.ui.theme.TehuurTheme class MainActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.R) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val model: TeModel by viewModels() setContent { TehuurTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { NavGraph(model = model) } } } } }
tehuur1/app/src/main/java/bz/micro/tehuur/MainActivity.kt
329205748
package bz.micro.tehuur.models import android.util.Log import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import com.babbel.mobile.android.commons.okhttpawssigner.OkHttpAwsV4Signer import okhttp3.Call import okhttp3.Callback import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okio.IOException import org.json.JSONArray import org.json.JSONObject import java.time.LocalDateTime import java.time.format.DateTimeFormatter class TeModel : ViewModel() { private val okClient: OkHttpClient val listAmount = MutableStateFlow(10) private var _loading = MutableStateFlow(false) val loading = _loading.asStateFlow() private var _offsetList = mutableStateOf(0) private var theEnd = mutableStateOf(false) private val _elementList = mutableStateListOf<Record>()// mutableListOf< private val _elementListHolder = MutableStateFlow(listOf<Record>()) val elementList = _elementListHolder.asStateFlow() init { val signer = OkHttpAwsV4Signer("us-east-1", "execute-api") okClient = OkHttpClient.Builder() .addInterceptor { chain -> val original = chain.request() val signed = signer.sign(original, "AKIA3V3KQQAXAL4FX7PB", "op+e6RpEXTNiUlb8mhnyzzPoziu8w8mKr7y+Ftrk") chain.proceed(signed) } .build() refreshList() } fun nextPage() { getList(_offsetList.value) } fun refreshList() { _elementList.clear() _offsetList.value = 0 theEnd.value= false getList(_offsetList.value) } private fun getList(offset:Int) { if (!_loading.value && !theEnd.value) { _loading.value = true val jsonObject = JSONObject() jsonObject.put("city", "amsterdam") jsonObject.put("count", listAmount.value) jsonObject.put("offset", offset) val formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'") val current = LocalDateTime.now().format(formatter) val request = Request.Builder() .url("https://g89gmy5d5b.execute-api.eu-central-1.amazonaws.com/list") .header("x-amz-date", current) .post(jsonObject.toString().toRequestBody("application/json".toMediaTypeOrNull())) .build() okClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.localizedMessage?.let { Log.e("okHTTP", it) } // redirect to error page } override fun onResponse(call: Call, response: Response) { response.use { if (!response.isSuccessful) { Log.e("okHttp", response.toString()) } val x = JSONArray(response.body!!.string()) if (x.length()<10) {theEnd.value=true} (0 until x.length()).forEach { val el = x.getJSONObject(it) val r = Record( id = el["id"].toString(), date = el["date"].toString(), provider = el["provider"].toString(), globalid = el["globalid"].toString().toInt(), country = el["country"].toString(), county = el["county"].toString(), city = el["city"].toString(), street = el["street"].toString(), house = el["house"].toString(), index1 = el["index1"].toString(), index2 = el["index2"].toString(), img = el["img"].toString(), rooms = el["rooms"].toString(), price = el["price"].toString(), metr = el["metr"].toString(), link = el["link"].toString(), description = el["description"].toString(), pathcity = el["pathcity"].toString(), telegramchatid = el["telegramchatid"].toString(), telegramid = el["telegramid"].toString(), whatsupid = el["whatsupid"].toString(), facebookid = el["facebookid"].toString(), instagramid = el["instagramid"].toString(), ) _elementList.add(r) } Log.d("array2", _elementListHolder.value.size.toString()) _elementListHolder.value = _elementList _offsetList.value+=10 _loading.value = false Log.d("array1", _elementList.size.toString()) Log.d("array2", _elementListHolder.value.size.toString()) } } }) } } }
tehuur1/app/src/main/java/bz/micro/tehuur/models/model.kt
4208510349
package bz.micro.tehuur.models data class Record( val id : String, val date:String, val provider:String, val globalid:Int, val country:String, val county:String, val city:String, val street:String, val house:String, val index1:String, val index2:String, val img:String, val rooms:String, val price:String, val metr:String, val link:String, val description:String, val pathcity:String, val telegramchatid:String, val telegramid:String, val whatsupid:String, val facebookid:String, val instagramid:String )
tehuur1/app/src/main/java/bz/micro/tehuur/models/data.kt
2024178233
package bz.micro.tehuur.screens import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import bz.micro.tehuur.ui.theme.TehuurTheme @Composable fun Splash(name: String, modifier: Modifier = Modifier) { Text( text = "here must been splash", textAlign = TextAlign.Center, modifier = modifier.fillMaxSize().wrapContentHeight(align = Alignment.CenterVertically) ) } @Preview(showBackground = true) @Composable fun SplashPreview() { TehuurTheme { Splash("Android") } }
tehuur1/app/src/main/java/bz/micro/tehuur/screens/Splash.kt
1501355823
package bz.micro.tehuur.screens import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import bz.micro.tehuur.models.TeModel import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import bz.micro.tehuur.modules.CardList import bz.micro.tehuur.modules.Skeleton import bz.micro.tehuur.modules.isReadyToLoad @RequiresApi(Build.VERSION_CODES.R) @Composable fun LS1(model: TeModel = viewModel()) { val listState = rememberLazyListState() val todoListState = model.elementList.collectAsState() val loading = model.loading.collectAsState() val configuration = LocalConfiguration.current LaunchedEffect(listState) { snapshotFlow { listState.isScrollInProgress } .collect { Log.d("Scroll", listState.firstVisibleItemIndex.toString()) if (listState.isReadyToLoad(model.listAmount.value)) { Log.d("Scroll", "last item") model.nextPage() } if (listState.isScrollInProgress) { Log.d("Scroll","${listState.layoutInfo.viewportStartOffset} - ${listState.firstVisibleItemScrollOffset}") } } } LazyColumn( modifier = Modifier .fillMaxHeight(), state = listState, userScrollEnabled = true) { items(items = todoListState.value, itemContent = { item -> CardList(item = item) }) if (loading.value) { item(key="0") { Skeleton(w = configuration.screenWidthDp.dp,h= 200.dp, r = 12.dp ) }} } }
tehuur1/app/src/main/java/bz/micro/tehuur/screens/List.kt
3977731124
package bz.micro.tehuur.modules import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Base64 import androidx.compose.foundation.Image import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import bz.micro.tehuur.models.Record val mystyle = TextStyle( //color = Color, fontSize = 10.sp, fontWeight = FontWeight(10), ) fun convertStringToBitmap(base64Str: String?): Bitmap? { val decodedString = Base64.decode(base64Str, Base64.DEFAULT) return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size) } @Composable fun CardList(item : Record ) { ElevatedCard(modifier = Modifier .fillMaxWidth() .height(300.dp) .padding(10.dp), ) { Image( modifier = Modifier.fillMaxWidth(), bitmap = convertStringToBitmap(item.img)!!.asImageBitmap(), contentDescription = null, contentScale = ContentScale.FillWidth) Text( text =item.city, style = mystyle) } }
tehuur1/app/src/main/java/bz/micro/tehuur/modules/CardList.kt
3463886316
package bz.micro.tehuur.modules import androidx.compose.foundation.lazy.LazyListState import kotlin.math.abs fun LazyListState.isReadyToLoad(countLoad:Int): Boolean { //LazyListState return this.layoutInfo.totalItemsCount - this.firstVisibleItemIndex < abs(countLoad/2) +1 }
tehuur1/app/src/main/java/bz/micro/tehuur/modules/isLastItemVisible.kt
826969264
package bz.micro.tehuur.modules import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.rounded.Menu import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector @OptIn(ExperimentalMaterial3Api::class) @Composable fun TeScaffold( title: String? = null, icon: ImageVector, navClick: () -> Unit, teContent: @Composable () -> Unit ) { Scaffold( topBar = { TopAppBar( title = { if (title != null) { Text(text = title) } }, navigationIcon = { IconButton( onClick = navClick ) { Icon(imageVector = icon, contentDescription = null) } } ) } ) { padding -> Column( modifier = Modifier .padding(padding) ) { teContent() } } }
tehuur1/app/src/main/java/bz/micro/tehuur/modules/teScaffold.kt
678133057
package bz.micro.tehuur.modules import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun Skeleton(modifier:Modifier = Modifier, w: Dp, h:Dp, r:Dp){ Box( modifier=modifier .size(width = w, height = h) .padding(10.dp) .shimmerBackground(RoundedCornerShape(r)) ) } fun Modifier.shimmerBackground(shape: Shape = RectangleShape): Modifier = composed { val transition = rememberInfiniteTransition(label = "") val translateAnimation by transition.animateFloat( initialValue = 0f, targetValue = 400f, animationSpec = infiniteRepeatable( tween(durationMillis = 1500, easing = LinearOutSlowInEasing), RepeatMode.Restart ), label = "", ) val shimmerColors = listOf( Color.LightGray.copy(alpha = 0.9f), Color.LightGray.copy(alpha = 0.4f), ) val brush = Brush.linearGradient( colors = shimmerColors, start = Offset(translateAnimation, translateAnimation), end = Offset(translateAnimation + 300f, translateAnimation + 0f), tileMode = TileMode.Mirror, ) return@composed this.then(background(brush, shape)) }
tehuur1/app/src/main/java/bz/micro/tehuur/modules/Skeleton.kt
3420842142
package bz.micro.tehuur.modules import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Menu import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import androidx.navigation.navDeepLink import bz.micro.tehuur.models.TeModel import bz.micro.tehuur.screens.LS1 @Composable fun List(city: String?){ Text( text = city?:"no city" ) } @RequiresApi(Build.VERSION_CODES.R) @Composable fun NavGraph(model: TeModel) { val uri = "https://tehuur.web.app" val navController = rememberNavController() NavHost(navController = navController, startDestination = "full") { composable(route = "full") { TeScaffold( title = "List", icon = Icons.Rounded.Menu, navClick = { model.nextPage()} ){ LS1(model = model) } } composable(route = "Splash") { TeScaffold( title = "Splash", icon = Icons.Rounded.Menu, navClick = { Log.d("------","Click")}) { } } composable( route = "list/{city}", arguments = listOf(navArgument("city") { type = NavType.StringType }), deepLinks = listOf(navDeepLink { uriPattern = "$uri/city={city}" }) ) { backStackEntry -> val arguments = backStackEntry.arguments List(city = arguments?.getString("city")) } } }
tehuur1/app/src/main/java/bz/micro/tehuur/modules/graph.kt
2812860569
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import java.math.BigInteger class LaboratoriRatolinsKtTest { @Test // El ejercicio planteado se resuelve con el fibonacci con saltos de 12 (meses) fun laboratoriRatolins() { val testCases = 100 val months = 12 val fibStep12: MutableList<BigInteger> = mutableListOf() for (num in 0..testCases * months step months) { fibStep12.add(fibonacci(num)) } for (any in 0.. testCases) { assertEquals(fibStep12[any], laboratoriRatolins(any)) } } }
M3UF2A11ArnauCasasEzequielGaribotto/test/LaboratoriRatolinsKtTest.kt
1500029338
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* class PintarRegioKtTest { // Podrem fer l'arrayInput com a valor constant, però ho redefinirem per cada test // per millorar la llegibilitat. @Test fun pintarRegio1() { val arrayInput = arrayOf( // v arrayOf(0, 1, 1, 1, 0, 1, 0, 0), arrayOf(0, 0, 1, 0, 0, 1, 0, 1), arrayOf(0, 1, 1, 1, 0, 1, 0, 1), arrayOf(0, 1, 1, 0, 0, 1, 0, 0), arrayOf(0, 0, 1, 1, 0, 1, 1, 1), arrayOf(0, 0, 0, 0, 0, 1, 0, 0), arrayOf(1, 1, 1, 1, 1, 1, 1, 0), arrayOf(0, 0, 0, 0, 0, 1, 0, 0) ) val posX = 3 val posY = 3 pintarRegio(arrayInput,posX-1,posY-1) val expectedArray = arrayOf( // v arrayOf(0, 2, 2, 2, 0, 1, 0, 0), arrayOf(0, 0, 2, 0, 0, 1, 0, 1), arrayOf(0, 2, 2, 2, 0, 1, 0, 1), arrayOf(0, 2, 2, 0, 0, 1, 0, 0), arrayOf(0, 0, 2, 2, 0, 1, 1, 1), arrayOf(0, 0, 0, 0, 0, 1, 0, 0), arrayOf(1, 1, 1, 1, 1, 1, 1, 0), arrayOf(0, 0, 0, 0, 0, 1, 0, 0)) assertArrayEquals(expectedArray,arrayInput) } @Test fun pintarRegio2() { val arrayInput = arrayOf( arrayOf(0, 1, 1, 1, 0, 1, 0, 0), arrayOf(0, 0, 1, 0, 0, 1, 0, 1), arrayOf(0, 1, 1, 1, 0, 1, 0, 1), arrayOf(0, 1, 1, 0, 0, 1, 0, 0), arrayOf(0, 0, 1, 1, 0, 1, 1, 1), // <-- arrayOf(0, 0, 0, 0, 0, 1, 0, 0), arrayOf(1, 1, 1, 1, 1, 1, 1, 0), arrayOf(0, 0, 0, 0, 0, 1, 0, 0) ) val posX = 7 val posY = 1 pintarRegio(arrayInput,posX-1,posY-1) val expectedArray = arrayOf( arrayOf(0, 1, 1, 1, 0, 2, 0, 0), arrayOf(0, 0, 1, 0, 0, 2, 0, 1), arrayOf(0, 1, 1, 1, 0, 2, 0, 1), arrayOf(0, 1, 1, 0, 0, 2, 0, 0), arrayOf(0, 0, 1, 1, 0, 2, 2, 2), // <-- arrayOf(0, 0, 0, 0, 0, 2, 0, 0), arrayOf(2, 2, 2, 2, 2, 2, 2, 0), arrayOf(0, 0, 0, 0, 0, 2, 0, 0)) assertArrayEquals(expectedArray,arrayInput) } @Test fun pintarRegio3() { val arrayInput = arrayOf( arrayOf(0, 1, 1, 1, 0, 1, 0, 0), arrayOf(0, 0, 1, 0, 0, 1, 0, 1), // <-- arrayOf(0, 1, 1, 1, 0, 1, 0, 1), // <-- arrayOf(0, 1, 1, 0, 0, 1, 0, 0), arrayOf(0, 0, 1, 1, 0, 1, 1, 1), arrayOf(0, 0, 0, 0, 0, 1, 0, 0), arrayOf(1, 1, 1, 1, 1, 1, 1, 0), arrayOf(0, 0, 0, 0, 0, 1, 0, 0) ) val posX = 2 val posY = 8 pintarRegio(arrayInput,posX-1,posY-1) val expectedArray = arrayOf( arrayOf(0, 1, 1, 1, 0, 1, 0, 0), arrayOf(0, 0, 1, 0, 0, 1, 0, 2), // <-- arrayOf(0, 1, 1, 1, 0, 1, 0, 2), // <-- arrayOf(0, 1, 1, 0, 0, 1, 0, 0), arrayOf(0, 0, 1, 1, 0, 1, 1, 1), arrayOf(0, 0, 0, 0, 0, 1, 0, 0), arrayOf(1, 1, 1, 1, 1, 1, 1, 0), arrayOf(0, 0, 0, 0, 0, 1, 0, 0) ) assertArrayEquals(expectedArray,arrayInput) } }
M3UF2A11ArnauCasasEzequielGaribotto/test/PintarRegioKtTest.kt
461191743
import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class MergeSortKtTest { @Test fun mergeSortTest() { // Por cada tamaño creamos una lista de su tamaño con numeros aleatorios de -1000 a 1000 // y luego la ordenamos con la funcion predeterminada de kotlin y comparamos con nuetra // función mergeSort for (tamanyo in (1..1000)) { repeat(tamanyo) { val lista = mutableListOf(tamanyo) for (i in lista.indices) { lista.add((-1000..1000).random()) } val listaEsperada = lista.sorted() mergeSort(lista) assertIterableEquals(listaEsperada, lista, "Las listas no son iguales") } } } }
M3UF2A11ArnauCasasEzequielGaribotto/test/MergeSortKtTest.kt
3898377798
import java.math.BigInteger import java.util.* /** * @author Ezeqyiel Garibotto * @since 12/DEC/2023 * * Aquesta funcio et demanarà que escullis un tipus d'IVA i comprovarà que si escrius qualsevol altra cosa que no * sigui el que et demana, si no poses l'opcio correcta et mostrarà que no és vàlid. * * * @param deQue string que s'utilitza en els prints per dir de per què et demana el tipus. * @param tipusValids array de strings, amb mida indefinida amb tots els tipus d'IVA que hi han * * @return dada de tipus String comprobada que estigui ben escrita */ fun comprovarTipus(deQue: String, vararg tipusValids: String): String { // No fa falta fer test, per funcions que interactuen amb l'usuari val scan = Scanner(System.`in`) var tipus: String var valid = false do { print("Insereix un tipus $deQue: ") tipus = scan.next().uppercase(Locale.getDefault()) if (tipus in tipusValids) valid = true else println("Insereix un tipus $deQue vàlid ${tipusValids.toList()}") } while (!valid) return tipus } /** * @author Ezequiel Garibotto * @since 24/DES/2023 * * Aquesta funció llegeix un nombre enter * * @param nom nom de paràmetre a introduir * @param rangMin rang minim de l'integer introduït, per defecte será MIN_VALUE * @param rangMax rang màxim de l'integer introduït, per defecte será MIN_VALUE * @return nombre introduït per l'usuari */ fun comprovar(nom: String, rangMin: Int = Int.MIN_VALUE, rangMax: Int = Int.MAX_VALUE): Int { // No fa falta fer test, per funcions que interactuen amb l'usuari val scan = Scanner(System.`in`) var input = 0 var valid = false while (!valid) { print("Insereix un enter [$nom]: ") if (scan.hasNextInt()) { input = scan.nextInt() if (input in rangMin..rangMax) { valid = true } else { println("Si us plau, insereix un enter [$nom] en el rang de $rangMin a $rangMax.") } } else { println("Si us plau, insereix un enter [$nom] valid.") scan.nextLine() } } return input } /** * @author Ezequiel Garibotto * @since 12/JAN/2024 * * Procediment que imprimeix una matriu * * @param matriu matriu que es vol imprimir * */ fun imprimirMatriuColor(matriu:Array<Array<Int>>){ // No cal fer tests, ja que no modifica cap valor, només imprimeix la matriu. for (fila in matriu.indices) { for (valor in matriu[fila].indices) { when (matriu[fila][valor]) { 0 -> print("\u001B[47m \u001B[0m") // fondo blanco 1 -> print("\u001B[40m \u001B[0m") // fondo negro 2 -> print("\u001B[100m \u001B[0m") // fondo gris } } println() } } /** * Funció tail recursive de fibonacci * * @param n número del qual es vol conèixer el seu fibonacci * * @return fibonacci d'n * * Funció treta dels apunts de classe, la utilitzem per fer testos. * Modificada amb BigInteger per poder fer testos amb laboratoriRatolins * @see laboratoriRatolins */ fun fibonacci(n:Int): BigInteger { tailrec fun fibonacci(n: Int, actual: BigInteger, seguent: BigInteger): BigInteger { if (n == 0) return actual return fibonacci(n - 1, seguent, actual + seguent) } return fibonacci(n, BigInteger.ZERO, BigInteger.ONE) }
M3UF2A11ArnauCasasEzequielGaribotto/src/Utils.kt
3057423052
/** * @author Arnau Casas * @since 12/GEN/2024 * * Aquest procediment rep una llista mutable d'enters i la divideix en dues parts. Després, * crida la funció "merge" recursivament amb les dues meitats de la llista. * * @param llista Llista mutable d'enters que es vol dividir. * * @see merge */ fun mergeSort(llista: MutableList<Int>){ if (llista.size <= 1) return val meitat = llista.size / 2 val meitatEsquerra = llista.subList(0, meitat).toMutableList() val meitatDreta = llista.subList(meitat, llista.size).toMutableList() mergeSort(meitatEsquerra) mergeSort(meitatDreta) merge(meitatEsquerra, meitatDreta, llista) } /** * @author Arnau Casas * @since 12/GEN/2024 * * Aquest procediment rep dues meitats de llistes mutables d'enters i les fusiona de manera ascendent. * * @param meitatEsquerra Meitat esquerra de la llista mutable d'enters. * @param meitatDreta Meitat dreta de la llista mutable d'enters. */ fun merge(meitatEsquerra: MutableList<Int>, meitatDreta: MutableList<Int>, llista: MutableList<Int>) { var iEsquerra = 0 var iDreta = 0 var tamany = 0 while (iEsquerra < meitatEsquerra.size && iDreta < meitatDreta.size) { if (meitatEsquerra[iEsquerra] <= meitatDreta[iDreta]) { llista[tamany++] = meitatEsquerra[iEsquerra++] } else { llista[tamany++] = meitatDreta[iDreta++] } } while (iEsquerra < meitatEsquerra.size) { llista[tamany++] = meitatEsquerra[iEsquerra] iEsquerra++ } while (iDreta < meitatDreta.size) { llista[tamany++] = meitatDreta[iDreta] iDreta++ } } fun main() { val llista= mutableListOf<Int>() var numero = comprovar("numero") while (numero != -1){ llista.add(numero) println("Insereix -1 per sortir.") numero = comprovar("numero") } println("Llista original: $llista") mergeSort(llista) println("Llista ordenada: $llista") }
M3UF2A11ArnauCasasEzequielGaribotto/src/Mergesort.kt
1268364089
/** * @author Ezequiel Garibotto * @since 12/JAN/2024 * * Aquesta funció pinta una regió d'una matriu donades la matriu i dues coordenades. * Es pinta una cella adjacent quan és a dalt, a sota, a l'esquerra o a la dreta * de la posició (posX, posY) de manera recursiva. * * @param matriu matriu que es vol pintar * @param posX posició posX a la que es vol pintar * @param posY posició posY a la que es vol pintar * * @return matriu amb la regió pintada */ fun pintarRegio(matriu: Array<Array<Int>>, posX: Int, posY: Int) { if (posX in matriu.indices && posY in matriu[0].indices && matriu[posX][posY] == 1) { matriu[posX][posY] = 2 pintarRegio(matriu, posX + 1, posY) pintarRegio(matriu, posX - 1, posY) pintarRegio(matriu, posX, posY + 1) pintarRegio(matriu, posX, posY - 1) } } val matriu = arrayOf( arrayOf(0, 1, 1, 1, 0, 1, 0, 0), arrayOf(0, 0, 1, 0, 0, 1, 0, 1), arrayOf(0, 1, 1, 1, 0, 1, 0, 1), arrayOf(0, 1, 1, 0, 0, 1, 0, 0), arrayOf(0, 0, 1, 1, 0, 1, 1, 1), arrayOf(0, 0, 0, 0, 0, 1, 0, 0), arrayOf(1, 1, 1, 1, 1, 1, 1, 0), arrayOf(0, 0, 0, 0, 0, 1, 0, 0) ) fun main() { // 3, 3 // 7, 1 // 2, 8 do { imprimirMatriuColor(matriu) println("Aquesta és la matriu, escull les coordenades a les que vols pintar una regió.") val posX = comprovar("fila", 1, matriu.size) val posY = comprovar("columna", 1, matriu[0].size) pintarRegio(matriu, posX - 1, posY - 1) imprimirMatriuColor(matriu) println("Aquesta és la matriu resultant de intentar pintar una regió a la posició ($posX,$posY)\n") println("Vols continuar? S/N") val resposta = comprovarTipus("resposta","S","N") val continuar = resposta == "S" } while (continuar) }
M3UF2A11ArnauCasasEzequielGaribotto/src/Pintar una regio.kt
282172398
import java.math.BigInteger /** * @author Ezequiel Garibotto * @since 12/JAN/2024 * * Aquesta funció calcula la quantitat de parelles de ratolins que hi haurà en passar d'una quantitat N d'anys * Utilitzem BigInteger per poder provar amb quantitats d'anys més grans. * * @param anys quantitat d'anys que passen * * @return quantitat de parelles que hi haurà passats N anys */ fun laboratoriRatolins(anys: Int): BigInteger { val numMesos = 12 tailrec fun laboratoriRatolins(mesos: Int, actual: BigInteger, seguent: BigInteger): BigInteger { if (mesos == 0) return actual return laboratoriRatolins(mesos - 1, seguent, actual + seguent) } return laboratoriRatolins(anys * numMesos, BigInteger.ZERO, BigInteger.ONE) } fun main() { var anys = comprovar("anys") while (anys != -1) { val parelles = laboratoriRatolins(anys) println(parelles) anys = comprovar("anys") println("Insereix -1 per sortir.") } }
M3UF2A11ArnauCasasEzequielGaribotto/src/Laboratori Ratolins.kt
2694390294
package com.example.navigationcomponentkullanimi import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.navigationcomponentkullanimi", appContext.packageName) } }
NavigationComponentKullanimi/NavigationComponentKullanimi/app/src/androidTest/java/com/example/navigationcomponentkullanimi/ExampleInstrumentedTest.kt
416390517
package com.example.navigationcomponentkullanimi import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
NavigationComponentKullanimi/NavigationComponentKullanimi/app/src/test/java/com/example/navigationcomponentkullanimi/ExampleUnitTest.kt
3693870189
package com.example.navigationcomponentkullanimi import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
NavigationComponentKullanimi/NavigationComponentKullanimi/app/src/main/java/com/example/navigationcomponentkullanimi/MainActivity.kt
4246686782
package com.example.navigationcomponentkullanimi import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.navigationcomponentkullanimi.databinding.FragmentDetayBinding class DetayFragment : Fragment() { private lateinit var binding: FragmentDetayBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding =FragmentDetayBinding.inflate(inflater, container, false) binding.textViewBilgi.text="Merhaba" return binding.root } }
NavigationComponentKullanimi/NavigationComponentKullanimi/app/src/main/java/com/example/navigationcomponentkullanimi/DetayFragment.kt
3408146457
package com.example.navigationcomponentkullanimi import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.Navigation import com.example.navigationcomponentkullanimi.databinding.FragmentAnasayfaBinding import com.google.android.material.snackbar.Snackbar class anasayfaFragment : Fragment() { private lateinit var binding: FragmentAnasayfaBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding=FragmentAnasayfaBinding.inflate(inflater, container, false) binding.buttonDetay.setOnClickListener { //Snackbar.make(it,"Merhaba",Snackbar.LENGTH_SHORT).show() // binding.textView.text="Nasılsın" Navigation.findNavController(it).navigate(R.id.detayGecis) } return binding.root } }
NavigationComponentKullanimi/NavigationComponentKullanimi/app/src/main/java/com/example/navigationcomponentkullanimi/anasayfaFragment.kt
163101838
package me.yufan.kmmtranslator.core.domain.util fun interface DisposableHandle: kotlinx.coroutines.DisposableHandle
KMMTranslator/shared/src/iosMain/kotlin/me/yufan/kmmtranslator/core/domain/util/DisposableHandle.kt
3477987921
package me.yufan.kmmtranslator.core.domain.util import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch actual open class CommonFlow<T> actual constructor( private val flow: Flow<T> ) : Flow<T> by flow { fun subscribe( coroutineScope: CoroutineScope, dispatcher: CoroutineDispatcher, onCollect: (T) -> Unit ): DisposableHandle { val job = coroutineScope.launch(dispatcher) { flow.collect(onCollect) } return DisposableHandle { job.cancel() } } }
KMMTranslator/shared/src/iosMain/kotlin/me/yufan/kmmtranslator/core/domain/util/CommonFlow.kt
1542002307
package me.yufan.kmmtranslator.core.domain.util import kotlinx.coroutines.flow.FlowCollector import kotlinx.coroutines.flow.StateFlow actual open class CommonStateFlow<T> actual constructor( private val flow: StateFlow<T> ) : CommonFlow<T>(flow), StateFlow<T> { override val replayCache: List<T> get() = flow.replayCache override val value: T get() = flow.value override suspend fun collect(collector: FlowCollector<T>): Nothing { flow.collect(collector) } }
KMMTranslator/shared/src/iosMain/kotlin/me/yufan/kmmtranslator/core/domain/util/CommonStateFlow.kt
578536161
package me.yufan.kmmtranslator.core.domain.util import kotlinx.coroutines.flow.MutableStateFlow class IOSMutableStateFlow<T>( initialValue: T ) : CommonMutableStateFlow<T>(MutableStateFlow(initialValue))
KMMTranslator/shared/src/iosMain/kotlin/me/yufan/kmmtranslator/core/domain/util/IOSMutableStateFlow.kt
2165270537