content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.aditya.mrapi
import retrofit2.Call
import retrofit2.http.GET
interface myInterface {
@GET("products")
fun getProductData(): Call<myData>
} | Mr-Api/app/src/main/java/com/aditya/mrapi/myInterface.kt | 428881948 |
package com.cursokotlin.jetpackcomposeinstagram
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.cursokotlin.jetpackcomposeinstagram", appContext.packageName)
}
} | JetpackComposeInstagramHilt/app/src/androidTest/java/com/cursokotlin/jetpackcomposeinstagram/ExampleInstrumentedTest.kt | 3800962224 |
package com.cursokotlin.jetpackcomposeinstagram
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)
}
} | JetpackComposeInstagramHilt/app/src/test/java/com/cursokotlin/jetpackcomposeinstagram/ExampleUnitTest.kt | 3535305844 |
package com.cursokotlin.jetpackcomposeinstagram.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/ui/theme/Shape.kt | 2307325263 |
package com.cursokotlin.jetpackcomposeinstagram.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/ui/theme/Color.kt | 471585635 |
package com.cursokotlin.jetpackcomposeinstagram.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun JetpackComposeInstagramTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/ui/theme/Theme.kt | 187412064 |
package com.cursokotlin.jetpackcomposeinstagram.ui.theme
import androidx.compose.material.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(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/ui/theme/Type.kt | 2489482415 |
package com.cursokotlin.jetpackcomposeinstagram
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.cursokotlin.jetpackcomposeinstagram.login.ui.LoginScreen
import com.cursokotlin.jetpackcomposeinstagram.login.ui.LoginViewModel
import com.cursokotlin.jetpackcomposeinstagram.ui.theme.JetpackComposeInstagramTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val loginViewModel:LoginViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackComposeInstagramTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
LoginScreen(loginViewModel)
}
}
}
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
JetpackComposeInstagramTheme {
Greeting("Android")
}
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/MainActivity.kt | 594086983 |
package com.cursokotlin.jetpackcomposeinstagram.core.di
import com.cursokotlin.jetpackcomposeinstagram.login.data.network.LoginClient
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
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Singleton
@Provides
fun provideRetrofit():Retrofit{
return Retrofit.Builder()
.baseUrl("https://run.mocky.io/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Singleton
@Provides
fun provideLoginClient(retrofit: Retrofit):LoginClient{
return retrofit.create(LoginClient::class.java)
}
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/core/di/NetworkModule.kt | 2224160620 |
package com.cursokotlin.jetpackcomposeinstagram
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class JetpackComposeApp:Application() {
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/JetpackComposeApp.kt | 3423426110 |
package com.cursokotlin.jetpackcomposeinstagram.login.ui
import android.util.Log
import android.util.Patterns
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cursokotlin.jetpackcomposeinstagram.login.domain.LoginUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(private val loginUseCase: LoginUseCase):ViewModel() {
private val _email = MutableLiveData<String>()
val email : LiveData<String> = _email
private val _password = MutableLiveData<String>()
val password : LiveData<String> = _password
private val _isLoginEnable = MutableLiveData<Boolean>()
val isLoginEnable:LiveData<Boolean> = _isLoginEnable
private val _isLoading = MutableLiveData<Boolean>()
val isLoading:LiveData<Boolean> = _isLoading
fun onLoginChanged(email:String, password:String){
_email.value = email
_password.value = password
_isLoginEnable.value = enableLogin(email, password)
}
fun enableLogin(email: String, password: String) =
Patterns.EMAIL_ADDRESS.matcher(email).matches() && password.length > 6
fun onLoginSelected(){
viewModelScope.launch {
_isLoading.value = true
val result = loginUseCase(email.value!!, password.value!!)
if(result){
//Navegar a la siguiente pantalla
Log.i("aris", "result OK")
}
_isLoading.value = false
}
}
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/ui/LoginViewModel.kt | 1087343184 |
package com.cursokotlin.jetpackcomposeinstagram.login.ui
import android.app.Activity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cursokotlin.jetpackcomposeinstagram.R
@Composable
fun LoginScreen(loginViewModel: LoginViewModel) {
Box(
Modifier
.fillMaxSize()
.padding(8.dp)
) {
val isLoading: Boolean by loginViewModel.isLoading.observeAsState(initial = false)
if (isLoading) {
Box(
Modifier
.fillMaxSize()
.align(Alignment.Center)
) {
CircularProgressIndicator()
}
} else {
Header(Modifier.align(Alignment.TopEnd))
Body(Modifier.align(Alignment.Center), loginViewModel)
Footer(Modifier.align(Alignment.BottomCenter))
}
}
}
@Composable
fun Footer(modifier: Modifier) {
Column(modifier = modifier.fillMaxWidth()) {
Divider(
Modifier
.background(Color(0xFFF9F9F9))
.height(1.dp)
.fillMaxWidth()
)
Spacer(modifier = Modifier.size(24.dp))
SignUp()
Spacer(modifier = Modifier.size(24.dp))
}
}
@Composable
fun SignUp() {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
Text(
text = "Don't have an account?", fontSize = 12.sp, color = Color(0xFFB5B5B5)
)
Text(
text = "Sign up.",
Modifier.padding(horizontal = 8.dp),
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF4EA8E9),
)
}
}
@Composable
fun Body(modifier: Modifier, loginViewModel: LoginViewModel) {
val email: String by loginViewModel.email.observeAsState(initial = "")
val password: String by loginViewModel.password.observeAsState(initial = "")
val isLoginEnable: Boolean by loginViewModel.isLoginEnable.observeAsState(initial = false)
Column(modifier = modifier) {
ImageLogo(Modifier.align(Alignment.CenterHorizontally))
Spacer(modifier = Modifier.size(16.dp))
Email(email) {
loginViewModel.onLoginChanged(email = it, password = password)
}
Spacer(modifier = Modifier.size(4.dp))
Password(password) {
loginViewModel.onLoginChanged(email = email, password = it)
}
Spacer(modifier = Modifier.size(8.dp))
ForgotPassword(Modifier.align(Alignment.End))
Spacer(modifier = Modifier.size(16.dp))
LoginButton(isLoginEnable, loginViewModel)
Spacer(modifier = Modifier.size(16.dp))
LoginDivider()
Spacer(modifier = Modifier.size(32.dp))
SocialLogin()
}
}
@Composable
fun SocialLogin() {
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.drawable.fb),
contentDescription = "Social login fb",
modifier = Modifier.size(16.dp)
)
Text(
text = "Continue as Aris",
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp),
color = Color(0xFF4EA8E9)
)
}
}
@Composable
fun LoginDivider() {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Divider(
Modifier
.background(Color(0xFFF9F9F9))
.height(1.dp)
.weight(1f)
)
Text(
text = "OR",
modifier = Modifier.padding(horizontal = 18.dp),
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFFB5B5B5)
)
Divider(
Modifier
.background(Color(0xFFF9F9F9))
.height(1.dp)
.weight(1f)
)
}
}
@Composable
fun LoginButton(loginEnable: Boolean, loginViewModel: LoginViewModel) {
Button(
onClick = { loginViewModel.onLoginSelected() },
enabled = loginEnable,
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(
backgroundColor = Color(0xFF4EA8E9),
disabledBackgroundColor = Color(0xFF78C8F9),
contentColor = Color.White,
disabledContentColor = Color.White
)
) {
Text(text = "Log In")
}
}
@Composable
fun ForgotPassword(modifier: Modifier) {
Text(
text = "Forgot password?",
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF4EA8E9),
modifier = modifier
)
}
@Composable
fun Password(password: String, onTextChanged: (String) -> Unit) {
var passwordVisibility by remember { mutableStateOf(false) }
TextField(
value = password,
onValueChange = { onTextChanged(it) },
modifier = Modifier.fillMaxWidth(),
placeholder = { Text("Password") },
colors = TextFieldDefaults.textFieldColors(
textColor = Color(0xFFB2B2B2),
backgroundColor = Color(0xFFFAFAFA),
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
singleLine = true,
maxLines = 1,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailingIcon = {
val imagen = if (passwordVisibility) {
Icons.Filled.VisibilityOff
} else {
Icons.Filled.Visibility
}
IconButton(onClick = { passwordVisibility = !passwordVisibility }) {
Icon(imageVector = imagen, contentDescription = "show password")
}
},
visualTransformation = if (passwordVisibility) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
}
)
}
@Composable
fun Email(email: String, onTextChanged: (String) -> Unit) {
TextField(
value = email,
onValueChange = { onTextChanged(it) },
modifier = Modifier.fillMaxWidth(),
placeholder = { Text(text = "Email") },
maxLines = 1,
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
colors = TextFieldDefaults.textFieldColors(
textColor = Color(0xFFB2B2B2),
backgroundColor = Color(0xFFFAFAFA),
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
)
)
}
@Composable
fun ImageLogo(modifier: Modifier) {
Image(
painter = painterResource(id = R.drawable.insta),
contentDescription = "logo",
modifier = modifier
)
}
@Composable
fun Header(modifier: Modifier) {
val activity = LocalContext.current as Activity
Icon(
imageVector = Icons.Default.Close,
contentDescription = "close app",
modifier = modifier.clickable { activity.finish() })
}
| JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/ui/LoginScreen.kt | 1489622730 |
package com.cursokotlin.jetpackcomposeinstagram.login.data.network
import com.cursokotlin.jetpackcomposeinstagram.login.data.network.response.LoginResponse
import retrofit2.Response
import retrofit2.http.GET
interface LoginClient {
@GET("/v3/f78c9d33-28b1-4f81-9cf1-6d6ff78fa014")
suspend fun doLogin():Response<LoginResponse>
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/data/network/LoginClient.kt | 1664043712 |
package com.cursokotlin.jetpackcomposeinstagram.login.data.network.response
import com.google.gson.annotations.SerializedName
data class LoginResponse(@SerializedName("success") val success:Boolean) | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/data/network/response/LoginResponse.kt | 2545845589 |
package com.cursokotlin.jetpackcomposeinstagram.login.data.network
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import javax.inject.Inject
class LoginService @Inject constructor(private val loginClient: LoginClient){
// private val retrofit = RetrofitHelper.getRetrofit()
suspend fun doLogin(user:String, password:String):Boolean{
return withContext(Dispatchers.IO){
val response = loginClient.doLogin()
response.body()?.success ?: false
}
}
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/data/network/LoginService.kt | 2474409797 |
package com.cursokotlin.jetpackcomposeinstagram.login.data
import com.cursokotlin.jetpackcomposeinstagram.login.data.network.LoginService
import javax.inject.Inject
class LoginRepository @Inject constructor(private val api:LoginService){
suspend fun doLogin(user:String, password:String):Boolean{
return api.doLogin(user, password)
}
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/data/LoginRepository.kt | 1676987681 |
package com.cursokotlin.jetpackcomposeinstagram.login.domain
import com.cursokotlin.jetpackcomposeinstagram.login.data.LoginRepository
import javax.inject.Inject
class LoginUseCase @Inject constructor(private val repository: LoginRepository) {
suspend operator fun invoke(user:String, password:String):Boolean{
return repository.doLogin(user, password)
}
} | JetpackComposeInstagramHilt/app/src/main/java/com/cursokotlin/jetpackcomposeinstagram/login/domain/LoginUseCase.kt | 3929470814 |
package com.github.imerfanahmed.erumium
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.components.service
import com.intellij.psi.xml.XmlFile
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.PsiErrorElementUtil
import com.github.imerfanahmed.erumium.services.MyProjectService
@TestDataPath("\$CONTENT_ROOT/src/test/testData")
class MyPluginTest : BasePlatformTestCase() {
fun testXMLFile() {
val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "<foo>bar</foo>")
val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java)
assertFalse(PsiErrorElementUtil.hasErrors(project, xmlFile.virtualFile))
assertNotNull(xmlFile.rootTag)
xmlFile.rootTag?.let {
assertEquals("foo", it.name)
assertEquals("bar", it.value.text)
}
}
fun testRename() {
myFixture.testRename("foo.xml", "foo_after.xml", "a2")
}
fun testProjectService() {
val projectService = project.service<MyProjectService>()
assertNotSame(projectService.getRandomNumber(), projectService.getRandomNumber())
}
override fun getTestDataPath() = "src/test/testData/rename"
}
| erumium/src/test/kotlin/com/github/imerfanahmed/erumium/MyPluginTest.kt | 2694642110 |
package com.github.imerfanahmed.erumium.toolWindow
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.ui.content.ContentFactory
import com.github.imerfanahmed.erumium.MyBundle
import com.github.imerfanahmed.erumium.services.MyProjectService
import javax.swing.JButton
class MyToolWindowFactory : ToolWindowFactory {
init {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val myToolWindow = MyToolWindow(toolWindow)
val content = ContentFactory.getInstance().createContent(myToolWindow.getContent(), null, false)
toolWindow.contentManager.addContent(content)
}
override fun shouldBeAvailable(project: Project) = true
class MyToolWindow(toolWindow: ToolWindow) {
private val service = toolWindow.project.service<MyProjectService>()
fun getContent() = JBPanel<JBPanel<*>>().apply {
val label = JBLabel(MyBundle.message("randomLabel", "?"))
add(label)
add(JButton(MyBundle.message("shuffle")).apply {
addActionListener {
label.text = MyBundle.message("randomLabel", service.getRandomNumber())
}
})
}
}
}
| erumium/src/main/kotlin/com/github/imerfanahmed/erumium/toolWindow/MyToolWindowFactory.kt | 3027205340 |
package com.github.imerfanahmed.erumium
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.MyBundle"
object MyBundle : DynamicBundle(BUNDLE) {
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getMessage(key, *params)
@Suppress("unused")
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getLazyMessage(key, *params)
}
| erumium/src/main/kotlin/com/github/imerfanahmed/erumium/MyBundle.kt | 3103816990 |
package com.github.imerfanahmed.erumium.listeners
import com.intellij.openapi.application.ApplicationActivationListener
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.wm.IdeFrame
internal class MyApplicationActivationListener : ApplicationActivationListener {
override fun applicationActivated(ideFrame: IdeFrame) {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
}
| erumium/src/main/kotlin/com/github/imerfanahmed/erumium/listeners/MyApplicationActivationListener.kt | 934801017 |
package com.github.imerfanahmed.erumium.services
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.github.imerfanahmed.erumium.MyBundle
@Service(Service.Level.PROJECT)
class MyProjectService(project: Project) {
init {
thisLogger().info(MyBundle.message("projectService", project.name))
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
fun getRandomNumber() = (1..100).random()
}
| erumium/src/main/kotlin/com/github/imerfanahmed/erumium/services/MyProjectService.kt | 473602669 |
package fundamentos
//Variáveis com If/Else (validar)
fun main(args: Array<String>){
val num1: Int = 2
val num2: Int = 3
val maiorValor = if(num1 > num2){
println("Processando...")
num1
}
else{
println("Processando...")
num2
}
println("O maior valor é $maiorValor")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc11.kt | 4101313152 |
package fundamentos
fun main(args: Array<String>){
var a: Int
var b = 2 //Tipo inferido
a = 10
print(a+b)
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc3.kt | 2481757286 |
package fundamentos
//Inline function
inline fun transacao(funcao: () -> Unit){
println("Abrindo transação...")
try{
funcao()
}
finally{
println("Fechando transação")
}
}
fun main(args: Array<String>){
transacao {
println("Executando SQL 1...")
println("Executando SQL 2...")
println("Executando SQL 3...")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc21.kt | 1669942892 |
package fundamentos
//Usando template String:
fun main(args: Array<String>){
val bomHumor = true
//"${if (bomHumor) "feliz" else "chateado"}" é um operador ternário, ele permite realizar uma operação condicional em uma única linha de código.
println("Hoje estou ${if (bomHumor) "feliz" else "chateado"}")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc7.kt | 1569465208 |
package fundamentos
//While
fun main(args: Array<String>){
var contador: Int = 1
while(contador <= 10){
println(contador)
contador++
}
}
| Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc15.kt | 1294463362 |
package fundamentos
//Break com label - matrix
// * Fun fact: é um ótimo jeito de mostrar a tabuada.
fun main(args: Array<String>){
loop@for (i in 1..15){
for(j in 1..15){
if (i == 2 && j == 9) break@loop
println("$i $j")
}
}
println("Fim!")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc20.kt | 2534980514 |
package fundamentos
//Usando template String:
fun main(args: Array<String>){
val aprovados = listOf("João", "Maria", "Pedro")
// "${aprovados[0]} é uma interpolação de string, ou seja, ela permite que variáveis sejam inseridas dentro de strings.
print("O primeiro colocado foi ${aprovados[0]}")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc6.kt | 3105447621 |
package fundamentos
//While
fun main(args: Array<String>){
var opcao: Int = 0
while(opcao != -1) {
val line = readLine() ?: "0"
opcao = line.toIntOrNull() ?: 0
println("Você escolheu a opção $opcao")
}
println("Até a próxima!")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc14.kt | 579526918 |
package fundamentos
//Utlizando If/Else
fun main(args: Array<String>){
val nota: Double = 6.9
if(nota >= 7.0){
println("Aprovado!!")
}
else{
println("Reprovado!")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc10.kt | 3525419030 |
package fundamentos
//Função
fun main() {
val name = "Kotlin"
println("Hello, " + name + "!")
for(i in 1..5){
println("i = $i")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc2.kt | 537012210 |
package fundamentos
//Utlizando a estrutura If
fun main(args: Array<String>){
val nota: Double = 8.3
if(nota >= 7.0){
println("Aprovado")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc9.kt | 2100588367 |
package fundamentos
//Notação ponto
fun main(args: Array<String>){
var a: Int = 33.dec()
var b: String = a.toString()
println("Int: $a")
println("Primeiro char da string b é: ${b.first()}")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc8.kt | 3118769200 |
package fundamentos
// Break
fun main(args: Array<String>){
for(i in 1..10){
if(i == 5){
break
}
println("Atual: $i")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc19.kt | 3135757021 |
package fundamentos
//Acesso ao índice
fun main(args: Array<String>){
val alunos = arrayListOf("André", "Carla", "Marcos")
for((indice, aluno) in alunos.withIndex()){
println("$indice - $aluno \n")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc18.kt | 3441263338 |
package fundamentos
//Duas funções
fun main(args: Array<String>){
print("O menor valor é ${min(3, 4)}")
}
fun min(a: Int, b: Int): Int{
return if (a < b) a else b
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc23.kt | 3874155154 |
package fundamentos
//Função com retorno:
fun main(args: Array<String>){
println(soma(2, 3))
println(soma(11))
}
fun soma(a: Int, b: Int = 1): Int{
return a + b
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc5.kt | 2540077653 |
package fundamentos
//Intervalo fixo (com passo)
fun main(args: Array<String>){
for(i in 0..100 step 5){
println(i)
}
for (i in 100 downTo 0 step 5){
println(i)
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc17.kt | 3265029290 |
package fundamentos
//Refatorando para When
fun main(args: Array<String>){
val nota = 4
when(nota){
10, 9 -> print("Fantástico")
8, 7 -> print("Parabéns")
6, 5, 4 -> print("Tem como recuperar")
in 3..0 -> print("Nota inválida")
else -> print("Nota inválida")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc13.kt | 1139732069 |
package fundamentos
fun main(args: Array<String>){
//Tipos numéricos inteiros
val num1: Byte = 127
val num2: Short = 32767
val num3: Int = 2_147_483_647
//Variável do tipo long; o valor máximo dessa variável foi atribuido a ela;
val num4: Long = 9_223_372_036_854_775_807
//Tipos numéricos reais
val num5: Float = 3.14F
val num6: Double = 3.14
//Tipo caractere
val char: Char = '?' //Outros exemplos... '1', 'g', ''
//Tipo boolean
val boolean: Boolean = true //ou false
println(listOf(num1, num2, num3, num4, num5, num6, char, boolean))
println(2 is Int)
println(2147483648 is Long)
println(1.0 is Double)
//A função "dec()" decrementa o valor de um número em uma unidade, ou seja, a função "println()" imprimirá o valor 9
println(10.dec())
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc1.kt | 674727696 |
package fundamentos
//If/Else If/Else
fun main(args: Array<String>){
val nota = 9
//Usando operador range
if(nota in 9..10){
println("Fantástico")
}
else if(nota in 7..8){
println("Parabéns")
}
else if(nota in 4..6){
println("Tem como recuperar")
}
else if(nota in 0..3){
println("Te vejo no próximo ano")
}
else{
println("Nota inválida")
}
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc12.kt | 3728761156 |
package fundamentos
//Inline function
inline fun <T> executarComLog(nomeFuncao: String, funcao: () -> T): T {
println("Entrando no método $nomeFuncao ...")
try{
return funcao()
}
finally{
println("Método $nomeFuncao finalizado...")
}
}
fun somar(a: Int, b: Int): Int{
return a + b
}
fun main(args: Array<String>){
val resultado = executarComLog("somar"){
somar(4, 5)
}
println(resultado)
}
| Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc22.kt | 2063007687 |
package fundamentos
//Função sem retorno (Mais ou Menos):
fun main(args: Array<String>){
imprimirSoma(4, 5)
}
fun imprimirSoma(a: Int, b: Int){
println(a + b)
} | Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc4.kt | 3353681814 |
package fundamentos
//Intervalo fixo (decrescente)
fun main(args: Array<String>){
for(i in 10 downTo 1){
println("i = $i")
}
}
| Aula_01-Lista_de_exercicios/src/main/kotlin/fundamentos/Exerc16.kt | 3541027111 |
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()}")
} | Aula_01-Lista_de_exercicios/src/main/kotlin/Main.kt | 3350697704 |
package com.klc.calculator
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.klc.calculator", appContext.packageName)
}
} | KotlinCalc/app/src/androidTest/java/com/klc/calculator/ExampleInstrumentedTest.kt | 26005064 |
package com.klc.calculator
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)
}
} | KotlinCalc/app/src/test/java/com/klc/calculator/ExampleUnitTest.kt | 3079772775 |
package com.klc.calculator
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import net.objecthunter.exp4j.ExpressionBuilder
class MainActivity : AppCompatActivity() {
private lateinit var textViewCalculo: TextView
private lateinit var textViewResultado: TextView
private var isResultShown = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textViewCalculo = findViewById(R.id.calculo)
textViewResultado = findViewById(R.id.resultado)
configureButtonListeners()
}
private fun configureButtonListeners() {
val buttons = arrayOf(
R.id.zero, R.id.um, R.id.dois, R.id.tres, R.id.quatro,
R.id.cinco, R.id.seis, R.id.sete, R.id.oito, R.id.nove,
R.id.soma, R.id.subtracao, R.id.multiplicacao, R.id.divisao
)
for (buttonId in buttons) {
findViewById<Button>(buttonId).setOnClickListener { v ->
if (isResultShown) {
clearCalculation()
isResultShown = false
}
val buttonText = (v as Button).text
appendTextToCalculation(buttonText.toString())
}
}
findViewById<Button>(R.id.ce).setOnClickListener {
clearCalculation()
}
findViewById<Button>(R.id.igual).setOnClickListener {
calculateResult()
}
}
private fun appendTextToCalculation(text: String) {
val currentText = textViewCalculo.text.toString()
if (currentText == "0" || isResultShown) {
textViewCalculo.text = text
} else {
textViewCalculo.text = currentText + text
}
isResultShown = false
}
private fun clearCalculation() {
textViewCalculo.text = "0"
textViewResultado.text = ""
}
private fun calculateResult() {
val expression = textViewCalculo.text.toString()
try {
val result = ExpressionBuilder(expression).build().evaluate()
val formattedResult = formatResult(result)
textViewResultado.text = formattedResult
isResultShown = true
} catch (e: Exception) {
textViewResultado.text = "Erro"
e.printStackTrace()
}
}
private fun formatResult(result: Double): String {
return if (result.isNaN() || result.isInfinite()) {
"Erro"
} else {
val formattedResult = if (result.toLong().toDouble() == result) {
result.toLong().toString()
} else {
String.format("%.6f", result)
.replace("0*$".toRegex(), "")
.replace("\\.$".toRegex(), "")
}
formattedResult
}}
} | KotlinCalc/app/src/main/java/com/klc/calculator/MainActivity.kt | 2945072218 |
package com.example.diceroller
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* 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.diceroller", appContext.packageName)
}
}
| roll/app/src/androidTest/java/com/example/diceroller/ExampleInstrumentedTest.kt | 671749908 |
package com.example.diceroller
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)
}
} | roll/app/src/test/java/com/example/diceroller/ExampleUnitTest.kt | 1412805653 |
package com.example.diceroller
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.button)
//create a listener to listen to when the button is clicked and return result
rollButton.setOnClickListener { rollDice() }
}
private fun rollDice() {
// create new Dice object with 6 sides and roll it
val dice = Dice(6)
val diceRoll = dice.roll()
// Find the ImageView in the layout
val diceImage: ImageView = findViewById(R.id.imageView)
// calls the setImageResource to set a image
val drawableResource = when (diceRoll) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
// update the ImageView with the correct drawable resource ID
diceImage.setImageResource(drawableResource)
}
}
class Dice(private val numSides: Int) {
//Dice method to be used to randomly generate a number
fun roll(): Int {
return (1..numSides).random()
}
} | roll/app/src/main/java/com/example/diceroller/MainActivity.kt | 1671935107 |
package com.example.kotlin_spring
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class KotlinSpringApplicationTests {
@Test
fun contextLoads() {
}
}
| kotlin_spring/src/test/kotlin/com/example/kotlin_spring/KotlinSpringApplicationTests.kt | 3614581890 |
package com.example.kotlin_spring.core.exception.response
data class ErrorResponse (
val message: String,
val errorType: String = "Invalid Argument"
) | kotlin_spring/src/main/kotlin/com/example/kotlin_spring/core/response/ErrorResponse.kt | 4284757109 |
package com.example.kotlin_spring.core.annotation
import jakarta.validation.Constraint
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import jakarta.validation.Payload
import kotlin.reflect.KClass
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [ValidEnumValidator::class])
annotation class ValidEnum(
val message: String = "Invalid enum value",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
val enumClass: KClass<out Enum<*>>
)
class ValidEnumValidator : ConstraintValidator<ValidEnum, Any> {
private lateinit var enumValues: Array<out Enum<*>>
override fun initialize(annotation: ValidEnum) {
enumValues = annotation.enumClass.java.enumConstants
}
override fun isValid(value: Any?, context: ConstraintValidatorContext?): Boolean {
if (value == null) {
return true
}
return enumValues.any { it.name == value.toString() }
}
} | kotlin_spring/src/main/kotlin/com/example/kotlin_spring/core/annotation/ValidEnum.kt | 3471527803 |
package com.example.kotlin_spring.core.exception
import java.lang.RuntimeException
class InvalidInputException(
message: String = "Invalid Input"
) : RuntimeException(message)
| kotlin_spring/src/main/kotlin/com/example/kotlin_spring/core/exception/InvalidInputException.kt | 564974753 |
package com.example.kotlin_spring.core.exception
import com.example.kotlin_spring.core.exception.response.ErrorResponse
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
@RestControllerAdvice
class CustomExceptionHandler {
@ExceptionHandler(InvalidInputException::class)
fun invalidInputException(ex: InvalidInputException): ResponseEntity<ErrorResponse> {
val errors = ErrorResponse(ex.message ?: "Not Exception Message")
return ResponseEntity(errors, HttpStatus.BAD_REQUEST)
}
@ExceptionHandler(MethodArgumentNotValidException::class)
protected fun handleValidationExceptions(ex: MethodArgumentNotValidException): ResponseEntity<Map<String, String>> {
val errors = mutableMapOf<String, String>()
ex.bindingResult.allErrors.forEach { error ->
val fieldName = (error as FieldError).field
val errorMessage = error.getDefaultMessage()
errors[fieldName] = errorMessage ?: "NULL"
}
return ResponseEntity(errors, HttpStatus.BAD_REQUEST)
}
} | kotlin_spring/src/main/kotlin/com/example/kotlin_spring/core/exception/CustomExceptionHandler.kt | 1042211182 |
package com.example.kotlin_spring
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class KotlinSpringApplication
fun main(args: Array<String>) {
runApplication<KotlinSpringApplication>(*args)
}
| kotlin_spring/src/main/kotlin/com/example/kotlin_spring/KotlinSpringApplication.kt | 3426946082 |
package com.example.kotlin_spring.blog.dto
import com.example.kotlin_spring.core.annotation.ValidEnum
import com.fasterxml.jackson.annotation.JsonProperty
import jakarta.validation.constraints.Max
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
data class BlogDto(
@field:NotBlank(message = "query parameter required")
@JsonProperty("query")
private val _query: String?,
@field:NotBlank(message = "sort parameter required")
@field:ValidEnum(enumClass = EnumSort::class, message = "sort parameter one of ACCURACY and RECENCY")
val sort: String?,
@field:NotNull(message = "page parameter required")
@field:Max(50, message = "page is more than max")
@field:Min(1, message = "page is less than min")
val page: Int?,
@field:NotNull(message = "page parameter required")
val size: Int?
) {
val query: String
get() = _query!!
private enum class EnumSort {
ACCURACY,
RECENCY
}
}
| kotlin_spring/src/main/kotlin/com/example/kotlin_spring/blog/dto/BlogDto.kt | 1063305995 |
package com.example.kotlin_spring.blog.repository
import com.example.kotlin_spring.blog.entity.Wordcount
import org.springframework.data.repository.CrudRepository
interface WordRepository: CrudRepository<Wordcount, String>{
fun findTop10ByOrderByCntDesc(): List<Wordcount>
} | kotlin_spring/src/main/kotlin/com/example/kotlin_spring/blog/repository/repositories.kt | 3455230389 |
package com.example.kotlin_spring.blog.entity
import jakarta.persistence.Entity
import jakarta.persistence.Id
@Entity
class Wordcount(
@Id val word: String,
var cnt: Int = 0
)
| kotlin_spring/src/main/kotlin/com/example/kotlin_spring/blog/entity/Entities.kt | 2836639866 |
package com.example.kotlin_spring.blog.controller
import com.example.kotlin_spring.blog.dto.BlogDto
import com.example.kotlin_spring.blog.entity.Wordcount
import com.example.kotlin_spring.blog.service.BlogService
import jakarta.validation.Valid
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RequestMapping("/api/blog")
@RestController
class BlogController(
val blogService: BlogService
) {
@GetMapping("")
fun search(@RequestBody @Valid blogDto: BlogDto): String? {
val result = blogService.search(blogDto)
return result
}
@GetMapping("/rank")
fun searchWordRank(): List<Wordcount> = blogService.searchWordRank()
} | kotlin_spring/src/main/kotlin/com/example/kotlin_spring/blog/controller/BlogController.kt | 3312596804 |
package com.example.kotlin_spring.blog.service
import com.example.kotlin_spring.blog.dto.BlogDto
import com.example.kotlin_spring.blog.entity.Wordcount
import com.example.kotlin_spring.blog.repository.WordRepository
import org.springframework.stereotype.Service
@Service
class BlogService (
val wordRepository: WordRepository
){
fun search(blogDto: BlogDto): String? {
val lowQuery: String = blogDto.query.lowercase()
val word: Wordcount = wordRepository.findById(lowQuery).orElse(Wordcount(lowQuery))
word.cnt++
wordRepository.save(word)
println(blogDto.toString())
return "Search"
}
fun searchWordRank(): List<Wordcount> = wordRepository.findTop10ByOrderByCntDesc()
}
| kotlin_spring/src/main/kotlin/com/example/kotlin_spring/blog/service/BlogService.kt | 4155073492 |
package com.bytesbuilder.boostvideos
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.bytesbuilder.boostvideos", appContext.packageName)
}
} | Boost-Videos/app/src/androidTest/java/com/bytesbuilder/boostvideos/ExampleInstrumentedTest.kt | 2372041561 |
package com.bytesbuilder.boostvideos
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)
}
} | Boost-Videos/app/src/test/java/com/bytesbuilder/boostvideos/ExampleUnitTest.kt | 4208784798 |
package com.bytesbuilder.boostvideos
import android.animation.ObjectAnimator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.android.material.button.MaterialButton
class MainActivity : AppCompatActivity() {
private lateinit var googleSignInClient: GoogleSignInClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.textViewAnimated)
val animator = ObjectAnimator.ofFloat(textView, "alpha", 0f, 1f)
animator.duration = 2000 // Duración de la animación en milisegundos
animator.start()
// Configurar Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
// Botón de inicio de sesión con Google
val signInButton = findViewById<MaterialButton>(R.id.btn_google_signin)
signInButton.setOnClickListener {
signIn()
}
}
companion object {
private const val RC_SIGN_IN = 9001
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Resultado devuelto del lanzamiento del Intent desde GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
val account = completedTask.getResult(ApiException::class.java)
// Autenticación exitosa, actualiza la UI con la información del usuario
updateUI(account)
} catch (e: ApiException) {
// La autenticación falla, maneja el error
updateUI(null)
}
}
private fun updateUI(account: GoogleSignInAccount?) {
if (account != null) {
// Usuario autenticado, iniciar DashboardActivity
val dashboardIntent = Intent(this, DashboardActivity::class.java)
startActivity(dashboardIntent)
// Cierra MainActivity
finish()
} else {
// El usuario no está autenticado, manejar el estado de inicio de sesión fallido
}
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
}
| Boost-Videos/app/src/main/java/com/bytesbuilder/boostvideos/MainActivity.kt | 488326444 |
package com.bytesbuilder.boostvideos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class DashboardActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
}
}
| Boost-Videos/app/src/main/java/com/bytesbuilder/boostvideos/DashboardActivity.kt | 1724962429 |
package com.gugas
import com.gugas.event.EventProcessor
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.server.LocalServerPort
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatusCode
import org.springframework.web.client.HttpClientErrorException.BadRequest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
internal class ControllerTest {
@Autowired
private lateinit var restTemplateBuilder: RestTemplateBuilder
@LocalServerPort
var port = 0
val eventEndpoint by lazy { "http://localhost:$port/event" }
val statsEndpoint by lazy { "http://localhost:$port/stats" }
@BeforeEach
fun setUp() {
EventProcessor.data.clear()
}
@Test
fun `Should return zeros when no events`() {
val response = restTemplateBuilder.build()
.getForEntity("http://localhost:$port/stats", String::class.java)
val expectedBody = "0,0.0000000000,0.0000000000,0,0.0000000000"
Assertions.assertThat(response.statusCode).isEqualTo(HttpStatusCode.valueOf(200))
Assertions.assertThat(response.body).isEqualTo(expectedBody)
}
@Test
fun `Should accept valid data`() {
val request = "1007341341814,0.0442672968,1282509067"
val response = restTemplateBuilder.build().postForEntity(eventEndpoint, request, String::class.java)
Assertions.assertThat(response.statusCode).isEqualTo(HttpStatusCode.valueOf(202))
}
@Test
fun `Should throw exception if x out of range`() {
val request = "1007341341814,1.0442672968,1282509067"
assertThrows<BadRequest> {
restTemplateBuilder.build().postForEntity(eventEndpoint, request, String::class.java)
}
}
@Test
fun `Should throw exception if y out of range`() {
val request = "1007341341814,0.0442672968,12825090670000"
assertThrows<BadRequest> {
restTemplateBuilder.build().postForEntity(eventEndpoint, request, String::class.java)
}
}
@Test
fun `Should return valid stats`() {
val now = System.currentTimeMillis()
val input = listOf(
"${now + 1},0.0442672968,1282509067",
"${now + 2},0.0442672968,1282509067",
"${now + 3},0.0442672968,1282509067",
)
insertData(input)
val response = restTemplateBuilder.build().getForEntity(statsEndpoint, String::class.java)
val expectedBody = "3,0.1328018904,0.0442672968,3847527201,1282509067.0000000000"
Assertions.assertThat(response.statusCode).isEqualTo(HttpStatus.OK)
Assertions.assertThat(response.body).isEqualTo(expectedBody)
}
@Test
fun `Should return valid stats if we get data with the same timestamp`() {
val now = System.currentTimeMillis()
val input = listOf(
"${now},0.0442672968,1282509067",
"${now},0.0442672968,1282509067",
"${now},0.0442672968,1282509067",
)
insertData(input)
val response = restTemplateBuilder.build().getForEntity(statsEndpoint, String::class.java)
val expectedBody = "3,0.1328018904,0.0442672968,3847527201,1282509067.0000000000"
Assertions.assertThat(response.statusCode).isEqualTo(HttpStatus.OK)
Assertions.assertThat(response.body).isEqualTo(expectedBody)
}
private fun insertData(input: List<String>) {
input.forEach {
restTemplateBuilder.build().postForEntity(eventEndpoint, it, String::class.java)
}
}
} | calculate-statistics-service/src/test/kotlin/com/gugas/ControllerTest.kt | 678990031 |
package com.gugas
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class HelloFreshApplicationTests {
@Test
fun contextLoads() {
}
}
| calculate-statistics-service/src/test/kotlin/com/gugas/HelloFreshApplicationTests.kt | 1894803909 |
package com.gugas
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
@ControllerAdvice
class ApplicationExceptionHandler {
fun handleException(e: IllegalArgumentException): ResponseEntity<String> {
return ResponseEntity(e.message, HttpStatus.BAD_REQUEST)
}
} | calculate-statistics-service/src/main/kotlin/com/gugas/ApplicationExceptionHandler.kt | 1442820474 |
package com.gugas
import com.gugas.event.EventParser
import com.gugas.event.EventProcessor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
@RestController
class Controller {
@PostMapping("/event", consumes = ["text/csv", MediaType.TEXT_PLAIN_VALUE])
suspend fun saveEvent(
@RequestBody data: String
) = withContext(Dispatchers.IO) {
val response = async {
try {
val event = EventParser.parseCSV(data)
EventProcessor.save(System.currentTimeMillis(), event)
println("Saved event: $event")
ResponseEntity("Successfully saved the data", HttpStatusCode.valueOf(202))
} catch (e: Exception) {
println(e.message)
ResponseEntity(e.message, HttpStatus.BAD_REQUEST)
}
}
response.await()
}
@GetMapping(path = ["/stats"])
suspend fun getStats() = withContext(Dispatchers.IO) {
val stats = async {
try {
val result = EventProcessor.stats(System.currentTimeMillis()).formatToString()
ResponseEntity(result, HttpStatus.OK)
} catch (e: Exception) {
ResponseEntity(e.message, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
stats.await()
}
} | calculate-statistics-service/src/main/kotlin/com/gugas/Controller.kt | 4027124447 |
package com.gugas
class TimestampIllegalArgumentException(message: String) : IllegalArgumentException(message)
class XIllegalArgumentException(message: String) : IllegalArgumentException(message)
class YIllegalArgumentException(message: String) : IllegalArgumentException(message)
| calculate-statistics-service/src/main/kotlin/com/gugas/HelloFreshExceptions.kt | 1034858440 |
package com.gugas
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class HelloFreshApplication
fun main(args: Array<String>) {
runApplication<HelloFreshApplication>(*args)
}
| calculate-statistics-service/src/main/kotlin/com/gugas/HelloFreshApplication.kt | 2786968999 |
package com.gugas.event
import java.math.BigInteger
import java.util.concurrent.ConcurrentHashMap
data class StatsResponse(
val num: Int = 0,
val xSum: Double = 0.0,
val xAvg: Double = 0.0,
val ySum: BigInteger = BigInteger.ZERO,
val yAvg: Double = 0.0,
) {
fun formatToString(): String {
return "$num,${formatDouble(xSum)},${formatDouble(xAvg)},$ySum,${formatDouble(yAvg)}"
}
private fun formatDouble(value: Double): String {
return String.format("%.10f", value)
}
}
object EventProcessor {
private const val LIVE_MILLISECONDS = 60 * 1000
internal val data = ConcurrentHashMap<Long, EventAgg>()
fun save(currentTimeMillis: Long, event: Event) {
if (currentTimeMillis - event.timestamp < LIVE_MILLISECONDS) {
saveValue(currentTimeMillis, Event(event.timestamp, event.x, event.y))
}
}
fun stats(currentTimeMillis: Long): StatsResponse {
var num = 0
var xSum = 0.0
var ySum: BigInteger = BigInteger.ZERO
cleanOldValues(currentTimeMillis)
data.forEach {
num += it.value.num
xSum += it.value.xSum
ySum += BigInteger.valueOf(it.value.ySum.toLong())
}
if (num == 0) {
return StatsResponse()
}
return StatsResponse(
num,
xSum,
xSum / num,
ySum,
ySum.toDouble() / num
)
}
private fun saveValue(currentTimeMillis: Long, event: Event) {
cleanOldValues(currentTimeMillis)
val eventAgg = data.getOrDefault(event.timestamp, null)
data[event.timestamp] = EventAgg(
(eventAgg?.xSum ?: 0.0).plus(event.x),
(eventAgg?.ySum ?: BigInteger.ZERO).plus(event.y.toBigInteger()),
(eventAgg?.num ?: 0) + 1
)
}
private fun cleanOldValues(currentTimeMillis: Long) {
val minAcceptableTimestamp = currentTimeMillis - LIVE_MILLISECONDS
data.keys.removeIf { it < minAcceptableTimestamp }
}
} | calculate-statistics-service/src/main/kotlin/com/gugas/event/EventProcessor.kt | 674165978 |
package com.gugas.event
import com.gugas.XIllegalArgumentException
import java.math.BigInteger
class Event(
val timestamp: Long,
val x: Float,
val y: Int
) {
//𝑥: A real number with a fractional part of up to 10 digits, always in 0..1.
private val xRange = 0.0..1.0
//𝑦: An integer in 1,073,741,823..2,147,483,647.
private val yRange = Integer.valueOf(1_073_741_823)..Integer.valueOf(2_147_483_647)
init {
require(x in xRange) { XIllegalArgumentException("X must be in 0..1, but received $x") }
require(y in yRange) { XIllegalArgumentException("Y must be in 1,073,741,823..2,147,483,647, but received $y") }
}
}
data class EventAgg(
val xSum: Double,
val ySum: BigInteger,
val num: Int
) | calculate-statistics-service/src/main/kotlin/com/gugas/event/Event.kt | 3533292735 |
package com.gugas.event
import com.gugas.TimestampIllegalArgumentException
import com.gugas.XIllegalArgumentException
import com.gugas.YIllegalArgumentException
object EventParser {
fun parseCSV(data: String): Event {
val params = data.split(",")
val timestamp = params[0].toLongOrNull()
?: throw TimestampIllegalArgumentException(
"Timestamp must be a Unix timestamp in millisecond resolution, but received ${params[0]}"
)
val x = params[1].toFloatOrNull()
?: throw XIllegalArgumentException("Couldn't parse x, received: ${params[1]}")
val y = params[2].toIntOrNull()
?: throw YIllegalArgumentException("Couldn't parse y, received ${params[2]}")
return Event(timestamp, x, y)
}
} | calculate-statistics-service/src/main/kotlin/com/gugas/event/EventParser.kt | 469966299 |
package com.example.assignment1
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.assignment1", appContext.packageName)
}
} | MAD-Lab-1/app/src/androidTest/java/com/example/assignment1/ExampleInstrumentedTest.kt | 1807440260 |
package com.example.assignment1
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)
}
} | MAD-Lab-1/app/src/test/java/com/example/assignment1/ExampleUnitTest.kt | 786327860 |
package com.example.assignment1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlin.random.Random
var randomInt = Random.nextInt(0,100)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myButton: Button = findViewById(R.id.button)
myButton.setOnClickListener {
// Code to be executed when the button is clicked
Validate()
}
}
fun Validate(){
val inputText : EditText = findViewById(R.id.Text)
val editText =findViewById<TextView>(R.id.TextVeiw)
val input= Integer.parseInt(inputText.text.toString())
if (input > randomInt){
editText.text="your guess i Too HIgh $randomInt"
}
else if (input < randomInt)
editText.text="your guess i Low $randomInt"
else{
editText.text="ohh Hurrah U guessed it correctly Now Number is Changed"
randomInt = Random.nextInt()
}
}
}
| MAD-Lab-1/app/src/main/java/com/example/assignment1/MainActivity.kt | 13520486 |
package com.gapiapja
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.*
import com.lagradost.cloudstream3.LoadResponse.Companion.addAniListId
import com.lagradost.cloudstream3.LoadResponse.Companion.addMalId
import com.lagradost.cloudstream3.extractors.JWPlayer
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.Qualities
import com.lagradost.cloudstream3.utils.loadExtractor
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
class OtakudesuProvider : MainAPI() {
override var mainUrl = "https://otakudesu.cloud"
override var name = "Otakudesu Fixed"
override val hasMainPage = true
override var lang = "id"
override val hasDownloadSupport = true
override val supportedTypes = setOf(
TvType.Anime,
TvType.AnimeMovie,
TvType.OVA
)
companion object {
const val acefile = "https://acefile.co"
val mirrorBlackList = arrayOf(
"Mega",
"MegaUp",
"Otakufiles",
)
fun getType(t: String): TvType {
return if (t.contains("OVA", true) || t.contains("Special")) TvType.OVA
else if (t.contains("Movie", true)) TvType.AnimeMovie
else TvType.Anime
}
fun getStatus(t: String): ShowStatus {
return when (t) {
"Completed" -> ShowStatus.Completed
"Ongoing" -> ShowStatus.Ongoing
else -> ShowStatus.Completed
}
}
}
override val mainPage = mainPageOf(
"$mainUrl/ongoing-anime/page/" to "Anime Ongoing",
"$mainUrl/complete-anime/page/" to "Anime Completed"
)
override suspend fun getMainPage(
page: Int,
request: MainPageRequest
): HomePageResponse {
val document = app.get(request.data + page).document
val home = document.select("div.venz > ul > li").mapNotNull {
it.toSearchResult()
}
return newHomePageResponse(request.name, home)
}
private fun Element.toSearchResult(): AnimeSearchResponse? {
val title = this.selectFirst("h2.jdlflm")?.text()?.trim() ?: return null
val href = this.selectFirst("a")!!.attr("href")
val posterUrl = this.select("div.thumbz > img").attr("src").toString()
val epNum = this.selectFirst("div.epz")?.ownText()?.replace(Regex("\\D"), "")?.trim()
?.toIntOrNull()
return newAnimeSearchResponse(title, href, TvType.Anime) {
this.posterUrl = posterUrl
addSub(epNum)
}
}
override suspend fun search(query: String): List<SearchResponse> {
return app.get("$mainUrl/?s=$query&post_type=anime").document.select("ul.chivsrc > li")
.map {
val title = it.selectFirst("h2 > a")!!.ownText().trim()
val href = it.selectFirst("h2 > a")!!.attr("href")
val posterUrl = it.selectFirst("img")!!.attr("src").toString()
newAnimeSearchResponse(title, href, TvType.Anime) {
this.posterUrl = posterUrl
}
}
}
override suspend fun load(url: String): LoadResponse {
val document = app.get(url).document
val title = document.selectFirst("div.infozingle > p:nth-child(1) > span")?.ownText()
?.replace(":", "")?.trim().toString()
val poster = document.selectFirst("div.fotoanime > img")?.attr("src")
val tags = document.select("div.infozingle > p:nth-child(11) > span > a").map { it.text() }
val type = getType(document.selectFirst("div.infozingle > p:nth-child(5) > span")?.ownText()
?.replace(":", "")?.trim() ?: "tv")
val year = Regex("\\d, (\\d*)").find(
document.select("div.infozingle > p:nth-child(9) > span").text()
)?.groupValues?.get(1)?.toIntOrNull()
val status = getStatus(
document.selectFirst("div.infozingle > p:nth-child(6) > span")!!.ownText()
.replace(":", "")
.trim()
)
val description = document.select("div.sinopc > p").text()
val episodes = document.select("div.episodelist")[1].select("ul > li").mapNotNull {
val name = it.selectFirst("a")?.text() ?: return@mapNotNull null
val episode = Regex("Episode\\s?(\\d+)").find(name)?.groupValues?.getOrNull(0)
?: it.selectFirst("a")?.text()
val link = fixUrl(it.selectFirst("a")!!.attr("href"))
Episode(link, episode = episode?.toIntOrNull())
}.reversed()
val recommendations =
document.select("div.isi-recommend-anime-series > div.isi-konten").map {
val recName = it.selectFirst("span.judul-anime > a")!!.text()
val recHref = it.selectFirst("a")!!.attr("href")
val recPosterUrl = it.selectFirst("a > img")?.attr("src").toString()
newAnimeSearchResponse(recName, recHref, TvType.Anime) {
this.posterUrl = recPosterUrl
}
}
val tracker = APIHolder.getTracker(listOf(title),TrackerType.getTypes(type),year,true)
return newAnimeLoadResponse(title, url, type) {
engName = title
posterUrl = tracker?.image ?: poster
backgroundPosterUrl = tracker?.cover
this.year = year
addEpisodes(DubStatus.Subbed, episodes)
showStatus = status
plot = description
this.tags = tags
this.recommendations = recommendations
addMalId(tracker?.malId)
addAniListId(tracker?.aniId?.toIntOrNull())
}
}
data class ResponseSources(
@JsonProperty("id") val id: String,
@JsonProperty("i") val i: String,
@JsonProperty("q") val q: String,
)
data class ResponseData(
@JsonProperty("data") val data: String
)
override suspend fun loadLinks(
data: String,
isCasting: Boolean,
subtitleCallback: (SubtitleFile) -> Unit,
callback: (ExtractorLink) -> Unit
): Boolean {
val document = app.get(data).document
argamap(
{
val scriptData =
document.select("script:containsData(action:)").lastOrNull()?.data()
val token =
scriptData?.substringAfter("{action:\"")?.substringBefore("\"}").toString()
val nonce =
app.post("$mainUrl/wp-admin/admin-ajax.php", data = mapOf("action" to token))
.parsed<ResponseData>().data
val action =
scriptData?.substringAfter(",action:\"")?.substringBefore("\"}").toString()
val mirrorData = document.select("div.mirrorstream > ul > li").mapNotNull {
base64Decode(it.select("a").attr("data-content"))
}.toString()
tryParseJson<List<ResponseSources>>(mirrorData)?.apmap { res ->
val id = res.id
val i = res.i
val q = res.q
val sources = Jsoup.parse(
base64Decode(
app.post(
"${mainUrl}/wp-admin/admin-ajax.php", data = mapOf(
"id" to id,
"i" to i,
"q" to q,
"nonce" to nonce,
"action" to action
)
).parsed<ResponseData>().data
)
).select("iframe").attr("src")
loadCustomExtractor(sources, data, subtitleCallback, callback, getQuality(q))
}
},
{
document.select("div.download li").map { ele ->
val quality = getQuality(ele.select("strong").text())
ele.select("a").map {
it.attr("href") to it.text()
}.filter {
!inBlacklist(it.first) && quality != Qualities.P360.value
}.apmap {
val link = app.get(it.first, referer = "$mainUrl/").url
loadCustomExtractor(
fixedIframe(link),
data,
subtitleCallback,
callback,
quality
)
}
}
}
)
return true
}
private suspend fun loadCustomExtractor(
url: String,
referer: String? = null,
subtitleCallback: (SubtitleFile) -> Unit,
callback: (ExtractorLink) -> Unit,
quality: Int = Qualities.Unknown.value,
) {
loadExtractor(url, referer, subtitleCallback) { link ->
callback.invoke(
ExtractorLink(
link.name,
link.name,
link.url,
link.referer,
quality,
link.type,
link.headers,
link.extractorData
)
)
}
}
private fun fixedIframe(url: String): String {
return when {
url.startsWith(acefile) -> {
val id = Regex("""(?:/f/|/file/)(\w+)""").find(url)?.groupValues?.getOrNull(1)
"${acefile}/player/$id"
}
else -> fixUrl(url)
}
}
private fun inBlacklist(host: String?): Boolean {
return mirrorBlackList.any { it.equals(host, true) }
}
private fun getQuality(str: String?): Int {
return Regex("(\\d{3,4})[pP]").find(str ?: "")?.groupValues?.getOrNull(1)?.toIntOrNull()
?: Qualities.Unknown.value
}
}
class Moedesu : JWPlayer() {
override val name = "Moedesu"
override val mainUrl = "https://desustream.me/moedesu/"
}
class DesuBeta : JWPlayer() {
override val name = "DesuBeta"
override val mainUrl = "https://desustream.me/beta/"
}
class Desudesuhd : JWPlayer() {
override val name = "Desudesuhd"
override val mainUrl = "https://desustream.me/desudesuhd/"
}
| cloudstreams/OtakudesuProvider/src/main/kotlin/com/gapiapja/OtakudesuProvider.kt | 2172319725 |
package com.gapiapja
import com.lagradost.cloudstream3.plugins.CloudstreamPlugin
import com.lagradost.cloudstream3.plugins.Plugin
import android.content.Context
@CloudstreamPlugin
class OtakudesuProviderPlugin: Plugin() {
override fun load(context: Context) {
// All providers should be added in this manner. Please don't edit the providers list directly.
registerMainAPI(OtakudesuProvider())
registerExtractorAPI(Moedesu())
registerExtractorAPI(DesuBeta())
registerExtractorAPI(Desudesuhd())
}
}
| cloudstreams/OtakudesuProvider/src/main/kotlin/com/gapiapja/OtakudesuProviderPlugin.kt | 2395719705 |
package com.example.tpfinaldap
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.tpfinaldap", appContext.packageName)
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/androidTest/java/com/example/tpfinaldap/ExampleInstrumentedTest.kt | 2551209081 |
package com.example.tpfinaldap
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)
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/test/java/com/example/tpfinaldap/ExampleUnitTest.kt | 1881599792 |
package com.example.tpfinaldap.recycleviewclasses
data class SuperHero (
var superhero:String? = null ,
var realName:String? = null ,
var publisher:String? = null,
var photo:String? = null,
var description:String? = null,
var idSuperHero:String? = null,
) | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/recycleviewclasses/SuperHero.kt | 736030874 |
package com.example.tpfinaldap.recycleviewclasses
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.tpfinaldap.R
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class SuperHeroAdapter(
superHerolist: ArrayList<SuperHero>,
private val onDeleteClick : (Int)->Unit,
private val onEditClick : (Int) -> Unit,
private val onItemClick: (Int) -> Unit
): RecyclerView.Adapter<SuperHeroAdapter.SuperHeroViewHolder>(){
private var superHerolist: ArrayList<SuperHero>
init {
this.superHerolist =superHerolist
}
class SuperHeroViewHolder(view: View): RecyclerView.ViewHolder(view) {
val superHero= view.findViewById<TextView>(R.id.tvSuperheroName)
val realName= view.findViewById<TextView>(R.id.tvRealName)
val publisher= view.findViewById<TextView>(R.id.tvPublisher)
val photo = view.findViewById<ImageView>(R.id.ivSuperHero)
val editar = view.findViewById<Button>(R.id.botonEditar)
val eliminar = view.findViewById<Button>(R.id.botonEliminar)
fun render(superHeroModel: SuperHero){
superHero.text = superHeroModel.superhero
realName.text = superHeroModel.realName
publisher.text = superHeroModel.publisher
Glide.with(photo.context).load(superHeroModel.photo).into(photo)
/*photo.setOnClickListener{
Toast.makeText(photo.context, superHeroModel.realName, Toast.LENGTH_SHORT).show()
}*/
//itemView.setOnClickListener{ Toast.makeText(photo.context, superHeroModel.superhero, Toast.LENGTH_SHORT).show()}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SuperHeroViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return SuperHeroViewHolder(layoutInflater.inflate(R.layout.item_superhero, parent, false))
}
override fun onBindViewHolder(holder: SuperHeroViewHolder, position: Int) {
val item = superHerolist[position]
holder.render(item)
holder.eliminar.setOnClickListener {
onDeleteClick(position)
}
holder.editar.setOnClickListener {
onEditClick(position)
}
holder.itemView.setOnClickListener {
onItemClick(position)
}
holder.photo.setOnClickListener {
onItemClick(position)
}
}
override fun getItemCount(): Int = superHerolist.size
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/recycleviewclasses/SuperHeroAdapter.kt | 1359849801 |
package com.example.tpfinaldap.viewmodels
import androidx.lifecycle.ViewModel
class SubirSuperHeroViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/viewmodels/SubirSuperHeroViewModel.kt | 3146200315 |
package com.example.tpfinaldap.viewmodels
import androidx.lifecycle.ViewModel
class EditSuperHeroViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/viewmodels/EditSuperHeroViewModel.kt | 1402844860 |
package com.example.tpfinaldap.viewmodels
import androidx.lifecycle.ViewModel
class PantallaLoginViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/viewmodels/PantallaLoginViewModel.kt | 1237283206 |
package com.example.tpfinaldap.viewmodels
import androidx.lifecycle.ViewModel
class PantallaRegisterViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/viewmodels/PantallaRegisterViewModel.kt | 2151931888 |
package com.example.tpfinaldap.viewmodels
import androidx.lifecycle.ViewModel
class PantallaInicioViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/viewmodels/PantallaInicioViewModel.kt | 2270539897 |
package com.example.tpfinaldap.viewmodels
import androidx.lifecycle.ViewModel
class DataSuperHeroesViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/viewmodels/DataSuperHeroesViewModel.kt | 3252096289 |
package com.example.tpfinaldap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/MainActivity.kt | 3968572317 |
package com.example.tpfinaldap
import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.example.tpfinaldap.viewmodels.PantallaLoginViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class PantallaLogin : Fragment() {
private lateinit var viewModel: PantallaLoginViewModel
lateinit var botonLogin: Button
lateinit var botonRegistrar: Button
lateinit var mail: EditText
lateinit var pass: EditText
lateinit var textoMail: String
lateinit var textoPass: String
private lateinit var auth: FirebaseAuth
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_pantalla_login, container, false)
botonRegistrar = view.findViewById(R.id.buttonRegistrar)
botonLogin = view.findViewById(R.id.botonLogin)
mail = view.findViewById(R.id.textoUsuario)
pass = view.findViewById(R.id.textoContra)
auth = Firebase.auth
botonRegistrar.setOnClickListener {
findNavController().navigate(R.id.action_pantallaLogin_to_pantallaRegister)
}
botonLogin.setOnClickListener {
textoMail = mail.text.toString()
textoPass = pass.text.toString()
auth.signInWithEmailAndPassword(textoMail, textoPass).addOnCompleteListener { }
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(ContentValues.TAG, "signInWithEmail:success")
val user = auth.currentUser
findNavController().navigate(R.id.action_pantallaLogin_to_pantallaInicio)
} else {
Log.w(ContentValues.TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(context, "El mail y/o contraseña ingresados son incorrectos", Toast.LENGTH_SHORT,).show()
} } }
return view
} } | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/PantallaLogin.kt | 2851817558 |
package com.example.tpfinaldap
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class sharedData : ViewModel() {
val dataID = MutableLiveData<String>()
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/sharedData.kt | 1152605725 |
package com.example.tpfinaldap
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.example.tpfinaldap.viewmodels.SubirSuperHeroViewModel
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class SubirSuperHero : Fragment() {
companion object {
fun newInstance() = SubirSuperHero()
}
private lateinit var viewModel: SubirSuperHeroViewModel
private lateinit var textSuperHero: EditText
private lateinit var textRealName: EditText
private lateinit var textPublisher: EditText
private lateinit var textFoto: EditText
private lateinit var textDescription: EditText
private var db = Firebase.firestore
private lateinit var botonSubir: Button
private lateinit var dataSuperHero: String
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_subir_super_hero, container, false)
textSuperHero = view.findViewById(R.id.textSuperHero)
textRealName = view.findViewById(R.id.textRealName)
textPublisher = view.findViewById(R.id.textPublisher)
textFoto = view.findViewById(R.id.textFoto)
textDescription = view.findViewById(R.id.textDescription)
botonSubir = view.findViewById(R.id.botonSubir)
botonSubir.setOnClickListener {
val documentId:String = db.collection("SuperHeroes").document().id
val superHeroeNuevo = hashMapOf(
"superhero" to textSuperHero.text.toString(),
"realName" to textRealName.text.toString(),
"publisher" to textPublisher.text.toString(),
"photo" to textFoto.text.toString(),
"description" to textDescription.text.toString(),
"idSuperHero" to documentId
)
db.collection("SuperHeroes").document(documentId).set(superHeroeNuevo)
.addOnSuccessListener {
Toast.makeText(context, "Subido", Toast.LENGTH_SHORT).show()}
.addOnFailureListener { e ->
Toast.makeText(context, "No se pudo subir",Toast.LENGTH_SHORT).show() }
findNavController().navigate(R.id.action_subirSuperHero_to_pantallaInicio)
}
return view
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/SubirSuperHero.kt | 4270396408 |
package com.example.tpfinaldap
import android.os.Bundle
import android.provider.ContactsContract.DisplayPhoto
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.tpfinaldap.recycleviewclasses.SuperHero
import com.example.tpfinaldap.recycleviewclasses.SuperHeroAdapter
import com.example.tpfinaldap.viewmodels.EditSuperHeroViewModel
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class EditSuperHero : Fragment() {
private lateinit var viewModel: EditSuperHeroViewModel
private lateinit var idCompartido: sharedData
private var db = Firebase.firestore
private lateinit var superHeroeNuevo: EditText
private lateinit var realNameNuevo: EditText
private lateinit var publisherNuevo: EditText
private lateinit var photoNuevo: EditText
private lateinit var descriptionNuevo: EditText
private lateinit var superHeroID: String
private lateinit var botonSubirDatos: Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_edit_super_hero, container, false)
superHeroeNuevo = view.findViewById(R.id.superheroNuevo)
realNameNuevo = view.findViewById(R.id.realNameNuevo)
publisherNuevo = view.findViewById(R.id.publisherNuevo)
photoNuevo = view.findViewById(R.id.photoNuevo)
descriptionNuevo = view.findViewById(R.id.descriptionNuevo)
botonSubirDatos = view.findViewById(R.id.botonSubirDatos)
db = FirebaseFirestore.getInstance()
idCompartido = ViewModelProvider(requireActivity()).get(sharedData::class.java)
idCompartido.dataID.observe(viewLifecycleOwner) { data1 ->
db.collection("SuperHeroes").document(data1).get().addOnSuccessListener {
superHeroeNuevo.setText(it.data?.get("superhero").toString())
realNameNuevo.setText(it.data?.get("realName").toString())
publisherNuevo.setText(it.data?.get("publisher").toString())
photoNuevo.setText(it.data?.get("photo").toString())
descriptionNuevo.setText(it.data?.get("description").toString())
superHeroID = it.data?.get("idSuperHero").toString()
}.addOnFailureListener {
Toast.makeText(context, "no se encontraron datos", Toast.LENGTH_SHORT).show()
}
botonSubirDatos.setOnClickListener {
val superHeroeNuevo = hashMapOf(
"superhero" to superHeroeNuevo.text.toString(),
"realName" to realNameNuevo.text.toString(),
"publisher" to publisherNuevo.text.toString(),
"photo" to photoNuevo.text.toString(),
"description" to descriptionNuevo.text.toString(),
"idSuperHero" to superHeroID
)
db.collection("SuperHeroes").document(data1).set(superHeroeNuevo)
.addOnSuccessListener {
Toast.makeText(context, "subido", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener { e ->
Toast.makeText(context, "no se pudo subir", Toast.LENGTH_SHORT).show()
}
findNavController().navigate(R.id.action_editSuperHero_to_pantallaInicio)
} }
return view
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/EditSuperHero.kt | 2879464925 |
package com.example.tpfinaldap
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.example.tpfinaldap.viewmodels.DataSuperHeroesViewModel
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class DataSuperHeroes : Fragment() {
private lateinit var viewModel: DataSuperHeroesViewModel
private lateinit var idCompartido: sharedData
private var db = Firebase.firestore
private lateinit var superHeroeData: TextView
private lateinit var realNameData: TextView
private lateinit var publisherData: TextView
private lateinit var photoData: ImageView
private lateinit var descriptionData: TextView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_data_super_heroes, container, false)
superHeroeData = view.findViewById(R.id.superheroData)
realNameData = view.findViewById(R.id.realNameData)
publisherData = view.findViewById(R.id.publisherData)
photoData = view.findViewById(R.id.photoData)
descriptionData = view.findViewById(R.id.descriptionData)
db = FirebaseFirestore.getInstance()
idCompartido = ViewModelProvider(requireActivity()).get(sharedData::class.java)
idCompartido.dataID.observe(viewLifecycleOwner) { data1 ->
db.collection("SuperHeroes").document(data1).get().addOnSuccessListener {
superHeroeData.text = (it.data?.get("superhero").toString())
realNameData.text = (it.data?.get("realName").toString())
publisherData.text = (it.data?.get("publisher").toString())
Glide.with(photoData.context).load(it.data?.get("photo").toString()).into(photoData)
descriptionData.text = (it.data?.get("description").toString())
}.addOnFailureListener {
Toast.makeText(context, "no se encontraron datos", Toast.LENGTH_SHORT).show()
}
}
return view
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/DataSuperHeroes.kt | 3205022284 |
package com.example.tpfinaldap
import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.tpfinaldap.viewmodels.PantallaRegisterViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class PantallaRegister : Fragment() {
private lateinit var viewModel: PantallaRegisterViewModel
lateinit var botonRegistrar: Button
lateinit var email: EditText
lateinit var password: EditText
lateinit var confPassword: EditText
lateinit var username: EditText
lateinit var datoMail: String
lateinit var datoPassword: String
lateinit var datoConfPassword: String
lateinit var nombreUsuario: String
private lateinit var auth: FirebaseAuth
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_pantalla_register, container, false)
botonRegistrar = view.findViewById(R.id.botonCrearCuenta)
email = view.findViewById(R.id.textUsuario)
password = view.findViewById(R.id.textContraseña)
confPassword = view.findViewById(R.id.textoRepContra)
username = view.findViewById(R.id.textoNombre)
botonRegistrar.setOnClickListener {
datoMail = email.text.toString()
datoPassword = password.text.toString()
datoConfPassword = confPassword.text.toString()
nombreUsuario = username.text.toString()
if (nombreUsuario.length < 4 ) {
Toast.makeText(context, "El nombre de Usuario es muy corto", Toast.LENGTH_SHORT,).show()
}
else if (datoPassword.length < 6) {
Toast.makeText(context, "La contraseña debe contener al menos 6 caracteres", Toast.LENGTH_SHORT,).show()
}
else if (datoPassword == datoConfPassword) {
auth = Firebase.auth
auth.createUserWithEmailAndPassword(datoMail, datoPassword).addOnCompleteListener { }
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(ContentValues.TAG, "createUserWithEmail:success")
val user = auth.currentUser
findNavController().navigate(R.id.action_pantallaRegister_to_pantallaInicio)
} else {
// If sign in fails, display a message to the user.
Log.w(ContentValues.TAG, "createUserWithEmail:failure", task.exception)
Toast.makeText(context, "Su mail ya esta registrado o no existe", Toast.LENGTH_SHORT,).show()
} } }
else {
Toast.makeText(context, "Las contraseñas no coinciden", Toast.LENGTH_SHORT,).show()
} }
return view
} } | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/PantallaRegister.kt | 623192740 |
package com.example.tpfinaldap
import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tpfinaldap.recycleviewclasses.SuperHero
import com.example.tpfinaldap.recycleviewclasses.SuperHeroAdapter
import com.example.tpfinaldap.viewmodels.PantallaInicioViewModel
import com.google.android.play.core.integrity.v
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class PantallaInicio : Fragment() {
private lateinit var viewModel: PantallaInicioViewModel
private lateinit var recyclerView: RecyclerView
private lateinit var superHeroList: ArrayList<SuperHero>
private var db = Firebase.firestore
private lateinit var botonAdd: Button
private lateinit var idSuperHeroeActual: String
private lateinit var idCompartido: sharedData
private lateinit var adapter : SuperHeroAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_pantalla_inicio, container, false)
db = FirebaseFirestore.getInstance()
recyclerView = view.findViewById(R.id.recyclerSuperHero)
recyclerView.layoutManager = LinearLayoutManager(context)
superHeroList = arrayListOf()
botonAdd = view.findViewById(R.id.botonAñadir)
initRecyclerView()
botonAdd.setOnClickListener {
findNavController().navigate(R.id.action_pantallaInicio_to_subirSuperHero)
}
return view
}
private fun initRecyclerView() {
db.collection("SuperHeroes").get().addOnSuccessListener {
if (!it.isEmpty) {
for (data in it.documents) {
val superHero:SuperHero? = data.toObject<SuperHero>(SuperHero::class.java)
superHeroList.add(superHero!!)
}
adapter = SuperHeroAdapter(superHeroList,
onDeleteClick = {position -> deleteHero(position)
},
onEditClick = {position -> editSuperHero(position)
},
onItemClick = {position -> seeSuperHeroData(position)})
recyclerView.adapter = adapter
}
}.addOnFailureListener {
Toast.makeText(context, it.toString(),Toast.LENGTH_SHORT).show()
}
}
fun seeSuperHeroData(position:Int) {
idSuperHeroeActual = superHeroList[position].idSuperHero.toString()
idCompartido = ViewModelProvider(requireActivity()).get(sharedData::class.java)
idCompartido.dataID.value = idSuperHeroeActual
findNavController().navigate(R.id.action_pantallaInicio_to_dataSuperHeroes)
}
fun editSuperHero(position: Int) {
idSuperHeroeActual = superHeroList[position].idSuperHero.toString()
idCompartido = ViewModelProvider(requireActivity()).get(sharedData::class.java)
idCompartido.dataID.value = idSuperHeroeActual
findNavController().navigate(R.id.action_pantallaInicio_to_editSuperHero)
}
fun deleteHero (position : Int){
db.collection("SuperHeroes").document(superHeroList[position].idSuperHero.toString()).delete()
.addOnSuccessListener {
Toast.makeText(requireContext(),"Equipo Eliminado", Toast.LENGTH_SHORT).show()
adapter.notifyItemRemoved(position)
superHeroList.removeAt(position)
}
.addOnFailureListener { Toast.makeText(requireContext(),"No se puedo eliminar el Equipo", Toast.LENGTH_SHORT).show() }
}
} | TPfinalDAP-bedacarratz/Tp final Dap/app/src/main/java/com/example/tpfinaldap/PantallaInicio.kt | 761363617 |
package com.example.practice
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.practice", appContext.packageName)
}
} | myfirstrepoproject/app/src/androidTest/java/com/example/practice/ExampleInstrumentedTest.kt | 283111831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.