path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/WebClientFactoryBean.kt
2873284723
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client.reactive import me.ahoo.coapi.spring.CoApiDefinition class WebClientFactoryBean(definition: CoApiDefinition) : AbstractWebClientFactoryBean(definition)
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/ClientProperties.kt
907374280
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client import org.springframework.http.client.ClientHttpRequestInterceptor import org.springframework.web.reactive.function.client.ExchangeFilterFunction interface ClientProperties { fun getFilter(coApiName: String): FilterDefinition fun getInterceptor(coApiName: String): InterceptorDefinition data class FilterDefinition( val names: List<String> = emptyList(), val types: List<Class<out ExchangeFilterFunction>> = emptyList() ) data class InterceptorDefinition( val names: List<String> = emptyList(), val types: List<Class<out ClientHttpRequestInterceptor>> = emptyList() ) }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/HttpClientBuilderCustomizer.kt
4181143062
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client import me.ahoo.coapi.spring.CoApiDefinition fun interface HttpClientBuilderCustomizer<Builder> { fun customize(coApiDefinition: CoApiDefinition, builder: Builder) }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/AbstractRestClientFactoryBean.kt
805856120
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client.sync import me.ahoo.coapi.spring.CoApiDefinition import me.ahoo.coapi.spring.client.ClientProperties import org.springframework.beans.factory.FactoryBean import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.http.client.ClientHttpRequestInterceptor import org.springframework.web.client.RestClient abstract class AbstractRestClientFactoryBean(private val definition: CoApiDefinition) : FactoryBean<RestClient>, ApplicationContextAware { protected lateinit var appContext: ApplicationContext protected open val builderCustomizer: RestClientBuilderCustomizer = RestClientBuilderCustomizer.NoOp override fun getObject(): RestClient { val clientBuilder = appContext .getBean(RestClient.Builder::class.java) clientBuilder.baseUrl(definition.baseUrl) val clientProperties = appContext.getBean(ClientProperties::class.java) val interceptorDefinition = clientProperties.getInterceptor(definition.name) clientBuilder.requestInterceptors { interceptorDefinition.initInterceptors(it) } builderCustomizer.customize(definition, clientBuilder) appContext.getBeanProvider(RestClientBuilderCustomizer::class.java) .orderedStream() .forEach { customizer -> customizer.customize(definition, clientBuilder) } return clientBuilder.build() } private fun ClientProperties.InterceptorDefinition.initInterceptors( interceptors: MutableList<ClientHttpRequestInterceptor> ) { names.forEach { filterName -> val filter = appContext.getBean(filterName, ClientHttpRequestInterceptor::class.java) interceptors.add(filter) } types.forEach { filterType -> val filter = appContext.getBean(filterType) interceptors.add(filter) } } override fun getObjectType(): Class<*> { return RestClient::class.java } override fun setApplicationContext(applicationContext: ApplicationContext) { this.appContext = applicationContext } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/SyncHttpExchangeAdapterFactory.kt
3393557943
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client.sync import me.ahoo.coapi.spring.HttpExchangeAdapterFactory import org.springframework.beans.factory.BeanFactory import org.springframework.web.client.RestClient import org.springframework.web.client.support.RestClientAdapter import org.springframework.web.service.invoker.HttpExchangeAdapter class SyncHttpExchangeAdapterFactory : HttpExchangeAdapterFactory { override fun create(beanFactory: BeanFactory, httpClientName: String): HttpExchangeAdapter { val httpClient = beanFactory.getBean(httpClientName, RestClient::class.java) return RestClientAdapter.create(httpClient) } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/RestClientFactoryBean.kt
2110079759
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client.sync import me.ahoo.coapi.spring.CoApiDefinition class RestClientFactoryBean(definition: CoApiDefinition) : AbstractRestClientFactoryBean(definition)
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/LoadBalancedRestClientFactoryBean.kt
2551711331
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client.sync import me.ahoo.coapi.spring.CoApiDefinition import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancedExchangeFilterFunction import org.springframework.web.client.RestClient class LoadBalancedRestClientFactoryBean(definition: CoApiDefinition) : AbstractRestClientFactoryBean(definition) { companion object { private val loadBalancerInterceptorClass = LoadBalancerInterceptor::class.java } override val builderCustomizer: RestClientBuilderCustomizer = LoadBalancedRestClientBuilderCustomizer() inner class LoadBalancedRestClientBuilderCustomizer : RestClientBuilderCustomizer { override fun customize(coApiDefinition: CoApiDefinition, builder: RestClient.Builder) { builder.requestInterceptors { val hasLoadBalancedFilter = it.any { filter -> filter is LoadBalancedExchangeFilterFunction } if (!hasLoadBalancedFilter) { val loadBalancerInterceptor = appContext.getBean(loadBalancerInterceptorClass) it.add(loadBalancerInterceptor) } } } } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/RestClientBuilderCustomizer.kt
2210674534
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.coapi.spring.client.sync import me.ahoo.coapi.spring.CoApiDefinition import me.ahoo.coapi.spring.client.HttpClientBuilderCustomizer import org.springframework.web.client.RestClient fun interface RestClientBuilderCustomizer : HttpClientBuilderCustomizer<RestClient.Builder> { object NoOp : RestClientBuilderCustomizer { override fun customize(coApiDefinition: CoApiDefinition, builder: RestClient.Builder) = Unit } }
mininsta/app/src/androidTest/java/com/beyzaterzioglu/kotlininstagram/ExampleInstrumentedTest.kt
3835146727
package com.beyzaterzioglu.kotlininstagram 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.beyzaterzioglu.kotlininstagram", appContext.packageName) } }
mininsta/app/src/test/java/com/beyzaterzioglu/kotlininstagram/ExampleUnitTest.kt
3714347917
package com.beyzaterzioglu.kotlininstagram 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) } }
mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/adapter/FeedRecyclerAdapter.kt
791329114
package com.beyzaterzioglu.kotlininstagram.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.beyzaterzioglu.kotlininstagram.databinding.RecyclerRowBinding import com.beyzaterzioglu.kotlininstagram.model.Post import com.squareup.picasso.Picasso class FeedRecyclerAdapter(val postList : ArrayList<Post>) : RecyclerView.Adapter<FeedRecyclerAdapter.PostHolder>() { class PostHolder(val binding:RecyclerRowBinding): RecyclerView.ViewHolder(binding.root) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder { val binding=RecyclerRowBinding.inflate(LayoutInflater.from(parent.context),parent,false) return PostHolder(binding) } override fun getItemCount(): Int { return postList.size } override fun onBindViewHolder(holder: PostHolder, position: Int) { holder.binding.recyclerEmailText.text=postList.get(position).email holder.binding.recyclerCommentText.text=postList.get(position).comment if (postList.get(position).downloadUrl.isNotEmpty()) { Picasso.get().load(postList.get(position).downloadUrl).into(holder.binding.recyclerImageView); } else { // Varsayılan bir resim yükleme veya hata durumunu ele alma } } }
mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/model/Post.kt
1008457718
package com.beyzaterzioglu.kotlininstagram.model data class Post (val email: String, val comment: String,val downloadUrl: String){ }
mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/view/MainActivity.kt
885047676
package com.beyzaterzioglu.kotlininstagram.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.beyzaterzioglu.kotlininstagram.databinding.ActivityMainBinding import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=ActivityMainBinding.inflate(layoutInflater) val view=binding.root setContentView(view) auth = Firebase.auth val currentUser=auth.currentUser if(currentUser!=null) { // geçerli bir kullanıcı var mı val intent=Intent(this, FeedActivity::class.java) startActivity(intent) finish() } } fun signinClick(view:View) { val email=binding.emailText.text.toString() val password=binding.passwordText.text.toString() if(email.equals("")|| password.equals("")) { Toast.makeText(this,"Enter email and password!!",Toast.LENGTH_LONG).show() } else { auth.signInWithEmailAndPassword(email,password) .addOnSuccessListener { val intent= Intent(this@MainActivity, FeedActivity::class.java) startActivity(intent) finish() } .addOnFailureListener { Toast.makeText(this@MainActivity,it.localizedMessage,Toast.LENGTH_LONG).show() } } } fun signupClick(view:View) { val email=binding.emailText.text.toString() val password=binding.passwordText.text.toString() if(email.equals("")|| password.equals("")) { Toast.makeText(this,"Enter email and password!!",Toast.LENGTH_LONG).show() } else { // Bu kısımda yapılan doğrulama isteği atıldıktan sonra cevabın dönmesi daha uzun sürebilir kodlara göre. // Bu sebeple bu işlem arkaplanda asenkron bir şekilde yapılmalıdır. // Aşağıda yapılan islemler de cevabın dönmesi sonrasında yapılacak işlemlerdir. auth.createUserWithEmailAndPassword(email,password) .addOnSuccessListener {// success val intent= Intent(this@MainActivity, FeedActivity::class.java) startActivity(intent) finish() } .addOnFailureListener {Toast.makeText(this@MainActivity,it.localizedMessage,Toast.LENGTH_LONG).show() } } } }
mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/view/UploadActivity.kt
3524932176
package com.beyzaterzioglu.kotlininstagram.view import android.content.pm.PackageManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.core.content.ContextCompat import com.beyzaterzioglu.kotlininstagram.databinding.ActivityUploadBinding import android.Manifest import android.content.Intent import android.net.Uri import android.provider.MediaStore import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import com.google.android.material.snackbar.Snackbar import com.google.firebase.Firebase import com.google.firebase.Timestamp import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.firestore import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.storage import java.util.UUID class UploadActivity : AppCompatActivity() { private lateinit var binding: ActivityUploadBinding private lateinit var activityResultLauncher: ActivityResultLauncher<Intent> private lateinit var permissionLauncher: ActivityResultLauncher<String> //izinler string private lateinit var auth: FirebaseAuth private lateinit var firestore: FirebaseFirestore private lateinit var storage: FirebaseStorage var selectedPicture: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityUploadBinding.inflate(layoutInflater) val view = binding.root setContentView(view) registerLauncher() auth = Firebase.auth firestore = Firebase.firestore storage = Firebase.storage } fun selectImage(view: View) { if (ContextCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ) { // izin yok izin isteyeceğiz if (ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.READ_EXTERNAL_STORAGE ) ) { //rasyoneli göstermeli miyiz?Evet Snackbar.make(view, "Permisson neededfor gallery.", Snackbar.LENGTH_INDEFINITE) .setAction("Give Permission") { permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) }.show() } else { //Hayır. permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } } else { // izin zaten var val intentToGallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) activityResultLauncher.launch(intentToGallery) } } fun upload(view: View) { //uuid, java sınıfındandır. Uydurma bir rakam veriyor. Böylece her kaydedilen resim benzersiz hale geliyor. val uuid = UUID.randomUUID() val imageName = "$uuid.jpg" val reference = storage.reference val imageReference = reference.child("images").child(imageName) if (selectedPicture != null) { imageReference.putFile(selectedPicture!!).addOnSuccessListener { //download url alıp firestore'a kaydedeceğiz. val uploadPictureReference = storage.reference.child("images").child(imageName) uploadPictureReference.downloadUrl.addOnSuccessListener { val downloadUrl = it.toString() if (auth.currentUser != null) { //Any, en kök veri tipidir. Her şey olabilir. val postMap = hashMapOf<String, Any>() postMap.put("downloadUrl", downloadUrl) postMap.put("userEmail", auth.currentUser!!.email!!) postMap.put("comment", binding.commentText.text.toString()) postMap.put("date", Timestamp.now()) firestore.collection("Posts").add(postMap).addOnSuccessListener { finish() }.addOnFailureListener { Toast.makeText( this@UploadActivity, it.localizedMessage, Toast.LENGTH_LONG ).show() } } }.addOnFailureListener { Toast.makeText(this, it.localizedMessage, Toast.LENGTH_LONG).show() } } } } private fun registerLauncher() {//StartActivityForResult() bir sonuç için aktivite başlatacağımızı belirtir.Sonuç da alınacak verinin URI'dir. activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { //seçim sonrası ne olur? result -> if (result.resultCode == RESULT_OK) {// bir aktivite sonucudur.Kullanıcı resim seçti mi? val intentFromResult = result.data if (intentFromResult != null) { selectedPicture = intentFromResult.data selectedPicture?.let {//null olmaktan çıkarıyoruz // farklı bir yöntem ise bitmap'e çevirmektir. binding.imageView.setImageURI(it) } } } } permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { // izin istiyoruz.boolean dönecek result -> if (result) { //izin verildi val intentToGallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) activityResultLauncher.launch(intentToGallery) } else { //izin verilmedi Toast.makeText(this@UploadActivity, "Permisson needed!", Toast.LENGTH_LONG) .show() } } } }
mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/view/FeedActivity.kt
2977149342
package com.beyzaterzioglu.kotlininstagram.view import android.content.AbstractThreadedSyncAdapter import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import com.beyzaterzioglu.kotlininstagram.R import com.beyzaterzioglu.kotlininstagram.adapter.FeedRecyclerAdapter import com.beyzaterzioglu.kotlininstagram.databinding.ActivityFeedBinding import com.beyzaterzioglu.kotlininstagram.model.Post import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Query import com.google.firebase.firestore.firestore class FeedActivity : AppCompatActivity() { private lateinit var binding: ActivityFeedBinding private lateinit var auth: FirebaseAuth private lateinit var db: FirebaseFirestore private lateinit var postArrayList: ArrayList<Post> private lateinit var feedAdapter: FeedRecyclerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=ActivityFeedBinding.inflate(layoutInflater) val view=binding.root setContentView(view) auth=Firebase.auth db=Firebase.firestore postArrayList=ArrayList<Post>() getdata() binding.recyclerView.layoutManager=LinearLayoutManager(this) feedAdapter=FeedRecyclerAdapter(postArrayList) binding.recyclerView.adapter=feedAdapter } private fun getdata() { // verileri db'den almak //.addSnapshotListener { değerlerimizi verir., Alınan hata varsa hatayı verir. -> } db.collection("Posts").orderBy("date",Query.Direction.DESCENDING).addSnapshotListener { value, error -> if(error!=null) { Toast.makeText(this,error.localizedMessage,Toast.LENGTH_LONG).show() } else { if(value!=null) { if(!value.isEmpty){ val documents=value.documents postArrayList.clear() for (document in documents) { // casting işlemi, gelecek olan verinin tipi ne olursa olsun stringe çevirilir. val comment=document.get("comment") as? String val userEmail=document.get("userEmail") as? String val downloadUrl = document.getString("downloadUrl") ?: "" val post= Post(userEmail!!,comment!!,downloadUrl) postArrayList.add(post) } feedAdapter.notifyDataSetChanged() // yeni verilerle güncelleme yap } } } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val menuInflater=menuInflater menuInflater.inflate(R.menu.insta_menu,menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if(item.itemId== R.id.add_post) { val intent= Intent(this, UploadActivity::class.java) startActivity(intent) } else if(item.itemId== R.id.signout) { auth.signOut() val intent= Intent(this, MainActivity::class.java) startActivity(intent) finish() } return super.onOptionsItemSelected(item) } }
ItemCompressor/src/main/java/me/_olios/itemcompressor/ItemCompressor.kt
453806219
package me._olios.itemcompressor import org.bukkit.plugin.java.JavaPlugin class ItemCompressor : JavaPlugin() { override fun onEnable() { // Plugin startup logic } override fun onDisable() { // Plugin shutdown logic } }
basic-app-kyle-android/app/src/androidTest/java/com/example/basic_app_kyle/ExampleInstrumentedTest.kt
2472244452
package com.example.basic_app_kyle 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.basic_app_kyle", appContext.packageName) } }
basic-app-kyle-android/app/src/test/java/com/example/basic_app_kyle/ExampleUnitTest.kt
3494617650
package com.example.basic_app_kyle 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) } }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/home/HomeViewModel.kt
679388821
package com.example.basic_app_kyle.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is home Fragment" } val text: LiveData<String> = _text }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/home/HomeFragment.kt
4258194111
package com.example.basic_app_kyle.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.basic_app_kyle.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textHome homeViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/gallery/GalleryViewModel.kt
567062627
package com.example.basic_app_kyle.ui.gallery import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class GalleryViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is gallery Fragment" } val text: LiveData<String> = _text }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/gallery/GalleryFragment.kt
2994070820
package com.example.basic_app_kyle.ui.gallery import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.basic_app_kyle.databinding.FragmentGalleryBinding class GalleryFragment : Fragment() { private var _binding: FragmentGalleryBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val galleryViewModel = ViewModelProvider(this).get(GalleryViewModel::class.java) _binding = FragmentGalleryBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textGallery galleryViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/slideshow/SlideshowViewModel.kt
1642141248
package com.example.basic_app_kyle.ui.slideshow import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SlideshowViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is slideshow Fragment" } val text: LiveData<String> = _text }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/slideshow/SlideshowFragment.kt
3404545204
package com.example.basic_app_kyle.ui.slideshow import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.basic_app_kyle.databinding.FragmentSlideshowBinding class SlideshowFragment : Fragment() { private var _binding: FragmentSlideshowBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val slideshowViewModel = ViewModelProvider(this).get(SlideshowViewModel::class.java) _binding = FragmentSlideshowBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textSlideshow slideshowViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/MainActivity.kt
182618043
package com.example.basic_app_kyle import android.os.Bundle import android.view.Menu import com.google.android.material.snackbar.Snackbar import com.google.android.material.navigation.NavigationView import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import com.example.basic_app_kyle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBarMain.toolbar) binding.appBarMain.fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = binding.drawerLayout val navView: NavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_content_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow ), drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
AndroidSamples/app/src/androidTest/java/com/example/androidsamples/ExampleInstrumentedTest.kt
2936191759
package com.example.androidsamples 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.androidsamples", appContext.packageName) } }
AndroidSamples/app/src/test/java/com/example/androidsamples/ExampleUnitTest.kt
3177318112
package com.example.androidsamples 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) } }
AndroidSamples/app/src/main/java/com/example/androidsamples/viewmodel/MainViewModel.kt
1364142007
package com.example.androidsamples.viewmodel import androidx.lifecycle.ViewModel import com.example.androidsamples.Screen import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class MainViewModel : ViewModel() { val uiState: StateFlow<UiState> = MutableStateFlow( UiState( listOf(Screen.RichEditText) ) ) data class UiState(val screens: List<Screen>) }
AndroidSamples/app/src/main/java/com/example/androidsamples/ui/theme/Color.kt
2110625062
package com.example.androidsamples.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)
AndroidSamples/app/src/main/java/com/example/androidsamples/ui/theme/Theme.kt
354852664
package com.example.androidsamples.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 AndroidSamplesTheme( 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 ) }
AndroidSamples/app/src/main/java/com/example/androidsamples/ui/theme/Type.kt
2972014825
package com.example.androidsamples.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 ) */ )
AndroidSamples/app/src/main/java/com/example/androidsamples/ui/screen/MainScreen.kt
3916137974
package com.example.androidsamples.ui.screen import android.content.Context import android.content.Intent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Divider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.example.androidsamples.Screen import com.example.androidsamples.activity.RichEditTextActivity import com.example.androidsamples.viewmodel.MainViewModel @Composable fun MainScreen( modifier: Modifier = Modifier, viewModel: MainViewModel = viewModel() ) { val context = LocalContext.current val uiState by viewModel.uiState.collectAsStateWithLifecycle() LazyColumn( modifier = modifier, ) { items(uiState.screens) { Column( modifier .clickable(onClick = { click(context, it) }) .padding(start = 4.dp, end = 4.dp, top = 8.dp, bottom = 8.dp) .fillMaxWidth() ) { Text( text = it.name, modifier = modifier, ) } Divider() } } } fun click(context: Context, screen: Screen) { when (screen) { Screen.RichEditText -> context.startActivity( Intent( context, RichEditTextActivity::class.java ) ) } }
AndroidSamples/app/src/main/java/com/example/androidsamples/activity/MainActivity.kt
3714093518
package com.example.androidsamples.activity import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.example.androidsamples.ui.screen.MainScreen import com.example.androidsamples.ui.theme.AndroidSamplesTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AndroidSamplesTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainScreen() } } } } }
AndroidSamples/app/src/main/java/com/example/androidsamples/activity/RichEditTextActivity.kt
818701243
package com.example.androidsamples.activity import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Typeface import android.os.Bundle import android.text.Spannable import android.text.SpannableStringBuilder import android.text.method.LinkMovementMethod import android.text.style.ForegroundColorSpan import android.text.style.RelativeSizeSpan import android.text.style.ReplacementSpan import android.text.style.StyleSpan import android.text.style.URLSpan import android.text.style.UnderlineSpan import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.text.clearSpans import androidx.core.text.toSpannable import com.example.androidsamples.R private val list = listOf( "文字中", "文字小", "文字大", "色変更", "太字", "下線", "取り消し線", "斜体", "色変更", "ハイパーリンク", "太字かつ斜体" ) private val exclude = listOf("太字かつ斜体", "斜体") class RichEditTextActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_rich_edit_text) findViewById<EditText>(R.id.rich_edit_text).apply { val builder = SpannableStringBuilder("文字大\n文字中\n文字小\n色変更\n太字\n下線\n取り消し線\n斜体\nハイパーリンク\n太字かつ斜体") for (item in list) { val first = this.text.indexOf(item) val last = first + item.length setSpan(builder, item, first, last) } this.text = builder this.movementMethod = LinkMovementMethod.getInstance() } findViewById<EditText>(R.id.rich_edit_text_all).apply { val builder = SpannableStringBuilder("全部") for (item in list) { if (exclude.contains(item)) continue setSpan(builder, item, 0, this.text.length) } this.text = builder this.movementMethod = LinkMovementMethod.getInstance() } findViewById<Button>(R.id.clearButton).setOnClickListener { val allSpan = findViewById<TextView>(R.id.rich_edit_text_all).text.toSpannable() allSpan.clearSpans() findViewById<TextView>(R.id.rich_edit_text).text = allSpan val textSpan = findViewById<TextView>(R.id.rich_edit_text).text.toSpannable() textSpan.clearSpans() findViewById<TextView>(R.id.rich_edit_text_all).text = textSpan } findViewById<EditText>(R.id.checkbox).apply { val builder = SpannableStringBuilder("- [x]あいうえお") builder.setSpan(CheckboxReplacementSpan(), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) this.text = builder } findViewById<EditText>(R.id.bold).apply { val builder = SpannableStringBuilder("**あいうえお**") builder.setSpan(GoneSpan(), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) builder.setSpan(StyleSpan(Typeface.BOLD), 2, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) builder.setSpan( GoneSpan(), this.text.length - 2, this.text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) this.text = builder } } private fun setSpan(builder: SpannableStringBuilder, item: String, start: Int, end: Int) { val span = when (item) { "文字大" -> RelativeSizeSpan(2f) "文字中" -> RelativeSizeSpan(1.5f) "文字小" -> RelativeSizeSpan(1f) "色変更" -> ForegroundColorSpan(Color.RED) "青変更" -> ForegroundColorSpan(Color.BLUE) "太字" -> StyleSpan(Typeface.BOLD) "下線" -> UnderlineSpan() "取り消し線" -> android.text.style.StrikethroughSpan() "斜体" -> StyleSpan(Typeface.ITALIC) "ハイパーリンク" -> URLSpan("https://stackoverflow.com/questions/18621691/custom-sized-italic-font-using-spannable") "太字かつ斜体" -> StyleSpan(Typeface.BOLD_ITALIC) else -> throw IllegalStateException(item) } if (start < 0) return builder.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } private inner class CheckboxReplacementSpan constructor() : ReplacementSpan() { override fun getSize( paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt? ): Int { return paint.measureText("✅", 0, 1).toInt() } override fun draw( canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint ) { canvas.drawText("✅", 0, 1, x, y.toFloat(), paint); } } class GoneSpan : ReplacementSpan() { override fun getSize( paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt? ): Int = 0 override fun draw( canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint ) { } } }
AndroidSamples/app/src/main/java/com/example/androidsamples/Screen.kt
1591483952
package com.example.androidsamples enum class Screen { RichEditText, }
demo-push-notifications/app/src/androidTest/java/com/example/firepush/ExampleInstrumentedTest.kt
1836422527
package com.example.firepush 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.firepush", appContext.packageName) } }
demo-push-notifications/app/src/test/java/com/example/firepush/ExampleUnitTest.kt
4005507136
package com.example.firepush 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) } }
demo-push-notifications/app/src/main/java/com/example/firepush/ui/theme/Color.kt
3412193677
package com.example.firepush.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)
demo-push-notifications/app/src/main/java/com/example/firepush/ui/theme/Theme.kt
1837646401
package com.example.firepush.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 FirePushTheme( 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 ) }
demo-push-notifications/app/src/main/java/com/example/firepush/ui/theme/Type.kt
2770799836
package com.example.firepush.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 ) */ )
demo-push-notifications/app/src/main/java/com/example/firepush/MainActivity.kt
2559449969
package com.example.firepush import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding 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.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.firepush.ui.theme.FirePushTheme import com.google.firebase.messaging.FirebaseMessaging class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FirePushTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Greeting("Mr. Wick") } } } FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (task.isSuccessful) { var token = task.result println("FCM Token: $token") } else { println("Failed to get FCM token: ${task.exception}") } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Hello, $name!", modifier = modifier ) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { FirePushTheme { Greeting("NexusCare User") } }
demo-push-notifications/app/src/main/java/com/example/firepush/MyFirebaseMessagingService.kt
2373026714
package com.example.firepush import android.util.Log import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class MyFirebaseMessagingService: FirebaseMessagingService() { private val TAG: String = String::class.java.simpleName override fun onNewToken(token: String) { super.onNewToken(token) Log.d("R", token) } private fun sendRegistrationToServer(token: String) { // send } override fun onMessageReceived(remoteMessage: RemoteMessage) { Log.d(TAG, "From: ${remoteMessage?.from}") remoteMessage?.data?.isNotEmpty()?.let { Log.d(TAG, "message data payload" + remoteMessage.data) if(!remoteMessage.data.isNullOrEmpty()) { val msg: String = remoteMessage.data["message"].toString() } } remoteMessage?.notification?.let{} } }
AbsolveTechAssignment/app/src/androidTest/java/com/example/absolvetechassignment/ExampleInstrumentedTest.kt
963583532
package com.example.absolvetechassignment 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.absolvetechassignment", appContext.packageName) } }
AbsolveTechAssignment/app/src/test/java/com/example/absolvetechassignment/ExampleUnitTest.kt
2665823350
package com.example.absolvetechassignment 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) } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/MainActivity.kt
3889386713
package com.example.absolvetechassignment import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/di/NetworkModule.kt
3733030804
package com.example.absolvetechassignment.di import com.example.absolvetechassignment.retrofit.ApiInterface import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class NetworkModule { @Singleton @Provides fun providesRetrofit(): Retrofit { return Retrofit.Builder().baseUrl("https://fakestoreapi.com/") .addConverterFactory(GsonConverterFactory.create()).build() } @Singleton @Provides fun providesApiInterface(retrofit: Retrofit): ApiInterface { return retrofit.create(ApiInterface::class.java) } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/fragments/TaskTwoFragment.kt
362784694
package com.example.absolvetechassignment.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.absolvetechassignment.databinding.TaskOneFragmentBinding import com.example.absolvetechassignment.databinding.TaskTwoFragmentBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class TaskTwoFragment : Fragment() { private var _binding: TaskTwoFragmentBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = TaskTwoFragmentBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/fragments/FirstFragment.kt
2893454542
package com.example.absolvetechassignment.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.absolvetechassignment.R import com.example.absolvetechassignment.databinding.FirstFragmentBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class FirstFragment : Fragment() { private var _binding: FirstFragmentBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FirstFragmentBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) addClickListeners() } private fun addClickListeners() { binding.btTask1.setOnClickListener { findNavController().navigate(R.id.action_firstFragment_to_taskOneFragment) } binding.btTask2.setOnClickListener { findNavController().navigate(R.id.action_firstFragment_to_taskTwoFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/fragments/TaskOneViewModel.kt
467578006
package com.example.absolvetechassignment.fragments import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.absolvetechassignment.models.Product import com.example.absolvetechassignment.retrofit.ApiInterface import com.example.absolvetechassignment.utils.GenericAdapter import com.example.absolvetechassignment.utils.NetworkResult import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TaskOneViewModel @Inject constructor(private val apiInterface: ApiInterface) : ViewModel() { lateinit var productAdapter:GenericAdapter<Product> private var _allProductsLiveData = MutableLiveData<NetworkResult<List<Product>>>() val allProduct: LiveData<NetworkResult<List<Product>>> get() = _allProductsLiveData fun getAllProducts() { viewModelScope.launch { _allProductsLiveData.postValue(NetworkResult.Loading()) val response = apiInterface.getAllProducts() if (response.isSuccessful && response.body() != null) { _allProductsLiveData.postValue(NetworkResult.Success<List<Product>>(response.body())) } else if (response.errorBody() != null) { _allProductsLiveData.postValue(NetworkResult.Error("Something Went wrong")) } else { _allProductsLiveData.postValue(NetworkResult.Error("Something Went wrong")) } } } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/fragments/TaskOneFragment.kt
1407605029
package com.example.absolvetechassignment.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import com.bumptech.glide.Glide import com.example.absolvetechassignment.R import com.example.absolvetechassignment.databinding.ItemProductBinding import com.example.absolvetechassignment.databinding.TaskOneFragmentBinding import com.example.absolvetechassignment.models.Product import com.example.absolvetechassignment.utils.GenericAdapter import com.example.absolvetechassignment.utils.NetworkResult import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class TaskOneFragment : Fragment() { private var _binding: TaskOneFragmentBinding? = null private val binding get() = _binding!! private val viewModel by viewModels<TaskOneViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = TaskOneFragmentBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.getAllProducts() addAdapter() addObservers() } private fun addAdapter() { viewModel.productAdapter = object : GenericAdapter<Product>(R.layout.item_product) { override fun onBindViewHolder(holder: ViewHolder, position: Int) { ItemProductBinding.bind(holder.itemView).let { rvBinding -> getItemAt(position)?.let { data -> rvBinding.tvName.text = data.category rvBinding.tvDescription.text = data.description val discount = String.format("%.2f", data.price * 0.2).replace(".00", "").toDouble() val price = String.format("%.2f", data.price).replace(".00", "").toDouble() rvBinding.tvPrice.text = "$${price - discount}" rvBinding.tvPriceStrike.text = "$$price" Glide.with(context) .load(data.image) .into(rvBinding.imgProduct) } } } } binding.rvProducts.adapter = viewModel.productAdapter } private fun addObservers() { viewModel.allProduct.observe(viewLifecycleOwner, Observer { when (it) { is NetworkResult.Success -> { Log.e("NETWORK_RESULT", "SUCCESS") Log.e("RESULT", it.data.toString()) binding.progressBar.visibility=View.GONE viewModel.productAdapter.submitList(it.data) } is NetworkResult.Error -> { binding.progressBar.visibility=View.GONE Log.e("NETWORK_RESULT", "ERROR") } is NetworkResult.Loading -> { binding.progressBar.visibility=View.VISIBLE Log.e("NETWORK_RESULT", "LOADING") } } }) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/utils/GenericAdapter.kt
430336742
package com.example.absolvetechassignment.utils import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.ListAdapter abstract class GenericAdapter<M : Any>(@LayoutRes private val layoutId: Int) : ListAdapter<M, GenericAdapter.ViewHolder>(GenericDiffUtil<M>()) { class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(layoutId, parent, false) return ViewHolder(view) } fun getItemAt(position: Int) = currentList.getOrNull(position) } class GenericDiffUtil<T> : DiffUtil.ItemCallback<T>() { override fun areItemsTheSame(oldItem: T & Any, newItem: T & Any): Boolean { return oldItem?.equals(newItem) ?: false } @SuppressLint("DiffUtilEquals") override fun areContentsTheSame(oldItem: T & Any, newItem: T & Any): Boolean { return oldItem?.equals(newItem) ?: false } }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/utils/NetworkResult.kt
3558075902
package com.example.absolvetechassignment.utils sealed class NetworkResult<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T?) : NetworkResult<T>(data = data) class Error<T>(message: String?) : NetworkResult<T>(message = message) class Loading<T>() : NetworkResult<T>() }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/models/Product.kt
2573268072
package com.example.absolvetechassignment.models data class Product( val category: String, val description: String, val id: Int, val image: String, val price: Double, val rating: Rating, val title: String )
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/models/Rating.kt
1136735709
package com.example.absolvetechassignment.models data class Rating( val count: Int, val rate: Double )
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/ApplicationClass.kt
3318652041
package com.example.absolvetechassignment import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class ApplicationClass : Application() { }
AbsolveTechAssignment/app/src/main/java/com/example/absolvetechassignment/retrofit/ApiInterface.kt
3863523170
package com.example.absolvetechassignment.retrofit import com.example.absolvetechassignment.models.Product import retrofit2.Response import retrofit2.http.GET interface ApiInterface { @GET("products") suspend fun getAllProducts(): Response<List<Product>> }
parsek-plugin-system-property/src/main/kotlin/co/statu/rule/systemProperty/SystemPropertyPlugin.kt
3206726486
package co.statu.rule.systemProperty import co.statu.parsek.api.ParsekPlugin import co.statu.rule.database.Dao import co.statu.rule.database.DatabaseMigration import co.statu.rule.database.api.DatabaseHelper import co.statu.rule.systemProperty.db.impl.SystemPropertyDaoImpl class SystemPropertyPlugin : ParsekPlugin(), DatabaseHelper { override val tables: List<Dao<*>> = listOf(SystemPropertyDaoImpl()) override val migrations: List<DatabaseMigration> = listOf() }
parsek-plugin-system-property/src/main/kotlin/co/statu/rule/systemProperty/SystemPropertyDefaults.kt
3155449201
package co.statu.rule.systemProperty enum class SystemPropertyDefaults(val value: String)
parsek-plugin-system-property/src/main/kotlin/co/statu/rule/systemProperty/db/impl/SystemPropertyDaoImpl.kt
29452877
package co.statu.rule.systemProperty.db.impl import co.statu.parsek.api.ParsekPlugin import co.statu.rule.systemProperty.SystemPropertyDefaults import co.statu.rule.systemProperty.db.dao.SystemPropertyDao import co.statu.rule.systemProperty.db.model.SystemProperty import io.vertx.jdbcclient.JDBCPool import io.vertx.kotlin.coroutines.await import io.vertx.sqlclient.Row import io.vertx.sqlclient.RowSet import io.vertx.sqlclient.Tuple class SystemPropertyDaoImpl : SystemPropertyDao() { override suspend fun init(jdbcPool: JDBCPool, plugin: ParsekPlugin) { jdbcPool .query( """ CREATE TABLE IF NOT EXISTS `${getTablePrefix() + tableName}` ( `id` UUID NOT NULL, `option` String NOT NULL, `value` String NOT NULL ) ENGINE = MergeTree() order by `id`; """ ) .execute() .await() addWebsiteConfig(jdbcPool) } override suspend fun add( systemProperty: SystemProperty, jdbcPool: JDBCPool ) { val query = "INSERT INTO `${getTablePrefix() + tableName}` (`id`, `option`, `value`) VALUES (?, ?, ?)" jdbcPool .preparedQuery(query) .execute( Tuple.of( systemProperty.id, systemProperty.option, systemProperty.value ) ) .await() } override suspend fun update( systemProperty: SystemProperty, jdbcPool: JDBCPool ) { val params = Tuple.tuple() params.addString(systemProperty.value) if (systemProperty.id == null) params.addString(systemProperty.option) else params.addUUID(systemProperty.id) val query = "UPDATE `${getTablePrefix() + tableName}` SET value = ? ${if (systemProperty.id != null) ", option = ?" else ""} WHERE `${if (systemProperty.id == null) "option" else "id"}` = ?" jdbcPool .preparedQuery(query) .execute( params ) .await() } override suspend fun isPropertyExists( systemProperty: SystemProperty, jdbcPool: JDBCPool ): Boolean { val query = "SELECT COUNT(`value`) FROM `${getTablePrefix() + tableName}` where `option` = ?" val rows: RowSet<Row> = jdbcPool .preparedQuery(query) .execute( Tuple.of(systemProperty.option) ) .await() return rows.toList()[0].getLong(0) != 0L } override suspend fun getValue( systemProperty: SystemProperty, jdbcPool: JDBCPool ): SystemProperty? { val query = "SELECT `id`, `option`, `value` FROM `${getTablePrefix() + tableName}` where `option` = ?" val rows: RowSet<Row> = jdbcPool .preparedQuery(query) .execute( Tuple.of( systemProperty.option ) ) .await() if (rows.size() == 0) { return null } val row = rows.toList()[0] return row.toEntity() } override suspend fun getAll(jdbcPool: JDBCPool): List<SystemProperty> { val query = "SELECT `id`, `option`, `value` FROM `${getTablePrefix() + tableName}`" val rows: RowSet<Row> = jdbcPool .preparedQuery(query) .execute() .await() return rows.toEntities() } private suspend fun addWebsiteConfig( jdbcPool: JDBCPool ) { SystemPropertyDefaults.entries.forEach { add(SystemProperty(option = it.name, value = it.value), jdbcPool) } } }
parsek-plugin-system-property/src/main/kotlin/co/statu/rule/systemProperty/db/dao/SystemPropertyDao.kt
4244234834
package co.statu.rule.systemProperty.db.dao import co.statu.rule.database.Dao import co.statu.rule.systemProperty.db.model.SystemProperty import io.vertx.jdbcclient.JDBCPool abstract class SystemPropertyDao : Dao<SystemProperty>(SystemProperty::class) { abstract suspend fun add( systemProperty: SystemProperty, jdbcPool: JDBCPool ) abstract suspend fun update( systemProperty: SystemProperty, jdbcPool: JDBCPool ) abstract suspend fun isPropertyExists( systemProperty: SystemProperty, jdbcPool: JDBCPool ): Boolean abstract suspend fun getValue( systemProperty: SystemProperty, jdbcPool: JDBCPool ): SystemProperty? abstract suspend fun getAll( jdbcPool: JDBCPool ): List<SystemProperty> }
parsek-plugin-system-property/src/main/kotlin/co/statu/rule/systemProperty/db/model/SystemProperty.kt
3588823548
package co.statu.rule.systemProperty.db.model import co.statu.rule.database.DBEntity import java.util.* data class SystemProperty( val id: UUID? = UUID.randomUUID(), val option: String, val value: String = "" ) : DBEntity()
parsek-plugin-system-property/src/main/kotlin/co/statu/rule/systemProperty/event/DatabaseEventHandler.kt
1776978128
package co.statu.rule.systemProperty.event import co.statu.parsek.api.annotation.EventListener import co.statu.rule.database.DatabaseManager import co.statu.rule.database.event.DatabaseEventListener import co.statu.rule.systemProperty.SystemPropertyPlugin @EventListener class DatabaseEventHandler(private val systemPropertyPlugin: SystemPropertyPlugin) : DatabaseEventListener { override suspend fun onReady(databaseManager: DatabaseManager) { databaseManager.migrateNewPluginId( "system-property", systemPropertyPlugin.pluginId, systemPropertyPlugin ) databaseManager.initialize(systemPropertyPlugin, systemPropertyPlugin) } }
QuizQu/app/src/androidTest/java/com/example/quizqu/ExampleInstrumentedTest.kt
3497642629
package com.example.quizqu 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.quizqu", appContext.packageName) } }
QuizQu/app/src/test/java/com/example/quizqu/ExampleUnitTest.kt
1172992593
package com.example.quizqu 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) } }
QuizQu/app/src/main/java/com/example/quizqu/MainActivity.kt
2850213739
package com.example.quizqu import android.graphics.Color import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.quizqu.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val question = arrayOf( "Siapa namamu tuan?", "Dimana rumahnya?", "Saya Siapa?" ) private val options = arrayOf( arrayOf("udin", "budi", "owi"), arrayOf("disini", "disana", "dimana ya"), arrayOf("asli rill", "up dulu", "kamu siapa") ) private val correctAnswer = arrayOf(2, 0, 2) private var currentQuestionIndex = 0 private var score = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) displayQuestion() binding.btnOption1.setOnClickListener { checkAnswer(0) } binding.btnOption2.setOnClickListener { checkAnswer(1) } binding.btnOption3.setOnClickListener { checkAnswer(2) } binding.btnRestart.setOnClickListener { restartQuiz() } } private fun correctBtnColors(buttonIndex: Int) { when(buttonIndex){ 0 -> binding.btnOption1.setBackgroundColor(Color.GREEN) 1 -> binding.btnOption2.setBackgroundColor(Color.GREEN) 2 -> binding.btnOption3.setBackgroundColor(Color.GREEN) } } private fun wrongBtnColors(buttonIndex: Int) { when(buttonIndex){ 0 -> binding.btnOption1.setBackgroundColor(Color.RED) 1 -> binding.btnOption2.setBackgroundColor(Color.RED) 2 -> binding.btnOption3.setBackgroundColor(Color.RED) } } private fun resetBtnColors() { binding.btnOption1.setBackgroundColor(Color.rgb(50, 59, 96)) binding.btnOption2.setBackgroundColor(Color.rgb(50, 59, 96)) binding.btnOption3.setBackgroundColor(Color.rgb(50, 59, 96)) } private fun showResults() { Toast.makeText(this, "Your Score : $score out of ${question.size}", Toast.LENGTH_LONG).show() binding.tvScore.text = "Benar $score dari soal" binding.btnRestart.isEnabled = true } private fun displayQuestion() { binding.tvQuestion.text = question[currentQuestionIndex] binding.btnOption1.text = options[currentQuestionIndex][0] binding.btnOption2.text = options[currentQuestionIndex][1] binding.btnOption3.text = options[currentQuestionIndex][2] resetBtnColors() } private fun checkAnswer(selectedAnswerIndex: Int) { val correctAnswerIndex = correctAnswer[currentQuestionIndex] if (selectedAnswerIndex == correctAnswerIndex){ score++ correctBtnColors(selectedAnswerIndex) }else { wrongBtnColors(selectedAnswerIndex) correctBtnColors(correctAnswerIndex) } if (currentQuestionIndex < question.size - 1) { currentQuestionIndex++ binding.tvQuestion.postDelayed({displayQuestion()}, 1500) }else{ showResults() } } private fun restartQuiz(){ currentQuestionIndex = 0 score = 0 displayQuestion() binding.btnRestart.isEnabled = false } }
AutoGG-Reimagined/src/main/kotlin/com/qwertz/autogg_reimagined/config/AutoGGConfig.kt
313317492
package com.qwertz.autogg_reimagined.config import com.qwertz.autogg_reimagined.AutoGG import cc.polyfrost.oneconfig.config.Config import cc.polyfrost.oneconfig.config.annotations.Header import cc.polyfrost.oneconfig.config.annotations.Switch import cc.polyfrost.oneconfig.config.annotations.Text import cc.polyfrost.oneconfig.config.annotations.Slider import cc.polyfrost.oneconfig.config.data.Mod import cc.polyfrost.oneconfig.config.data.ModType import cc.polyfrost.oneconfig.config.data.OptionSize import scala.tools.cmd.Opt class AutoGGConfig : Config(Mod(AutoGG.NAME, ModType.UTIL_QOL, "/AutoGG.png"), AutoGG.MODID + ".json") { init { initialize() } @Header(text = "AutoGG", size = OptionSize.DUAL) var abc: Boolean = false @Text(name = "GG MESSAGE") var GGMessage: String = "GG" @Switch(name = "ENABLE SECOND MESSAGE") var GG2ndSwitch: Boolean = false @Text(name = "SECOND MESSAGE", size = OptionSize.DUAL) var GG2ndMessage: String = "AutoGG Reimagined by QWERTZ_EXE!" @Slider( name = "SECOND MESSAGE DELAY (IN SECONDS)", min = 0f, max = 5f ) var GG2ndDelay: Float = 1.0F @Text(name = "TRIGGERS (SEPERATE WITH ';')", size = OptionSize.DUAL, multiline = true) var GGTriggers: String = "WINNER;Winner;Blocks Placed;Blocks Broken" @Header(text = "AntiGG", size = OptionSize.DUAL) var abc2: Boolean = false @Switch( name = "HIDE GG MESSAGES" ) var AntiGGSwitch: Boolean = false @Switch( name = "NOTIFY ON HIDDEN MESSAGES" ) var NotifySwitch: Boolean = true @Text(name = "TRIGGERS (SEPERATE WITH ';')", size = OptionSize.DUAL, multiline = true) var AntiGGTriggers: String = "gg;GG;Good Game;Gg;gG;GoOd GaMe;gOoD GaMe" }
AutoGG-Reimagined/src/main/kotlin/com/qwertz/autogg_reimagined/command/AutoGGCommand.kt
1842553488
package com.qwertz.autogg_reimagined.command import cc.polyfrost.oneconfig.utils.commands.annotations.Command import com.qwertz.autogg_reimagined.AutoGG import net.minecraft.command.CommandBase import net.minecraft.command.ICommandSender import com.qwertz.autogg_reimagined.AutoGG.Companion.config import net.minecraft.client.Minecraft import net.minecraft.util.ChatComponentText val AGConfig = config // Check the value of the enable/disable option for the current mod class IsEnabled { fun EnabledCheck(): Boolean { if (AGConfig.enabled) { return true } else { return false } } } @Command(value = AutoGG.MODID, description = "Access the " + AutoGG.NAME + " Config") class AutoGGCommand : CommandBase() { override fun getCommandName() = "gg" override fun getCommandUsage(sender: ICommandSender) = "/gg" override fun processCommand(sender: ICommandSender, args: Array<String>) { // Ensure that this command is only executed on the client side if (IsEnabled().EnabledCheck()) { AGConfig.openGui() } else { Minecraft.getMinecraft().thePlayer.addChatMessage(ChatComponentText("§4[§6§lAUTOGG REIMAGINED§4]§a: The mod is disabled in OneConfig. Please enable it.")) }} // Make sure the command can be used by any player override fun canCommandSenderUseCommand(sender: ICommandSender) = true }
AutoGG-Reimagined/src/main/kotlin/com/qwertz/autogg_reimagined/AutoGG.kt
2263306072
package com.qwertz.autogg_reimagined import cc.polyfrost.oneconfig.utils.gui.GuiUtils import net.minecraftforge.fml.common.Mod import kotlinx.coroutines.* import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.client.ClientCommandHandler import net.minecraftforge.fml.common.event.FMLInitializationEvent import com.qwertz.autogg_reimagined.command.AutoGGCommand import net.minecraftforge.common.MinecraftForge import net.minecraft.client.Minecraft import com.qwertz.autogg_reimagined.AutoGG.Companion.config import com.qwertz.autogg_reimagined.command.IsEnabled import net.minecraft.util.ChatComponentText import kotlin.math.roundToLong @Mod(modid = AutoGG.MODID, name = AutoGG.NAME, version = AutoGG.VERSION) class AutoGG { // Register the config and commands. @Mod.EventHandler fun onInit(event: FMLInitializationEvent?) { config = com.qwertz.autogg_reimagined.config.AutoGGConfig() MinecraftForge.EVENT_BUS.register(CommandEventHandler()) ClientCommandHandler.instance.registerCommand(AutoGGCommand()) } companion object { const val MODID: String = "@ID@" const val NAME: String = "@NAME@" const val VERSION: String = "@VER@" @Mod.Instance(MODID) lateinit var INSTANCE: AutoGG lateinit var config: com.qwertz.autogg_reimagined.config.AutoGGConfig } } var ggSaid = false class CommandEventHandler { @SubscribeEvent fun onChatReceived(event: ClientChatReceivedEvent) { val message = event.message.unformattedText val triggers = config.GGTriggers.split(";") for (trigger in triggers) { if (trigger in message) { if (!ggSaid) { ggSaid = true val GGMessage = config.GGMessage if (IsEnabled().EnabledCheck()) { Minecraft.getMinecraft().thePlayer.sendChatMessage("/ac $GGMessage") if (config.GG2ndSwitch) { sendDelayedMsg() } } allowgg() } } } val triggers2 = config.AntiGGTriggers.split(";") for (trigger2 in triggers2) { if (event.message.unformattedText.contains(": $trigger2") && config.AntiGGSwitch) { // Cancel the event or manipulate the message to prevent it from being displayed event.isCanceled = true if (config.NotifySwitch) { Minecraft.getMinecraft().thePlayer.addChatMessage(ChatComponentText("§4[§6§lAUTOGG REIMAGINED§4]§a: GG message hidden")) } } } } @OptIn(DelicateCoroutinesApi::class) private fun sendDelayedMsg() { val time = (config.GG2ndDelay * 1000).roundToLong() GlobalScope.launch { delay(time) val GG2ndMessage = config.GG2ndMessage Minecraft.getMinecraft().thePlayer.sendChatMessage("/ac $GG2ndMessage") } } fun allowgg() { val time = 2000L GlobalScope.launch { delay(time) ggSaid = false } } }
PracticaRetrofit_JoseTrista/app/src/androidTest/java/trista/josecarlos/practicaretrofit_josetrista/ExampleInstrumentedTest.kt
2262253947
package trista.josecarlos.practicaretrofit_josetrista 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("trista.josecarlos.practicaretrofit_josetrista", appContext.packageName) } }
PracticaRetrofit_JoseTrista/app/src/test/java/trista/josecarlos/practicaretrofit_josetrista/ExampleUnitTest.kt
4255173126
package trista.josecarlos.practicaretrofit_josetrista 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) } }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/ui/theme/Color.kt
3875619331
package trista.josecarlos.practicaretrofit_josetrista.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)
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/ui/theme/Theme.kt
2359706902
package trista.josecarlos.practicaretrofit_josetrista.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 PracticaRetrofit_JoseTristaTheme( 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 ) }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/ui/theme/Type.kt
1481896924
package trista.josecarlos.practicaretrofit_josetrista.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 ) */ )
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/MainActivity.kt
1191619213
package trista.josecarlos.practicaretrofit_josetrista import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import coil.compose.AsyncImagePainter import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import coil.size.Size import trista.josecarlos.practicaretrofit_josetrista.Presentation.ProductsViewModel import trista.josecarlos.practicaretrofit_josetrista.data.ProductsRepositoryImpl import trista.josecarlos.practicaretrofit_josetrista.ui.theme.PracticaRetrofit_JoseTristaTheme import kotlinx.coroutines.flow.collectLatest import trista.josecarlos.practicaretrofit_josetrista.data.model.Products class MainActivity : ComponentActivity() { private val viewModel by viewModels<ProductsViewModel>(factoryProducer = { object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return ProductsViewModel(ProductsRepositoryImpl(RetrofitInstance.api)) as T } } }) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PracticaRetrofit_JoseTristaTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val productList = viewModel.products.collectAsState().value val context = LocalContext.current LaunchedEffect(key1 = viewModel.showErrorToastChannel) { viewModel.showErrorToastChannel.collectLatest { show -> if (show) { Toast.makeText( context, "Error", Toast.LENGTH_SHORT ).show() } } } if (productList.isEmpty()) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator() } } else { LazyColumn( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, contentPadding = PaddingValues(16.dp) ) { items(productList.size) { index -> Product(productList[index]) Spacer(modifier = Modifier.height(16.dp)) } } } } } } } } @Composable fun Product(product: Products) { val imageState = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current).data(product.thumbnail) .size(Size.ORIGINAL).build() ).state Column( modifier = Modifier .clip(RoundedCornerShape(20.dp)) .height(300.dp) .fillMaxWidth() .background(MaterialTheme.colorScheme.primaryContainer) ) { if (imageState is AsyncImagePainter.State.Error) { Box( modifier = Modifier .fillMaxWidth() .height(200.dp), contentAlignment = Alignment.Center ) { CircularProgressIndicator() } } if (imageState is AsyncImagePainter.State.Success) { Image( modifier = Modifier .fillMaxWidth() .height(200.dp), painter = imageState.painter, contentDescription = product.title, contentScale = ContentScale.Crop ) } Spacer(modifier = Modifier.height(6.dp)) Text( modifier = Modifier.padding(horizontal = 16.dp), text = "${product.title} -- Price: ${product.price}$", fontSize = 17.sp, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(6.dp)) Text( modifier = Modifier.padding(horizontal = 16.dp), text = product.description, fontSize = 13.sp, ) } }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/RetrofitInstance.kt
852675799
package trista.josecarlos.practicaretrofit_josetrista import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import trista.josecarlos.practicaretrofit_josetrista.data.Api object RetrofitInstance { private val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } private val client: OkHttpClient = OkHttpClient.Builder() .addInterceptor(interceptor) .build() val api: Api = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(Api.BASE_URL) .client(client) .build() .create(Api::class.java) }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/data/ProductsRepositoryImpl.kt
3826819258
package trista.josecarlos.practicaretrofit_josetrista.data import retrofit2.HttpException import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import trista.josecarlos.practicaretrofit_josetrista.data.model.Products import okio.IOException class ProductsRepositoryImpl (private val api: Api): ProductsRepository { override suspend fun getProductsList(): Flow<Result<List<Products>>> { return flow { val productsFromApi = try { api.getProductsList() } catch (e: IOException) { e.printStackTrace() emit(Result.Error(message = "Error loading products")) return@flow } catch (e: HttpException) { e.printStackTrace() emit(Result.Error(message = "Error loading products")) return@flow } catch (e: Exception) { e.printStackTrace() emit(Result.Error(message = "Error loading products")) return@flow } emit(Result.Success(productsFromApi.products)) } } }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/data/Api.kt
3783584449
package trista.josecarlos.practicaretrofit_josetrista.data import retrofit2.http.GET import trista.josecarlos.practicaretrofit_josetrista.data.model.Product interface Api { @GET("products") suspend fun getProductsList(): Product companion object { const val BASE_URL = "https://dummyjson.com/" } }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/data/Result.kt
1375004628
package trista.josecarlos.practicaretrofit_josetrista.data sealed class Result<T> ( val data: T? = null, val message: String? = null ){ class Success<T> (data: T?): Result<T>(data) class Error<T> (data: T? = null, message: String): Result<T>(data, message) }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/data/ProductsRepository.kt
1281103228
package trista.josecarlos.practicaretrofit_josetrista.data import kotlinx.coroutines.flow.Flow import trista.josecarlos.practicaretrofit_josetrista.data.model.Products interface ProductsRepository{ suspend fun getProductsList(): Flow<Result<List<Products>>> }
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/data/model/Product.kt
1125818283
package trista.josecarlos.practicaretrofit_josetrista.data.model data class Product( val limit: Int, val products: List<Products>, val skip: Int, val total: Int )
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/data/model/Products.kt
2347546365
package trista.josecarlos.practicaretrofit_josetrista.data.model data class Products( val brand: String, val category: String, val description: String, val discountPercentage: Double, val id: Int, val images: List<String>, val price: Int, val rating: Double, val stock: Int, val thumbnail: String, val title: String )
PracticaRetrofit_JoseTrista/app/src/main/java/trista/josecarlos/practicaretrofit_josetrista/Presentation/ProductsViewModel.kt
3079945086
package trista.josecarlos.practicaretrofit_josetrista.Presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import trista.josecarlos.practicaretrofit_josetrista.data.Result import trista.josecarlos.practicaretrofit_josetrista.data.ProductsRepository import trista.josecarlos.practicaretrofit_josetrista.data.model.Products class ProductsViewModel(private val productsRepository: ProductsRepository ) :ViewModel(){ private val _products = MutableStateFlow<List<Products>>(emptyList()) val products = _products.asStateFlow() private val _showErrorToastChannel = Channel<Boolean>() val showErrorToastChannel = _showErrorToastChannel.receiveAsFlow() init { viewModelScope.launch { productsRepository.getProductsList().collectLatest { result -> when(result) { is Result.Error -> { _showErrorToastChannel.send(true) } is Result.Success -> { result.data?.let { products -> _products.update { products } } } } } } } }
kmp-curso/site/src/commonMain/kotlin/org/example/blogmultiplatform/models/User.kt
2975320773
package org.example.blogmultiplatform.models expect class User { val id: String val username: String val password: String } expect class UserDTO { val id: String val username: String }
kmp-curso/site/src/jvmMain/kotlin/org/example/blogmultiplatform/utils/Constants.kt
2025570097
package org.example.blogmultiplatform.utils object Constants { const val DATABASE_NAME = "my_blog" }
kmp-curso/site/src/jvmMain/kotlin/org/example/blogmultiplatform/models/User.kt
347395832
package org.example.blogmultiplatform.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.litote.kmongo.id.ObjectIdGenerator @Serializable actual data class User( @SerialName(value = "_id") actual val id: String = ObjectIdGenerator.newObjectId<String>().id.toHexString(), actual val username: String = "", actual val password: String = "" ) @Serializable actual data class UserDTO( @SerialName(value = "_id") actual val id: String = ObjectIdGenerator.newObjectId<String>().id.toHexString(), actual val username: String = "" )
kmp-curso/site/src/jvmMain/kotlin/org/example/blogmultiplatform/api/UserCheck.kt
459881385
package org.example.blogmultiplatform.api import com.varabyte.kobweb.api.Api import com.varabyte.kobweb.api.ApiContext import com.varabyte.kobweb.api.data.getValue import com.varabyte.kobweb.api.http.setBodyText import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.example.blogmultiplatform.data.MongoDb import org.example.blogmultiplatform.models.User import org.example.blogmultiplatform.models.UserDTO import java.nio.charset.StandardCharsets import java.security.MessageDigest @Api(routeOverride = "usercheck") suspend fun userCheck(context: ApiContext) { try { val userRequest = context.req.body?.decodeToString()?.let { Json.decodeFromString<User>(it) } val user = userRequest?.let { context.data.getValue<MongoDb>().checkUserExistence( User(username = it.username, password = hashPassword(it.password)) ) } if (user != null) { context.res.setBodyText( Json.encodeToString(UserDTO(id = user.id, username = user.username)) ) } else { context.res.setBodyText(Json.encodeToString(Exception("User doesn't exist."))) } } catch (e: Exception) { context.res.setBodyText(Json.encodeToString(Exception(e.message))) } } private fun hashPassword(password: String): String { val messageDigest = MessageDigest.getInstance("SHA-256") val hashBytes = messageDigest.digest(password.toByteArray(StandardCharsets.UTF_8)) val hexString = StringBuffer() for (byte in hashBytes) { hexString.append(String.format("%02x", byte)) } return hexString.toString() }
kmp-curso/site/src/jvmMain/kotlin/org/example/blogmultiplatform/data/MongoRepository.kt
891051349
package org.example.blogmultiplatform.data import org.example.blogmultiplatform.models.User interface MongoRepository { suspend fun checkUserExistence(user: User): User? }
kmp-curso/site/src/jvmMain/kotlin/org/example/blogmultiplatform/data/MongoDb.kt
1643861944
package org.example.blogmultiplatform.data import com.varabyte.kobweb.api.data.add import com.varabyte.kobweb.api.init.InitApi import com.varabyte.kobweb.api.init.InitApiContext import kotlinx.coroutines.reactive.awaitFirst import org.example.blogmultiplatform.models.User import org.example.blogmultiplatform.utils.Constants import org.litote.kmongo.and import org.litote.kmongo.eq import org.litote.kmongo.reactivestreams.KMongo import org.litote.kmongo.reactivestreams.getCollection @InitApi fun initMongoDb(context: InitApiContext) { System.setProperty( "org.litote.mongo.test.mapping.service", "org.litote.kmongo.serialization.SerializationClassMappingTypeService" ) context.data.add(MongoDb(context)) } class MongoDb(private val context: InitApiContext) : MongoRepository { private val client = KMongo.createClient() private val database = client.getDatabase(Constants.DATABASE_NAME) private val userCollection = database.getCollection<User>() override suspend fun checkUserExistence(user: User): User? { return try { userCollection.find( and( User::username eq user.username, User::password eq user.password ) ).awaitFirst() } catch (e: Exception) { context.logger.error(e.message.toString()) null } } }
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/util/Constants.kt
78178044
package org.example.blogmultiplatform.util object Constants { const val FONT_FAMILY = "Roboto" } object Res { object Image { const val logo = "/logo.svg" } }
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/models/Theme.kt
3543742340
package org.example.blogmultiplatform.models import org.jetbrains.compose.web.css.CSSColorValue import org.jetbrains.compose.web.css.rgb enum class Theme( val hex: String, val rgb: CSSColorValue ) { Primary( hex = "#00A2FF", rgb = rgb(r = 0, g = 162, b = 255) ), LightGray( hex = "#FAFAFA", rgb = rgb(r = 250, g = 250, b = 250) ) }
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/models/User.kt
1592731297
package org.example.blogmultiplatform.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable actual data class User( @SerialName(value = "_id") actual val id: String = "", actual val username: String = "", actual val password: String = "" ) @Serializable actual data class UserDTO( @SerialName(value = "_id") actual val id: String = "", actual val username: String = "" )
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/styles/LoginStyle.kt
1196083059
package org.example.blogmultiplatform.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.border import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.focus import org.example.blogmultiplatform.models.Theme import org.jetbrains.compose.web.css.LineStyle import org.jetbrains.compose.web.css.ms import org.jetbrains.compose.web.css.px val LoginInputStyle by ComponentStyle { base { Modifier .border( width = 2.px, style = LineStyle.Solid, color = Colors.Transparent ) .transition(CSSTransition(property = "border", duration = 300.ms)) } focus { Modifier.border( width = 2.px, style = LineStyle.Solid, color = Theme.Primary.rgb ) } }
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/AppEntry.kt
3708939192
package org.example.blogmultiplatform import androidx.compose.runtime.* import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.core.App import com.varabyte.kobweb.silk.SilkApp import com.varabyte.kobweb.silk.components.layout.Surface import com.varabyte.kobweb.silk.components.style.common.SmoothColorStyle import com.varabyte.kobweb.silk.components.style.toModifier import org.jetbrains.compose.web.css.* @App @Composable fun AppEntry(content: @Composable () -> Unit) { SilkApp { Surface(SmoothColorStyle.toModifier().minHeight(100.vh)) { content() } } }
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/pages/admin/Login.kt
3713757234
package org.example.blogmultiplatform.pages.admin import androidx.compose.runtime.* import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.css.TextAlign import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.core.Page import com.varabyte.kobweb.silk.components.graphics.Image import com.varabyte.kobweb.silk.components.style.toModifier import com.varabyte.kobweb.silk.components.text.SpanText import org.example.blogmultiplatform.models.Theme import org.example.blogmultiplatform.styles.LoginInputStyle import org.example.blogmultiplatform.util.Constants import org.example.blogmultiplatform.util.Res import org.jetbrains.compose.web.attributes.InputType import org.jetbrains.compose.web.css.LineStyle import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.Button import org.jetbrains.compose.web.dom.Input @Page @Composable fun LoginScreen() { var errorText by remember { mutableStateOf("") } Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Column( modifier = Modifier .padding(leftRight = 50.px, top = 80.px, bottom = 24.px) .background(Theme.LightGray.rgb), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( modifier = Modifier .width(100.px) .margin(bottom = 50.px), src = Res.Image.logo, description = "Logo Image" ) Input( type = InputType.Text, attrs = LoginInputStyle.toModifier() .margin(bottom = 12.px) .width(350.px) .height(54.px) .padding(leftRight = 20.px) .backgroundColor(Colors.White) .fontFamily(Constants.FONT_FAMILY) .fontSize(14.px) .outline( width = 0.px, style = LineStyle.None, color = Colors.Transparent ) .toAttrs { attr("placeholder", "Username") } ) Input( type = InputType.Password, attrs = LoginInputStyle.toModifier() .margin(bottom = 20.px) .width(350.px) .height(54.px) .padding(leftRight = 20.px) .backgroundColor(Colors.White) .fontFamily(Constants.FONT_FAMILY) .fontSize(14.px) .outline( width = 0.px, style = LineStyle.None, color = Colors.Transparent ) .toAttrs { attr("placeholder", "Password") } ) Button( attrs = Modifier .margin(bottom = 24.px) .width(350.px) .height(54.px) .backgroundColor(Theme.Primary.rgb) .color(Colors.White) .fontFamily(Constants.FONT_FAMILY) .fontWeight(FontWeight.Medium) .fontSize(14.px) .border( width = 0.px, style = LineStyle.None, color = Colors.Transparent ) .borderRadius(r = 4.px) .outline( width = 0.px, style = LineStyle.None, color = Colors.Transparent ) .toAttrs() ) { SpanText(text = "Sign In") } SpanText( modifier =Modifier .width(350.px) .color(Colors.Red) .textAlign(TextAlign.Center), text = errorText ) } } }
kmp-curso/site/src/jsMain/kotlin/org/example/blogmultiplatform/pages/Index.kt
1841949229
package org.example.blogmultiplatform.pages import androidx.compose.runtime.* import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.fillMaxSize import com.varabyte.kobweb.core.Page import org.jetbrains.compose.web.dom.Text import com.varabyte.kobweb.worker.rememberWorker import org.example.blogmultiplatform.worker.EchoWorker @Page @Composable fun HomePage() { val worker = rememberWorker { EchoWorker { output -> console.log("Echoed: $output") } } LaunchedEffect(Unit) { worker.postInput("Hello, worker!") } // TODO: Replace the following with your own content Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text("THIS PAGE INTENTIONALLY LEFT BLANK") } }
kmp-curso/worker/src/jsMain/kotlin/org/example/blogmultiplatform/worker/EchoWorkerFactory.kt
1841511232
package org.example.blogmultiplatform.worker import com.varabyte.kobweb.worker.WorkerFactory import com.varabyte.kobweb.worker.WorkerStrategy import com.varabyte.kobweb.worker.createPassThroughSerializer // TODO: Worker checklist // - Review https://github.com/varabyte/kobweb#worker // - Rename this class to a more appropriate worker for your project // - Choose appropriate input/output generic types for WorkerFactory<I, O> // - Consider using Kotlinx serialization for rich I/O types // - Write strategy implementation logic // - Update IO serialization override if I/O types changed // - Delete this checklist! internal class EchoWorkerFactory : WorkerFactory<String, String> { override fun createStrategy(postOutput: (String) -> Unit) = WorkerStrategy<String> { input -> postOutput(input) // Add real worker logic here } override fun createIOSerializer() = createPassThroughSerializer() }
second-exam/problme6.kt
4179804939
import java.util.Scanner fun main(args: Array<String>) { var reader = Scanner(System.`in`) var num1: Int = reader.nextInt() var n = 5 var fact = 1 for (i in 1..n) { fact *= i } println("${fact}") }
second-exam/Main.kt
3350697704
fun main(args: Array<String>) { println("Hello World!") // Try adding program arguments via Run/Debug configuration. // Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html. println("Program arguments: ${args.joinToString()}") }
second-exam/bonusproblem.kt
1881424584
fun main (args:Array<String>) { //Fahim var num1:Int = 2 var num2:Int = 3 var num3:Int = 5 var num4:Int = 4 var num5:Int = 10 //1. addition var add = num1+num2 println("${add}") //2. subtraction var sub = num3-num1 println("${sub}") //3. multiplication var multi = num4*num1 println("${multi}") //4. divison var div = num5/num1 println("${div}") }
second-exam/problem4.kt
3902380846
import java.util.Scanner fun main(args: Array<String>) { var reader = Scanner(System.`in`) var mark: Int = reader.nextInt() if (mark < 90 - 100) { println("A") } else if (mark > 80 - 89) { println("B") } else if (mark < 70 - 79) { println("C") } else if (mark < 60 - 69) { println("D") } else { println("FAIL") } }