content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.srhan.easymarkt.firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import com.srhan.easymarkt.data.models.CartProduct
class FirebaseCommon(
private val firestore: FirebaseFirestore,
private val auth: FirebaseAuth
) {
private val cartCollection: CollectionReference?
get() = auth.uid?.let {
firestore.collection("user").document(it).collection("cart")
}
// firestore.collection("user").document(auth.uid!!).collection("cart")
// fun addProductToCart(cartProduct: CartProduct, onResult: (CartProduct?, Exception?) -> Unit) {
// cartCollection?.document()?.set(cartProduct)
// ?.addOnSuccessListener {
// onResult(cartProduct, null)
// }?.addOnFailureListener {
// onResult(null, it)
// }
// }
fun addProductToCart(cartProduct: CartProduct, onResult: (CartProduct?, Exception?) -> Unit) {
val collection = cartCollection
if (collection != null) {
collection.document().set(cartProduct)
.addOnSuccessListener {
onResult(cartProduct, null)
}.addOnFailureListener {
onResult(null, it)
}
} else {
onResult(null, NullPointerException("auth.uid is null"))
}
}
fun increaseQuantity(documentId: String, onResult: (String?, Exception?) -> Unit) {
firestore.runTransaction { transition ->
val documentRef = cartCollection?.document(documentId)
val document = transition.get(documentRef!!)
val productObject = document.toObject(CartProduct::class.java)
productObject?.let { cartProduct ->
val newQuantity = cartProduct.quantity + 1
val newProductObject = cartProduct.copy(quantity = newQuantity)
transition.set(documentRef, newProductObject)
}
}.addOnSuccessListener {
onResult(documentId, null)
}.addOnFailureListener {
onResult(null, it)
}
}
fun decreaseQuantity(documentId: String, onResult: (String?, Exception?) -> Unit) {
firestore.runTransaction { transition ->
val documentRef = cartCollection?.document(documentId)
val document = transition.get(documentRef!!)
val productObject = document.toObject(CartProduct::class.java)
productObject?.let { cartProduct ->
val newQuantity = cartProduct.quantity - 1
val newProductObject = cartProduct.copy(quantity = newQuantity)
transition.set(documentRef, newProductObject)
}
}.addOnSuccessListener {
onResult(documentId, null)
}.addOnFailureListener {
onResult(null, it)
}
}
enum class QuantityChanging {
INCREASE, DECREASE
}
} | EasyMarkt/app/src/main/java/com/srhan/easymarkt/firebase/FirebaseCommon.kt | 3896312449 |
package com.srhan.easymarkt.data.models.order
sealed class OrderStatus(val status: String) {
object Ordered : OrderStatus("Ordered")
object Canceled : OrderStatus("Canceled")
object Confirmed : OrderStatus("Confirmed")
object Shipped : OrderStatus("Shipped")
object Delivered : OrderStatus("Delivered")
object Returned : OrderStatus("Returned")
}
fun getOrderStatus(status: String): OrderStatus {
return when (status) {
"Ordered" -> {
OrderStatus.Ordered
}
"Canceled" -> {
OrderStatus.Canceled
}
"Confirmed" -> {
OrderStatus.Confirmed
}
"Shipped" -> {
OrderStatus.Shipped
}
"Delivered" -> {
OrderStatus.Delivered
}
else -> OrderStatus.Returned
}
}
| EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/order/OrderStatus.kt | 622191412 |
package com.srhan.easymarkt.data.models.order
import android.os.Parcelable
import com.srhan.easymarkt.data.models.Address
import com.srhan.easymarkt.data.models.CartProduct
import kotlinx.parcelize.Parcelize
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.random.Random.Default.nextLong
@Parcelize
data class Order(
val orderStatus: String = "",
val totalPrice: Float = 0f,
val products: List<CartProduct> = emptyList(),
val address: Address = Address(),
val date: String = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(Date()),
val orderId: Long = nextLong(0, 100_000_000_000) + totalPrice.toLong()
) : Parcelable | EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/order/Order.kt | 1958814722 |
package com.srhan.easymarkt.data.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Product(
val id: String,
val name: String,
val category: String,
val price: Float,
val offerPercentage: Float? = null,
val description: String? = null,
val colors: List<Int>? = null,
val sizes: List<String>? = null,
val images: List<String>
) : Parcelable {
constructor() : this("0", "", "", 0f, images = emptyList())
} | EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/Product.kt | 3026855833 |
package com.srhan.easymarkt.data.models
sealed class MyCategory(val category: String) {
object Chair : MyCategory("Chair")
object Cupboard : MyCategory("Cupboard")
object Table : MyCategory("Table")
object Accessory : MyCategory("Accessory")
object Furniture : MyCategory("Furniture")
} | EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/MyCategory.kt | 1713596846 |
package com.srhan.easymarkt.data.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Address(
val addressTitle: String,
val fullName: String,
val street: String,
val phone: String,
val city: String,
val state: String
) : Parcelable {
constructor() : this("", "", "", "", "", "")
}
| EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/Address.kt | 3874333647 |
package com.srhan.easymarkt.data.models
data class User(
val firstName: String,
val lastName: String,
val email: String,
var imagePath: String = ""
) {
constructor() : this("", "", "", "")
}
| EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/User.kt | 2911192538 |
package com.srhan.easymarkt.data.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class CartProduct(
val product: Product,
val quantity: Int,
val selectedColor: Int? = null,
val selectedSize: String? = null
) : Parcelable {
constructor() : this(Product(), 1, null, null)
}
| EasyMarkt/app/src/main/java/com/srhan/easymarkt/data/models/CartProduct.kt | 3879600434 |
package com.srhan.easymarkt.helper
fun Float?.getProductPrice(price: Float): Float {
//this --> Percentage
if (this == null)
return price
val remainingPricePercentage = 1f - this
val priceAfterOffer = remainingPricePercentage * price
return priceAfterOffer
} | EasyMarkt/app/src/main/java/com/srhan/easymarkt/helper/PriceCalculator.kt | 2164139878 |
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
*/
package com.examples.lite.examples.ocr
import androidx.lifecycle.ViewModel
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExecutorCoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
private const val TAG = "MLExecutionViewModel"
class MLExecutionViewModel : ViewModel() {
private val _resultingBitmap = MutableLiveData<ModelExecutionResult>()
val resultingBitmap: LiveData<ModelExecutionResult>
get() = _resultingBitmap
private val viewModelJob = Job()
private val viewModelScope = CoroutineScope(viewModelJob)
// the execution of the model has to be on the same thread where the interpreter
// was created
fun onApplyModel(
context: Context,
fileName: Uri?,
ocrModel: OCRModelExecutor?,
inferenceThread: ExecutorCoroutineDispatcher
) {
viewModelScope.launch(inferenceThread) {
// val inputStream = context.assets.open(fileName)
val contentImage = MediaStore.Images.Media.getBitmap(context.contentResolver, fileName)
try {
val result = ocrModel?.execute(contentImage)
_resultingBitmap.postValue(result)
} catch (e: Exception) {
Log.e(TAG, "Fail to execute OCRModelExecutor: ${e.message}")
_resultingBitmap.postValue(null)
}
}
}
}
| TextRecognition/app/src/main/java/com/examples/lite/examples/ocr/MLExecutionViewModel.kt | 2347806206 |
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
*/
package com.examples.lite.examples.ocr
import android.app.Activity
import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.ClipboardManager
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
import com.bumptech.glide.Glide
import com.github.dhaval2404.imagepicker.ImagePicker
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.tensorflow.lite.examples.ocr.R
import java.util.concurrent.Executors
private const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
private var FOTO_URI: Uri? = null
private lateinit var viewModel: MLExecutionViewModel
private lateinit var resultImageView: ImageView
private lateinit var tfImageView: ImageView
private lateinit var runButton: Button
private lateinit var copyButton: ImageView
private lateinit var tvResult: TextView
private lateinit var tvRes: TextView
private lateinit var divRes: LinearLayout
private var useGPU = false
private var ocrModel: OCRModelExecutor? = null
private val inferenceThread = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
private val mainScope = MainScope()
private val mutex = Mutex()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tfe_is_activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
tfImageView = findViewById(R.id.tf_imageview)
tfImageView.setOnClickListener {
ImagePicker.with(this)
.crop()
.start()
}
resultImageView = findViewById(R.id.result_imageview)
copyButton = findViewById(R.id.btn_copy)
tvResult = findViewById(R.id.tv_result)
tvRes = findViewById(R.id.tv_res)
divRes = findViewById(R.id.div_res)
viewModel = AndroidViewModelFactory(application).create(MLExecutionViewModel::class.java)
viewModel.resultingBitmap.observe(
this,
Observer { resultImage ->
if (resultImage != null) {
updateUIWithResults(resultImage)
}
enableControls(true)
}
)
mainScope.async(inferenceThread) { createModelExecutor(useGPU) }
runButton = findViewById(R.id.rerun_button)
runButton.setOnClickListener {
enableControls(false)
mainScope.async(inferenceThread) {
mutex.withLock {
if (ocrModel != null) {
viewModel.onApplyModel(
baseContext,
FOTO_URI,
ocrModel,
inferenceThread
)
} else {
Log.d(
TAG,
"Skipping running OCR since the ocrModel has not been properly initialized ..."
)
}
}
}
}
copyButton.setOnClickListener {
setClipboard(this, tvResult.text.toString())
if (tvResult.text.toString() != "" || tvResult.text.toString() != null){
Toast.makeText(this, "teks disalin", Toast.LENGTH_SHORT).show()
}
}
// setChipsToLogView(HashMap<String, Int>())
enableControls(true)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == ImagePicker.REQUEST_CODE && data != null) {
val layoutParams = tfImageView.layoutParams as LinearLayout.LayoutParams
layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT
tfImageView.layoutParams = layoutParams
FOTO_URI = data.data
Glide.with(this)
.load(FOTO_URI)
.into(tfImageView)
} else if (resultCode == ImagePicker.RESULT_ERROR) {
Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "membatalkan ambil gambar", Toast.LENGTH_SHORT).show()
}
}
private suspend fun createModelExecutor(useGPU: Boolean) {
mutex.withLock {
if (ocrModel != null) {
ocrModel!!.close()
ocrModel = null
}
try {
ocrModel = OCRModelExecutor(this, useGPU)
} catch (e: Exception) {
Log.e(TAG, "Fail to create OCRModelExecutor: ${e.message}")
}
}
}
private fun getColorStateListForChip(color: Int): ColorStateList {
val states =
arrayOf(
intArrayOf(android.R.attr.state_enabled), // enabled
intArrayOf(android.R.attr.state_pressed) // pressed
)
val colors = intArrayOf(color, color)
return ColorStateList(states, colors)
}
private fun setImageView(imageView: ImageView, image: Bitmap) {
copyButton.visibility = View.VISIBLE
tvRes.visibility = View.VISIBLE
divRes.visibility = View.VISIBLE
imageView.visibility = View.VISIBLE
Glide.with(baseContext).load(image).override(250, 250).fitCenter().into(imageView)
}
private fun updateUIWithResults(modelExecutionResult: ModelExecutionResult) {
setImageView(resultImageView, modelExecutionResult.bitmapResult)
displayTextFromHashMap(tvResult, modelExecutionResult.itemsFound)
// setChipsToLogView(modelExecutionResult.itemsFound)
enableControls(true)
}
private fun enableControls(enable: Boolean) {
runButton.isEnabled = enable
}
private fun setClipboard(context: Context, text: String) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
val clipboard = context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipboard.text = text
} else {
val clipboard =
context.getSystemService(CLIPBOARD_SERVICE) as android.content.ClipboardManager
val clip = ClipData.newPlainText("Copied Text", text)
clipboard.setPrimaryClip(clip)
}
}
private fun displayTextFromHashMap(textView: TextView, hashMap: Map<String, Int>) {
val stringBuilder = StringBuilder()
for ((word, _) in hashMap) {
stringBuilder.append("$word ")
}
textView.text = stringBuilder.toString()
}
}
| TextRecognition/app/src/main/java/com/examples/lite/examples/ocr/MainActivity.kt | 3526123023 |
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
*/
package com.examples.lite.examples.ocr
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import androidx.exifinterface.media.ExifInterface
import java.io.File
import org.tensorflow.lite.DataType
import org.tensorflow.lite.support.common.ops.NormalizeOp
import org.tensorflow.lite.support.image.ImageProcessor
import org.tensorflow.lite.support.image.TensorImage
import org.tensorflow.lite.support.image.ops.ResizeOp
import org.tensorflow.lite.support.image.ops.TransformToGrayscaleOp
/** Collection of image reading and manipulation utilities in the form of static functions. */
abstract class ImageUtils {
companion object {
/**
* Helper function used to convert an EXIF orientation enum into a transformation matrix that
* can be applied to a bitmap.
*
* @param orientation
* - One of the constants from [ExifInterface]
*/
private fun decodeExifOrientation(orientation: Int): Matrix {
val matrix = Matrix()
// Apply transformation corresponding to declared EXIF orientation
when (orientation) {
ExifInterface.ORIENTATION_NORMAL, ExifInterface.ORIENTATION_UNDEFINED -> Unit
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90F)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180F)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270F)
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1F, 1F)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1F, -1F)
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.postScale(-1F, 1F)
matrix.postRotate(270F)
}
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.postScale(-1F, 1F)
matrix.postRotate(90F)
}
// Error out if the EXIF orientation is invalid
else -> throw IllegalArgumentException("Invalid orientation: $orientation")
}
// Return the resulting matrix
return matrix
}
/**
* sets the Exif orientation of an image. this method is used to fix the exit of pictures taken
* by the camera
*
* @param filePath
* - The image file to change
* @param value
* - the orientation of the file
*/
fun setExifOrientation(filePath: String, value: String) {
val exif = ExifInterface(filePath)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, value)
exif.saveAttributes()
}
/** Transforms rotation and mirroring information into one of the [ExifInterface] constants */
fun computeExifOrientation(rotationDegrees: Int, mirrored: Boolean) =
when {
rotationDegrees == 0 && !mirrored -> ExifInterface.ORIENTATION_NORMAL
rotationDegrees == 0 && mirrored -> ExifInterface.ORIENTATION_FLIP_HORIZONTAL
rotationDegrees == 180 && !mirrored -> ExifInterface.ORIENTATION_ROTATE_180
rotationDegrees == 180 && mirrored -> ExifInterface.ORIENTATION_FLIP_VERTICAL
rotationDegrees == 270 && mirrored -> ExifInterface.ORIENTATION_TRANSVERSE
rotationDegrees == 90 && !mirrored -> ExifInterface.ORIENTATION_ROTATE_90
rotationDegrees == 90 && mirrored -> ExifInterface.ORIENTATION_TRANSPOSE
rotationDegrees == 270 && mirrored -> ExifInterface.ORIENTATION_ROTATE_270
rotationDegrees == 270 && !mirrored -> ExifInterface.ORIENTATION_TRANSVERSE
else -> ExifInterface.ORIENTATION_UNDEFINED
}
/**
* Decode a bitmap from a file and apply the transformations described in its EXIF data
*
* @param file
* - The image file to be read using [BitmapFactory.decodeFile]
*/
fun decodeBitmap(file: File): Bitmap {
// First, decode EXIF data and retrieve transformation matrix
val exif = ExifInterface(file.absolutePath)
val transformation =
decodeExifOrientation(
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_90)
)
// Read bitmap using factory methods, and transform it using EXIF data
val options = BitmapFactory.Options()
val bitmap = BitmapFactory.decodeFile(file.absolutePath, options)
return Bitmap.createBitmap(
BitmapFactory.decodeFile(file.absolutePath),
0,
0,
bitmap.width,
bitmap.height,
transformation,
true
)
}
/**
* Convert a bitmap to a TensorImage for the recognition model with target size and
* normalization
*
* @param bitmapIn
* - the bitmap to convert
* @param width
* - target width of the converted TensorImage
* @param height
* - target height of the converted TensorImage
* @param means
* - means of the images
* @param stds
* - stds of the images
*/
fun bitmapToTensorImageForRecognition(
bitmapIn: Bitmap,
width: Int,
height: Int,
mean: Float,
std: Float
): TensorImage {
val imageProcessor =
ImageProcessor.Builder()
.add(ResizeOp(height, width, ResizeOp.ResizeMethod.BILINEAR))
.add(TransformToGrayscaleOp())
.add(NormalizeOp(mean, std))
.build()
var tensorImage = TensorImage(DataType.FLOAT32)
tensorImage.load(bitmapIn)
tensorImage = imageProcessor.process(tensorImage)
return tensorImage
}
/**
* Convert a bitmap to a TensorImage for the detection model with target size and normalization
*
* @param bitmapIn
* - the bitmap to convert
* @param width
* - target width of the converted TensorImage
* @param height
* - target height of the converted TensorImage
* @param means
* - means of the images
* @param stds
* - stds of the images
*/
fun bitmapToTensorImageForDetection(
bitmapIn: Bitmap,
width: Int,
height: Int,
means: FloatArray,
stds: FloatArray
): TensorImage {
val imageProcessor =
ImageProcessor.Builder()
.add(ResizeOp(height, width, ResizeOp.ResizeMethod.BILINEAR))
.add(NormalizeOp(means, stds))
.build()
var tensorImage = TensorImage(DataType.FLOAT32)
tensorImage.load(bitmapIn)
tensorImage = imageProcessor.process(tensorImage)
return tensorImage
}
fun createEmptyBitmap(
imageWidth: Int,
imageHeigth: Int,
color: Int = 0,
imageConfig: Bitmap.Config = Bitmap.Config.RGB_565
): Bitmap {
val ret = Bitmap.createBitmap(imageWidth, imageHeigth, imageConfig)
if (color != 0) {
ret.eraseColor(color)
}
return ret
}
}
}
| TextRecognition/app/src/main/java/com/examples/lite/examples/ocr/ImageUtils.kt | 71661420 |
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
*/
package com.examples.lite.examples.ocr
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.Log
import java.io.FileInputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
import java.util.Random
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import org.opencv.android.OpenCVLoader
import org.opencv.android.Utils.bitmapToMat
import org.opencv.android.Utils.matToBitmap
import org.opencv.core.Mat
import org.opencv.core.MatOfFloat
import org.opencv.core.MatOfInt
import org.opencv.core.MatOfPoint2f
import org.opencv.core.MatOfRotatedRect
import org.opencv.core.Point
import org.opencv.core.RotatedRect
import org.opencv.core.Size
import org.opencv.dnn.Dnn.NMSBoxesRotated
import org.opencv.imgproc.Imgproc.boxPoints
import org.opencv.imgproc.Imgproc.getPerspectiveTransform
import org.opencv.imgproc.Imgproc.warpPerspective
import org.opencv.utils.Converters.vector_RotatedRect_to_Mat
import org.opencv.utils.Converters.vector_float_to_Mat
import org.tensorflow.lite.Interpreter
import org.tensorflow.lite.gpu.GpuDelegate
/**
* Class to run the OCR models. The OCR process is broken down into 2 stages: 1) Text detection
* using [EAST model](https://tfhub.dev/sayakpaul/lite-model/east-text-detector/fp16/1) 2) Text
* recognition using
* [Keras OCR model](https://tfhub.dev/tulasiram58827/lite-model/keras-ocr/float16/2)
*/
class OCRModelExecutor(context: Context, private var useGPU: Boolean = false) : AutoCloseable {
private var gpuDelegate: GpuDelegate? = null
private val recognitionResult: ByteBuffer
private val detectionInterpreter: Interpreter
private val recognitionInterpreter: Interpreter
private var ratioHeight = 0.toFloat()
private var ratioWidth = 0.toFloat()
private var indicesMat: MatOfInt
private var boundingBoxesMat: MatOfRotatedRect
private var ocrResults: HashMap<String, Int>
init {
try {
if (!OpenCVLoader.initDebug()) throw Exception("Unable to load OpenCV")
else Log.d(TAG, "OpenCV loaded")
} catch (e: Exception) {
val exceptionLog = "something went wrong: ${e.message}"
Log.d(TAG, exceptionLog)
}
detectionInterpreter = getInterpreter(context, textDetectionModel, useGPU)
// Recognition model requires Flex so we disable GPU delegate no matter user choice
recognitionInterpreter = getInterpreter(context, textRecognitionModel, false)
recognitionResult = ByteBuffer.allocateDirect(recognitionModelOutputSize * 8)
recognitionResult.order(ByteOrder.nativeOrder())
indicesMat = MatOfInt()
boundingBoxesMat = MatOfRotatedRect()
ocrResults = HashMap<String, Int>()
}
fun execute(data: Bitmap): ModelExecutionResult {
try {
ratioHeight = data.height.toFloat() / detectionImageHeight
ratioWidth = data.width.toFloat() / detectionImageWidth
ocrResults.clear()
detectTexts(data)
val bitmapWithBoundingBoxes = recognizeTexts(data, boundingBoxesMat, indicesMat)
return ModelExecutionResult(bitmapWithBoundingBoxes, "OCR result", ocrResults)
} catch (e: Exception) {
val exceptionLog = "something went wrong: ${e.message}"
Log.d(TAG, exceptionLog)
val emptyBitmap = ImageUtils.createEmptyBitmap(displayImageSize, displayImageSize)
return ModelExecutionResult(emptyBitmap, exceptionLog, HashMap<String, Int>())
}
}
private fun detectTexts(data: Bitmap) {
val detectionTensorImage =
ImageUtils.bitmapToTensorImageForDetection(
data,
detectionImageWidth,
detectionImageHeight,
detectionImageMeans,
detectionImageStds
)
val detectionInputs = arrayOf(detectionTensorImage.buffer.rewind())
val detectionOutputs: HashMap<Int, Any> = HashMap<Int, Any>()
val detectionScores =
Array(1) { Array(detectionOutputNumRows) { Array(detectionOutputNumCols) { FloatArray(1) } } }
val detectionGeometries =
Array(1) { Array(detectionOutputNumRows) { Array(detectionOutputNumCols) { FloatArray(5) } } }
detectionOutputs.put(0, detectionScores)
detectionOutputs.put(1, detectionGeometries)
detectionInterpreter.runForMultipleInputsOutputs(detectionInputs, detectionOutputs)
val transposeddetectionScores =
Array(1) { Array(1) { Array(detectionOutputNumRows) { FloatArray(detectionOutputNumCols) } } }
val transposedDetectionGeometries =
Array(1) { Array(5) { Array(detectionOutputNumRows) { FloatArray(detectionOutputNumCols) } } }
// transpose detection output tensors
for (i in 0 until transposeddetectionScores[0][0].size) {
for (j in 0 until transposeddetectionScores[0][0][0].size) {
for (k in 0 until 1) {
transposeddetectionScores[0][k][i][j] = detectionScores[0][i][j][k]
}
for (k in 0 until 5) {
transposedDetectionGeometries[0][k][i][j] = detectionGeometries[0][i][j][k]
}
}
}
val detectedRotatedRects = ArrayList<RotatedRect>()
val detectedConfidences = ArrayList<Float>()
for (y in 0 until transposeddetectionScores[0][0].size) {
val detectionScoreData = transposeddetectionScores[0][0][y]
val detectionGeometryX0Data = transposedDetectionGeometries[0][0][y]
val detectionGeometryX1Data = transposedDetectionGeometries[0][1][y]
val detectionGeometryX2Data = transposedDetectionGeometries[0][2][y]
val detectionGeometryX3Data = transposedDetectionGeometries[0][3][y]
val detectionRotationAngleData = transposedDetectionGeometries[0][4][y]
for (x in 0 until transposeddetectionScores[0][0][0].size) {
if (detectionScoreData[x] < 0.5) {
continue
}
// Compute the rotated bounding boxes and confiences (heavily based on OpenCV example):
// https://github.com/opencv/opencv/blob/master/samples/dnn/text_detection.py
val offsetX = x * 4.0
val offsetY = y * 4.0
val h = detectionGeometryX0Data[x] + detectionGeometryX2Data[x]
val w = detectionGeometryX1Data[x] + detectionGeometryX3Data[x]
val angle = detectionRotationAngleData[x]
val cos = Math.cos(angle.toDouble())
val sin = Math.sin(angle.toDouble())
val offset =
Point(
offsetX + cos * detectionGeometryX1Data[x] + sin * detectionGeometryX2Data[x],
offsetY - sin * detectionGeometryX1Data[x] + cos * detectionGeometryX2Data[x]
)
val p1 = Point(-sin * h + offset.x, -cos * h + offset.y)
val p3 = Point(-cos * w + offset.x, sin * w + offset.y)
val center = Point(0.5 * (p1.x + p3.x), 0.5 * (p1.y + p3.y))
val textDetection =
RotatedRect(
center,
Size(w.toDouble(), h.toDouble()),
(-1 * angle * 180.0 / Math.PI)
)
detectedRotatedRects.add(textDetection)
detectedConfidences.add(detectionScoreData[x])
}
}
val detectedConfidencesMat = MatOfFloat(vector_float_to_Mat(detectedConfidences))
boundingBoxesMat = MatOfRotatedRect(vector_RotatedRect_to_Mat(detectedRotatedRects))
NMSBoxesRotated(
boundingBoxesMat,
detectedConfidencesMat,
detectionConfidenceThreshold.toFloat(),
detectionNMSThreshold.toFloat(),
indicesMat
)
}
private fun recognizeTexts(
data: Bitmap,
boundingBoxesMat: MatOfRotatedRect,
indicesMat: MatOfInt
): Bitmap {
val bitmapWithBoundingBoxes = data.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmapWithBoundingBoxes)
val paint = Paint()
paint.style = Paint.Style.STROKE
paint.strokeWidth = 10.toFloat()
paint.setColor(Color.GREEN)
for (i in indicesMat.toArray()) {
val boundingBox = boundingBoxesMat.toArray()[i]
val targetVertices = ArrayList<Point>()
targetVertices.add(Point(0.toDouble(), (recognitionImageHeight - 1).toDouble()))
targetVertices.add(Point(0.toDouble(), 0.toDouble()))
targetVertices.add(Point((recognitionImageWidth - 1).toDouble(), 0.toDouble()))
targetVertices.add(
Point((recognitionImageWidth - 1).toDouble(), (recognitionImageHeight - 1).toDouble())
)
val srcVertices = ArrayList<Point>()
val boundingBoxPointsMat = Mat()
boxPoints(boundingBox, boundingBoxPointsMat)
for (j in 0 until 4) {
srcVertices.add(
Point(
boundingBoxPointsMat.get(j, 0)[0] * ratioWidth,
boundingBoxPointsMat.get(j, 1)[0] * ratioHeight
)
)
if (j != 0) {
canvas.drawLine(
(boundingBoxPointsMat.get(j, 0)[0] * ratioWidth).toFloat(),
(boundingBoxPointsMat.get(j, 1)[0] * ratioHeight).toFloat(),
(boundingBoxPointsMat.get(j - 1, 0)[0] * ratioWidth).toFloat(),
(boundingBoxPointsMat.get(j - 1, 1)[0] * ratioHeight).toFloat(),
paint
)
}
}
canvas.drawLine(
(boundingBoxPointsMat.get(0, 0)[0] * ratioWidth).toFloat(),
(boundingBoxPointsMat.get(0, 1)[0] * ratioHeight).toFloat(),
(boundingBoxPointsMat.get(3, 0)[0] * ratioWidth).toFloat(),
(boundingBoxPointsMat.get(3, 1)[0] * ratioHeight).toFloat(),
paint
)
val srcVerticesMat =
MatOfPoint2f(srcVertices[0], srcVertices[1], srcVertices[2], srcVertices[3])
val targetVerticesMat =
MatOfPoint2f(targetVertices[0], targetVertices[1], targetVertices[2], targetVertices[3])
val rotationMatrix = getPerspectiveTransform(srcVerticesMat, targetVerticesMat)
val recognitionBitmapMat = Mat()
val srcBitmapMat = Mat()
bitmapToMat(data, srcBitmapMat)
warpPerspective(
srcBitmapMat,
recognitionBitmapMat,
rotationMatrix,
Size(recognitionImageWidth.toDouble(), recognitionImageHeight.toDouble())
)
val recognitionBitmap =
ImageUtils.createEmptyBitmap(
recognitionImageWidth,
recognitionImageHeight,
0,
Bitmap.Config.ARGB_8888
)
matToBitmap(recognitionBitmapMat, recognitionBitmap)
val recognitionTensorImage =
ImageUtils.bitmapToTensorImageForRecognition(
recognitionBitmap,
recognitionImageWidth,
recognitionImageHeight,
recognitionImageMean,
recognitionImageStd
)
recognitionResult.rewind()
recognitionInterpreter.run(recognitionTensorImage.buffer, recognitionResult)
var recognizedText = ""
for (k in 0 until recognitionModelOutputSize) {
var alphabetIndex = recognitionResult.getInt(k * 8)
if (alphabetIndex in 0..alphabets.length - 1)
recognizedText = recognizedText + alphabets[alphabetIndex]
}
Log.d("Recognition result:", recognizedText)
if (recognizedText != "") {
ocrResults.put(recognizedText, getRandomColor())
}
}
return bitmapWithBoundingBoxes
}
// base:
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/java/demo/app/src/main/java/com/example/android/tflitecamerademo/ImageClassifier.java
@Throws(IOException::class)
private fun loadModelFile(context: Context, modelFile: String): MappedByteBuffer {
val fileDescriptor = context.assets.openFd(modelFile)
val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
val fileChannel = inputStream.channel
val startOffset = fileDescriptor.startOffset
val declaredLength = fileDescriptor.declaredLength
val retFile = fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
fileDescriptor.close()
return retFile
}
@Throws(IOException::class)
private fun getInterpreter(
context: Context,
modelName: String,
useGpu: Boolean = false
): Interpreter {
val tfliteOptions = Interpreter.Options()
tfliteOptions.setNumThreads(numberThreads)
gpuDelegate = null
if (useGpu) {
gpuDelegate = GpuDelegate()
tfliteOptions.addDelegate(gpuDelegate)
}
return Interpreter(loadModelFile(context, modelName), tfliteOptions)
}
override fun close() {
detectionInterpreter.close()
recognitionInterpreter.close()
if (gpuDelegate != null) {
gpuDelegate!!.close()
}
}
fun getRandomColor(): Int {
val random = Random()
return Color.argb(
(128),
(255 * random.nextFloat()).toInt(),
(255 * random.nextFloat()).toInt(),
(255 * random.nextFloat()).toInt()
)
}
companion object {
public const val TAG = "TfLiteOCRDemo"
private const val textDetectionModel = "text_detection.tflite"
private const val textRecognitionModel = "text_recognition.tflite"
private const val numberThreads = 4
private const val alphabets = "0123456789abcdefghijklmnopqrstuvwxyz"
private const val displayImageSize = 257
private const val detectionImageHeight = 320
private const val detectionImageWidth = 320
private val detectionImageMeans =
floatArrayOf(103.94.toFloat(), 116.78.toFloat(), 123.68.toFloat())
private val detectionImageStds = floatArrayOf(1.toFloat(), 1.toFloat(), 1.toFloat())
private val detectionOutputNumRows = 80
private val detectionOutputNumCols = 80
private val detectionConfidenceThreshold = 0.5
private val detectionNMSThreshold = 0.4
private const val recognitionImageHeight = 31
private const val recognitionImageWidth = 200
private const val recognitionImageMean = 0.toFloat()
private const val recognitionImageStd = 255.toFloat()
private const val recognitionModelOutputSize = 48
}
}
| TextRecognition/app/src/main/java/com/examples/lite/examples/ocr/OCRModelExecutor.kt | 4088919324 |
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
*/
package com.examples.lite.examples.ocr
import android.graphics.Bitmap
data class ModelExecutionResult(
val bitmapResult: Bitmap,
val executionLog: String,
// A map between words and colors of the items found.
val itemsFound: Map<String, Int>
)
| TextRecognition/app/src/main/java/com/examples/lite/examples/ocr/ModelExecutionResult.kt | 3570191834 |
package org.example
import kotlinx.benchmark.*
import kotlinx.cinterop.*
import platform.Foundation.NSString
import platform.Foundation.create
import platform.posix.memcpy
@OptIn(ExperimentalForeignApi::class)
@Warmup(iterations = 2, time = 1, BenchmarkTimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, BenchmarkTimeUnit.SECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(BenchmarkTimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
class Utf8Benchmark {
@Param("well-formed-utf8", "\uD83D\uDE18\uFE0F\uD83D\uDE02\uD83D\uDE00\uD83D\uDE1D")
var original: String = ""
var originalBytes = ByteArray(0)
var originalBytesPtr: CPointer<ByteVar> = nativeHeap.allocArray(0)
@Setup
fun setup() {
originalBytes = original.repeat(128).encodeToByteArray()
originalBytesPtr = nativeHeap.allocArrayOf(originalBytes)
}
@TearDown
fun cleanup() {
nativeHeap.free(originalBytesPtr)
}
@Benchmark
fun toKString(): String {
return originalBytesPtr.toKStringFromUtf8()
}
@Benchmark
@OptIn(BetaInteropApi::class)
fun copyingValidatingNSString(): String {
return NSString.create(uTF8String = originalBytesPtr).toString()
}
@Benchmark
fun strlenMemcpyThenDecodeByteArray(): String {
val count = strlenNativeImpl(originalBytesPtr)
ByteArray(count.toInt()).usePinned {
memcpy(it.addressOf(0), originalBytesPtr, count.toULong())
return it.get().decodeToString()
}
}
@Benchmark
fun copyToByteArrayThenDecodeByteArray(): String {
val count = originalBytes.size
ByteArray(count).usePinned {
memcpy(it.addressOf(0), originalBytesPtr, count.toULong())
return it.get().decodeToString()
}
}
@Benchmark
fun justDecodeByteArray(): String = originalBytes.decodeToString()
}
| KT-44357-reproducer/benchmarks/src/macosArm64Main/kotlin/Utf8Benchmark.kt | 2021223839 |
package org.example
import kotlinx.cinterop.*
// Doesn't look pretty, but I didn't find a better way as SymbolName is no longer public
@OptIn(ExperimentalForeignApi::class)
fun strlenNativeImpl(ptr: CPointer<ByteVar>): ULong = libc.strlenNative(ptr)
| KT-44357-reproducer/functions/src/macosArm64Main/kotlin/NativeStrlen.kt | 1650167645 |
package com.github.firusv.smarti18n
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.firusv.smarti18n.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"
}
| smart-i18n/src/test/kotlin/com/github/firusv/smarti18n/MyPluginTest.kt | 1964709206 |
package com.github.firusv.smarti18n.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.firusv.smarti18n.MyBundle
import com.github.firusv.smarti18n.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())
}
})
}
}
}
| smart-i18n/src/main/kotlin/com/github/firusv/smarti18n/toolWindow/MyToolWindowFactory.kt | 612436832 |
package com.github.firusv.smarti18n
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)
}
| smart-i18n/src/main/kotlin/com/github/firusv/smarti18n/MyBundle.kt | 1977805597 |
package com.github.firusv.smarti18n.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`.")
}
}
| smart-i18n/src/main/kotlin/com/github/firusv/smarti18n/listeners/MyApplicationActivationListener.kt | 414299361 |
package com.github.firusv.smarti18n.services
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.github.firusv.smarti18n.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()
}
| smart-i18n/src/main/kotlin/com/github/firusv/smarti18n/services/MyProjectService.kt | 668447994 |
package ru.reosfire.minestom.utils
import net.minestom.server.coordinate.Pos
import net.minestom.server.network.packet.server.play.SpawnEntityPacket
import java.util.*
fun spawnEntityPacket(
entityId: Int,
uuid: UUID = UUID.randomUUID(),
type: Int,
position: Pos,
headRotation: Float = 0f,
data: Int = 0,
velocityX: Short = 0,
velocityY: Short = 0,
velocityZ: Short = 0
) = SpawnEntityPacket(entityId, uuid, type, position, headRotation, data, velocityX, velocityY, velocityZ) | 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/PacketBuilders.kt | 909307812 |
package ru.reosfire.minestom.utils
import net.minestom.server.coordinate.Pos
import net.minestom.server.entity.EntityType
import net.minestom.server.entity.Metadata
import net.minestom.server.instance.block.BlockFace
import net.minestom.server.item.ItemStack
import net.minestom.server.item.Material
import net.minestom.server.network.packet.server.ServerPacket
import net.minestom.server.network.packet.server.play.DestroyEntitiesPacket
import net.minestom.server.network.packet.server.play.EntityMetaDataPacket
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.min
private const val initialEntityId = 10000
private const val initialBlockData = 1000
class NumberRenderer {
private val itemsCache: Array<Map<Int, Metadata.Entry<*>>>
private var currentEntityId = AtomicInteger(initialEntityId)
init {
itemsCache = Array(9) { number ->
val item = ItemStack.builder(Material.SHULKER_SHELL).meta {
it.customModelData(initialBlockData + number)
}.build()
createDataValues(item)
}
}
fun renderNumber(location: Pos, facing: BlockFace, number: Int): List<ServerPacket> {
if (number !in 0..8) throw IllegalArgumentException("number must be in [0..8]")
val entityId = currentEntityId.getAndIncrement()
val result = listOf(
createSpawnFramePacket(entityId, location, facing),
EntityMetaDataPacket(entityId, itemsCache[number])
)
return result
}
fun clearNumbers(): List<ServerPacket> {
val range = initialEntityId..<currentEntityId.get()
return createDestroyEntitiesPackets(range.toList())
}
private fun createDataValues(item: ItemStack): Map<Int, Metadata.Entry<*>> {
return mapOf(
0 to Metadata.Byte(IS_INVISIBLE),
8 to Metadata.Slot(item)
)
}
}
private fun createDestroyEntitiesPackets(
ids: List<Int>,
batching: Int = 256,
): List<ServerPacket> {
val result = mutableListOf<ServerPacket>()
var start = 0
while (start < ids.size) {
val packet = DestroyEntitiesPacket(ids.subList(start, min(start + batching, ids.size)))
result.add(packet)
start += batching
}
return result
}
private fun createSpawnFramePacket(entityId: Int, position: Pos, facing: BlockFace) = spawnEntityPacket(
entityId = entityId,
type = EntityType.ITEM_FRAME.id(),
position = position,
data = facing.frameDirection,
)
private val BlockFace.frameDirection: Int
get() = when(this) {
BlockFace.BOTTOM -> 0
BlockFace.TOP -> 1
BlockFace.NORTH -> 2
BlockFace.SOUTH -> 3
BlockFace.WEST -> 4
BlockFace.EAST -> 5
else -> throw UnsupportedOperationException()
}
private const val IS_INVISIBLE: Byte = 0x20
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/NumberRenderer.kt | 1588062121 |
package ru.reosfire.minestom.utils.extensions.minestom
import net.minestom.server.event.Event
import net.minestom.server.event.EventNode
import java.util.function.Consumer
inline fun <reified T : Event> EventNode<Event>.addListener(action: Consumer<T>) =
addListener(T::class.java, action) | 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/extensions/minestom/EventExtensions.kt | 3292309789 |
package ru.reosfire.minestom.utils.extensions.minestom
import net.minestom.server.coordinate.Point
import net.minestom.server.instance.Chunk
import net.minestom.server.instance.Explosion
import net.minestom.server.instance.Instance
import net.minestom.server.instance.LightingChunk
import net.minestom.server.network.packet.server.play.data.LightData
import net.minestom.server.utils.chunk.ChunkSupplier
import java.util.*
fun Instance.explode(point: Point, force: Float) {
explode(point.x().toFloat(), point.y().toFloat(), point.z().toFloat(), force)
}
fun Instance.useConstantLighting(light: Byte = 0xFF.toByte()) {
chunkSupplier = ConstantLightChunkSupplier(ByteArray(2048) { light })
}
fun Instance.useHarmlessExplosions() {
val emptyExplodedBlocks = mutableListOf<Point>()
setExplosionSupplier { x, y, z, st, _ ->
object : Explosion(x, y, z, st) {
override fun prepare(p0: Instance?) = emptyExplodedBlocks
}
}
}
private class ConstantLightChunkSupplier(private val sectionLighting: ByteArray): ChunkSupplier {
override fun createChunk(instance: Instance, x: Int, z: Int): Chunk =
ConstantLightChunk(sectionLighting, instance, x, z)
}
private class ConstantLightChunk(
private val sectionLighting: ByteArray,
instance: Instance,
x: Int,
z: Int
) : LightingChunk(instance, x, z) {
override fun createLightData(): LightData {
val skyMask = BitSet()
val blockMask = BitSet()
val emptySkyMask = BitSet()
val emptyBlockMask = BitSet()
val skyLights: MutableList<ByteArray> = ArrayList<ByteArray>()
val blockLights: MutableList<ByteArray> = ArrayList<ByteArray>()
for (i in 1..sections.size) {
skyMask.set(i)
emptyBlockMask.set(i)
skyLights.add(sectionLighting)
}
return LightData(skyMask, blockMask, emptySkyMask, emptyBlockMask, skyLights, blockLights)
}
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/extensions/minestom/InstanceExtensions.kt | 169884842 |
package ru.reosfire.minestom.utils.extensions.minestom
import net.minestom.server.coordinate.Pos
infix fun Pos.addX(addition: Int) = Pos(x + addition, y, z)
infix fun Pos.addY(addition: Int) = Pos(x, y + addition, z)
infix fun Pos.addZ(addition: Int) = Pos(x, y, z + addition)
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/extensions/minestom/PointExtensions.kt | 2128039504 |
package ru.reosfire.minestom.utils
import java.util.concurrent.ThreadLocalRandom
class Array3d<T>(private val data: Array<Array<Array<T>>>) {
val size: Size3d
get() = Size3d(data.size, data.first().size, data.first().first().size)
val indices: Iterable<Index3d> = object : Iterable<Index3d> {
override fun iterator() = Index3dRegionIterator(size)
}
fun getSlice(layer: Int, plane: Plane) = Slice2d(data, layer, plane)
fun get(x: Int, y: Int, z: Int): T {
return data[x][y][z]
}
fun set(x: Int, y: Int, z: Int, value: T) {
data[x][y][z] = value
}
operator fun get(at: Index3d): T {
return data[at.x][at.y][at.z]
}
operator fun set(at: Index3d, value: T) {
data[at.x][at.y][at.z] = value
}
}
class Slice2d<T>(private val data: Array<Array<Array<T>>>, private val layer: Int, private val plane: Plane) {
fun get(x: Int, y: Int): T {
return when (plane) {
Plane.YZ -> data[layer][x][y]
Plane.XZ -> data[x][layer][y]
Plane.XY -> data[x][y][layer]
}
}
fun set(x: Int, y: Int, value: T) {
when (plane) {
Plane.YZ -> data[layer][x][y] = value
Plane.XZ -> data[x][layer][y] = value
Plane.XY -> data[x][y][layer] = value
}
}
operator fun get(at: Index2d): T {
return get(at.x, at.y)
}
operator fun set(at: Index2d, value: T) {
set(at.x, at.y, value)
}
}
enum class Plane {
YZ,
XZ,
XY,
}
private class Index3dRegionIterator(private val size: Size3d) : Iterator<Index3d> {
private val bound = size.volume - 1
private var current: Int = -1
override fun hasNext() = current < bound
override fun next(): Index3d {
current++
return current.toIndex3d(size)
}
}
inline fun <reified T> array3dOf(size: Size3d, init: () -> T) =
Array3d(Array(size.width) { Array(size.height) { Array(size.depth) { init() } } })
data class Size3d(
val width: Int,
val height: Int,
val depth: Int
) {
val volume: Int
get() = width * height * depth
operator fun contains(index: Index3d): Boolean {
return index.x in 0..<width && index.y in 0..<height && index.z in 0..<depth
}
fun projection(plane: Plane): Size2d {
return when (plane) {
Plane.YZ -> Size2d(height, depth)
Plane.XZ -> Size2d(width, depth)
Plane.XY -> Size2d(width, height)
}
}
}
data class Size2d(
val width: Int,
val height: Int
) {
val area: Int
get() = width * height
operator fun contains(index: Index3d): Boolean {
return index.x in 0..<width && index.y in 0..<height
}
}
data class Index3d(
val x: Int,
val y: Int,
val z: Int
) {
fun projection(plane: Plane): Index2d {
return when (plane) {
Plane.YZ -> Index2d(y, z)
Plane.XZ -> Index2d(x, z)
Plane.XY -> Index2d(x, y)
}
}
fun getIndependent(plane: Plane) = when(plane) {
Plane.YZ -> x
Plane.XZ -> y
Plane.XY -> z
}
fun layInSamePlane(other: Index3d): Boolean {
return x == other.x || y == other.y || z == other.z
}
companion object {
fun random(bound: Size3d) = Index3d(
ThreadLocalRandom.current().nextInt(bound.width),
ThreadLocalRandom.current().nextInt(bound.height),
ThreadLocalRandom.current().nextInt(bound.depth)
)
}
}
data class Index2d(
val x: Int,
val y: Int
) {
fun mooreNeighboursIn(size: Size2d) = sequence {
for (i in x - 1..x + 1) {
if (i < 0 || i >= size.width) continue
for (j in y - 1..y + 1) {
if (j < 0 || j >= size.height) continue
yield(Index2d(i, j))
}
}
}
fun to3d(plane: Plane, level: Int) = when(plane) {
Plane.YZ -> Index3d(level, x, y)
Plane.XZ -> Index3d(x, level, y)
Plane.XY -> Index3d(x, y, level)
}
}
fun Int.toIndex3d(size: Size3d) = Index3d(
z = this / size.width / size.height,
y = (this / size.width) % size.height,
x = (this % size.width) % size.height,
)
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/Arrays.kt | 2001116008 |
package ru.reosfire.minestom.utils
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import net.kyori.adventure.resource.ResourcePackInfo
import net.minestom.server.MinecraftServer
import net.minestom.server.event.EventListener
import net.minestom.server.event.EventNode
import net.minestom.server.event.player.AsyncPlayerConfigurationEvent
import ru.reosfire.minestom.IP
import java.io.InputStream
import java.net.URI
import java.security.MessageDigest
import java.util.*
fun applyResourcePackPrompting(
endpointRoute: String = "resource_pack.zip",
resourcePath: String = "/resource_pack.zip",
) {
val port = 25500
createWebApp(
ip = IP,
port = port,
endpointRoute = endpointRoute,
resourcePath = resourcePath
)
RPPromptEventsHandler(
rpUri = "http://$IP:$port/$endpointRoute",
resourcePath = resourcePath,
)
MinecraftServer.getGlobalEventHandler().addChild(
EventNode
.all("rp prompting node")
.addListener(
RPPromptEventsHandler(
rpUri = "http://$IP:$port/$endpointRoute",
resourcePath = resourcePath,
)
)
)
}
private class RPPromptEventsHandler(
private val rpUri: String,
private val resourcePath: String
): EventListener<AsyncPlayerConfigurationEvent> {
val hash = calculateHash()
private fun calculateHash(): ByteArray {
val digest = MessageDigest.getInstance("SHA-1")
javaClass.getResourceAsStream(resourcePath)!!.use {
digest.update(javaClass.getResourceAsStream(resourcePath)!!)
}
return digest.digest()
}
override fun eventType(): Class<AsyncPlayerConfigurationEvent> = AsyncPlayerConfigurationEvent::class.java
@OptIn(ExperimentalStdlibApi::class)
override fun run(event: AsyncPlayerConfigurationEvent): EventListener.Result {
event.player.sendResourcePacks(
ResourcePackInfo.resourcePackInfo(UUID.randomUUID(), URI.create(rpUri), hash.toHexString()))
return EventListener.Result.SUCCESS
}
}
private fun MessageDigest.update(stream: InputStream, bufferSize: Int = 1024) {
val buffer = ByteArray(bufferSize)
do {
val read = stream.read(buffer)
update(buffer, 0, read)
} while (read == bufferSize)
}
//Web server
private fun createWebApp(
port: Int,
ip: String,
endpointRoute: String,
resourcePath: String,
): ApplicationEngine {
return embeddedServer(
factory = Netty,
port = port,
host = ip
) {
configureRouting(
endpointRoute = endpointRoute,
resourcePath = resourcePath,
)
}.start(wait = false)
}
private fun Application.configureRouting(
endpointRoute: String,
resourcePath: String,
) {
routing {
get("/$endpointRoute") {
call.respondOutputStream {
javaClass.getResourceAsStream(resourcePath)?.copyTo(this)
}
}
}
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/utils/ResourcePackPrompt.kt | 1034112533 |
package ru.reosfire.minestom.minesweper
sealed interface GameCell {
data class Opened(val yz: Int, val xz: Int, val xy: Int) : GameCell
data object Closed : GameCell
data object Flag : GameCell
} | 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/minesweper/GameCell.kt | 353577268 |
package ru.reosfire.minestom.minesweper
import ru.reosfire.minestom.utils.Size3d
data class GameSettings(
val size: Size3d,
val minesCount: Int
) {
companion object {
val DEFAULT = GameSettings(Size3d(4, 5, 6), 30)
}
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/minesweper/GameSettings.kt | 3380203836 |
package ru.reosfire.minestom.minesweper.presentation
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.runBlocking
import net.kyori.adventure.audience.Audience
import net.kyori.adventure.text.Component
import net.kyori.adventure.title.Title
import net.minestom.server.coordinate.Point
import net.minestom.server.coordinate.Pos
import net.minestom.server.entity.Player
import net.minestom.server.event.EventNode
import net.minestom.server.event.player.PlayerBlockBreakEvent
import net.minestom.server.event.player.PlayerBlockInteractEvent
import net.minestom.server.instance.Instance
import net.minestom.server.instance.block.Block
import net.minestom.server.instance.block.BlockFace
import net.minestom.server.network.packet.server.ServerPacket
import ru.reosfire.minestom.minesweper.GameCell
import ru.reosfire.minestom.utils.Index3d
import ru.reosfire.minestom.utils.NumberRenderer
import ru.reosfire.minestom.utils.Size3d
import ru.reosfire.minestom.utils.extensions.minestom.*
import java.time.Duration
const val cellSize = 3
const val yShift = 0
class InstanceGamePresenter(
private val instance: Instance,
private val players: List<Player>,
private val size: Size3d,
) : GamePresenter {
override val openEventFlow: Flow<Index3d>
get() = _openEventFlow
override val flagEventFlow: Flow<Index3d>
get() = _flagEventFlow
private val _openEventFlow = MutableSharedFlow<Index3d>(extraBufferCapacity = 10)
private val _flagEventFlow = MutableSharedFlow<Index3d>(extraBufferCapacity = 10)
private val numbersRenderer = NumberRenderer()
private val playersIds = players.map { it.uuid }.toSet()
override suspend fun renderCell(cell: GameCell, at: Index3d) {
val location = at.toPoint()
when (cell) {
GameCell.Closed -> location.setStone()
GameCell.Flag -> location.setRedstone()
is GameCell.Opened -> {
if (cell.yz == 0 && cell.xy == 0 && cell.xz == 0) {
location.setAir()
} else {
location.setWool()
numbersRenderer.renderNumber(location addX 1, BlockFace.EAST, cell.yz).send()
numbersRenderer.renderNumber(location addX -1, BlockFace.WEST, cell.yz).send()
numbersRenderer.renderNumber(location addZ 1, BlockFace.SOUTH, cell.xy).send()
numbersRenderer.renderNumber(location addZ -1, BlockFace.NORTH, cell.xy).send()
numbersRenderer.renderNumber(location addY 1, BlockFace.TOP, cell.xz).send()
numbersRenderer.renderNumber(location addY -1, BlockFace.BOTTOM, cell.xz).send()
}
}
}
}
override suspend fun clear() {
val clearNumbersPackets = numbersRenderer.clearNumbers()
clearNumbersPackets.send()
}
override suspend fun showWin(at: Index3d) {
for (player in players) {
player.showTitle(
Title.title(
Component.text("Win!!"),
Component.text("Not bruh"),
Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(1), Duration.ofSeconds(1))
)
)
}
}
override suspend fun showLoose(at: Index3d) {
for (player in players) {
player.showTitle(
Title.title(
Component.text("Lose!!"),
Component.text("Bruh"),
Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(1), Duration.ofSeconds(1))
)
)
}
instance.explode(at.toPoint(), 10f)
}
override fun showMinesFlagsCount(mines: Int, flags: Int) {
Audience.audience(players).sendActionBar(Component.text("flags/mines $flags/$mines"))
}
val eventNode = EventNode.all("presenter events")
.addListener<PlayerBlockBreakEvent> {
println("block break")
if (it.player.uuid !in playersIds) return@addListener
val clickedPoint = it.blockPosition.toIndex3d()
if (clickedPoint !in size) return@addListener
runBlocking {
_openEventFlow.emit(clickedPoint)
}
it.isCancelled = true
}
.addListener<PlayerBlockInteractEvent> {
println("interact")
if (it.player.uuid !in playersIds) return@addListener
val clickedPoint = it.blockPosition.toIndex3d()
if (clickedPoint !in size) return@addListener
if (System.currentTimeMillis() - lastRClick < 100) return@addListener
runBlocking {
_flagEventFlow.emit(clickedPoint)
}
lastRClick = System.currentTimeMillis()
it.isCancelled = true
}
private var lastRClick = 0L
private fun List<ServerPacket>.send() {
for (packetContainer in this@send) {
packetContainer.send()
}
}
private fun ServerPacket.send() {
for (player in players) {
player.playerConnection.sendPacket(this)
}
}
private fun Point.setAir() {
set(Block.AIR)
}
private fun Point.setStone() {
set(Block.STONE)
}
private fun Point.setWool() {
set(Block.WHITE_WOOL)
}
private fun Point.setRedstone() {
set(Block.REDSTONE_BLOCK)
}
private fun Point.set(block: Block) {
instance.setBlock(this, block)
}
private fun Point.toIndex3d() = Index3d(
(x() / cellSize).toInt(),
((y() - yShift) / cellSize).toInt(),
(z() / cellSize).toInt(),
)
private fun Index3d.toPoint() = Pos(
x * cellSize.toDouble(),
y * cellSize.toDouble() + yShift,
z * cellSize.toDouble(),
)
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/minesweper/presentation/InstanceGamePresenter.kt | 2593507636 |
package ru.reosfire.minestom.minesweper.presentation
import kotlinx.coroutines.flow.Flow
import ru.reosfire.minestom.minesweper.GameCell
import ru.reosfire.minestom.utils.Index3d
interface GamePresenter {
val openEventFlow: Flow<Index3d>
val flagEventFlow: Flow<Index3d>
suspend fun renderCell(cell: GameCell, at: Index3d)
suspend fun clear()
suspend fun showWin(at: Index3d)
suspend fun showLoose(at: Index3d)
fun showMinesFlagsCount(mines: Int, flags: Int)
//fun showCount(count: Int)
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/minesweper/presentation/GamePresenter.kt | 3865825367 |
package ru.reosfire.minestom.minesweper
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import ru.reosfire.minestom.minesweper.presentation.GamePresenter
import ru.reosfire.minestom.utils.*
class Game(
private val presenter: GamePresenter,
private val settings: GameSettings = GameSettings.DEFAULT,
) {
private val size: Size3d
get() = settings.size
private var mines: Array3d<Boolean>? = null
private var field: Array3d<GameCell> = createEmptyField()
private val scope = CoroutineScope(Dispatchers.Default)
init {
scope.launch {
launch {
presenter.flagEventFlow.collect {
flag(it)
}
}
launch {
presenter.openEventFlow.collect {
open(it)
}
}
renderField()
}
}
private suspend fun open(at: Index3d) {
if (field[at] !is GameCell.Closed) return
if (mines == null) mines = generateMines(at)
if (mines!![at]) {
presenter.showLoose(at)
regenerate()
return
}
openRecursively(at)
recount(at)
}
private suspend fun flag(at: Index3d) {
when (field[at]) {
is GameCell.Flag -> field[at] = GameCell.Closed
is GameCell.Closed -> field[at] = GameCell.Flag
else -> return
}
presenter.renderCell(field[at], at)
recount(at)
}
private fun generateMines(initialPoint: Index3d): Array3d<Boolean> {
val result = array3dOf(size) { false }
var generated = 0
while (generated < settings.minesCount) {
val randomPoint3d = Index3d.random(size)
if (result[randomPoint3d] || randomPoint3d == initialPoint) continue
result[randomPoint3d] = true
generated++
}
return result
}
private suspend fun openRecursively(
current: Index3d,
initialPoint: Index3d = current,
awaitRender: Boolean = true
): List<Job> {
if (field[current] is GameCell.Opened) return emptyList()
val yz = getCountAround(current, Plane.YZ)
val xz = getCountAround(current, Plane.XZ)
val xy = getCountAround(current, Plane.XY)
val cell = GameCell.Opened(yz, xz, xy)
field[current] = cell
val renderJobsMutex = Mutex()
val renderJobs = mutableListOf(scope.launch {
presenter.renderCell(cell, current)
})
val recursiveJobs = mutableListOf<Job>()
fun travers(plane: Plane) {
for (neighbour in current.projection(plane).mooreNeighboursIn(size.projection(plane))) {
val next = neighbour.to3d(plane, current.getIndependent(plane))
if (next.layInSamePlane(initialPoint)) {
recursiveJobs.add(scope.launch {
val renderJobsToAdd = openRecursively(next, initialPoint, false)
renderJobsMutex.withLock {
renderJobs.addAll(renderJobsToAdd)
}
})
}
}
}
if (yz == 0) travers(Plane.YZ)
if (xz == 0) travers(Plane.XZ)
if (xy == 0) travers(Plane.XY)
recursiveJobs.joinAll()
return if (awaitRender) {
renderJobs.joinAll()
emptyList()
} else renderJobs
}
private fun getCountAround(point: Index3d, plane: Plane): Int {
val slice = mines!!.getSlice(point.getIndependent(plane), plane)
val neighbours = point.projection(plane).mooreNeighboursIn(settings.size.projection(plane))
return neighbours.count { slice[it] }
}
private suspend fun recount(at: Index3d) {
var closed = 0
for (i in field.indices) {
if (field[i] !is GameCell.Opened) closed++
}
if (closed == settings.minesCount) {
presenter.showWin(at)
mines = null
regenerate()
}
var flags = 0
for (i in field.indices) {
if (field[i] is GameCell.Flag) flags++
}
presenter.showMinesFlagsCount(settings.minesCount, flags)
println("flags $flags/${settings.minesCount} $closed")
}
private suspend fun regenerate() {
mines = null
field = createEmptyField()
presenter.clear()
renderField()
}
private suspend fun renderField() {
field.indices.map {
scope.launch {
presenter.renderCell(field[it], it)
}
}.joinAll()
}
private fun createEmptyField(): Array3d<GameCell> = array3dOf(settings.size) { GameCell.Closed }
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/minesweper/Game.kt | 3402723127 |
package ru.reosfire.minestom
import net.minestom.server.MinecraftServer
import net.minestom.server.entity.GameMode
import net.minestom.server.event.EventNode
import net.minestom.server.event.player.AsyncPlayerConfigurationEvent
import net.minestom.server.event.player.PlayerSpawnEvent
import net.minestom.server.instance.Instance
import net.minestom.server.world.DimensionType
import ru.reosfire.minestom.utils.applyResourcePackPrompting
import ru.reosfire.minestom.minesweper.Game
import ru.reosfire.minestom.minesweper.GameSettings
import ru.reosfire.minestom.minesweper.presentation.InstanceGamePresenter
import ru.reosfire.minestom.utils.extensions.minestom.addListener
import ru.reosfire.minestom.utils.extensions.minestom.useConstantLighting
import ru.reosfire.minestom.utils.extensions.minestom.useHarmlessExplosions
const val IP = "127.0.0.1"
private object Router {
private val instanceManager = MinecraftServer.getInstanceManager()
private fun createGameInstance(): Instance {
return instanceManager.createInstanceContainer(DimensionType.OVERWORLD).apply {
useConstantLighting()
useHarmlessExplosions()
}
}
val PLAYERS_ROUTER_NODE = EventNode.all("routing node")
.addListener<AsyncPlayerConfigurationEvent> { event ->
val instance = createGameInstance()
event.spawningInstance = instance
val presenter = InstanceGamePresenter(
instance = instance,
players = listOf(event.player),
size = GameSettings.DEFAULT.size,
)
MinecraftServer.getGlobalEventHandler().addChild(presenter.eventNode)
Game(presenter)
}
.addListener<PlayerSpawnEvent> { event ->
with(event.player) {
gameMode = GameMode.CREATIVE
permissionLevel = 4
isFlying = true
}
}
}
fun main() {
val minecraftServer = MinecraftServer.init()
MinecraftServer.getGlobalEventHandler().addChild(Router.PLAYERS_ROUTER_NODE)
applyResourcePackPrompting()
minecraftServer.start(IP, 25565)
}
| 3dMinesweeper/src/main/kotlin/ru/reosfire/minestom/Main.kt | 3258050345 |
package com.example.learnnavcomponentjc
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.learnnavcomponentjc", appContext.packageName)
}
} | LearnNavComponentJC/app/src/androidTest/java/com/example/learnnavcomponentjc/ExampleInstrumentedTest.kt | 819687865 |
package com.example.learnnavcomponentjc
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)
}
} | LearnNavComponentJC/app/src/test/java/com/example/learnnavcomponentjc/ExampleUnitTest.kt | 346403658 |
package com.example.learnnavcomponentjc.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) | LearnNavComponentJC/app/src/main/java/com/example/learnnavcomponentjc/ui/theme/Color.kt | 582031044 |
package com.example.learnnavcomponentjc.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 LearnNavComponentJCTheme(
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
)
} | LearnNavComponentJC/app/src/main/java/com/example/learnnavcomponentjc/ui/theme/Theme.kt | 285436412 |
package com.example.learnnavcomponentjc.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
)
*/
) | LearnNavComponentJC/app/src/main/java/com/example/learnnavcomponentjc/ui/theme/Type.kt | 781134747 |
package com.example.learnnavcomponentjc
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.material3.Button
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.sp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.learnnavcomponentjc.ui.theme.LearnNavComponentJCTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LearnNavComponentJCTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DisplayNavComponent()
}
}
}
}
}
@Composable
fun DisplayNavComponent(){
val navController= rememberNavController()
//существует 2 способа использование навигационного компонента:
//1. Через ключевые слова
//2. Через закрытый класс
//в коде ниже используется 1-й способ
// NavHost(navController = navController, startDestination = "MainScreen"){
// composable("MainScreen"){
// MainScreen(navController=navController)
// }
// composable("HomeScreen"){
// HomeScreen(navController=navController)
// }
// }
//а теперь 2-ой
NavHost(navController = navController, startDestination = Destinations.MainScreen.toString()){
composable(route=Destinations.MainScreen.toString()){
MainScreen(navController=navController)
}
composable(route=Destinations.HomeScreen.toString()){
HomeScreen(navController=navController)
}
}
}
@Composable
fun MainScreen(navController: NavController){
Column(verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Main Screen", fontSize = 30.sp)
Button(onClick = { navController.navigate(Destinations.HomeScreen.toString())}) {
Text(text = "Go to Home Screen")
}
}
}
@Preview
@Composable
fun Preview(){
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DisplayNavComponent()
}
}
| LearnNavComponentJC/app/src/main/java/com/example/learnnavcomponentjc/MainActivity.kt | 625880326 |
package com.example.learnnavcomponentjc
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
@Composable
fun HomeScreen(navController: NavController){
Column(verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Home Screen", fontSize = 30.sp)
Button(onClick = { navController.popBackStack(Destinations.MainScreen.toString(), inclusive = false) }) {
Text(text = "Go to Main Screen")
}
}
} | LearnNavComponentJC/app/src/main/java/com/example/learnnavcomponentjc/HomeScreen.kt | 490769481 |
package com.example.learnnavcomponentjc
sealed class Destinations (val route:String){
data object MainScreen:Destinations("MainScreen")
data object HomeScreen:Destinations("HomeScreen")
} | LearnNavComponentJC/app/src/main/java/com/example/learnnavcomponentjc/Destinations.kt | 434903743 |
package com.example.myageassignment1
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.myageassignment1", appContext.packageName)
}
} | MyAgeAssignment1/app/src/androidTest/java/com/example/myageassignment1/ExampleInstrumentedTest.kt | 2583620627 |
package com.example.myageassignment1
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)
}
} | MyAgeAssignment1/app/src/test/java/com/example/myageassignment1/ExampleUnitTest.kt | 3645100687 |
package com.example.myageassignment1
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
/* name of celebrities that have passed on. this array links to the ages below.*/
private var infOfDeadPeople = arrayOf(
"Cameron Boyce, A Disney star who was well-known for staring in projects like Jessie, Descendants and Juby Moody the Bummer Summer. He passed away due to a Epileptic seizure.",
"Glen Quinn, An Irish Actor that appeared on numerous projects in the 90s. He passed away due to drug overdose in late 2002.",
"Virgil Abloh, famed fashion designer and Louis Vuitton artistic director. Passed away due to a rare cancer he'd been battling in private for several years.",
"Kirshnik Khari Ball aka Takeoff, was murdered in a fatal shooting in Texas in late 2022.",
"Chadwick Boseman, he was a in Marvels Black Panther. He passed away in 2020 due to colon cancer.",
"Aaliyah,Groundbreaking R&B singer. An airplane crashed in the Bahamas and killed 9 other passengers.",
"Luke Perry, Beverly Hills actor. unexpectedly died due to a stroke.",
"Frederik Willem de Klerk, He was a South African politician. He due to Mestheliom.",
"Pablo Escobar, He was a Colombian drug lord, narcoterrorist and politician. He was the founder and sole leader of the Medellin Cartel.",
"Theodore Roosevelt, the 26th president os the United states. he died in his sleep.",
/* (Ballhau L, 2023)
* https://www.sheknows.com
* Module Manual IMAD page 79*/
)
/* the ages of when the celebrities passed on. linked to the array above. Module Manual IMAD page 79 */
private var ages = arrayOf(
20,
32,
41,
28,
43,
22,
53,
85,
44,
61,
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* declaration of buttons Module Manual IMAD page 67*/
val btnClear = findViewById<Button>(R.id.btnClear)
val btnGenerate = findViewById<Button>(R.id.btnGenerate)
/* declaration of the EditText and TextView module manual IMAD page 67*/
val txtAge = findViewById<EditText>(R.id.txtAge)
val txtHistory = findViewById<TextView>(R.id.txtHistory)
/* Generate Button Instructions, this is what the Button is supposed to do. module manual IMAD page 45 */
btnGenerate.setOnClickListener {
val enteredAge = txtAge.text.toString().toIntOrNull()
if (enteredAge in 20..100) /* check if the age range is between 20 and 100 */
if(enteredAge != null) {
val index = ages.indexOf(enteredAge)
if (index != -1 && index < infOfDeadPeople.size) {
val name = infOfDeadPeople[index]
txtHistory.text ="The person who died at the age $enteredAge, is $name."
} else {
txtHistory.text = "No person died at the age of $enteredAge."
}
}
/* Error Handling, if unknown value is entered you will have to enter a valid value. */
else {
txtHistory.text = "The age you've entered is invalid, Please enter ages between 20 and 100!!!"
}
}
/* Clear Button Instructions, instructed to clear any text that hase been entered. Module manual IMAD page 45 */
btnClear.setOnClickListener {
txtAge.text.clear()
txtHistory.text = ""
}
}
}
| MyAgeAssignment1/app/src/main/java/com/example/myageassignment1/MainActivity.kt | 1557338809 |
package com.eightbitstechnology.userroledrawer
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.eightbitstechnology.userroledrawer", appContext.packageName)
}
} | UserRoleDrawer/app/src/androidTest/java/com/eightbitstechnology/userroledrawer/ExampleInstrumentedTest.kt | 3844307879 |
package com.eightbitstechnology.userroledrawer
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)
}
} | UserRoleDrawer/app/src/test/java/com/eightbitstechnology/userroledrawer/ExampleUnitTest.kt | 1720075892 |
package com.eightbitstechnology.userroledrawer.ui.home
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.eightbitstechnology.userroledrawer.MyApp
import com.eightbitstechnology.userroledrawer.data.model.User
class HomeViewModel(application: Application) : AndroidViewModel(application) {
private val userDao = (application as MyApp).database.userDao()
suspend fun getUserByUsername(username: String): User? {
return userDao.getUserByUsername(username)
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/home/HomeViewModel.kt | 2748390072 |
package com.eightbitstechnology.userroledrawer.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.eightbitstechnology.userroledrawer.MainActivity
import com.eightbitstechnology.userroledrawer.R
import com.eightbitstechnology.userroledrawer.data.model.User
import com.eightbitstechnology.userroledrawer.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private val userViewModel: HomeViewModel by viewModels()
private var user: User? = null
private val userArgs: HomeFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View = FragmentHomeBinding.inflate(inflater, container, false).also { binding = it }.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
user = userArgs.loggedInUser
val welcome = getString(R.string.welcome) + user?.firstName
binding.username.text = welcome
updateUserRoleInActivity(user?.role ?: 0)
Toast.makeText(
requireContext(),
" wow ${user?.role ?: 0} now : ${user?.role}",
Toast.LENGTH_SHORT
).show()
binding.logout.setOnClickListener {
user = null
findNavController().navigate(
HomeFragmentDirections.actionHomeToLogin()
)
}
}
private fun updateUserRoleInActivity(userRole: Int) {
if (activity is MainActivity) {
(activity as MainActivity).updateMenuItemsBasedOnRole(userRole)
}
}
}
| UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/home/HomeFragment.kt | 1816638997 |
package com.eightbitstechnology.userroledrawer.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
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/gallery/GalleryViewModel.kt | 965400140 |
package com.eightbitstechnology.userroledrawer.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.eightbitstechnology.userroledrawer.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
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/gallery/GalleryFragment.kt | 3964924422 |
package com.eightbitstechnology.userroledrawer.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
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/slideshow/SlideshowViewModel.kt | 757323367 |
package com.eightbitstechnology.userroledrawer.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.eightbitstechnology.userroledrawer.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
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/slideshow/SlideshowFragment.kt | 2704630644 |
package com.eightbitstechnology.userroledrawer.ui.login
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.eightbitstechnology.userroledrawer.databinding.FragmentLoginBinding
import kotlinx.coroutines.launch
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private val loginViewModel: LoginViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View = FragmentLoginBinding.inflate(inflater, container, false).also { binding = it }.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val username = binding.username
val password = binding.password
val loginButton = binding.login
val loadingProgressBar = binding.loading
loginButton.setOnClickListener {
lifecycleScope.launch {
val user = loginViewModel.login(username.text.toString(), password.text.toString())
if (user != null) {
// Login successful, navigate to the main screen
findNavController().navigate(
LoginFragmentDirections.actionLoginToHome(loggedInUser = user)
)
} else {
// Display an error message
Toast.makeText(requireContext(), "$user", Toast.LENGTH_SHORT).show()
}
}
}
binding.register.setOnClickListener {
findNavController().navigate(
LoginFragmentDirections.actionLoginToRegister()
)
}
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/login/LoginFragment.kt | 221339592 |
package com.eightbitstechnology.userroledrawer.ui.login
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.eightbitstechnology.userroledrawer.MyApp
import com.eightbitstechnology.userroledrawer.data.model.User
class LoginViewModel(application: Application) : AndroidViewModel(application) {
private val userDao = (application as MyApp).database.userDao()
suspend fun register(user: User) {
userDao.insert(user)
}
suspend fun login(username: String, password: String): User? {
return userDao.login(username, password)
}
suspend fun getUserByUsername(username: String): User ?{
return userDao.getUserByUsername(username)
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/login/LoginViewModel.kt | 1039208704 |
package com.eightbitstechnology.userroledrawer.ui.login
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.eightbitstechnology.userroledrawer.data.model.User
import com.eightbitstechnology.userroledrawer.databinding.FragmentRegisterBinding
import kotlinx.coroutines.launch
class RegisterFragment : Fragment() {
private val loginViewModel: LoginViewModel by viewModels()
private lateinit var binding: FragmentRegisterBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View = FragmentRegisterBinding.inflate(inflater, container, false).also { binding = it }.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val username = binding.username
val password = binding.password
val firstName = binding.firstName
val otherName = binding.otherName
val loadingProgressBar = binding.loading
binding.btnSignUp.setOnClickListener {
lifecycleScope.launch {
val selectedRole: String = binding.spinnerRole.selectedItem.toString()
val newUser = User(
username = username.text.toString(),
password = password.text.toString(),
role = mapRoleStringToInt(selectedRole),
firstName = firstName.text.toString(),
otherName = otherName.text.toString()
)
val user = loginViewModel.register(newUser)
if (user != null) {
// Login successful, navigate to the main screen
findNavController().navigate(RegisterFragmentDirections.actionRegisterToLogin())
} else {
// Display an error message
Toast.makeText(requireContext(), "$user", Toast.LENGTH_SHORT).show()
}
}
}
}
private fun mapRoleStringToInt(role: String): Int {
return when (role) {
"User" -> 0
"Admin" -> 1
else -> 0 // Default to User role
}
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/ui/login/RegisterFragment.kt | 2220809934 |
package com.eightbitstechnology.userroledrawer
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.onNavDestinationSelected
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.eightbitstechnology.userroledrawer.databinding.ActivityMainBinding
import com.eightbitstechnology.userroledrawer.ui.home.HomeViewModel
import com.google.android.material.navigation.NavigationView
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
private lateinit var toolbar: Toolbar
private val userViewModel: HomeViewModel by viewModels()
lateinit var navView: NavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
toolbar = binding.appBarMain.toolbar
setSupportActionBar(toolbar)
val drawerLayout: DrawerLayout = binding.drawerLayout
navView = binding.navView
// Get the NavController
val navHost = supportFragmentManager.findFragmentById(R.id.navHost) as NavHostFragment
navController = navHost.navController
// 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, R.id.settingsFragment
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.loginFragment, R.id.registerFragment -> {
toolbar.visibility = View.GONE
// bottomNav.visibility = View.GONE
}
else -> {
toolbar.visibility = View.VISIBLE
// bottomNav.visibility = View.VISIBLE
}
}
}
}
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 onOptionsItemSelected(item: MenuItem): Boolean =
item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
override fun onSupportNavigateUp(): Boolean =
navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
fun updateMenuItemsBasedOnRole(userRole: Int) {
val menu = navView.menu
val menuItemIds = listOf(
R.id.nav_gallery,
R.id.settingsFragment,
)
menuItemIds.forEach { menuItemId ->
val menuItem = menu.findItem(menuItemId)
menuItem?.isVisible = userRole == 1 // Change 1 to the role ID for admin
}
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/MainActivity.kt | 3335083321 |
package com.eightbitstechnology.userroledrawer
import android.app.Application
import androidx.room.Room
import com.eightbitstechnology.userroledrawer.data.AppDatabase
class MyApp : Application() {
val database by lazy {
Room.databaseBuilder(this, AppDatabase::class.java, "my-database")
.fallbackToDestructiveMigration()
.build()
}
}
| UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/MyApp.kt | 3170089257 |
package com.eightbitstechnology.userroledrawer
import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
} | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/SettingsFragment.kt | 1931261174 |
package com.eightbitstechnology.userroledrawer.data
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.eightbitstechnology.userroledrawer.data.model.User
@Dao
interface UserDao {
@Insert
suspend fun insert(user: User):Long
@Query("SELECT * FROM users WHERE username = :username AND password = :password")
suspend fun login(username: String, password: String): User?
@Query("SELECT * FROM users WHERE username = :username")
suspend fun getUserByUsername(username: String): User?
}
| UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/data/UserDao.kt | 185702630 |
package com.eightbitstechnology.userroledrawer.data
import androidx.room.Database
import androidx.room.RoomDatabase
import com.eightbitstechnology.userroledrawer.data.model.User
@Database(
entities = [User::class], version = 5, exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
| UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/data/AppDatabase.kt | 1001752440 |
package com.eightbitstechnology.userroledrawer.data.model
import android.os.Parcelable
import androidx.annotation.Keep
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
@Keep
@Parcelize
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val userNumber: String = java.util.UUID.randomUUID().toString(),
val username: String,
val password: String,
val role: Int = 0,//user = 0 or admin = 1
val firstName: String,
val otherName: String,
) : Parcelable | UserRoleDrawer/app/src/main/java/com/eightbitstechnology/userroledrawer/data/model/User.kt | 3096210196 |
package com.example.fittracker
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.fittracker", appContext.packageName)
}
} | Fitness-Tracker/app/src/androidTest/java/com/example/fittracker/ExampleInstrumentedTest.kt | 4096313108 |
package com.example.fittracker
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)
}
} | Fitness-Tracker/app/src/test/java/com/example/fittracker/ExampleUnitTest.kt | 2186880119 |
package com.example.fittracker.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) | Fitness-Tracker/app/src/main/java/com/example/fittracker/ui/theme/Color.kt | 2404008365 |
package com.example.fittracker.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 FitTrackerTheme(
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
)
} | Fitness-Tracker/app/src/main/java/com/example/fittracker/ui/theme/Theme.kt | 3157325688 |
package com.example.fittracker.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
)
*/
) | Fitness-Tracker/app/src/main/java/com/example/fittracker/ui/theme/Type.kt | 2549161093 |
package com.example.fittracker
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.outlined.DateRange
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.fittracker.ui.theme.FitTrackerTheme
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.ResolverStyle
import java.util.Locale
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FitTrackerTheme {
MyApp();
}
}
}
}
data class NavItemState(
val title : String,
val selectedIcon : ImageVector,
val unselectedIcon : ImageVector
)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "UnrememberedMutableState")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyApp(modifier: Modifier = Modifier) {
val items = listOf(
NavItemState(
title = "Kalkulator BMI",
selectedIcon = Icons.Filled.Menu,
unselectedIcon = Icons.Outlined.Menu
),
NavItemState(
title = "Trening",
selectedIcon = Icons.Filled.Person,
unselectedIcon = Icons.Outlined.Person
),
NavItemState(
title = "Pomiary",
selectedIcon = Icons.Filled.DateRange,
unselectedIcon = Icons.Outlined.DateRange
)
)
var bottomNavState by mutableStateOf(0)
var currentDayOfWeek by mutableStateOf(getCurrentDayOfWeek())
var bodyHeight by remember { mutableStateOf("") }
var bodyWeight by remember { mutableStateOf("") }
var BMI by remember { mutableStateOf("") }
var weightChart by remember { mutableStateOf("") }
Scaffold (
modifier = modifier.fillMaxSize(),
bottomBar = {
NavigationBar (
containerColor = Color(0xFFC1F0F0)
) {
items.forEachIndexed { index, item ->
NavigationBarItem(selected = bottomNavState == index,
onClick = { bottomNavState = index },
icon = {
Icon(
imageVector =
if(bottomNavState == index)
item.selectedIcon
else
item.unselectedIcon
, contentDescription = item.title
)
},
label = {
Text(text = item.title)
},
colors = NavigationBarItemDefaults.colors(
selectedIconColor = Color(0xFF000000),
selectedTextColor = Color(0xFF000000),
indicatorColor = Color( 0xFF29A3A3)
)
)
}
}
}
) { contentPadding ->
Column(
modifier
.padding(top = contentPadding.calculateTopPadding())
.fillMaxSize(),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (items[bottomNavState].title == "Trening") {
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(color = Color(0xFFC1F0F0))
) {
Text(
text = "$currentDayOfWeek",
modifier = Modifier
.padding(top = 45.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold,
fontSize = 30.sp,
color = LocalContentColor.current
)
}
Text(
text = "Dzień treningu",
modifier = Modifier
.padding(top = 20.dp, bottom = 15.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color(0xFFC1F0F0),
thickness = 2.dp
)
Text(
text = "Twój zestaw ćwiczeń na \ndzień dzisiejszy:",
modifier = Modifier
.padding(top = 20.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(top = 20.dp)
.weight(0.5f),
verticalArrangement = Arrangement.spacedBy(25.dp)
) {
items(listOf("Ćwiczenie 1 \nOpis", "Ćwiczenie 2 \nOpis", "Ćwiczenie 3 \nOpis", "Ćwiczenie 4 \nOpis")) { item ->
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 32.dp, vertical = 5.dp)
.size(width = 300.dp, height = 70.dp)
.background(
color = Color(0xFFC1F0F0),
shape = RoundedCornerShape(16.dp)
)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = item,
fontSize = 18.sp,
color = LocalContentColor.current,
textAlign = TextAlign.Start
)
}
}
}
}
}
if (items[bottomNavState].title == "Kalkulator BMI") {
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(color = Color(0xFFC1F0F0))
) {
Text(
text = "Kalkulator BMI",
modifier = Modifier
.padding(top = 45.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold,
fontSize = 30.sp,
color = LocalContentColor.current
)
}
Text(
text = "Oblicz swoje zapotrzebowanie \nkaloryczne",
modifier = Modifier
.padding(top = 20.dp, bottom = 15.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color(0xFFC1F0F0),
thickness = 2.dp
)
Text(
text = "Wprowadź dane:",
modifier = Modifier
.padding(top = 20.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp)
.height(40.dp)
.background(color = Color(0xFFC1F0F0))
) {
Text(
text = "Wzrost w cm",
modifier = Modifier
.fillMaxWidth()
.padding(top = 5.dp),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
}
TextField(
modifier = Modifier
.padding(15.dp)
.size(width = 200.dp, height = 50.dp),
value = bodyWeight,
onValueChange = { newText -> bodyWeight = newText },
placeholder = { Text("Wprowadź...") }
)
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp)
.height(40.dp)
.background(color = Color(0xFFC1F0F0))
) {
Text(
text = "Masa ciała w kg",
modifier = Modifier
.fillMaxWidth()
.padding(top = 5.dp),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
}
TextField(
modifier = Modifier
.padding(15.dp)
.size(width = 200.dp, height = 50.dp),
value = bodyHeight,
onValueChange = { newText -> bodyHeight = newText },
placeholder = { Text("Wprowadź...") }
)
Button(
onClick = {
val height = bodyHeight.toFloatOrNull() ?: 0f
val weight = bodyWeight.toFloatOrNull() ?: 0f
val bmiValue = weight / height * height
BMI = "$bmiValue"
},
modifier = Modifier.padding(10.dp),
colors = ButtonDefaults.buttonColors(
contentColor = Color.Black,
containerColor = Color(0xFF29A3A3)
)
) {
Text(text = "Oblicz")
}
if (BMI.isNotBlank()) {
Text(
text = BMI,
modifier = Modifier.padding(16.dp)
)
}
}
if (items[bottomNavState].title == "Pomiary") {
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(color = Color(0xFFC1F0F0))
) {
Text(
text = "Pomiary",
modifier = Modifier
.padding(top = 45.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold,
fontSize = 30.sp,
color = LocalContentColor.current
)
}
Text(
text = "Wykres zmiany masy \nciała",
modifier = Modifier
.padding(top = 20.dp, bottom = 15.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
Divider(
modifier = Modifier.fillMaxWidth(),
color = Color(0xFFC1F0F0),
thickness = 2.dp
)
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp)
.height(40.dp)
.background(color = Color(0xFFC1F0F0))
) {
Text(
text = "Wprowadź masę ciała w kg:",
modifier = Modifier
.fillMaxWidth()
.padding(top = 5.dp),
textAlign = TextAlign.Center,
fontSize = 18.sp,
color = LocalContentColor.current
)
}
Spacer(modifier = Modifier.height(10.dp))
TextField(
modifier = Modifier
.padding(15.dp)
.size(width = 200.dp, height = 50.dp),
value = bodyWeight,
onValueChange = { newText -> bodyWeight = newText },
placeholder = { Text("Wprowadź...") }
)
Button(
onClick = {
val newWeightValue = bodyWeight.toFloatOrNull() ?: 0f
weightChart = "$newWeightValue"
},
modifier = Modifier.padding(10.dp),
colors = ButtonDefaults.buttonColors(
contentColor = Color.Black,
containerColor = Color(0xFF29A3A3)
)
) {
Text(text = "Dodaj")
}
if (BMI.isNotBlank()) {
Text(
text = BMI,
modifier = Modifier.padding(16.dp)
)
}
}
}
}
}
@Composable
fun getCurrentDayOfWeek(): String {
val currentDayOfWeek = LocalDate.now().format(DateTimeFormatter.ofPattern("EEEE", Locale("pl")))
val formattedCurrentDayOfWeek = currentDayOfWeek.replaceFirstChar {
if (it.isLowerCase())
it.titlecase(Locale.getDefault())
else
it.toString()
}
return formattedCurrentDayOfWeek;
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
FitTrackerTheme {
MyApp();
}
} | Fitness-Tracker/app/src/main/java/com/example/fittracker/MainActivity.kt | 1729708430 |
package com.example.kotlinbootcampodev2
class Odev2 {
//soru 1
fun kilometreyiMileCevir(km: Double): Double {
if (km > 0) {
return km * 0.621
} else {
return 0.0
}
}
//soru 2
fun dikdortgeninAlaniniHesapla(kenar1: Int, kenar2: Int) {
if (kenar1 > 0 && kenar2 > 0) {
println("Dikdörtgenin alanı : ${kenar1 * kenar2}")
} else {
println("Lütfen pozitif değer giriniz.")
}
}
//soru 3
fun faktoriyelHesapla(sayi: Int): Int {
if (sayi > 0) {
var faktoriyel = 1
for (i in sayi downTo 1) {
faktoriyel *= i
}
return faktoriyel
} else {
return 0
}
}
//soru 4
fun kacAdetEHarfiVar(kelime: String) {
var count = 0
kelime.onEach {
if (it == 'e') {
count++
}
}
println("$kelime kelimesinin içinde $count adet e harfi vardır.")
}
//soru 5
fun icAciHesapla(kenarSayisi: Int): Int {
if (kenarSayisi > 2) {
return (kenarSayisi - 2) * 180
} else {
return 0
}
}
//soru 6
fun maasHesapla(gun: Int): Int {
var maas = 0
var mesai = 0
if (gun * 8 > 150) {
mesai = ((gun * 8) - 150) * 80
maas = 150 * 40 + mesai
} else if (gun * 8 in 1..149){
maas = gun * 8 * 40
} else {
maas = 0
}
return maas
}
//soru 7
fun otoparkUcretiHesapla(sure: Int): Int {
var otoparkUcreti = 0
if (sure == 1) {
otoparkUcreti = 50
} else if (sure > 1) {
otoparkUcreti = ((sure - 1) * 10) + 50
} else {
otoparkUcreti = 0
}
return otoparkUcreti
}
}
| android-kotlin-bootcamp-odev2-functions/Odev2.kt | 2650638162 |
package com.example.kotlinbootcampodev2
fun main() {
val odev2 = Odev2()
//soru 1
val km = 50.0
val mil = odev2.kilometreyiMileCevir(km)
println("$km KM $mil mil'dir.")
//soru 2
odev2.dikdortgeninAlaniniHesapla(5, 10)
//soru 3
val sayi = 5
val faktoriyelSonuc = odev2.faktoriyelHesapla(sayi)
println("$sayi faktoriyelin sonucu : $faktoriyelSonuc")
//soru 4
val kelime = "Techcareer"
odev2.kacAdetEHarfiVar(kelime)
//soru 5
val kenarSayisi = 3
val icAci = odev2.icAciHesapla(kenarSayisi)
println("İç açı sonucu : $icAci")
//soru 6
val gun = 25
val maas = odev2.maasHesapla(gun)
println("$gun gün maaş sonucu : $maas")
//soru 7
val sure = 5
val otoparkUcreti = odev2.otoparkUcretiHesapla(sure)
println("$sure saatlik otopark ücreti : $otoparkUcreti")
} | android-kotlin-bootcamp-odev2-functions/Odev2Main.kt | 3210096288 |
package ru.glassnekeep
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
import ru.glassnekeep.plugins.*
class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
configureRouting()
}
client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("Hello World!", bodyAsText())
}
}
}
| ru.glassnekeep.parallel-mephi/src/test/kotlin/ru/glassnekeep/ApplicationTest.kt | 1442096569 |
package ru.glassnekeep.parallel
import kotlinx.coroutines.*
import java.util.concurrent.Executors
class CoroutinesConfig private constructor(
var default: CoroutineDispatcher = Dispatchers.Default,
var then: CoroutineDispatcher = Dispatchers.Default,
var every: CoroutineDispatcher = Dispatchers.Default,
var project: CoroutineDispatcher = Dispatchers.Default,
var join: CoroutineDispatcher = Dispatchers.Default,
var map: CoroutineDispatcher = Dispatchers.Default,
var all: CoroutineDispatcher = Dispatchers.Default,
var any: CoroutineDispatcher = Dispatchers.Default,
var flatMap: CoroutineDispatcher = Dispatchers.Default,
var fold: CoroutineDispatcher = Dispatchers.Default,
var rec: CoroutineDispatcher = Dispatchers.Default,
var zip: CoroutineDispatcher = Dispatchers.Default,
var unzip: CoroutineDispatcher = Dispatchers.Default
) {
companion object {
val scope = CoroutineScope(Dispatchers.IO)
val myDispatcher = Executors.newFixedThreadPool(10).asCoroutineDispatcher()
val DEFAULT = build {
// every = myDispatcher
// project = myDispatcher
// all = myDispatcher
// any = myDispatcher
// map = myDispatcher
// flatMap = myDispatcher
// fold = myDispatcher
// rec = myDispatcher
}
fun build(block: CoroutinesConfig.() -> Unit) = CoroutinesConfig().apply(block)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/parallel/CoroutinesConfig.kt | 3067469187 |
package ru.glassnekeep
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.runBlocking
import org.jetbrains.kotlin.com.google.common.math.IntMath.pow
import ru.glassnekeep.client.UIHolder
import ru.glassnekeep.dsl.core.expressions.Expression
import ru.glassnekeep.dsl.core.expressions.ExpressionList
import ru.glassnekeep.dsl.lists.values.ValuesList
import ru.glassnekeep.parallel.CoroutinesConfig
import ru.glassnekeep.plugins.configureRouting
fun main() {
embeddedServer(Netty, port = 8080, host = "127.0.0.1", module = Application::module)
.start(wait = true)
}
fun Application.module() {
configureRouting()
UIHolder(this).run()
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/Application.kt | 3569554179 |
package ru.glassnekeep.plugins
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.html.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.css.CssBuilder
import kotlinx.html.body
import kotlinx.html.head
import ru.glassnekeep.controllers.ExpressionController
suspend inline fun ApplicationCall.respondCss(builder: CssBuilder.() -> Unit) {
this.respondText(CssBuilder().apply(builder).toString(), ContentType.Text.CSS)
}
fun Application.configureRouting() {
val expController = ExpressionController(this)
routing {
get {
call.respondHtml(HttpStatusCode.OK) {
head {}
body {
text("Test screen")
}
}
}
post {
val result = expController.handleExpression(call)
call.respond(result)
}
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/plugins/Routing.kt | 2956564657 |
package ru.glassnekeep.plugins
import freemarker.cache.ClassTemplateLoader
import freemarker.core.HTMLOutputFormat
import io.ktor.server.application.*
import io.ktor.server.freemarker.*
fun Application.configureTemplating() {
install(FreeMarker) {
templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
outputFormat = HTMLOutputFormat.INSTANCE
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/plugins/Templating.kt | 33329542 |
package ru.glassnekeep.controllers
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.util.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.html.*
import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback
import ru.glassnekeep.dsl.core.expressions.Expression
import ru.glassnekeep.parallel.CoroutinesConfig
import javax.script.ScriptEngineManager
class ExpressionController(application: Application) : Controller(application) {
var count = 0
val loader = Thread.currentThread().contextClassLoader
val engine by lazy {
ScriptEngineManager(loader).getEngineByExtension("kts")
}
init {
setIdeaIoUseFallback()
}
suspend fun handleExpression(call: ApplicationCall) : String {
count++
val startTime = currentTimeMillis()
val expression = call.receiveParameters()
.getOrFail("entry")
.parseExpression()
val res = engine.eval(expression).toString()
val endTime = currentTimeMillis()
logInfo("For request #$count: time = ${endTime - startTime}")
return res
}
suspend fun handleExpression(expression: String) : String {
count++
val startTime = currentTimeMillis()
logInfo("For request #$count: startTime = $startTime")
val res = with(ScriptEngineManager().getEngineByExtension("kts")) {
val final = imports + "\n" + expression
eval(final)
} as Deferred<*>
val result = res.await()
val endTime = currentTimeMillis()
logInfo("For request #$count: time = ${endTime - startTime}")
return result
.toString()
.replace("[", "")
.replace("]", "")
}
private companion object {
const val EXPRESSION = "import ru.glassnekeep.dsl.core.expressions.Expression"
const val EXPRESSION_LIST = "import ru.glassnekeep.dsl.core.expressions.ExpressionList"
const val COROUTINES_CONFIG = "import ru.glassnekeep.parallel.CoroutinesConfig"
const val ASYNC = "import kotlinx.coroutines.async"
const val POW = "import org.jetbrains.kotlin.com.google.common.math.IntMath.pow"
const val VALUE_LIST = "import ru.glassnekeep.dsl.lists.values.ValuesList"
const val LIST = "import ru.glassnekeep.dsl.lists.values.ValueList"
val imports = listOf(EXPRESSION, EXPRESSION_LIST, COROUTINES_CONFIG, ASYNC, POW, VALUE_LIST, LIST)
.joinToString(separator = "\n")
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/controllers/ExpressionController.kt | 896174323 |
package ru.glassnekeep.controllers
fun String.parseExpression(): String {
return ParsingStrategy.parse(this)
}
sealed interface ParsingStrategy {
fun parse(expr: String): String {
return "CoroutinesConfig.scope.async {\n" +
expr.replace("Expression", "Expression(CoroutinesConfig.DEFAULT)") +
"\n}"
}
fun fit(expr: String): Boolean
companion object {
private val strategies = arrayListOf(SingleValueStrategy, MultipleValuesStrategy, ParseValueListStrategy)
fun parse(expr: String) = strategies
.first { it.fit(expr) }
.parse(expr)
}
}
private object SingleValueStrategy : ParsingStrategy {
override fun parse(expr: String): String {
return super.parse(expr)
.replace("[", "")
.replace("]", "")
}
override fun fit(expr: String) = expr.contains("Value\\(\\d+\\)".toRegex())
}
private object MultipleValuesStrategy : ParsingStrategy {
override fun fit(expr: String) = expr.contains("Value\\(\\d+,".toRegex())
}
private object ParseValueListStrategy : ParsingStrategy {
override fun parse(expr: String): String {
return "CoroutinesConfig.scope.async {\n" + expr
.replace("Expression", "ExpressionList(CoroutinesConfig.DEFAULT)")
.replace("Value(", "Value(ValueList(")
.replace("])", ")))")
.replace("[", "listOf(")
.replace("]", ")") +
"\n}"
}
override fun fit(expr: String) = expr.startsWith("Expression.Value([")
}
| ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/controllers/Parsing.kt | 4087271421 |
package ru.glassnekeep.controllers
import io.ktor.server.application.*
abstract class Controller(application: Application) {
private val logger = application.log
fun logError(message: String) {
logger.error(message)
}
fun logInfo(message: String) {
logger.info(message)
}
companion object {
const val errorMsg = "Unknown error occurred"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/controllers/Controller.kt | 346286781 |
package ru.glassnekeep.client
import io.ktor.server.application.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import ru.glassnekeep.controllers.ExpressionController
import ru.glassnekeep.controllers.parseExpression
import java.util.*
class UIHolder(application: Application) {
private val log = application.log
private val controller = ExpressionController(application)
fun run() {
while (true) {
log.info("Enter expression below:")
val text = scanner.nextLine()
scope.launch {
delay(5000)
log.info(controller.handleExpression(text.parseExpression()))
}
}
}
private companion object {
private val client = Client()
private val scanner = Scanner(System.`in`)
private val scope = CoroutineScope(Dispatchers.IO)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/client/UIHolder.kt | 1455126724 |
package ru.glassnekeep.client
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
class Client {
private val client = HttpClient(CIO) {
install(ContentNegotiation) {
json()
}
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.HEADERS
}
}
suspend fun sendExpression(expression: String): Int {
return client.runCatching {
get(BASIC_URL) {
contentType(ContentType.Application.Json)
setBody(expression)
}.body<Int>()
}.onFailure {
println("Expression sending error!")
throw it
}.getOrNull() ?: 0
}
private companion object {
const val BASIC_URL = "http://127.0.0.1:8080/"
const val URL = "http://10.0.2.2:8080/"
const val LOCAL_URL = "http://0.0.0.0:8080/"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/client/Client.kt | 890590184 |
package ru.glassnekeep.dsl.core.markers
@DslMarker
annotation class ExpressionDsl
| ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/markers/ExpressionDsl.kt | 2069426835 |
package ru.glassnekeep.dsl.core
import ru.glassnekeep.dsl.multiple.EveryTag
import ru.glassnekeep.dsl.multiple.JoinTag
import ru.glassnekeep.dsl.multiple.ProjectTag
import ru.glassnekeep.dsl.multiple.ThenTag
import ru.glassnekeep.dsl.multiple.values.Values
import kotlinx.coroutines.CoroutineScope
import ru.glassnekeep.parallel.CoroutinesConfig
abstract class MultipleElement(
private val parent: Element?,
config: CoroutinesConfig,
scope: CoroutineScope = DEFAULT_COROUTINE_SCOPE
) : Element(scope, parent, config) {
abstract suspend fun process(input: Array<Int>): List<Int>
final override suspend fun processElement(): List<Int> {
val res = parent?.processElement() ?: listOf(0)
return process(res.toTypedArray())
}
protected fun <T: Element> initTag(tag: T, vararg init: (T.(values: Array<Int>) -> Int)): T {
return tag
}
fun Then(block: (Values) -> Int) = initTag(ThenTag(block, this, config))
fun Every(vararg values: (Values) -> Int) = initTag(EveryTag(values, this, config))
fun Project(vararg values: (Int) -> Int?) = initTag(ProjectTag(values, this, config))
fun JoinValues(vararg values: Int) = initTag(JoinTag(values, this, config))
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/MultipleElement.kt | 4155989688 |
package ru.glassnekeep.dsl.core
import kotlinx.coroutines.*
import ru.glassnekeep.dsl.core.markers.ExpressionDsl
import ru.glassnekeep.dsl.lists.*
import ru.glassnekeep.parallel.CoroutinesConfig
@ExpressionDsl
abstract class ListElement(
private val parent: ListElement?,
protected val config: CoroutinesConfig,
protected val scope: CoroutineScope = DEFAULT_COROUTINE_SCOPE
) {
abstract val dispatcher: CoroutineDispatcher
private val children: ListElement? = null
abstract suspend fun process(input: List<List<Int>>): List<List<Int>>
suspend fun processElement(): List<List<Int>> {
return runAsync {
val res = children?.processElement() ?: listOf(listOf(0))
process(res)
}.await()
}
protected fun <T: ListElement> initTag(tag: T, vararg init: (T.(values: List<List<Int>>) -> List<Int>)) : T {
//parent?.children?.add(tag)
return tag
}
protected fun<T> runAsync(block: suspend () -> T): Deferred<T> = scope.async(dispatcher) { block.invoke() }
fun Map(block: (Int) -> Int) = initTag(MapTag(block, this, config))
fun All(block: (Int) -> Boolean) = initTag(AllTag(block, this, config))
fun Any(block: (Int) -> Boolean) = initTag(AnyTag(block, this, config))
fun FlatMap(block: (Int) -> Int) = initTag(FlatMapTag(block, this, config))
fun Fold(init: Int, block: (Int, Int) -> Int) = initTag(FoldTag(init, block, this, config))
fun Zip() = initTag(ZipTag(this, config))
fun Unzip() = initTag(UnzipTag(this, config))
protected companion object {
val DEFAULT_COROUTINE_SCOPE = CoroutineScope(Dispatchers.IO)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/ListElement.kt | 438467979 |
package ru.glassnekeep.dsl.core.expressions
import ru.glassnekeep.dsl.core.SingleElement
import ru.glassnekeep.dsl.multiple.values.ValueMany
import ru.glassnekeep.dsl.single.values.ValueSingle
import ru.glassnekeep.parallel.CoroutinesConfig
class Expression(config: CoroutinesConfig) : SingleElement(null, config) {
override val dispatcher = config.default
override fun process(input: Int): List<Int> {
return listOf(input)
}
fun Value(value: Int) = initTag(ValueSingle(value, this, config))
fun Value(vararg values: Int) = initTag(ValueMany(values, this, config))
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/expressions/Expression.kt | 4090415237 |
package ru.glassnekeep.dsl.core.expressions
import ru.glassnekeep.dsl.core.ListElement
import ru.glassnekeep.dsl.lists.values.ValueList
import ru.glassnekeep.dsl.lists.values.ValuesList
import ru.glassnekeep.parallel.CoroutinesConfig
class ExpressionList(config: CoroutinesConfig) : ListElement(null, config) {
override val dispatcher = config.default
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
return input
}
fun Value(values: ValuesList) = initTag(ValueList(values, this, config))
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/expressions/ExpressionList.kt | 3800830199 |
package ru.glassnekeep.dsl.core
import kotlinx.coroutines.*
import ru.glassnekeep.dsl.core.markers.ExpressionDsl
import ru.glassnekeep.parallel.CoroutinesConfig
@ExpressionDsl
abstract class Element(
protected val scope: CoroutineScope = DEFAULT_COROUTINE_SCOPE,
private val parent: Element?,
protected val config: CoroutinesConfig
) {
abstract val dispatcher: CoroutineDispatcher
internal var child: Element? = null
abstract suspend fun processElement(): List<Int>
protected fun<T> runAsync(block: suspend () -> T): Deferred<T> = scope.async(dispatcher) { block.invoke() }
protected companion object {
val DEFAULT_COROUTINE_SCOPE = CoroutineScope(Dispatchers.IO)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/Element.kt | 3459666039 |
package ru.glassnekeep.dsl.core
import ru.glassnekeep.dsl.single.RecurseTag
import ru.glassnekeep.dsl.single.clauses.IfClause
import ru.glassnekeep.dsl.single.clauses.SwitchClause
import kotlinx.coroutines.CoroutineScope
import ru.glassnekeep.dsl.single.Apply
import ru.glassnekeep.parallel.CoroutinesConfig
abstract class SingleElement(
private val parent: Element?,
config: CoroutinesConfig,
scope: CoroutineScope = DEFAULT_COROUTINE_SCOPE
) : Element(scope, parent, config) {
abstract fun process(input: Int): List<Int>
final override suspend fun processElement(): List<Int> {
val res = parent?.processElement()?.single() ?: 0
return process(res)
}
protected fun <T: Element> initTag(tag: T, init: (T.(value: Int) -> Int)? = null): T {
//parent?.child = tag
return tag
}
fun If(condition: (Int) -> Boolean, ) = initTag(IfClause(condition, this, config))
fun Swtich(block: (Int) -> Int) = initTag(SwitchClause(block, this, config))
fun Apply(block: (Int) -> Int) = initTag(Apply(block, this, config))
fun Recurse(block: (Int) -> Boolean) = initTag(RecurseTag(block, this, config))
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/core/SingleElement.kt | 2352319983 |
package ru.glassnekeep.dsl.multiple
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.MultipleElement
import ru.glassnekeep.parallel.CoroutinesConfig
import java.util.Collections.addAll
class JoinTag(
private val values: IntArray,
parent: Element,
config: CoroutinesConfig
) : MultipleElement(parent, config) {
override val dispatcher = config.join
override suspend fun process(input: Array<Int>): List<Int> {
return input.toMutableList().also { addAll(values.toMutableList()) }
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/multiple/JoinTag.kt | 4149212675 |
package ru.glassnekeep.dsl.multiple.values
data class Values(
val a: Int,
val b: Int = 0,
val c: Int = 0,
val d: Int = 0,
val e: Int = 0,
val f: Int = 0
) {
fun toList() = listOf(a, b, c, d, e, f).filter { it != 0 }
}
fun Array<Int>.toValues(): Values {
return when(this.size) {
1 -> Values(this[0])
2 -> Values(this[0], this[1])
3 -> Values(this[0], this[1], this[2])
4 -> Values(this[0], this[1], this[2], this[3])
5 -> Values(this[0], this[1], this[2], this[3], this[4])
6 -> Values(this[0], this[1], this[2], this[3], this[4], this[5])
else -> throw ImpossibleNumberOfArguments("Введено некорректное значение списков = ${this.size}")
}
}
fun List<Int>.toValues(): Values {
return when(this.size) {
1 -> Values(this[0])
2 -> Values(this[0], this[1])
3 -> Values(this[0], this[1], this[2])
4 -> Values(this[0], this[1], this[2], this[3])
5 -> Values(this[0], this[1], this[2], this[3], this[4])
6 -> Values(this[0], this[1], this[2], this[3], this[4], this[5])
else -> throw ImpossibleNumberOfArguments("Введено некорректное значение списков = ${this.size}")
}
}
class ImpossibleNumberOfArguments(msg: String) : Exception(msg)
| ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/multiple/values/Values.kt | 1876520316 |
package ru.glassnekeep.dsl.multiple.values
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.MultipleElement
import ru.glassnekeep.parallel.CoroutinesConfig
class ValueMany(
private val values: IntArray,
parent: Element,
config: CoroutinesConfig
) : MultipleElement(parent, config) {
override val dispatcher = config.default
override suspend fun process(input: Array<Int>): List<Int> {
return values.toList()
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/multiple/values/ValueMany.kt | 3501042847 |
package ru.glassnekeep.dsl.multiple
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.MultipleElement
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.dsl.multiple.values.Values
import ru.glassnekeep.dsl.multiple.values.toValues
import ru.glassnekeep.parallel.CoroutinesConfig
class ThenTag(
private val block: (Values) -> Int,
parent: Element,
config: CoroutinesConfig
) : MultipleElement(parent, config) {
override val dispatcher = config.then
override suspend fun process(input: Array<Int>): List<Int> {
return coroutineScope {
runAsync { block.invoke(input.toValues()) }
}.await().let(::listOf)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/multiple/ThenTag.kt | 3932361615 |
package ru.glassnekeep.dsl.multiple
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.MultipleElement
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.parallel.CoroutinesConfig
class ProjectTag(
private val blocks: Array<out (Int) -> Int?>,
parent: Element,
config: CoroutinesConfig
) : MultipleElement(parent, config) {
override val dispatcher = config.project
override suspend fun process(input: Array<Int>): List<Int> {
return coroutineScope {
blocks.mapIndexed { index, function ->
runAsync { function.invoke(input[index]) }
}.awaitAll().filterNotNull()
}
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/multiple/ProjectTag.kt | 3052167583 |
package ru.glassnekeep.dsl.multiple
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.MultipleElement
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.dsl.multiple.values.Values
import ru.glassnekeep.dsl.multiple.values.toValues
import ru.glassnekeep.parallel.CoroutinesConfig
class EveryTag(
private val blocks: Array<out (Values) -> Int>,
parent: Element,
config: CoroutinesConfig
) : MultipleElement(parent, config) {
override val dispatcher = config.every
override suspend fun process(input: Array<Int>): List<Int> {
return coroutineScope {
blocks.map { block ->
runAsync { block.invoke(input.toValues()) }
}.awaitAll()
}
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/multiple/EveryTag.kt | 1888877863 |
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import ru.glassnekeep.parallel.CoroutinesConfig
class UnzipTag(parent: ListElement, config: CoroutinesConfig) : ListElement(parent, config) {
override val dispatcher = config.unzip
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
if (input.any { it.size != 2 }) throw UnzipInconsistencyException(INVALID_SIZE_OF_LISTS)
return input
.map { list -> Pair(list[0], list[1]) }
.unzip()
.let { listOf(it.first, it.second) }
}
class UnzipInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val INVALID_SIZE_OF_LISTS = "Unzip called on number of lists with not all sizes equal to 2"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/UnzipTag.kt | 1185644569 |
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.dsl.multiple.values.Values
import ru.glassnekeep.dsl.multiple.values.toValues
import ru.glassnekeep.parallel.CoroutinesConfig
class AnyTag(
private val block: (Int) -> Boolean,
parent: ListElement,
config: CoroutinesConfig
) : ListElement(parent, config) {
override val dispatcher = config.any
private var thenBranch: ((Values) -> List<Int>)? = null
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
val thenBr = thenBranch ?: throw AnyClauseInconsistencyException(MISSING_THEN_BRANCH_ERROR_MSG)
val values = input.singleOrNull() ?: throw AnyClauseInconsistencyException(
MANY_LISTS_PASSED_AS_PARAMETERS_ERROR_MSG
)
return coroutineScope {
val fit = values.map { value ->
runAsync { block.invoke(value) }
}.awaitAll().any { it }
val res = if (fit) thenBr(values.toValues()) else values
listOf(res)
}
}
fun ThenDo(block: (Values) -> List<Int>) : ListElement {
thenBranch = block
return this
}
class AnyClauseInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val MISSING_THEN_BRANCH_ERROR_MSG = "Missing `Then` branch"
const val MANY_LISTS_PASSED_AS_PARAMETERS_ERROR_MSG = "More than one list passed to `Any` operation"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/AnyTag.kt | 2808119065 |
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.parallel.CoroutinesConfig
class FoldTag(
private val initValue: Int,
private val block: (Int, Int) -> Int,
parent: ListElement,
config: CoroutinesConfig
) : ListElement(parent, config) {
override val dispatcher = config.fold
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
val list = input.singleOrNull() ?: throw FoldClauseInconsistencyException(
MANY_LISTS_PASSED_AS_PARAMETERS_ERROR_MSG
)
return coroutineScope {
list.fold(runAsync {initValue}) { res, new ->
runAsync { block(res.await(), new) }
}.let { listOf(listOf(it.await())) }
}
}
class FoldClauseInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val MANY_LISTS_PASSED_AS_PARAMETERS_ERROR_MSG = "More than one list passed to `All` operation"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/FoldTag.kt | 3122823288 |
package ru.glassnekeep.dsl.lists.values
import ru.glassnekeep.dsl.core.ListElement
import ru.glassnekeep.parallel.CoroutinesConfig
class ValueList(
private val values: ValuesList,
parent: ListElement,
config: CoroutinesConfig
) : ListElement(parent, config) {
override val dispatcher = config.default
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
return values.toList()
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/values/ValueList.kt | 406398880 |
package ru.glassnekeep.dsl.lists.values
import ru.glassnekeep.dsl.multiple.values.ImpossibleNumberOfArguments
data class ValuesList(
val a: List<Int>,
val b: List<Int> = emptyList(),
val c: List<Int> = emptyList(),
val d: List<Int> = emptyList(),
val e: List<Int> = emptyList(),
val f: List<Int> = emptyList()
) {
fun toList() = listOf(a, b, c, d, e, f).filter { it.isNotEmpty() }
}
fun String.toValuesList(): ValuesList {
if (!startsWith('(') && !startsWith('[')) error(ARRAY_MARKDOWN_PARSING_ERROR)
if (!endsWith(')') && !endsWith(']')) error(ARRAY_MARKDOWN_PARSING_ERROR)
if (!contains(',')) error(ARRAY_MARKDOWN_PARSING_ERROR)
val list = split(", ").map { str ->
str
.removePrefix("(")
.removeSuffix(")")
.split(", ")
.map { it.toInt() }
}
return list.toValuesList()
}
fun List<List<Int>>.toValuesList(): ValuesList {
return when(size) {
1 -> ValuesList(get(0))
2 -> ValuesList(get(0), get(1))
3 -> ValuesList(get(0), get(1), get(2))
4 -> ValuesList(get(0), get(1), get(2), get(3))
5 -> ValuesList(get(0), get(1), get(2), get(3), get(4))
6 -> ValuesList(get(0), get(1), get(2), get(3), get(4), get(5))
else -> throw ImpossibleNumberOfArguments("Введено некорректное значение списков = ${size}")
}
}
const val ARRAY_MARKDOWN_PARSING_ERROR = "Ошибка ввода входного выражения" | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/values/ValuesList.kt | 4139643475 |
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.parallel.CoroutinesConfig
class FlatMapTag(
private val block: (Int) -> Int,
parent: ListElement,
config: CoroutinesConfig
) : ListElement(parent, config) {
override val dispatcher = config.flatMap
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
return coroutineScope {
input.flatMap { list ->
list.map {
runAsync { block(it) }
}.awaitAll()
}.let(::listOf)
}
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/FlatMapTag.kt | 1073312797 |
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import ru.glassnekeep.parallel.CoroutinesConfig
class ZipTag(parent: ListElement, config: CoroutinesConfig) : ListElement(parent, config) {
override val dispatcher = config.zip
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
if (input.size != 2) throw ZipInconsistencyException(INVALID_NUMBER_OF_LISTS)
return input[0].zip(input[1]).map { listOf(it.first, it.second) }
}
class ZipInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val INVALID_NUMBER_OF_LISTS = "Zip called on number of lists not equal to 2"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/ZipTag.kt | 2720613569 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.