path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/mars/co/liftmetrics/data/dao/ExerciseDao.kt
|
Veljko97
| 447,738,317
| false
|
{"Kotlin": 82806}
|
package com.mars.co.liftmetrics.data.dao
import androidx.room.*
import com.mars.co.liftmetrics.data.model.Exercise
import com.mars.co.liftmetrics.data.model.Muscle
import kotlinx.coroutines.flow.Flow
@Dao
interface ExerciseDao {
@Query("SELECT * FROM exercise")
fun getAll(): Flow<List<Exercise>>
// Muscles are a string in DB and it can be bigger the one muscle
// https://stackoverflow.com/a/60652893
@Transaction
@Query("SELECT * FROM exercise WHERE muscles LIKE '%' || :muscle || '%'")
fun getByMuscle(muscle: Muscle): Flow<List<Exercise>>
@Query("SELECT * FROM exercise WHERE uid IN (SELECT exerciseId FROM workout)")
suspend fun getUsedExercises(): List<Exercise>
@Insert
suspend fun insertAll(vararg items: Exercise)
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(exercise: Exercise)
companion object {
suspend fun initialData(dao: ExerciseDao) {
dao.insertAll(
Exercise(
muscles = setOf(Muscle.CHEST),
name = "exercise_name_barbell_bench_press",
description = "exercise_desc_barbell_bench_press",
videoLink = "https://www.youtube.com/watch?v=tuwHzzPdaGc&ab_channel=Muscle%26Strength"
),
Exercise(
muscles = setOf(Muscle.CHEST),
name = "exercise_name_standing_cable_fly",
description = "exercise_desc_standing_cable_fly",
videoLink = "https://www.youtube.com/watch?v=OPYrUGZL8nU&ab_channel=Muscle%26Strength"
),
Exercise(
muscles = setOf(Muscle.BICEPS),
name = "exercise_name_standing_cable_fly",
description = "exercise_desc_standing_cable_fly",
videoLink = "https://www.youtube.com/watch?v=UeleXjsE-98&ab_channel=Muscle%26Strength"
),
Exercise(
muscles = setOf(Muscle.BICEPS),
name = "exercise_name_dumbbell_hammer_preacher_curl",
description = "exercise_desc_dumbbell_hammer_preacher_curl",
videoLink = "https://www.youtube.com/watch?v=ZdcFOgFi1Dg&ab_channel=Muscle%26Strength"
),
Exercise(
muscles = setOf(Muscle.TRICEPS),
name = "exercise_name_ez_bar_skullcrusher",
description = "exercise_desc_ez_bar_skullcrusher",
videoLink = "https://www.youtube.com/watch?v=K6MSN4hCDM4&ab_channel=Muscle%26Strength"
),
Exercise(
muscles = setOf(Muscle.TRICEPS),
name = "exercise_name_rope_tricep_extension",
description = "exercise_desc_rope_tricep_extension",
videoLink = "https://www.youtube.com/watch?v=LzwgB15UdO8&ab_channel=Muscle%26Strength"
),
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f767fff4571999d0cc560679918b91a356b8e7e0
| 3,058
|
lift_metrics_public
|
Apache License 2.0
|
android-compose/src/main/kotlin/com/amarland/iconvector/androidcompose/IconVGResources.kt
|
amarland
| 433,039,075
| false
|
{"Kotlin": 113847, "Java": 7176}
|
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amarland.iconvector.androidcompose
import android.content.res.Resources
import android.util.Log
import androidx.annotation.RawRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import com.amarland.iconvector.lib.FormatException
import com.amarland.iconvector.lib.IconVGMachine
import com.amarland.iconvector.lib.toImageVector
import okio.buffer
import okio.source
@Composable
@ExperimentalUnsignedTypes
fun ImageVector.Companion.iconVGResource(
@RawRes id: Int,
palette: List<Color> = emptyList()
) = with(LocalContext.current) {
remember(id) {
loadIconVGResource(resources, id, palette)
}
}
@ExperimentalUnsignedTypes
@Throws(FormatException::class)
fun loadIconVGResource(
resources: Resources,
id: Int,
palette: List<Color> = emptyList()
): ImageVector =
resources.openRawResource(id)
.source().buffer()
.use { source ->
IconVGMachine(
source,
UIntArray(palette.size) { index -> palette[index].toArgb().toUInt() }
).intermediateRepresentation
.toImageVector { expectation ->
RadialGradient(
expectation.colors,
expectation.stops,
center = Offset.Zero,
radius = 1F,
expectation.tileMode,
expectation.matrix
)
}.also { imageVector: ImageVector ->
if (BuildConfig.DEBUG) {
Log.d("loadIconVGResource", imageVector.asString())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e05c63280dc922ce6bd3ea961c53ce1f9a415213
| 2,523
|
iconvector
|
Apache License 2.0
|
src/main/kotlin/strategies/FeeCalculationStrategy.kt
|
Dnyaneshwar-dev
| 616,314,996
| false
| null |
package strategies
import models.FeeInterval
import models.VehicleType
import utilities.DateTimeUtil
import java.time.LocalDateTime
import kotlin.math.min
open class FeeCalculationStrategy(private val intervals: Map<VehicleType, ArrayList<FeeInterval>>) {
open fun getBillAmount(startTime: LocalDateTime, endTime: LocalDateTime, vehicleType: VehicleType): Int {
var totalAmount = 0
val numberOfHours = DateTimeUtil.getNumberOfHoursBetween(startTime, endTime)
val chargeIntervals = intervals[vehicleType]
if (chargeIntervals != null) {
for (interval in chargeIntervals) {
if (interval.start > numberOfHours) {
break
}
val chargableHours = min(numberOfHours - interval.start , interval.end - interval.start)
totalAmount += (chargableHours * interval.charge)
}
} else {
throw Exception("Invalid Vehicle Type")
}
return totalAmount
}
}
| 0
|
Kotlin
|
0
| 0
|
7a1e929549d9674278315ec2b4fa85d29289178f
| 1,024
|
parking-lot-design-kotlin
|
Apache License 2.0
|
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/injection/OpenTelemetryModuleImplTest.kt
|
embrace-io
| 704,537,857
| false
|
{"Kotlin": 3067335, "C": 189946, "Java": 179438, "C++": 13140, "CMake": 4188}
|
package io.embrace.android.embracesdk.injection
import io.embrace.android.embracesdk.internal.logs.LogSinkImpl
import io.embrace.android.embracesdk.internal.spans.CurrentSessionSpanImpl
import io.embrace.android.embracesdk.internal.spans.EmbraceSpanService
import io.embrace.android.embracesdk.internal.spans.SpanSinkImpl
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
internal class OpenTelemetryModuleImplTest {
@Test
fun testInitModuleImplDefaults() {
val openTelemetryModule = OpenTelemetryModuleImpl(InitModuleImpl())
assertTrue(openTelemetryModule.spanSink is SpanSinkImpl)
assertTrue(openTelemetryModule.spanService is EmbraceSpanService)
assertTrue(openTelemetryModule.currentSessionSpan is CurrentSessionSpanImpl)
assertTrue(openTelemetryModule.logSink is LogSinkImpl)
assertNotNull(openTelemetryModule.logger)
}
}
| 20
|
Kotlin
|
7
| 130
|
ca3da94e2055251ec6b3afc35fc9a1fc1bb5f57d
| 934
|
embrace-android-sdk
|
Apache License 2.0
|
business-layer-abstract/src/main/java/ru/ar2code/business_layer_abstract/usecases/AbstractLoginUserCase.kt
|
ar2code
| 260,705,668
| false
| null |
package ru.ar2code.business_layer_abstract.usecases
import ru.ar2code.business_layer_abstract.models.LoginParameters
import ru.ar2code.business_layer_abstract.models.UserWithColor
import ru.ar2code.common.UseCase
abstract class AbstractLoginUserCase : UseCase<UserWithColor, LoginParameters>()
| 0
|
Kotlin
|
1
| 13
|
e95e53e8130d8137e04709d8053193625fe660c1
| 295
|
AndroidArchitectureSample
|
MIT License
|
src/main/kotlin/sam/st/demoredlist/RedListConsumer.kt
|
samuelstuetz
| 188,720,101
| false
| null |
package sam.st.demoredlist
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.client.exchange
import java.security.cert.CertPath
interface RedListConsumerDefinition {
val baseURI: String
fun reachAPI(): Version?
fun listCountries(): List<Country>
fun listRegions(): List<Region>
fun listSpecies(path: String, page: Int): List<Species>
fun listSpeciesByRegion(region: Region, page: Int): List<Species>
fun listConservationMeasure(id: Int): List<ConservationMeasure>
}
@Component
class RedListConsumer(templateBuilder: RestTemplateBuilder) : RedListConsumerDefinition {
final override val baseURI = "https://apiv3.iucnredlist.org/api/v3"
val restTemplate: RestTemplate = templateBuilder.rootUri(baseURI).build()
val token = "<KEY>"
override fun reachAPI(): Version? {
return restTemplate.getForObject("/version", Version::class.java)
}
override fun listCountries(): List<Country> {
return restTemplate
.getForObject("/country/list?token=$token", CountryResponse::class.java)
?.results
?: throw IllegalStateException("Api should always return data")
}
override fun listRegions(): List<Region> {
return restTemplate
.getForObject("/region/list?token=$token", RegionResponse::class.java)
?.results
?: throw IllegalStateException("Api should always return data")
}
override fun listSpecies(path: String, page: Int): List<Species> {
return restTemplate.getForObject("/$path/page/$page?token=$token", SpeciesResponse::class.java)
?.result
?: emptyList()
}
override fun listSpeciesByRegion(region: Region, page: Int): List<Species> {
return listSpecies("/species/region/${region.identifier}", page = page)
}
override fun listConservationMeasure(id: Int): List<ConservationMeasure> {
println("$baseURI/measures/species/id/$id?token=$token")
return restTemplate
.getForObject(
"/measures/species/id/$id?token=$token",
ConservationMeasureResponse::class.java)
?.result
?: emptyList()
}
}
| 0
|
Kotlin
|
0
| 0
|
37d759e71cb3ae8dda93c457fbea8733a89e173e
| 2,438
|
demo-redlist-consumer
|
MIT License
|
features/tvshows/src/main/java/com/andhiratobing/moviecompose/tvshows/data/models/TvShowsList.kt
|
andhiratobing
| 443,302,737
| false
|
{"Kotlin": 69028}
|
package com.andhiratobing.moviecompose.tvshows.data.models
data class TvShowsList(
val results: List<TvShows>
)
| 0
|
Kotlin
|
0
| 1
|
05495ac44369f5fa11b3b23236f18b65b2241c62
| 116
|
movie-compose
|
Apache License 2.0
|
examples/src/tl/td/JsonValue.kt
|
andreypfau
| 719,064,910
| false
|
{"Kotlin": 62259}
|
// This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.td
import io.github.andreypfau.tl.serialization.TLCombinatorId
import kotlin.jvm.JvmName
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonClassDiscriminator
@Serializable
@JsonClassDiscriminator("@type")
public sealed interface JsonValue {
@Serializable
@SerialName("jsonValueNull")
@TLCombinatorId(0xFA76E0CD)
public object JsonValueNull : JsonValue
@Serializable
@SerialName("jsonValueBoolean")
@TLCombinatorId(0x8050D3B0)
public data class JsonValueBoolean(
@get:JvmName("value")
public val `value`: Boolean,
) : JsonValue {
public companion object
}
@Serializable
@SerialName("jsonValueNumber")
@TLCombinatorId(0xC3C0146F)
public data class JsonValueNumber(
@get:JvmName("value")
public val `value`: Double,
) : JsonValue {
public companion object
}
@Serializable
@SerialName("jsonValueString")
@TLCombinatorId(0x5F3EBDB1)
public data class JsonValueString(
@get:JvmName("value")
public val `value`: String,
) : JsonValue {
public companion object
}
@Serializable
@SerialName("jsonValueArray")
@TLCombinatorId(0xF509B3B6)
public data class JsonValueArray(
@get:JvmName("values")
public val values: List<JsonValue>,
) : JsonValue {
public companion object
}
@Serializable
@SerialName("jsonValueObject")
@TLCombinatorId(0x1F026A7A)
public data class JsonValueObject(
@get:JvmName("members")
public val members: List<JsonObjectMember>,
) : JsonValue {
public companion object
}
public companion object
}
| 0
|
Kotlin
|
0
| 1
|
11f05ad1f977235e3e360cd6f6ada6f26993208e
| 1,824
|
tl-kotlin
|
MIT License
|
packages/expo-modules-core/android/src/test/java/expo/modules/kotlin/types/BasicTypeConverterTest.kt
|
RohanChimna
| 427,819,004
| true
|
{"Objective-C": 20221207, "Java": 14570671, "C++": 11135407, "Objective-C++": 4168395, "TypeScript": 4157771, "Kotlin": 3945940, "JavaScript": 999211, "Swift": 807304, "Starlark": 688383, "Ruby": 575982, "C": 283446, "Makefile": 159674, "HTML": 60406, "Shell": 51235, "Assembly": 46734, "CMake": 19798, "CSS": 2612, "Batchfile": 89}
|
@file:OptIn(ExperimentalStdlibApi::class)
package expo.modules.kotlin.types
import com.facebook.react.bridge.DynamicFromObject
import com.facebook.react.bridge.JavaOnlyArray
import com.google.common.truth.Truth
import org.junit.Test
import kotlin.reflect.typeOf
class BasicTypeConverterTest {
private val converter = BasicTypeConverter()
@Test
fun `should convert to float array`() {
val dynamic = DynamicFromObject(
JavaOnlyArray().apply {
pushDouble(1.0)
pushDouble(2.0)
pushDouble(3.0)
}
)
val converted = converter.convert(dynamic, KClassTypeWrapper(typeOf<FloatArray>()))
Truth.assertThat(converted).isInstanceOf(FloatArray::class.java)
Truth.assertThat(converted as FloatArray).usingExactEquality().containsExactly(1f, 2f, 3f)
}
}
| 0
| null |
0
| 0
|
6bf128b8d962f93188fbaece734accf72a9342e3
| 807
|
expo
|
MIT License
|
app/src/main/java/dae/rounder/ui/fragments/RulesFragment.kt
|
DavidEdwards
| 177,984,336
| false
| null |
package dae.rounder.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import dae.rounder.databinding.FragmentRulesBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
class RulesFragment: Fragment(), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
private lateinit var binding: FragmentRulesBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentRulesBinding.inflate(inflater, container, false)
binding.webviewRules.webViewClient = WebViewClient()
binding.webviewRules.loadUrl("https://en.wikipedia.org/wiki/Rule")
binding.executePendingBindings()
return binding.root
}
}
| 0
|
Kotlin
|
1
| 35
|
cb9986b7ef60b0c1304e93625d49d20750fa5925
| 1,061
|
mvvm-example
|
MIT License
|
app/src/main/java/com/gdsctsec/smartt/ui/main/HomeScreenFragment.kt
|
Krishanadave671
| 442,094,336
| true
|
{"Kotlin": 55820}
|
package com.gdsctsec.smartt.ui.main
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gdsctsec.smartt.R
import com.gdsctsec.smartt.data.Weekday
import com.gdsctsec.smartt.ui.edit.EditScreenActivity
import com.gdsctsec.smartt.util.SwipeGestureUtil
import com.gdsctsec.smartt.data.TimeTable
import com.gdsctsec.smartt.ui.main.adapter.SubjectsAdapter
import com.gdsctsec.smartt.viewmodel.HomeScreenViewModel
import com.gdsctsec.smartt.viewmodel.HomeScreenViewModelFactory
class HomeScreenFragment : Fragment(), SubjectsAdapter.OnItemclicklistener {
private lateinit var weekDay: String
val timeList: MutableList<String> = mutableListOf("0:00 - 0:00")
val subjectList: MutableList<String> = mutableListOf("No Lectures as of now")
val lectureObjectList: MutableList<TimeTable> =
mutableListOf(TimeTable(-1, "", "", "", Weekday.Monday))
private lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_home_screen, container, false)
return view
}
@RequiresApi(Build.VERSION_CODES.N)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val titleTextView = view.findViewById<TextView>(R.id.remindi_header)
val dayDateTextView = view.findViewById<TextView>(R.id.home_day_textview)
val noLecturesTextView = view.findViewById<TextView>(R.id.zero_lectures_msg_textView)
@RequiresApi(Build.VERSION_CODES.O)
dayDateTextView.text = HomeScreenViewModel(requireActivity()).getMonthDate()
val viewModelFactory = HomeScreenViewModelFactory(requireActivity())
/*Remindi header code*/
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
val word: Spannable = SpannableString("Rem")
word.setSpan(
ForegroundColorSpan(Color.BLACK),
0,
word.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
titleTextView.setText(word)
val wordTwo: Spannable = SpannableString("i")
wordTwo.setSpan(
ForegroundColorSpan(
ContextCompat.getColor(
requireContext(),
R.color.remindi_icon_i
)
), 0, wordTwo.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
titleTextView.append(wordTwo)
val wordThree: Spannable = SpannableString("ndi")
wordThree.setSpan(
ForegroundColorSpan(Color.BLACK),
0,
wordThree.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
titleTextView.append(wordThree)
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
recyclerView = view.findViewById(R.id.home_recyclerView)
recyclerView.adapter = SubjectsAdapter(subjectList, timeList, this)
//1 means list is not empty and 0 means isEmpty
var dataIsThere = 1
val adapter = SubjectsAdapter(subjectList, timeList, this)
val viewModel =
ViewModelProvider(this, viewModelFactory).get(HomeScreenViewModel::class.java)
@RequiresApi(Build.VERSION_CODES.O)
weekDay = viewModel.getWeekDayString();
viewModel.getLiveLectureData().observe(requireActivity(), Observer {
if (it.size != 0) {
dataIsThere = 1
recyclerView.visibility = View.VISIBLE
noLecturesTextView.visibility = View.GONE
subjectList.clear()
timeList.clear()
lectureObjectList.clear()
for (i in 0..it.size - 1) {
subjectList.add(i, it.get(i).lec)
timeList.add(i, (it.get(i).startTime + " - " + it.get(i).endTime))
lectureObjectList.add(it.get(i))
}
adapter.notifyDataSetChanged()
} else {
dataIsThere = 0
subjectList.clear()
timeList.clear()
lectureObjectList.clear()
adapter.notifyDataSetChanged()
recyclerView.visibility = View.GONE
noLecturesTextView.visibility = View.VISIBLE
}
})
//mutableListOf("subjects")
recyclerView = view.findViewById(R.id.home_recyclerView)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireActivity())
val swipeDelete = object : SwipeGestureUtil() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
@RequiresApi(Build.VERSION_CODES.O)
if (dataIsThere == 0) {
Toast.makeText(requireActivity(), "Deleted Lecture", Toast.LENGTH_SHORT).show()
} else {
viewModel.removeLecture(lectureObjectList.get(position))
lectureObjectList.removeAt(position)
subjectList.removeAt(position)
timeList.removeAt(position)
Toast.makeText(requireActivity(), "Deleted Lecture", Toast.LENGTH_SHORT).show()
}
}
}
val itemTouchHelper = ItemTouchHelper(swipeDelete)
itemTouchHelper.attachToRecyclerView(recyclerView)
}
override fun onItemClick(position: Int) {
val chosenSubject = subjectList.get(position)
val startTime = timeList.get(position).split(" - ")[0]
val endTime = timeList.get(position).split(" - ")[1]
Toast.makeText(context, "$startTime $endTime $chosenSubject", Toast.LENGTH_SHORT).show()
val intent = Intent(context, EditScreenActivity::class.java).apply {
putExtra("Lecture_Choosen_subject", chosenSubject)
putExtra("Lecture_start_Time", startTime)
putExtra("Lecture_End_time", endTime)
putExtra("Lecture_Weekday", weekDay)
putExtra("TAG","HomeScreenFragment")
putExtra("id",lectureObjectList.get(position).id.toString())
}
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
467dedd95defbb4bc506fbbbafdc4088dfc077bc
| 7,129
|
ASJ_2021
|
MIT License
|
app/src/main/java/com/jajinba/pixabaydemo/network/ApiClient.kt
|
HMW
| 115,176,644
| false
| null |
package com.jajinba.pixabaydemo.network
import com.jajinba.pixabaydemo.BuildConfig
import com.jajinba.pixabaydemo.Constants
import com.jajinba.pixabaydemo.model.PixabayResponseObject
import com.jajinba.pixabaydemo.utils.SearchUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
class ApiClient private constructor() {
companion object {
private const val API_KEY: String = "key"
private const val API_PAGE: String = "page"
private const val API_IMAGE_PER_PAGE: String = "per_page"
private const val API_KEYWORD: String = "q"
@Volatile
private var sClient: ApiClient? = null
fun getInstance(): ApiClient? {
if (sClient == null) {
synchronized(ApiClient::class.java) {
if (sClient == null) {
sClient = ApiClient()
}
}
}
return sClient
}
}
private var mApiService: ApiService? = null
init {
initialize()
}
private fun initialize() {
val retrofit = Retrofit.Builder()
.baseUrl(Constants.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
mApiService = retrofit.create(ApiService::class.java)
}
fun searchImages(
keyword: String, page: Int,
subscriber: Observer<Response<PixabayResponseObject?>?>
) {
val params = HashMap<String?, String?>()
params[API_KEY] = BuildConfig.API_KEY
params[API_PAGE] = page.toString()
params[API_IMAGE_PER_PAGE] =
Constants.IMAGE_PER_PAGE.toString()
params[API_KEYWORD] = SearchUtils.formatSearchKeyword(keyword)
apiCall(params, subscriber)
}
private fun apiCall(
filtersMap: HashMap<String?, String?>,
subscriber: Observer<Response<PixabayResponseObject?>?>
) {
mApiService?.searchImages(filtersMap)
?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(subscriber)
}
}
| 0
|
Kotlin
|
0
| 1
|
d077ac28a8f17ba3e19fcf21e1059f0baa46f245
| 2,209
|
PixabayDemo
|
Apache License 2.0
|
app/src/main/java/com/anangkur/movieku/feature/main/tv/TvFragment.kt
|
anangkur
| 228,177,144
| false
| null |
package com.anangkur.movieku.feature.main.tv
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.anangkur.movieku.data.model.Result
import com.anangkur.movieku.databinding.FragmentTvBinding
import com.anangkur.movieku.feature.detail.DetailActivity
import com.anangkur.movieku.feature.main.MainActivity
import com.anangkur.movieku.feature.main.MainItemListener
import com.anangkur.movieku.feature.main.MainViewModel
import com.anangkur.movieku.utils.Const
class TvFragment : Fragment(), MainItemListener {
private lateinit var tvViewModel: MainViewModel
private lateinit var tvNewAdapter: TvAdapter
private lateinit var tvPopularAdapter: TvAdapter
private lateinit var tvRatingAdapter: TvAdapter
private lateinit var binding: FragmentTvBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return FragmentTvBinding.inflate(inflater, container, false).also { binding = it }.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupTvNewAdapter()
setupTvPopularAdapter()
setupTvRatingAdapter()
setupViewModel()
if (savedInstanceState == null){
tvViewModel.getTvNew(1)
tvViewModel.getTvPopular(1)
tvViewModel.getTvRating(1)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(Const.EXTRA_STATE_ROTATE, Const.STATE_ROTATE)
}
private fun setupViewModel(){
tvViewModel = (requireActivity() as MainActivity).viewModel
tvViewModel.apply {
tvNewLive.observe(viewLifecycleOwner) {
tvNewAdapter.setRecyclerData(it)
binding.layoutErrorTvNew.root.visibility = View.GONE
}
tvPopularLive.observe(viewLifecycleOwner) {
tvPopularAdapter.setRecyclerData(it)
binding.layoutErrorTvPopular.root.visibility = View.GONE
}
tvRatingLive.observe(viewLifecycleOwner) {
tvRatingAdapter.setRecyclerData(it)
binding.layoutErrorTvRating.root.visibility = View.GONE
}
showProgressNew.observe(viewLifecycleOwner) {
if (it) {
binding.pbTvNew.visibility = View.VISIBLE
binding.layoutErrorTvNew.root.visibility = View.GONE
} else {
binding.pbTvNew.visibility = View.GONE
}
}
showProgressPopular.observe(viewLifecycleOwner) {
if (it) {
binding.pbTvPopular.visibility = View.VISIBLE
binding.layoutErrorTvPopular.root.visibility = View.GONE
} else {
binding.pbTvPopular.visibility = View.GONE
}
}
showProgressRating.observe(viewLifecycleOwner) {
if (it) {
binding.pbTvRating.visibility = View.VISIBLE
binding.layoutErrorTvRating.root.visibility = View.GONE
} else {
binding.pbTvRating.visibility = View.GONE
}
}
showErrorNew.observe(viewLifecycleOwner) {
binding.layoutErrorTvNew.root.visibility = View.VISIBLE
binding.layoutErrorTvNew.root.setOnClickListener { getTvNew(1) }
}
showErrorPopular.observe(viewLifecycleOwner) {
binding.layoutErrorTvPopular.root.visibility = View.VISIBLE
binding.layoutErrorTvPopular.root.setOnClickListener { getTvPopular(1) }
}
showErrorRating.observe(viewLifecycleOwner) {
binding.layoutErrorTvRating.root.visibility = View.VISIBLE
binding.layoutErrorTvRating.root.setOnClickListener { getTvRating(1) }
}
}
}
private fun setupTvNewAdapter(){
tvNewAdapter = TvAdapter(this)
binding.recyclerTvNew.apply {
adapter = tvNewAdapter
itemAnimator = DefaultItemAnimator()
layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
}
}
private fun setupTvPopularAdapter(){
tvPopularAdapter = TvAdapter(this)
binding.recyclerTvPopular.apply {
adapter = tvPopularAdapter
itemAnimator = DefaultItemAnimator()
layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
}
}
private fun setupTvRatingAdapter(){
tvRatingAdapter = TvAdapter(this)
binding.recyclerTvRating.apply {
adapter = tvRatingAdapter
itemAnimator = DefaultItemAnimator()
layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
}
}
override fun onClickItem(data: Result) {
DetailActivity.startActivity(requireActivity(), data, Const.TYPE_TV, Const.requestCodeFavTv)
}
}
| 0
|
Kotlin
|
2
| 5
|
f1211a54519f32258b087b20b63d53e3666d4419
| 5,425
|
Movie-Ku
|
MIT License
|
app/src/main/java/com/anangkur/movieku/feature/main/tv/TvFragment.kt
|
anangkur
| 228,177,144
| false
| null |
package com.anangkur.movieku.feature.main.tv
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.anangkur.movieku.data.model.Result
import com.anangkur.movieku.databinding.FragmentTvBinding
import com.anangkur.movieku.feature.detail.DetailActivity
import com.anangkur.movieku.feature.main.MainActivity
import com.anangkur.movieku.feature.main.MainItemListener
import com.anangkur.movieku.feature.main.MainViewModel
import com.anangkur.movieku.utils.Const
class TvFragment : Fragment(), MainItemListener {
private lateinit var tvViewModel: MainViewModel
private lateinit var tvNewAdapter: TvAdapter
private lateinit var tvPopularAdapter: TvAdapter
private lateinit var tvRatingAdapter: TvAdapter
private lateinit var binding: FragmentTvBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return FragmentTvBinding.inflate(inflater, container, false).also { binding = it }.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupTvNewAdapter()
setupTvPopularAdapter()
setupTvRatingAdapter()
setupViewModel()
if (savedInstanceState == null){
tvViewModel.getTvNew(1)
tvViewModel.getTvPopular(1)
tvViewModel.getTvRating(1)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(Const.EXTRA_STATE_ROTATE, Const.STATE_ROTATE)
}
private fun setupViewModel(){
tvViewModel = (requireActivity() as MainActivity).viewModel
tvViewModel.apply {
tvNewLive.observe(viewLifecycleOwner) {
tvNewAdapter.setRecyclerData(it)
binding.layoutErrorTvNew.root.visibility = View.GONE
}
tvPopularLive.observe(viewLifecycleOwner) {
tvPopularAdapter.setRecyclerData(it)
binding.layoutErrorTvPopular.root.visibility = View.GONE
}
tvRatingLive.observe(viewLifecycleOwner) {
tvRatingAdapter.setRecyclerData(it)
binding.layoutErrorTvRating.root.visibility = View.GONE
}
showProgressNew.observe(viewLifecycleOwner) {
if (it) {
binding.pbTvNew.visibility = View.VISIBLE
binding.layoutErrorTvNew.root.visibility = View.GONE
} else {
binding.pbTvNew.visibility = View.GONE
}
}
showProgressPopular.observe(viewLifecycleOwner) {
if (it) {
binding.pbTvPopular.visibility = View.VISIBLE
binding.layoutErrorTvPopular.root.visibility = View.GONE
} else {
binding.pbTvPopular.visibility = View.GONE
}
}
showProgressRating.observe(viewLifecycleOwner) {
if (it) {
binding.pbTvRating.visibility = View.VISIBLE
binding.layoutErrorTvRating.root.visibility = View.GONE
} else {
binding.pbTvRating.visibility = View.GONE
}
}
showErrorNew.observe(viewLifecycleOwner) {
binding.layoutErrorTvNew.root.visibility = View.VISIBLE
binding.layoutErrorTvNew.root.setOnClickListener { getTvNew(1) }
}
showErrorPopular.observe(viewLifecycleOwner) {
binding.layoutErrorTvPopular.root.visibility = View.VISIBLE
binding.layoutErrorTvPopular.root.setOnClickListener { getTvPopular(1) }
}
showErrorRating.observe(viewLifecycleOwner) {
binding.layoutErrorTvRating.root.visibility = View.VISIBLE
binding.layoutErrorTvRating.root.setOnClickListener { getTvRating(1) }
}
}
}
private fun setupTvNewAdapter(){
tvNewAdapter = TvAdapter(this)
binding.recyclerTvNew.apply {
adapter = tvNewAdapter
itemAnimator = DefaultItemAnimator()
layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
}
}
private fun setupTvPopularAdapter(){
tvPopularAdapter = TvAdapter(this)
binding.recyclerTvPopular.apply {
adapter = tvPopularAdapter
itemAnimator = DefaultItemAnimator()
layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
}
}
private fun setupTvRatingAdapter(){
tvRatingAdapter = TvAdapter(this)
binding.recyclerTvRating.apply {
adapter = tvRatingAdapter
itemAnimator = DefaultItemAnimator()
layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
}
}
override fun onClickItem(data: Result) {
DetailActivity.startActivity(requireActivity(), data, Const.TYPE_TV, Const.requestCodeFavTv)
}
}
| 0
|
Kotlin
|
2
| 5
|
f1211a54519f32258b087b20b63d53e3666d4419
| 5,425
|
Movie-Ku
|
MIT License
|
src/routes/interactions/utils/ReportCreatedMessageJsonCreator.kt
|
bucketplace
| 216,353,542
| false
| null |
package routes.interactions.utils
import db.members.MemberDao
import enums.Channel
import enums.Developer
import enums.Track
import routes.interactions.requests.InteractionRequestBody
import secrets.JiraSecrets
import utils.SlackJsonCreator.createMarkdownText
import utils.escapeDoubleQuotation
import utils.escapeNewLine
import utils.toJson
class ReportCreatedMessageJsonCreator(
private val requestBody: InteractionRequestBody,
private val slackChannelId: String,
private val issueKey: String
) {
fun create() = """
{
"channel": "$slackChannelId",
"blocks": [
${createQaMentionSection()},
${createFieldsSection()}
]
}
""".toJson()
private fun createQaMentionSection() = """
{
"type": "section",
"text": ${createMarkdownText("@dev_qa")}
}
"""
private fun createFieldsSection(): String {
val submissionValues = requestBody.view.state.values
return """
{
"type": "section",
"text": ${createMarkdownText(
buildString {
append(createField("보고자", "<@${requestBody.user.id}>"))
append(createField("카드 제목", submissionValues.subject?.action?.value?.escapeDoubleQuotation() ?: "-"))
append(createField("발생 경로", submissionValues.path.action.value!!.escapeDoubleQuotation()))
append(createField("오류 현상", submissionValues.situation.action.value!!.escapeDoubleQuotation()))
append(createField("기대 결과", submissionValues.expectedResult?.action?.value?.escapeDoubleQuotation() ?: "-"))
append(createField("발생 버전", submissionValues.version.action.selectedOption!!.value.escapeDoubleQuotation()))
append(createField("서버", submissionValues.server?.action?.selectedOption?.value ?: "-"))
append(createField("기타 환경", submissionValues.etcEnvironment?.action?.value?.escapeDoubleQuotation() ?: "-"))
append(createField("심각도", submissionValues.priority.action.selectedOption!!.value))
append(createField("예상 오류 유형", submissionValues.errorType?.action?.selectedOption?.value ?: "-"))
append(createField("재현 가능 여부", submissionValues.reproducing?.action?.selectedOption?.value ?: "-"))
if(hasPmNickName(submissionValues.pm?.action?.value?.escapeDoubleQuotation()?.replace("@", ""))){
append(createField("예상 담당PM", createPmMention(submissionValues.pm?.action?.value?.escapeDoubleQuotation()?.replace("@", ""))))
} else if (requestBody.hasReleaseReportingChannel() && hasTrackPo(submissionValues.track.action.selectedOption!!.value)) {
append(createField("예상 담당PO", createPoMention(submissionValues.track.action.selectedOption.value)))
} else if(!submissionValues.track.action.selectedOption?.value.isNullOrBlank()) {
append(createField("예상 담당트랙", createTrackMention(submissionValues.track.action.selectedOption!!.value)))
}
if(hasTrackTechLead(submissionValues.track.action.selectedOption!!.value)){
append(createField("Tech Lead", createTechLeadMention(submissionValues.track.action.selectedOption!!.value)))
}
if(!isWebChannel(submissionValues.channel.action.selectedOption!!.value)){
append(createField("예상 담당개발자", createDeveloperMention(submissionValues.developer.action.selectedOption!!.value)))
}
append(createField("리포팅 채널", submissionValues.channel.action.selectedOption!!.value))
append(createField("지라 링크", getIssueUrl(issueKey)))
}.escapeNewLine()
)}
}
"""
}
private fun createField(label: String, text: String) = "\n*$label*\n$text"
private fun hasTrackPo(displayName: String): Boolean {
return Track.get(displayName).poNicknames.isNotEmpty()
}
private fun createPoMention(displayName: String): String {
return Track.get(displayName).poNicknames.joinToString(" ") { po ->
"<@${po.slackId}>"
}
}
private fun hasPmNickName(pmNickName: String?): Boolean {
return kotlin.runCatching {
pmNickName
?.replace(Regex("\\(.*\\)"), "")
?.let { !getMemberId(it).isNullOrEmpty() }
}.getOrNull()
?: false
}
private fun createPmMention(displayName: String?): String {
return displayName
?.replace(Regex("\\(.*\\)"), "")
?.let { getMemberId(it) }
?.let { "<@${it}>" }
?: " - "
}
private fun getMemberId(nickname: String): String? {
return MemberDao().getMemberByNickname(nickname)?.id
}
private fun createTrackMention(displayName: String): String {
return Track.get(displayName).slackUserGroupHandles
.map { handle -> "@$handle" }
.toList().toString()
}
private fun hasTrackTechLead(displayName: String): Boolean {
return Track.get(displayName).techLead.isNotEmpty()
}
private fun createTechLeadMention(displayName: String): String {
return Track.get(displayName).techLead.joinToString(" ") { techLeadName ->
Developer.findByNickname(techLeadName)?.let {
"<@${it.slackId}>"
} ?: ""
}
}
private fun createDeveloperMention(displayName: String): String {
return "<@${Developer.get(displayName).slackId}>"
}
private fun getIssueUrl(issueKey: String): String {
return "${JiraSecrets.DOMAIN}/browse/$issueKey"
}
private fun isWebChannel(channelName: String): Boolean {
return Channel.WEB_RELEASE.displayName == channelName
}
}
| 0
|
Kotlin
|
0
| 0
|
58e2270ed92bf19fe196613b67172aaf12442368
| 5,874
|
error-report-v2
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/broken/money/MoneyBag.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.broken.money
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.broken.MoneyGroup
val MoneyGroup.MoneyBag: ImageVector
get() {
if (_moneyBag != null) {
return _moneyBag!!
}
_moneyBag = Builder(
name = "MoneyBag", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(3.1716f, 20.8284f)
curveTo(4.3432f, 22.0f, 6.2288f, 22.0f, 10.0f, 22.0f)
horizontalLineTo(14.0f)
curveTo(17.7712f, 22.0f, 19.6569f, 22.0f, 20.8284f, 20.8284f)
curveTo(22.0f, 19.6569f, 22.0f, 17.7712f, 22.0f, 14.0f)
curveTo(22.0f, 12.8302f, 22.0f, 11.8419f, 21.965f, 11.0f)
moveTo(20.8284f, 7.1716f)
curveTo(19.6569f, 6.0f, 17.7712f, 6.0f, 14.0f, 6.0f)
horizontalLineTo(10.0f)
curveTo(6.2288f, 6.0f, 4.3432f, 6.0f, 3.1716f, 7.1716f)
curveTo(2.0f, 8.3432f, 2.0f, 10.2288f, 2.0f, 14.0f)
curveTo(2.0f, 15.1698f, 2.0f, 16.1581f, 2.035f, 17.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 2.0f)
curveTo(13.8856f, 2.0f, 14.8284f, 2.0f, 15.4142f, 2.5858f)
curveTo(16.0f, 3.1716f, 16.0f, 4.1144f, 16.0f, 6.0f)
moveTo(8.5858f, 2.5858f)
curveTo(8.0f, 3.1716f, 8.0f, 4.1144f, 8.0f, 6.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 17.3333f)
curveTo(13.1046f, 17.3333f, 14.0f, 16.5871f, 14.0f, 15.6667f)
curveTo(14.0f, 14.7462f, 13.1046f, 14.0f, 12.0f, 14.0f)
curveTo(10.8954f, 14.0f, 10.0f, 13.2538f, 10.0f, 12.3333f)
curveTo(10.0f, 11.4129f, 10.8954f, 10.6667f, 12.0f, 10.6667f)
moveTo(12.0f, 17.3333f)
curveTo(10.8954f, 17.3333f, 10.0f, 16.5871f, 10.0f, 15.6667f)
moveTo(12.0f, 17.3333f)
verticalLineTo(18.0f)
moveTo(12.0f, 10.0f)
verticalLineTo(10.6667f)
moveTo(12.0f, 10.6667f)
curveTo(13.1046f, 10.6667f, 14.0f, 11.4129f, 14.0f, 12.3333f)
}
}
.build()
return _moneyBag!!
}
private var _moneyBag: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 3,626
|
SolarIconSetAndroid
|
MIT License
|
socket/src/commonMain/kotlin/pw.binom.io.socket/RawServerSocketChannel.kt
|
RdeWilde
| 226,810,340
| true
|
{"C": 4788382, "C++": 546364, "Kotlin": 471870, "Shell": 86}
|
package pw.binom.io.socket
expect class RawServerSocketChannel() : ServerSocketChannel, NetworkChannel
| 0
| null |
0
| 0
|
c41c8cb96395035c59a90f0fce37969c853b23c5
| 103
|
pw.binom.io
|
Apache License 2.0
|
homework/Day11_Storage/app/src/main/java/io/sethclark/dogceo/screens/breeds/BreedListFragment.kt
|
setheclark
| 155,976,009
| false
| null |
package io.sethclark.dogceo.screens.breeds
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.sethclark.dogceo.Injection
import io.sethclark.dogceo.R
class BreedListFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: BreedAdapter
private lateinit var loadingBar: View
private lateinit var viewModel: BreedListViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val viewModelFactory = Injection.provideViewModelFactory(context!!)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(BreedListViewModel::class.java)
adapter = BreedAdapter { breed ->
findNavController().navigate(
BreedListFragmentDirections.actionShowBreedImage(breed.id)
)
}
recyclerView.adapter = adapter
viewModel.breeds.observe(this, Observer { breeds ->
loadingBar.visibility = if (breeds?.isEmpty() == true) View.VISIBLE else View.GONE
adapter.breeds = breeds
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_breed_list, container, false)
loadingBar = view.findViewById(R.id.loading_bar)
recyclerView = view.findViewById(R.id.breed_list_view)
recyclerView.layoutManager = LinearLayoutManager(context).apply { orientation = RecyclerView.VERTICAL }
return view
}
}
| 0
|
Kotlin
|
0
| 0
|
07e6284d7dd21191b5477df91b681f3026272846
| 1,958
|
android_course_resources
|
Apache License 2.0
|
embedded_video_lib/src/main/java/com/gapps/library/api/models/api/StreamableVideoInfoModel.kt
|
TalbotGooday
| 225,641,422
| false
|
{"Kotlin": 118314}
|
package com.gapps.library.api.models.api
import com.gapps.library.api.URL
import com.gapps.library.api.models.api.base.VideoInfoModel
import com.gapps.library.api.models.video.streamable.StreamableResponse
class StreamableVideoInfoModel : VideoInfoModel<StreamableResponse>() {
override val baseUrl: String
get() = "https://api.streamable.com"
override val pattern: String
get() = STREAMABLE_PATTERN
override val idPattern: String
get() = pattern
override val type: Class<StreamableResponse>
get() = StreamableResponse::class.java
override val hostingName: String
get() = STREAMABLE_HOST_NAME
override fun getInfoUrl(incomingUrl: String?): String? {
return "$baseUrl/oembed.json?$URL=$incomingUrl"
}
override fun getPlayLink(videoId: String): String {
return "https://streamable.com/o/$videoId"
}
}
| 3
|
Kotlin
|
5
| 38
|
39b1de22842a1d2ebee6edf5c2802ababd6b4f9f
| 894
|
Android-Oembed-Video
|
Apache License 2.0
|
src/me/anno/mesh/Line.kt
|
AntonioNoack
| 266,471,164
| false
| null |
package me.anno.mesh
import org.joml.Vector3f
import org.joml.Vector3fc
data class Line(val a: Vector3f, val b: Vector3f){
fun scale(s: Float){
a.mul(s)
b.mul(s)
}
fun switchYZ(){
a.set(a.x, a.z, -a.y)
b.set(b.x, b.z, -b.y)
}
fun switchXZ(){
a.set(a.z, a.y, -a.x)
b.set(b.z, b.y, -b.x)
}
fun translate(delta: Vector3fc){
a.add(delta)
b.add(delta)
}
}
| 0
|
Kotlin
|
1
| 8
|
421ba71c93c2b660476f96ffb6f4332fa07bd2b3
| 448
|
RemsStudio
|
Apache License 2.0
|
network/src/main/java/com/example/network/StateLiveData.kt
|
zcyyouminghuo
| 434,528,820
| false
| null |
package com.example.network
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.network.entity.*
/**
* @Description:
* @CreateDate: 2021/12/3 11:18
*/
typealias StateLiveData<T> = LiveData<ApiResponse<T>>
typealias StateMutableLiveData<T> = MutableLiveData<ApiResponse<T>>
@MainThread
inline fun <T> StateMutableLiveData<T>.observeState(
owner: LifecycleOwner,
listenerBuilder: ResultBuilder<T>.() -> Unit
) {
val listener = ResultBuilder<T>().also(listenerBuilder)
observe(owner) { apiResponse ->
when (apiResponse) {
is ApiSuccessResponse -> listener.onSuccess(apiResponse.response)
is ApiEmptyResponse -> listener.onDataEmpty()
is ApiFailedResponse -> listener.onFailed(apiResponse.code, apiResponse.msg)
is ApiErrorResponse -> listener.onError(apiResponse.throwable)
}
listener.onComplete()
}
}
@MainThread
inline fun <T> LiveData<ApiResponse<T>>.observeState(
owner: LifecycleOwner,
listenerBuilder: ResultBuilder<T>.() -> Unit
) {
val listener = ResultBuilder<T>().also(listenerBuilder)
observe(owner) { apiResponse ->
when (apiResponse) {
is ApiSuccessResponse -> listener.onSuccess(apiResponse.response)
is ApiEmptyResponse -> listener.onDataEmpty()
is ApiFailedResponse -> listener.onFailed(apiResponse.code, apiResponse.msg)
is ApiErrorResponse -> listener.onError(apiResponse.throwable)
}
listener.onComplete()
}
}
class ResultBuilder<T> {
var onSuccess: (data: T?) -> Unit = {}
var onDataEmpty: () -> Unit = {}
var onFailed: (errorCode: String?, errorMsg: String?) -> Unit = { _, errorMsg ->
errorMsg?.let { toast(it) }
}
var onError: (e: Throwable) -> Unit = { e ->
e.message?.let { toast(it) }
}
var onComplete: () -> Unit = {}
}
| 0
|
Kotlin
|
0
| 0
|
ac73d78a5d9a65ad32e3a87abad73512be085e71
| 2,004
|
KotlinCampus
|
Apache License 2.0
|
minenzyme/src/jsMain/kotlin/com/zegreatrob/minenzyme/EnzymeWrapper.kt
|
epabst
| 284,880,640
| true
|
{"Kotlin": 142700, "Batchfile": 697, "Dockerfile": 282}
|
package com.zegreatrob.minenzyme
import react.*
import kotlin.js.Json
import kotlin.js.json
@JsModule("enzyme")
external val enzyme: Enzyme
@JsModule("enzyme-adapter-react-16")
external class Adapter
val setup = object {
init {
enzyme.configure(json("adapter" to Adapter()))
}
}
external interface Enzyme {
fun shallow(element: dynamic): ShallowWrapper<dynamic>
fun configure(config: Json)
}
external interface ShallowWrapper<T> {
fun <T2 : RProps> find(target: RClass<T2>): ShallowWrapper<T2>
fun <T2> find(target: dynamic): ShallowWrapper<T2>
val length: Int
fun props(): T
fun update(): ShallowWrapper<T>
fun debug(): String
fun text(): String
fun key(): String?
fun simulate(eventName: String)
fun simulate(eventName: String, event: dynamic)
fun <O> map(mapper: (ShallowWrapper<T>) -> O): Array<O>
fun <T> find(mapper: (ShallowWrapper<T>) -> Boolean): ShallowWrapper<T>
fun hasClass(className: String): Boolean
fun prop(key: String): Any
fun at(index: Int): ShallowWrapper<T>
fun shallow(): ShallowWrapper<T>
}
fun <T> ShallowWrapper<T>.simulateInputChange(fieldName: String, fieldValue: String) {
return findInputByName(fieldName)
.simulate(
"change",
json(
"target" to json("name" to fieldName, "value" to fieldValue),
"persist" to {}
)
)
}
fun <T> ShallowWrapper<T>.findByClass(className: String) = find<T>(".${className}")
fun <T> ShallowWrapper<T>.findInputByName(inputName: String) = find<T>("input[name='${inputName}']")
fun <P : RProps> shallow(reactFunction: RClass<P>, props: P, handler: RHandler<P> = {}) = enzyme.shallow(buildElement {
child(reactFunction, props, handler)
})
fun <P : RProps, T> shallow(reactFunction: FunctionalComponent<P>, props: P, children: RBuilder.(T) -> Unit = {}) =
enzyme.shallow(buildElement {
childFunction(reactFunction, props, {}, children)
})
fun shallow(handler: RBuilder.() -> Unit) = enzyme.shallow(buildElement(handler))
| 0
| null |
0
| 0
|
d10d932b2dc486755c184613573643bc7842daa5
| 2,089
|
testmints
|
MIT License
|
ground/src/test/java/com/google/android/ground/ui/home/mapcontainer/HomeScreenMapContainerFragmentTest.kt
|
google
| 127,777,820
| false
|
{"Kotlin": 1182603, "Java": 19970, "Python": 3111}
|
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.home.mapcontainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isEnabled
import androidx.test.espresso.matcher.ViewMatchers.withId
import app.cash.turbine.test
import com.google.android.ground.*
import com.google.android.ground.NavGraphDirections.ShowMapTypeDialogFragment
import com.google.android.ground.ui.common.Navigator
import com.google.android.ground.ui.map.MapType
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
@RunWith(RobolectricTestRunner::class)
class HomeScreenMapContainerFragmentTest : BaseHiltTest() {
@Inject lateinit var navigator: Navigator
@Before
override fun setUp() {
super.setUp()
launchFragmentInHiltContainer<HomeScreenMapContainerFragment>()
}
@Test
fun clickMapType_launchesMapTypeDialogFragment() = runWithTestDispatcher {
onView(withId(R.id.map_type_btn)).perform(click()).check(matches(isEnabled()))
navigator.getNavigateRequests().test {
val result = expectMostRecentItem()
assertThat(result).isInstanceOf(ShowMapTypeDialogFragment::class.java)
assertThat((result as ShowMapTypeDialogFragment).mapTypes).isEqualTo(MapType.values())
}
}
}
| 189
|
Kotlin
|
114
| 208
|
d1d66c7834a4b74122523a6dbc347a1a54e45c98
| 2,244
|
ground-android
|
Apache License 2.0
|
src/main/kotlin/com/vaadin/plugin/starter/StarterModel.kt
|
vaadin
| 203,115,867
| false
|
{"Kotlin": 80112}
|
package com.vaadin.plugin.starter
import com.intellij.openapi.project.Project
class StarterModel(
var framework: String, // flow / hilla-react
var language: String, // java / kotlin
var buildTool: String, // maven / gradle
var architecture: String // springboot / servlet / ...
) : DownloadableModel {
override fun getDownloadLink(project: Project): String {
return "https://start.vaadin.com/helloworld?framework=$framework&language=$language&buildtool=$buildTool&stack=$architecture"
}
override fun getProjectType(): String {
return buildTool
}
}
| 10
|
Kotlin
|
0
| 3
|
96e66cb44798100d950368108fa5ebee5b017c76
| 620
|
intellij-plugin
|
Apache License 2.0
|
core/src/main/java/com/vimal/core/models/LoadingMessageData.kt
|
vimalpsojan
| 338,297,169
| false
| null |
package com.vimal.core.models
import android.content.Context
open class LoadingMessageData(context: Context? = null, var isLoading: Boolean = true) : MessageData(context) {
}
| 0
|
Kotlin
|
0
| 1
|
ed56628397a7711c052b47f2abd44affd6105c5b
| 177
|
AndroisBaseTemplate
|
Apache License 2.0
|
base/src/main/kotlin/browser/chromeosInfoPrivate/ManagedDeviceStatus.kt
|
DATL4G
| 372,873,797
| false
| null |
package browser.chromeosInfoPrivate
import kotlin.String
/**
* Status of enterprise enrollment.
*/
public enum class ManagedDeviceStatus(
private val `value`: String,
) {
managed("managed"),
not_managed("not managed"),
;
public override fun toString(): String = value
}
| 0
|
Kotlin
|
1
| 37
|
ab2a825dd8dd8eb704278f52c603dbdd898d1875
| 285
|
Kromex
|
Apache License 2.0
|
libraries/core_network/src/main/kotlin/dev/marlonlom/demos/melishop/core/network/api_impl.kt
|
marlonlom
| 615,867,775
| false
| null |
package dev.marlonlom.demos.melishop.core.network
import dev.marlonlom.demos.melishop.core.network.categories.CategoriesResponseItem
import dev.marlonlom.demos.melishop.core.network.categories.CategoryResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.url
class MeliShopApi(private val client: HttpClient) : ApiService {
override suspend fun getCategories(siteCode: String): Result<Array<CategoriesResponseItem>> = try {
val response = client.get { url(ApiRoutes.getCategoriesList(siteCode)) }.body<Array<CategoriesResponseItem>>()
Result.success(response)
} catch (ex: Exception) {
Result.failure(ex)
}
override suspend fun getCategory(categoryCode: String): Result<CategoryResponse> = try {
val response =
client.get { url(ApiRoutes.getCategoryDetail(categoryCode)) }.body<CategoryResponse>()
Result.success(response)
} catch (ex: Exception) {
Result.failure(ex)
}
}
| 0
|
Kotlin
|
0
| 0
|
bad0c479ba448682f80a83116465427b78832e7e
| 1,002
|
melishop
|
MIT License
|
src/test/kotlin/com/discounts/nearby/service/scheduler/SupermarketDataUpdateScheduledServiceImplTest.kt
|
MarchenkoVladislav
| 330,028,034
| false
|
{"HTML": 3540056, "Kotlin": 111830, "JavaScript": 26285, "CSS": 755}
|
package com.discounts.nearby.service.scheduler
import com.discounts.nearby.model.Good
import com.discounts.nearby.model.Goods
import com.discounts.nearby.model.Supermarket
import com.discounts.nearby.model.SupermarketCode
import com.discounts.nearby.model.category.GoodCategory
import com.discounts.nearby.service.SupermarketService
import com.discounts.nearby.service.scheduler.impl.SupermarketDataUpdateScheduledServiceImpl
import com.discounts.nearby.service.supermarket.parser.manager.SupermarketSiteDataManager
import com.nhaarman.mockitokotlin2.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import java.math.BigDecimal
@ExtendWith(MockitoExtension::class)
internal class SupermarketDataUpdateScheduledServiceImplTest {
@Mock
private lateinit var supermarketManager: SupermarketSiteDataManager
@Mock
private lateinit var supermarketService: SupermarketService
@InjectMocks
private lateinit var service: SupermarketDataUpdateScheduledServiceImpl
@BeforeEach
fun setUp() {
whenever(supermarketService.findAll()).thenReturn(SUPERMARKETS)
whenever(supermarketManager.getAllCategoriesData(eq(SupermarketCode.OKEY), any(), any()))
.thenReturn(
mapOf(
GoodCategory.BEER to Goods(
listOf(
Good(
name = "Beer",
goodCategory = GoodCategory.BEER,
weight = "1kg",
discount = BigDecimal.TEN,
price = BigDecimal.ONE
)
)
)
)
)
}
@Test
fun `update data in DB`() {
service.runScheduled()
argumentCaptor<Supermarket> {
verify(supermarketService, times(1)).save(capture())
assertEquals(SUPERMARKETS[0].id, firstValue.id)
assertFalse { firstValue.goodsSortedByPrice?.goods.isNullOrEmpty() }
assertFalse { firstValue.goodsSortedByDiscount?.goods.isNullOrEmpty() }
}
}
private companion object {
val SUPERMARKETS = listOf(
Supermarket().apply {
id = 1L
code = SupermarketCode.OKEY
name = "Okey"
}
)
}
}
| 0
|
HTML
|
0
| 0
|
035fc24a53c2313a7f0a17acd66324982c05fd98
| 2,675
|
DiscountsNearby
|
MIT License
|
view/src/main/java/com/carlitosdroid/view/CroppedBitmapCallback.kt
|
CarlitosDroid
| 100,199,272
| false
| null |
package com.carlitosdroid.view
import android.graphics.Bitmap
/**
* @author carlosleonardocamilovargashuaman on 7/6/18.
*/
interface CroppedBitmapCallback {
fun onCroppedBitmapReady(croppedBitmap: Bitmap)
}
| 0
|
Kotlin
|
4
| 0
|
a6826d664009a340d1afff0238c4e46144735204
| 214
|
android-ImageCropperView
|
MIT License
|
local-aws/src/test/java/com/nimbusframework/nimbusawslocal/deployment/services/resource/LocalDynamoDbDocumentStoreCreatorTest.kt
|
ihsmarkitoss
| 230,110,781
| true
|
{"Kotlin": 258342, "JavaScript": 71112, "CSS": 28446, "HTML": 3721, "Java": 2673}
|
package com.nimbusframework.nimbusawslocal.deployment.services.resource
import com.nimbusframework.nimbuslocal.LocalNimbusDeployment
import exampleresources.DynamoDbDocument
import io.kotlintest.shouldNotBe
import io.kotlintest.specs.AnnotationSpec
internal class LocalDynamoDbDocumentStoreCreatorTest: AnnotationSpec() {
@Test
fun canCorrectlyDetectAnnotation() {
val localNimbusDeployment = LocalNimbusDeployment.getNewInstance("exampleresources")
val document = localNimbusDeployment.getDocumentStore(DynamoDbDocument::class.java);
document shouldNotBe null
}
}
| 0
| null |
0
| 0
|
9f54c7a04c3d71a417c4c5677d299be5e9dec7a0
| 603
|
nimbus-local
|
Apache License 2.0
|
one.lfa.updater.app/src/main/java/au/org/libraryforall/updater/app/BackgroundExecutor.kt
|
AULFA
| 189,855,520
| false
| null |
package au.org.libraryforall.updater.app
import com.google.common.util.concurrent.ListeningExecutorService
data class BackgroundExecutor(
val executor: ListeningExecutorService)
| 2
|
Kotlin
|
0
| 0
|
ed34818d3f92243a68e2f31a28fa75e216d76994
| 183
|
updater
|
Apache License 2.0
|
compiler/testData/codegen/box/variadicGenerics/helloWorld.kt
|
KirpichenkovPavel
| 153,478,731
| true
|
{"Kotlin": 36246661, "Java": 7496492, "JavaScript": 155884, "HTML": 75262, "Lex": 23159, "TypeScript": 21255, "IDL": 10801, "ANTLR": 9803, "Shell": 7727, "Groovy": 6940, "Batchfile": 5362, "CSS": 4679, "Swift": 2253, "Ruby": 668, "Objective-C": 293, "Scala": 80}
|
// !LANGUAGE: +NewInference
// TARGET_BACKEND: JVM
// WITH_RUNTIME
import kotlin.experimental.*
class Tuple<Ts...> (vararg values: Ts) {
private val _values: Array<Any?> = arrayOf(*values)
operator fun <T> get(ix: @TypeIndex(Ts::class, T::class) Int): T = _values[ix] as T
}
fun box(): String {
val t = Tuple(15, "O", "K")
return t[1] + t[2]
}
| 0
|
Kotlin
|
0
| 0
|
63f0e934cd793a9241ede6838c0b905b77af0b6a
| 362
|
kotlin
|
Apache License 2.0
|
browser-kotlin/src/jsMain/kotlin/web/performance/PerformanceMarkOptions.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6630901}
|
// Automatically generated - do not modify!
package web.performance
import web.time.DOMHighResTimeStamp
sealed external interface PerformanceMarkOptions {
var detail: Any?
var startTime: DOMHighResTimeStamp?
}
| 0
|
Kotlin
|
6
| 28
|
664781d7bdaf5f4aca206e11990b1d304fd45212
| 221
|
types-kotlin
|
Apache License 2.0
|
core/src/jvmMain/kotlin/it/unibo/tuprolog/argumentation/core/libs/language/RuleParser.kt
|
tuProlog
| 333,103,830
| false
|
{"Kotlin": 300090, "Prolog": 61781, "JavaScript": 917, "Java": 258}
|
package it.unibo.tuprolog.argumentation.core.libs.language
import it.unibo.tuprolog.argumentation.core.TheoryUtils
actual object RuleParser : RuleParserBase() {
override val prologRawTheory: String
get() = TheoryUtils.loadTheoryFromPrologFile("core/translation/ruleTranslator")
}
| 15
|
Kotlin
|
0
| 6
|
2cf65e2f1c94bc625447a10f12e765a20245bdcc
| 294
|
arg2p-kt
|
MIT License
|
core/src/jvmMain/kotlin/it/unibo/tuprolog/argumentation/core/libs/language/RuleParser.kt
|
tuProlog
| 333,103,830
| false
|
{"Kotlin": 300090, "Prolog": 61781, "JavaScript": 917, "Java": 258}
|
package it.unibo.tuprolog.argumentation.core.libs.language
import it.unibo.tuprolog.argumentation.core.TheoryUtils
actual object RuleParser : RuleParserBase() {
override val prologRawTheory: String
get() = TheoryUtils.loadTheoryFromPrologFile("core/translation/ruleTranslator")
}
| 15
|
Kotlin
|
0
| 6
|
2cf65e2f1c94bc625447a10f12e765a20245bdcc
| 294
|
arg2p-kt
|
MIT License
|
app/src/main/java/com/itscoderslife/hellokotlinandroid/activities/LoginActivity.kt
|
itsdamslife
| 140,426,155
| false
|
{"Kotlin": 20326}
|
package com.itscoderslife.hellokotlinandroid.activities
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.itscoderslife.hellokotlinandroid.R
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
var mAuth: FirebaseAuth? = null
var mUserDB: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mAuth = FirebaseAuth.getInstance()
loginPageButton.setOnClickListener {
if(!loginEmailText.text.toString().isEmpty() && !loginPasswordText.text.toString().isEmpty()) {
this.login(loginEmailText.text.toString().trim(), loginPasswordText.text.toString().trim())
} else {
Toast.makeText(applicationContext, "Please fill in valid details!", Toast.LENGTH_LONG).show()
}
}
}
fun login(email: String, password: String) {
Toast.makeText(this, "Entries are valid!", Toast.LENGTH_LONG).show()
mAuth!!.signInWithEmailAndPassword(email, password).addOnCompleteListener {
task: Task<AuthResult> ->
if (task.isSuccessful) {
Toast.makeText(this, "${email.split("@")[0]} logged in successfully!", Toast.LENGTH_LONG).show()
val userID = this.mAuth!!.currentUser!!.uid
mUserDB = FirebaseDatabase.getInstance().reference.child("Users").child(userID)
val intent = Intent(this, DashboardActivity::class.java)
intent.putExtra("user", email.split("@")[0])
startActivity(intent)
finish()
} else {
Toast.makeText(this, "Login for ${email.split("@")[0]} failed!", Toast.LENGTH_LONG).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dc3f9e0e4b45f78dd71de76be5e64c647e1df346
| 2,142
|
AndroidKotlin
|
MIT License
|
src/test/kotlin/non_test/_main_/view/preferences.kt
|
christophpickl
| 56,092,216
| false
| null |
package non_test._main_.view
import at.cpickl.gadsu.preferences.PreferencesData
import at.cpickl.gadsu.preferences.testInstance
import at.cpickl.gadsu.preferences.view.PreferencesSwingWindow
import at.cpickl.gadsu.service.RealClock
import at.cpickl.gadsu.view.MainFrame
import at.cpickl.gadsu.view.SwingFactory
import com.google.common.eventbus.EventBus
import org.mockito.Mockito.mock
fun main(args: Array<String>) {
val mainFrame = mock(MainFrame::class.java)
val bus = EventBus()
val clock = RealClock()
val swingFactory = SwingFactory(bus, clock)
val window = PreferencesSwingWindow(mainFrame, bus, swingFactory)
window.initData(PreferencesData.testInstance())
window.txtApplicationDirectory = "/test/app/dir"
window.txtLatestBackup = "Letztes Backup: Gestern"
window.start()
}
| 43
|
Kotlin
|
1
| 2
|
f6a84c42e1985bc53d566730ed0552b3ae71d94b
| 822
|
gadsu
|
Apache License 2.0
|
android/app/src/main/kotlin/com/me/matchgame/match_game/MainActivity.kt
|
amuhaimin02
| 254,057,942
| false
|
{"Dart": 51870, "Swift": 403, "Kotlin": 343, "HTML": 183, "Objective-C": 37}
|
package com.me.matchgame.match_game
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
| 0
|
Dart
|
1
| 0
|
d1212bd74271435d8d43826280c0cf83a775c5ca
| 343
|
match_game
|
MIT License
|
domain/src/main/java/com/pthw/domain/usecase/GetChallengeUseCase.kt
|
PhyoThihaWin
| 769,428,664
| false
|
{"Kotlin": 66565}
|
package com.pthw.domain.usecase
import com.pthw.domain.DispatcherProvider
import com.pthw.domain.repository.BiometricRepository
import com.pthw.domain.usecase.utils.CoroutineUseCase
import javax.inject.Inject
/**
* Created by P.T.H.W on 11/03/2024.
*/
class GetChallengeUseCase @Inject constructor(
dispatcherProvider: DispatcherProvider,
private val repository: BiometricRepository
) : CoroutineUseCase<String, String>(dispatcherProvider) {
override suspend fun provide(params: String): String {
return repository.getChallenge(params)
}
}
| 0
|
Kotlin
|
0
| 0
|
a96fb34881e17b6bef8ca3048605900abd9977e4
| 568
|
compose-rsa-biometric
|
Apache License 2.0
|
src/main/kotlin/com/xy/designpatterns/state/DayState.kt
|
monkey1992
| 482,294,811
| false
| null |
package com.xy.designpatterns.state
/**
* 白天状态
*/
class DayState : IState {
init {
run()
}
override fun run() {
println("进入白天,吃饭、上班、运动!")
}
}
| 0
|
Kotlin
|
0
| 1
|
18f1d2657b4688a7f518421ae160a75eaa34f121
| 178
|
XyDesignPatterns
|
Apache License 2.0
|
src/main/kotlin/com/github/tagwan/japm/core/MonitorMethodVisitor.kt
|
tagwan
| 465,237,066
| false
| null |
package com.github.tagwan.japm.core
import com.github.tagwan.japm.const.FUNC_VOID_STRING
import com.github.tagwan.japm.const.INSTANCE
import com.github.tagwan.japm.const.METHOD_OVER
import com.github.tagwan.japm.const.METHOD_START
import com.github.tagwan.japm.monitor.TimeMonitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
/**
* Monitor method visitor
*
* @param api
* @param mv
*/
class MonitorMethodVisitor(
api: Int,
mv: MethodVisitor,
private val key: String
) : MethodVisitor(api, mv) {
/**
* 方法开始时回调
*
*/
override fun visitCode() {
mv.visitFieldInsn(
Opcodes.GETSTATIC,
TimeMonitor.clazzName,
INSTANCE,
"L${TimeMonitor.clazzName};"
)
// LDC
mv.visitLdcInsn(key)
mv.visitMethodInsn(
Opcodes.INVOKEVIRTUAL,
TimeMonitor.clazzName,
METHOD_START,
FUNC_VOID_STRING,
false
)
}
/**
* Visit insn
* <p>
* 在每个 return 指令前插入 TimeMonitor.end
*
* @param opcode
*/
override fun visitInsn(opcode: Int) {
if (opcode in Opcodes.IRETURN..Opcodes.RETURN) {
mv.visitFieldInsn(
Opcodes.GETSTATIC,
TimeMonitor.clazzName,
INSTANCE,
"L${TimeMonitor.clazzName};"
)
// LDC
mv.visitLdcInsn(key)
mv.visitMethodInsn(
Opcodes.INVOKEVIRTUAL,
TimeMonitor.clazzName,
METHOD_OVER,
FUNC_VOID_STRING,
false
)
}
super.visitInsn(opcode)
}
}
| 0
|
Kotlin
|
0
| 4
|
8184b5df18daf19005309bd58122afe78c23a6ba
| 1,731
|
japm
|
MIT License
|
src/test/kotlin/com/namics/oss/gradle/license/DependencyTest.kt
|
merkle-open
| 175,251,589
| false
|
{"Kotlin": 26631}
|
/**
* MIT License
*
* Copyright (c) 2019 Namics AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.namics.oss.gradle.license
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.Test
/**
* DependencyTest.
*
* @author aschaefer, Namics AG
* @since 2019-05-06 14:49
*/
class DependencyTest {
@Test
fun matchesWIthoutVersion() {
assertTrue(Dependency("hello:world:1.2.3", emptyList()).matches(Dependency("hello:world:1.2.3", emptyList())))
assertTrue(Dependency("hello:world:1.2.3", emptyList()).matches(Dependency("hello:world", emptyList())))
}
@Test
fun matchesNoMatch() {
assertFalse(Dependency("hello:world:1.2.3", emptyList()).matches(Dependency("hello:worlds:1.2.3", emptyList())))
assertFalse(Dependency("hello:world:1.2.3", emptyList()).matches(Dependency("hello:1.2.3", emptyList())))
assertFalse(Dependency("hello:world:1.2.3", emptyList()).matches(Dependency("", emptyList())))
}
}
| 0
|
Kotlin
|
4
| 6
|
3de359c051ac9980444da6453a98462b802620d6
| 2,037
|
gradle-license-enforce-plugin
|
MIT License
|
app/src/main/kotlin/com/gmail/yaroslavlancelot/technarium/tabs/articles/ArticlesScreen.kt
|
YaroslavHavrylovych
| 228,385,485
| false
| null |
package com.gmail.yaroslavlancelot.technarium.tabs.articles
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun ArticlesScreen(viewModel: ArticlesViewModel = viewModel()) {
Text(
viewModel.displayedString,
color = Color.Blue,
)
}
@Composable
@Preview
fun ArticlesScreenPreview() {
MaterialTheme {
ArticlesScreen()
}
}
| 0
|
Kotlin
|
0
| 1
|
6fffd4bede6927009760bbca82810695e1203926
| 599
|
technical_news
|
Apache License 2.0
|
src/test/kotlin/day16/ParseRuleTest.kt
|
lukasz-marek
| 317,632,409
| false
| null |
package day16
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.isEqualTo
class ParseRuleTest {
@Test
fun `test 1`() {
// given
val rule = "arrival station: 49-353 or 360-967"
// when
val parsed = parseRule(rule)
// then
expectThat(parsed) {
get { name }.isEqualTo("arrival station")
get { ranges }.isEqualTo(listOf(Pair(49, 353), Pair(360, 967)))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6
| 485
|
aoc2020
|
MIT License
|
shared/src/iosMain/kotlin/com/teewhydope/melotune/util/Logger.kt
|
teewhydope
| 418,884,621
| false
|
{"Kotlin": 82483, "Ruby": 2034, "Swift": 345}
|
package com.teewhydope.melotune.util
actual class Logger actual constructor(className: String) {
actual fun log(msg: String) {
}
}
| 0
|
Kotlin
|
0
| 3
|
57a7f6579d36bd642a5646283465596d248aae52
| 139
|
MeloTune
|
MIT License
|
src/jvmTest/kotlin/guilds.kt
|
LunalaProject
| 310,613,687
| false
| null |
import com.gabriel.lunala.project.LunalaWrapper
import com.gabriel.lunala.project.entity.Guild
import com.gabriel.lunala.project.entity.GuildCreateDTO
import com.gabriel.lunala.project.entity.GuildUpdateDTO
import com.gabriel.lunala.project.service.GuildService
import com.gabriel.lunala.project.util.prepareClient
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.util.*
import org.junit.jupiter.api.Test
class GuildOperationsTest {
@Test
@KtorExperimentalAPI
suspend fun `test operations`() {
operate(GuildService(LunalaWrapper("http://localhost:8080/api", "key", client = HttpClient(CIO.create()) {
prepareClient()
})))
}
}
private suspend fun operate(service: GuildService) {
create(service) {
println("Created $this")
}
update(service) {
println("Updated $this")
}
get(service) {
println("Got $this")
}
delete(service) {
println("Deleted $this")
}
}
suspend fun create(service: GuildService, block: Guild.() -> Unit) =
service.create(GuildCreateDTO(1, "en-us", false)).also(block)
suspend fun update(service: GuildService, block: Guild.() -> Unit) =
service.update(1, GuildUpdateDTO(locale = "pt-br")).also(block)
suspend fun get(service: GuildService, block: Guild?.() -> Unit) =
service.retrieve(1).also(block)
suspend fun delete(service: GuildService, id: Long = 1, block: Long.() -> Unit) =
service.delete(id).also { block(id) }
suspend fun main() = GuildOperationsTest().`test operations`()
| 0
|
Kotlin
|
0
| 1
|
5bf00add899b197b498168436b830ffa5b0d03ee
| 1,557
|
wrapper
|
MIT License
|
webrtc-kmp/src/jsAndWasmJsMain/kotlin/com/shepeliev/webrtckmp/externals/RTCTrackEvent.kt
|
shepeliev
| 329,550,581
| false
|
{"Kotlin": 233515}
|
package com.shepeliev.webrtckmp.externals
internal external interface RTCTrackEvent {
val receiver: RTCRtpReceiver
val track: PlatformMediaStreamTrack
val transceiver: RTCRtpTransceiver
}
internal expect val RTCTrackEvent.streams: List<PlatformMediaStream>
| 13
|
Kotlin
|
38
| 181
|
73e482e70dc7192601acd3482a6774c017c072de
| 271
|
webrtc-kmp
|
Apache License 2.0
|
src/test/kotlin/dev/mbo/logging/LeveledLoggerTest.kt
|
mbogner
| 878,723,166
| false
|
{"Kotlin": 1992}
|
package dev.mbo.logging
import org.junit.jupiter.api.Test
import java.util.UUID
class LeveledLoggerTest {
private val log = logger()
@Test
fun log() {
val exc = Exception("this is on purpose: ${UUID.randomUUID()}")
LeveledLogger.log(log, LogLevel.TRACE, exc)
LeveledLogger.log(log, LogLevel.DEBUG, exc)
LeveledLogger.log(log, LogLevel.INFO, exc)
LeveledLogger.log(log, LogLevel.WARN, exc)
LeveledLogger.log(log, LogLevel.ERROR, exc)
LeveledLogger.log(log, LogLevel.FATAL, exc)
LeveledLogger.log(log, LogLevel.OFF, exc)
}
}
| 0
|
Kotlin
|
0
| 0
|
cca2ae6eaa8ae6319557b9034a7725ebb065dd89
| 606
|
library-kotlin-logging
|
Apache License 2.0
|
app/src/main/java/io/github/ytam/githubusers/domain/usecase/GetUsersUseCase.kt
|
ytam
| 482,583,043
| false
| null |
package io.github.ytam.githubusers.domain.usecase
import io.github.ytam.githubusers.domain.repository.UserRepository
class GetUsersUseCase(private val userRepository: UserRepository) {
operator fun invoke() = userRepository.getAllUser()
}
| 0
|
Kotlin
|
0
| 0
|
404e048975cea26b5888747638fb36b1b40f551e
| 246
|
Jet-Users
|
Apache License 2.0
|
ViolinDS/app/src/main/java/ds/violin/v1/util/common/Common.kt
|
DSolyom
| 59,245,536
| false
| null |
/*
Copyright 2016 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ds.violin.v1.util.common
import android.app.Activity
import android.content.*
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.database.Cursor
import android.graphics.Shader
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.Html
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import ds.violin.v1.Global
import java.io.*
import java.text.Collator
import java.text.NumberFormat
import java.util.*
val SEND_EMAIL_ACTION_CODE = 21345
/**
*
* @param context
* @param url
*/
fun openInBrowser(context: Context, url: String) {
try {
if (url.contains("mailto:")) {
val intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
context.startActivity(intent);
return;
}
} catch(e: Throwable) {
Debug.logException(e);
}
val uri = createHttpUri(url);
val intent = Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
/**
*
* @param activity
* @param url
* @param requestCode
*/
fun openInBrowser(activity: Activity, url: String, requestCode: Int) {
val uri = createHttpUri(url);
val intent = Intent(Intent.ACTION_VIEW, uri);
activity.startActivityForResult(intent, requestCode);
}
/**
*
* @param url
* @return
*/
fun isDocument(url: String): Boolean {
try {
if (!url.contains("docs.google.com")) {
val url = url.split("\\?")[0];
if (url.endsWith(".pdf") || url.endsWith(".PDF") || url.endsWith(".doc") || url.endsWith(".DOC") ||
url.endsWith(".xls") || url.endsWith(".XLS")) {
return true;
}
}
} catch(e: Throwable) {
;
}
return false;
}
/**
*
* @param url
* @return
*/
fun createHttpUri(url: String): Uri {
var url = url
if (url.length < 8 || !"http://".equals(url.substring(0, 7)) && !"https://".equals(url.substring(0, 8))) {
url = "http://" + url;
}
return Uri.parse(url);
}
/**
*
* @param context
* @param packageName
* @param minVersionCode = -1
* @return
*/
fun getAppOpenIntent(context: Context, packageName: String, minVersionCode: Int = -1): Intent? {
val pm = context.getPackageManager();
var intent = Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
for (ri in pm.queryIntentActivities(intent, 0)) {
if (ri.activityInfo.packageName.equals(packageName)) {
try {
if (minVersionCode != -1 && pm.getPackageInfo(packageName, 0).versionCode < minVersionCode) {
return null
}
} catch (e: PackageManager.NameNotFoundException) {
// wont happen but still
return null
}
// create intent
intent = Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName(packageName, ri.activityInfo.name));
intent.addCategory("android.intent.category.LAUNCHER");
return intent;
}
}
return null;
}
/**
* open market at app's details screen
*
* @param context
* @param packageName
*/
fun openMarket(context: Context, packageName: String) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("market://details?id=" + packageName)
context.startActivity(intent)
}
/**
* open market at app's details screen
*
* @param context
* @param marketUrl
* @param dummy
*/
fun openMarket(context: Context, marketUrl: String, dummy: Boolean) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(marketUrl)
context.startActivity(intent)
}
/**
* open app or market at app's details screen if app not installed
*
* @param context
* @param packageName
* @param minVersion
*/
fun openAppOrMarket(context: Context, packageName: String, minVersion: Int) {
val i = getAppOpenIntent(context, packageName, minVersion)
if (i != null) {
context.startActivity(i)
} else {
openMarket(context, packageName)
}
}
/**
* open app or market at app's details screen if app not installed
*
* @param context
* @param packageName
* @param minVersion
*/
fun openAppOrMarket(context: Context, i: Intent?, packageName: String, minVersion: Int) {
if (i != null) {
context.startActivity(i)
} else {
openMarket(context, packageName)
}
}
/**
* start phone call api
*
* @param context
* @param phoneNumber
*/
fun startPhoneCallingDialog(context: Context, phoneNumber: String) {
try {
context.startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)))
} catch (e: Throwable) {
Debug.logException(e)
}
}
/**
* start email - context must be an activity if you want to add attachments
*
* @param context
* @param emails
* @param subject
* @param defaultMessage
*/
fun startSendingEmail(context: Context, emails: Array<String>,
subject: String, defaultMessage: String, vararg attachments: Uri) {
val emailIntent = Intent(android.content.Intent.ACTION_SEND)
emailIntent.setType("plain/text")
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emails)
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, Html.fromHtml(subject).toString())
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(defaultMessage))
if (attachments != null && attachments.size > 0) {
for (attachment in attachments) {
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, attachment)
}
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
(context as Activity).startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), SEND_EMAIL_ACTION_CODE)
} else {
context.startActivity(Intent.createChooser(emailIntent, "Send mail..."))
}
}
/**
* to fix tile mode bug
*
* @param view
*/
fun fixTiledBackground(view: View) {
try {
fixTiledDrawable(view.background as BitmapDrawable)
} catch (e: ClassCastException) {
}
}
/**
* to fix tile mode bug
*
* @param tiled
*/
fun fixTiledDrawable(tiled: BitmapDrawable?) {
if (tiled == null) {
return
}
tiled!!.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)
}
/**
* validate email
*
* @param string
* @return
*/
fun checkEmail(string: String): Boolean {
return string.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$".toRegex())
}
/**
* copy from assets
*
* @param context
* @param assetDirOrFile
* @param targetPath
* @throws IOException
*/
@Throws(IOException::class)
fun copyFromAssets(context: Context, assetDirOrFile: String,
targetPath: String) {
val assetManager = context.getAssets()
var assets: Array<String>? = null
assets = assetManager.list(assetDirOrFile)
if (assets.size == 0) {
copyFileFromAsset(assetManager, assetDirOrFile, targetPath)
} else {
if (targetPath.length > 0) {
val fTargetPath = File(targetPath)
if (!fTargetPath.exists()) {
fTargetPath.mkdir()
}
}
for (i in assets.indices) {
copyFromAssets(context, assetDirOrFile + "/" + assets[i],
targetPath + "/" + assets[i])
}
}
}
@Throws(IOException::class)
fun createDirStructureFromAssets(context: Context, assetDir: String,
targetPath: String?) {
val assetManager = context.getAssets()
var assets: Array<String>? = null
assets = assetManager.list(assetDir)
if (assets.size != 0) {
if (targetPath != null && targetPath.length > 0) {
val fTargetPath = File(targetPath)
if (!fTargetPath.exists()) {
fTargetPath.mkdir()
}
}
for (i in assets.indices) {
createDirStructureFromAssets(context, assetDir + "/" + assets[i],
targetPath + "/" + assets[i])
}
}
}
@Throws(IOException::class)
fun copyFileFromAsset(assetManager: AssetManager, assetFile: String,
targetFilePath: String) {
var `in`: InputStream? = null
var out: OutputStream? = null
`in` = assetManager.open(assetFile)
out = FileOutputStream(targetFilePath)
val buffer = ByteArray(1024)
var read: Int = `in`!!.read(buffer)
while (read != -1) {
out.write(buffer, 0, read)
read = `in`.read(buffer)
}
`in`.close()
out.flush()
out.close()
}
fun deleteDirRec(dirPath: String) {
val fDirPath = File(dirPath)
if (!fDirPath.exists()) {
return
}
val fileOrDirs = fDirPath.list()
if (fileOrDirs.size > 0) {
for (i in fileOrDirs.indices) {
deleteDirRec(dirPath + "/" + fileOrDirs[i])
}
}
fDirPath.delete()
}
/**
* remove every view from a viewgroup
*
* @param vg
*/
@SuppressWarnings("unchecked", "rawtypes")
fun removeAllViewsRec(vg: ViewGroup) {
val cnt = vg.getChildCount()
for (i in 0..cnt - 1) {
val child = vg.getChildAt(i)
child.setBackground(null)
if (child is ViewGroup) {
removeAllViewsRec(child)
} else if (child is ImageView) {
child.setImageDrawable(null)
}
if (child is AdapterView<*>) {
child.setAdapter(null)
}
}
vg.removeAllViewsInLayout()
}
/**
*
* @param a
* @param editResource
*/
fun showKeyboard(a: Activity, editResource: Int) {
showKeyboard(a, a.findViewById(editResource))
}
/**
* @param a
* @param v
*/
fun showKeyboard(a: Activity, v: View) {
val mgr = (a as Context).getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
mgr.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT)
}
/**
*
* @param a
* @param editResource
*/
fun hideKeyboard(a: Activity, editResource: Int) {
hideKeyboard(a, a.findViewById(editResource))
}
/**
*
* @param context
* @param v
*/
fun hideKeyboard(context: Context, v: View) {
try {
val mgr = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
mgr.hideSoftInputFromWindow(v.getWindowToken(), 0)
} catch (e: Exception) {
}
}
/**
* @param a
*/
fun hideKeyboard(a: Activity) {
val im = a.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
im.hideSoftInputFromWindow(a.getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS)
}
/**
* open soft keyboard
*
* @param context
* @param view
*/
fun openKeyboard(context: Context, view: View) {
val mgr = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
mgr.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
/**
* close soft keyboard
*
* @param context
* @param view
*/
fun closeKeyboard(context: Context, view: View) {
val mgr = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
mgr.hideSoftInputFromWindow(view.getWindowToken(), 0)
}
/**
* @param number
* @param currency
* @return
*/
fun formatByCurrency(number: Float, currency: String): String {
try {
val cur = Currency.getInstance(currency)
val format = NumberFormat.getCurrencyInstance(Global.context.resources.configuration.locale)
format.setCurrency(cur)
val digits = cur.getDefaultFractionDigits()
format.setMinimumFractionDigits(digits)
format.setMaximumFractionDigits(digits)
val ret = format.format(number)
return ret
} catch (e: Throwable) {
return number.toString() + currency
}
}
/**
* format number by currency
*
* @param number
* @param currency
* @return
*/
fun formatNumberByCurrency(number: Any, currency: String): String {
try {
return formatNumberByCurrency(number, Currency.getInstance(currency))
} catch (e: Exception) {
return number.toString()
}
}
/**
* @param number
* @param currency
* @param fractionDigits
* @return
*/
fun formatNumberByCurrency(number: Any, currency: String, fractionDigits: Int): String {
try {
return formatNumberByCurrency(number, Currency.getInstance(currency), fractionDigits)
} catch (e: Exception) {
return number.toString()
}
}
/**
* format number by currency
*
* @param number
* @param currency
* @return
*/
fun formatNumberByCurrency(number: Any, currency: Currency): String {
return formatNumberByCurrency(number, currency, currency.defaultFractionDigits)
}
/**
* @param number
* @param currency
* @param fractionDigits
* @return
*/
fun formatNumberByCurrency(number: Any, currency: Currency, fractionDigits: Int): String {
val nf: NumberFormat
nf = NumberFormat.getCurrencyInstance()
try {
nf.currency = currency
nf.minimumFractionDigits = fractionDigits
nf.maximumFractionDigits = fractionDigits
return nf.format(number)
} catch (e: Exception) {
return number.toString()
}
}
/**
* @param number
* @param fractionDigits
* @return
*/
fun formatNumber(number: Any, fractionDigits: Int): String {
val nf: NumberFormat
nf = NumberFormat.getNumberInstance()
nf.minimumFractionDigits = fractionDigits
nf.maximumFractionDigits = fractionDigits
return nf.format(number)
}
/**
* @param left
* @param right
* @param locale
* @param caseSensitive
* @return
*/
fun compareLettersAccentSame(left: String, right: String, locale: Locale, caseSensitive: Boolean): Int {
var left = left
var right = right
val collator = Collator.getInstance(locale)
if (!caseSensitive) {
left = left.toUpperCase(locale)
right = right.toUpperCase(locale)
}
collator.strength = Collator.PRIMARY
return collator.compare(left, right)
}
/**
* @param context
* @param msg
*/
fun toastMessage(context: Context, msg: String) {
try {
val t = Toast.makeText(context, msg, Toast.LENGTH_LONG)
((t.getView() as ViewGroup).getChildAt(0) as TextView).gravity = Gravity.CENTER
t.show()
} catch (e: Exception) {
Debug.logException(e) // closed app just before this
}
}
/**
* @param context
* @param msgResId
*/
fun toastMessage(context: Context, msgResId: Int) {
try {
val t = Toast.makeText(context, msgResId, Toast.LENGTH_LONG)
((t.getView() as ViewGroup).getChildAt(0) as TextView).gravity = Gravity.CENTER
t.show()
} catch (e: Exception) {
Debug.logException(e) // closed app just before this
}
}
/**
* @param root
* @param font
*/
fun setTypefaceRec(root: View, font: Typeface) {
if (root is ViewGroup) {
for (i in 0..root.childCount - 1) {
setTypefaceRec(root.getChildAt(i), font)
}
} else if (root is TextView) {
root.typeface = font
}
}
fun hasExternalStorage(): Boolean {
val state = Environment.getExternalStorageState()
return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)
}
/**
* read a file
*
* @param file
* @return
* @throws IOException
*/
@Throws(IOException::class)
fun readFile(file: String): ByteArray {
// Open file
var f: RandomAccessFile? = null
var data: ByteArray? = null
try {
f = RandomAccessFile(File(file), "r")
// Get and check length
val longlength = f!!.length()
val length = longlength.toInt()
if (length.toLong() != longlength) throw IOException("File too big")
// Read file and return data
data = ByteArray(length)
f!!.readFully(data)
return data
} catch (e: Exception) {
e.printStackTrace()
}
if (f != null) {
f!!.close()
}
return data!!
}
/**
* for locations
*
* @return
*/
val calendarTimeInMillisUTC: Long
get() {
val calendar = Calendar.getInstance()
calendar.setTimeZone(TimeZone.getTimeZone("UTC"))
return calendar.getTimeInMillis()
}
/**
* calendar base uri - different from among phones
*
* @return
*/
val calendarUriBase: String
get() {
val activity = Global.currentActivity
var calendarUriBase: String? = null
var calendars = Uri.parse("content://calendar/calendars")
var managedCursor: Cursor? = null
try {
managedCursor = activity!!.managedQuery(calendars, null, null, null, null)
} catch (e: Exception) {
try {
calendars = Uri.parse("content://calendarEx/calendars")
managedCursor = activity!!.managedQuery(calendars, null, null, null, null)
} catch (ex: Exception) {
}
}
if (managedCursor != null) {
calendarUriBase = calendars.toString().replace("/calendars", "")
} else {
calendars = Uri.parse("content://com.android.calendar/calendars")
try {
managedCursor = activity!!.managedQuery(calendars, null, null, null, null)
} catch (e: Exception) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/"
}
}
return calendarUriBase!!
}
/**
* set event to default calendar
*
* @param context
* @param title
* @param description
* @param startInMillis
* @param endInMillis
* @return
*/
fun putIntoDefaultCalendar(context: Context, title: String, description: String,
startInMillis: Long, endInMillis: Long): Long? {
val event = ContentValues()
try {
val cBase = calendarUriBase
val cr = context.contentResolver
val cursor = cr.query(Uri.parse(cBase + "calendars"),
arrayOf("_id"), null, null, null)
cursor.moveToLast()
val cid = Integer.parseInt(cursor.getString(0))
event.put("calendar_id", cid)
event.put("title", title)
event.put("description", description)
event.put("dtstart", startInMillis.toString())
event.put("dtend", endInMillis.toString())
event.put("eventTimezone", Global.timezone.id)
val eventUri = cr.insert(Uri.parse(cBase + "events"), event)
return java.lang.Long.parseLong(eventUri.lastPathSegment)
} catch (e: Throwable) {
return null
}
}
/**
* remove from calendar by id
*
* @param context
* @param calId
* @return
*/
fun removeFromDefaultCalendar(context: Context, calId: Long): Int? {
try {
val cBase = calendarUriBase
val cr = context.getContentResolver()
var iNumRowsDeleted = 0
try {
val eventUri = ContentUris.withAppendedId(Uri.parse(cBase + "events"), calId)
iNumRowsDeleted = cr.delete(eventUri, null, null)
} catch (e: Throwable) {
}
if (iNumRowsDeleted == 0) {
// maybe another method?
val cursor = cr.query(Uri.parse(cBase + "events"), arrayOf("_id"), "calendar_id=" + calId, null, null)
do {
val eventId = cursor.getLong(cursor.getColumnIndex("_id"))
cr.delete(ContentUris.withAppendedId(Uri.parse(cBase + "events"), eventId), null, null)
++iNumRowsDeleted
} while (cursor.moveToNext())
cursor.close()
}
return iNumRowsDeleted
} catch (e: Throwable) {
return null
}
}
/**
*
* @param v
* @return
*/
fun enableListViewInScrollView(v: View) {
val parent = findScrollViewParent(v) ?: return
v.setOnTouchListener { v, event ->
parent!!.requestDisallowInterceptTouchEvent(true)
false
}
}
/**
*
* @param v
* @return
*/
fun findScrollViewParent(v: View): ScrollView? {
val parent = v.getParent()
if (parent == null || parent !is View) {
return null
}
if (parent is ScrollView) {
return parent
}
return findScrollViewParent(parent)
}
/**
*
* @return
*/
fun getActionBarHeight(context: Context): Int {
var actionBarHeight = 0
val tv = TypedValue()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv,
true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(
tv.data, context.getResources().getDisplayMetrics())
} else {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
context.getResources().getDisplayMetrics())
}
return actionBarHeight
}
/** ------------------------------------------------------------------------------------------*/
/**
* serialize object
*
* @param o
* @return
*/
fun serializeObject(o: Any): ByteArray? {
val bos = ByteArrayOutputStream();
try {
val out = ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
val buf = bos.toByteArray();
return buf;
} catch(error: IOException) {
error.printStackTrace();
return null;
}
}
/**
* deserialize object
*
* @param b
* @return
*/
fun deserializeObject(b: ByteArray): Serializable? {
try {
val input = ObjectInputStream(ByteArrayInputStream(b))
val result = input.readObject()
input.close();
return result as Serializable;
} catch(error: ClassNotFoundException) {
error.printStackTrace();
return null;
} catch(error: IOException) {
error.printStackTrace();
return null;
}
}
fun textFromTextView(resID: Int, rootView: View): String? {
val textView = rootView.findViewById(resID)
if (textView is TextView) {
return textView.text.toString()
}
return null
}
| 0
|
Kotlin
|
0
| 2
|
01a49c551f0cc0f2188250460c907572ba12acf3
| 22,734
|
ViolinDs
|
Apache License 2.0
|
app/src/main/java/io/nosyntax/foundation/di/AppEntryPoint.kt
|
aelrahmanashraf
| 683,553,348
| false
|
{"Kotlin": 192257, "Groovy": 3276, "HTML": 1491, "Batchfile": 1149, "Shell": 744}
|
package io.nosyntax.foundation.di
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@EntryPoint
@InstallIn(SingletonComponent::class)
interface AppEntryPoint {
}
| 0
|
Kotlin
|
0
| 0
|
5918bafc18feb5a579ef11f1fdffdea53fbffa6d
| 222
|
nosyntax-foundation-android
|
MIT License
|
processor/src/main/kotlin/com/casadetasha/kexp/sproute/processor/sproutes/SprouteParent.kt
|
Path-to-plunder
| 427,878,747
| false
| null |
package com.casadetasha.kexp.sproute.processor.sproutes
import com.squareup.kotlinpoet.MemberName
internal sealed class SprouteParent(
val packageName: String,
val classSimpleName: String
) : Comparable<SprouteParent> {
val memberName = MemberName(packageName, classSimpleName)
abstract val sprouteRequestFunctions: Set<SprouteRequestFunction>
override fun compareTo(other: SprouteParent): Int {
return this.memberName.toString().compareTo(other.memberName.toString())
}
}
| 0
|
Kotlin
|
0
| 1
|
3e75b3b053aac64c508568900f38b018b54b5e9e
| 510
|
Sproutes
|
Apache License 2.0
|
feature-wallet-api/src/main/java/io/novafoundation/nova/feature_wallet_api/presentation/view/amount/ChooseAmountInputView.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 8152538, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_wallet_api.presentation.view.amount
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintLayout
import coil.ImageLoader
import io.novafoundation.nova.common.di.FeatureUtils
import io.novafoundation.nova.common.utils.setTextOrHide
import io.novafoundation.nova.common.view.shape.getInputBackground
import io.novafoundation.nova.feature_account_api.presenatation.chain.loadTokenIcon
import io.novafoundation.nova.feature_wallet_api.R
import io.novafoundation.nova.feature_wallet_api.presentation.model.ChooseAmountInputModel
import kotlinx.android.synthetic.main.view_choose_amount_input.view.chooseAmountInputFiat
import kotlinx.android.synthetic.main.view_choose_amount_input.view.chooseAmountInputField
import kotlinx.android.synthetic.main.view_choose_amount_input.view.chooseAmountInputImage
import kotlinx.android.synthetic.main.view_choose_amount_input.view.chooseAmountInputToken
class ChooseAmountInputView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
) : ConstraintLayout(context, attrs, defStyle) {
val amountInput: EditText
get() = chooseAmountInputField
private val imageLoader: ImageLoader by lazy(LazyThreadSafetyMode.NONE) {
FeatureUtils.getCommonApi(context).imageLoader()
}
init {
View.inflate(context, R.layout.view_choose_amount_input, this)
setAddStatesFromChildren(true) // so view will be focused when `chooseAmountInput` is focused
background = context.getInputBackground()
}
fun loadAssetImage(imageUrl: String?) {
chooseAmountInputImage.loadTokenIcon(imageUrl, imageLoader)
}
fun setAssetName(name: String) {
chooseAmountInputToken.text = name
}
fun setFiatAmount(priceAmount: String?) {
chooseAmountInputFiat.setTextOrHide(priceAmount)
}
}
fun ChooseAmountInputView.setChooseAmountInputModel(model: ChooseAmountInputModel) {
loadAssetImage(model.tokenIcon)
setAssetName(model.tokenSymbol)
}
| 13
|
Kotlin
|
6
| 9
|
b39307cb56302ce7298582dbd03f33f6b2e2a807
| 2,159
|
nova-wallet-android
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/controller/NovaChaveController.kt
|
abner-ribeiro
| 410,858,566
| true
|
{"Kotlin": 20288}
|
package br.com.zup.controller
import br.com.zup.KeyManagerRegistraServiceGrpc
import br.com.zup.dto.NovaChaveDto
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Post
import io.micronaut.validation.Validated
import jakarta.inject.Inject
import javax.validation.Valid
@Validated
@Controller("/clientes/{clienteId}/keys")
class NovaChaveController(val client: KeyManagerRegistraServiceGrpc.KeyManagerRegistraServiceBlockingStub) {
@Post
fun cadastra(clienteId: String, @Valid @Body request: NovaChaveDto): HttpResponse<Any> {
val response = client.cadastraChave(request.paraNovaChavePixGrpc(clienteId))
return HttpResponse.created(HttpResponse.uri("/clientes/$clienteId/keys/${response.pixId}"))
}
}
| 0
|
Kotlin
|
0
| 0
|
c2ed26c8c10f9765d4d0c45e0f99840c331f0898
| 841
|
orange-talents-07-template-pix-keymanager-rest
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/deliusapi/mapper/ContactMapperTest.kt
|
uk-gov-mirror
| 356,783,147
| false
|
{"Kotlin": 522238, "Dockerfile": 3159, "Shell": 2477}
|
package uk.gov.justice.digital.hmpps.deliusapi.mapper
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.deliusapi.dto.v1.contact.ContactDto
import uk.gov.justice.digital.hmpps.deliusapi.dto.v1.contact.UpdateContact
import uk.gov.justice.digital.hmpps.deliusapi.util.Fake
import uk.gov.justice.digital.hmpps.deliusapi.util.hasProperty
class ContactMapperTest {
@Test
fun `Mapping from entity to dto`() {
val source = Fake.contact()
val observed = ContactMapper.INSTANCE.toDto(source)
assertThat(observed)
.hasProperty(ContactDto::id, source.id)
.hasProperty(ContactDto::offenderCrn, source.offender.crn)
.hasProperty(ContactDto::type, source.type.code)
.hasProperty(ContactDto::outcome, source.outcome?.code)
.hasProperty(ContactDto::enforcement, source.enforcements[0].action?.code!!)
.hasProperty(ContactDto::provider, source.provider?.code)
.hasProperty(ContactDto::team, source.team?.code)
.hasProperty(ContactDto::staff, source.staff?.code)
.hasProperty(ContactDto::officeLocation, source.officeLocation?.code)
.hasProperty(ContactDto::date, source.date)
.hasProperty(ContactDto::startTime, source.startTime)
.hasProperty(ContactDto::endTime, source.endTime)
.hasProperty(ContactDto::alert, source.alert)
.hasProperty(ContactDto::sensitive, source.sensitive)
.hasProperty(ContactDto::notes, source.notes)
.hasProperty(ContactDto::description, source.description)
.hasProperty(ContactDto::eventId, source.event?.id!!)
.hasProperty(ContactDto::requirementId, source.requirement?.id!!)
}
@Test
fun `Mapping from entity to update`() {
val source = Fake.contact()
val observed = ContactMapper.INSTANCE.toUpdate(source)
assertThat(observed)
.hasProperty(UpdateContact::outcome, source.outcome?.code)
.hasProperty(UpdateContact::enforcement, source.enforcements[0].action?.code!!)
.hasProperty(UpdateContact::provider, source.provider?.code)
.hasProperty(UpdateContact::team, source.team?.code)
.hasProperty(UpdateContact::staff, source.staff?.code)
.hasProperty(UpdateContact::officeLocation, source.officeLocation?.code)
.hasProperty(UpdateContact::date, source.date)
.hasProperty(UpdateContact::startTime, source.startTime)
.hasProperty(UpdateContact::endTime, source.endTime)
.hasProperty(UpdateContact::alert, source.alert)
.hasProperty(UpdateContact::sensitive, source.sensitive)
.hasProperty(UpdateContact::notes, null)
.hasProperty(UpdateContact::description, source.description)
}
}
| 0
|
Kotlin
|
0
| 0
|
ed5f77a92a1f6f0615998bfdb4282d600a3ada71
| 2,687
|
ministryofjustice.hmpps-delius-api
|
MIT License
|
demo/src/main/java/com/zwy/demo/views/MainActivity.kt
|
hesiming
| 273,230,049
| true
|
{"Kotlin": 88762}
|
package com.zwy.demo.views
import android.app.Activity
import android.os.Bundle
import com.zwy.demo.R
import com.zwy.demo.base.BaseActivity
import com.zwy.demo.databinding.MainLayoutBinding
import com.zwy.demo.models.MainViewModel
import d
import org.jetbrains.anko.toast
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
class MainActivity : BaseActivity<MainLayoutBinding, MainViewModel>() {
/**
* 初始化根布局
*
* @return 布局layout的id
*/
override fun initContentView(savedInstanceState: Bundle?): Int = R.layout.activity_main
override fun initData() {
binding.titles = viewModel.titles
viewModel.getTitles()
// copyAssetsFile2Phone(this,"nsfw.tflite")
}
private var mExitTime: Long = 0
override fun onBackPressed() {
if (System.currentTimeMillis() - mExitTime < 2000) {
super.onBackPressed();
} else {
mExitTime = System.currentTimeMillis();
toast("再按一次返回键退出应用")
}
}
// /**
// * 将文件从assets目录,考贝到 /data/data/包名/files/ 目录中。assets 目录中的文件,会不经压缩打包至APK包中,使用时还应从apk包中导出来
// * @param fileName 文件名,如aaa.txt
// */
// fun copyAssetsFile2Phone(activity: Activity, fileName: String) {
// try {
// val inputStream: InputStream = activity.assets.open(fileName)
// //getFilesDir() 获得当前APP的安装路径 /data/data/包名/files 目录
// val file = File(
// activity.filesDir.absolutePath + File.separator.toString() + fileName
// )
// if (!file.exists() || file.length()==0L) {
// val fos = FileOutputStream(file) //如果文件不存在,FileOutputStream会自动创建文件
// var len = -1
// val buffer = ByteArray(1024)
// while (inputStream.read(buffer).also({ len = it }) != -1) {
// fos.write(buffer, 0, len)
// }
// fos.flush() //刷新缓存区
// inputStream.close()
// fos.close()
// "模型文件复制完毕".d()
// } else {
// "模型文件已存在,无需复制".d()
// }
// } catch (e: IOException) {
// e.printStackTrace()
// }
// }
}
| 0
| null |
0
| 1
|
01102e2f4ee839cb5753535a399be34e43b2d325
| 2,250
|
open_nsfw_android
|
Apache License 2.0
|
src/main/kotlin/br/com/fiap/mikes/production/application/core/domain/ProductionHistory.kt
|
matheuscosantos
| 738,716,181
| false
|
{"Kotlin": 106333, "HCL": 7152, "Gherkin": 3690, "Shell": 533, "Dockerfile": 209}
|
package br.com.fiap.mikes.production.application.core.domain
import br.com.fiap.mikes.production.application.core.domain.valueobject.OrderId
import br.com.fiap.mikes.production.application.core.domain.valueobject.ProductionHistoryId
import br.com.fiap.mikes.production.application.core.domain.valueobject.ProductionStatus
import java.time.LocalDateTime
class ProductionHistory private constructor(
val id: ProductionHistoryId,
val orderId: OrderId,
val status: ProductionStatus,
val createdAt: LocalDateTime,
val updatedAt: LocalDateTime,
) {
companion object {
fun new(
id: ProductionHistoryId,
orderId: OrderId,
status: ProductionStatus,
createdAt: LocalDateTime,
updatedAt: LocalDateTime,
): Result<ProductionHistory> = Result.success(ProductionHistory(id, orderId, status, createdAt, updatedAt))
}
}
| 0
|
Kotlin
|
0
| 0
|
786c0143e1ef6c584b05a81ff003f9d360e1c355
| 910
|
mikes-producao
|
Apache License 2.0
|
Pokedex/app/src/main/java/com/example/pokedex/data/model/PokemonType.kt
|
ricardovalverde
| 400,578,357
| false
| null |
package com.example.pokedex.data.model
data class PokemonType(
val type: String
)
| 0
|
Kotlin
|
0
| 0
|
a4c51ffb3e7ff8252ac78ec2544ea8dafd6b913d
| 86
|
pokedex
|
MIT License
|
app/src/main/java/com/geovannycode/jetpackcompose/ecoeats/data/util/Util.kt
|
geovannymcode
| 857,588,318
| false
|
{"Kotlin": 61091}
|
package com.geovannycode.jetpackcompose.ecoeats.data.util
import android.content.SharedPreferences
object Util {
fun saveTokenSharePreferences(sharedPreferences: SharedPreferences, data:String){
sharedPreferences.edit().putString("KEY_TOKEN", data).apply()
}
fun SharedPreferences.save(data:String){
this.edit().putString("KEY_TOKEN", data).apply()
}
fun SharedPreferences.getToken(): String{
return this.getString("KEY_TOKEN","") ?: ""
}
}
| 0
|
Kotlin
|
0
| 0
|
d6277851c15c8d40c92e2a586e8cf5b0eb77266a
| 493
|
jetpackcompose-ecoeats
|
Apache License 2.0
|
shared/src/desktopMain/kotlin/de/xorg/gsapp/data/sources/local/PathSource.kt
|
libf-de
| 689,474,523
| false
|
{"Kotlin": 372877, "Swift": 743, "Ruby": 406, "Shell": 228}
|
package de.xorg.gsapp.data.sources.local
import net.harawata.appdirs.AppDirsFactory
import org.kodein.di.DI
import org.kodein.di.DIAware
import java.util.prefs.Preferences
actual class PathSource actual constructor(override val di: DI) : DIAware {
val appDir: String = AppDirsFactory.getInstance().getUserCacheDir("gsapp", "3", "de.xorg")
actual fun getSubstitutionPath(): String {
return "$appDir/substitutions.json"
}
actual fun getSubjectsPath(): String {
return "$appDir/subjects.json"
}
actual fun getTeachersPath(): String {
return "$appDir/teachers.json"
}
actual fun getFoodplanPath(): String {
return "$appDir/foodplan.json"
}
actual fun getAdditivesPath(): String {
return "$appDir/additives.json"
}
}
| 6
|
Kotlin
|
0
| 1
|
f9bba225649a71636f407c2a47e877d828fcfe73
| 803
|
GSApp3-MP
|
Apache License 2.0
|
src/main/kotlin/be/zvz/alsong/deserializer/LyricDeserializer.kt
|
JellyBrick
| 373,705,678
| false
| null |
package be.zvz.alsong.deserializer
import be.zvz.alsong.Utils
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
class LyricDeserializer : JsonDeserializer<Map<Long, List<String>>>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Map<Long, List<String>> =
Utils.parseLyric(p.valueAsString)
}
| 1
|
Kotlin
|
0
| 7
|
7a586b94fac0dde4e9eb04ff776f1c5853562142
| 442
|
alsong-kt
|
Apache License 2.0
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/codebuild/CfnProjectLogsConfigPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION")
package cloudshift.awscdk.dsl.services.codebuild
import cloudshift.awscdk.common.CdkDslMarker
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.codebuild.CfnProject
/**
* `LogsConfig` is a property of the [AWS CodeBuild
* Project](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html)
* resource that specifies information about logs for a build project. These can be logs in Amazon
* CloudWatch Logs, built in a specified S3 bucket, or both.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.codebuild.*;
* LogsConfigProperty logsConfigProperty = LogsConfigProperty.builder()
* .cloudWatchLogs(CloudWatchLogsConfigProperty.builder()
* .status("status")
* // the properties below are optional
* .groupName("groupName")
* .streamName("streamName")
* .build())
* .s3Logs(S3LogsConfigProperty.builder()
* .status("status")
* // the properties below are optional
* .encryptionDisabled(false)
* .location("location")
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-logsconfig.html)
*/
@CdkDslMarker
public class CfnProjectLogsConfigPropertyDsl {
private val cdkBuilder: CfnProject.LogsConfigProperty.Builder =
CfnProject.LogsConfigProperty.builder()
/**
* @param cloudWatchLogs Information about CloudWatch Logs for a build project.
* CloudWatch Logs are enabled by default.
*/
public fun cloudWatchLogs(cloudWatchLogs: IResolvable) {
cdkBuilder.cloudWatchLogs(cloudWatchLogs)
}
/**
* @param cloudWatchLogs Information about CloudWatch Logs for a build project.
* CloudWatch Logs are enabled by default.
*/
public fun cloudWatchLogs(cloudWatchLogs: CfnProject.CloudWatchLogsConfigProperty) {
cdkBuilder.cloudWatchLogs(cloudWatchLogs)
}
/**
* @param s3Logs Information about logs built to an S3 bucket for a build project.
* S3 logs are not enabled by default.
*/
public fun s3Logs(s3Logs: IResolvable) {
cdkBuilder.s3Logs(s3Logs)
}
/**
* @param s3Logs Information about logs built to an S3 bucket for a build project.
* S3 logs are not enabled by default.
*/
public fun s3Logs(s3Logs: CfnProject.S3LogsConfigProperty) {
cdkBuilder.s3Logs(s3Logs)
}
public fun build(): CfnProject.LogsConfigProperty = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 2,800
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
common/src/main/kotlin/com/vnapnic/common/entities/ResultCode.kt
|
alphaNumericEntity
| 763,513,563
| false
|
{"Kotlin": 397164, "Java": 8775, "HTML": 6673, "Dockerfile": 224}
|
package com.vnapnic.common.entities
enum class ResultCode(val code: Int, val message: String) {
// Successfully
SUCCESS(200, "Successful"),
FAILED(500, "Failed"),
UNAUTHORIZED(401, "Not logged in yet or token has expired"),
FORBIDDEN(403, "No relevant permissions"),
NOT_FOUND(404, "Not found"),
EXPECTATION_FAILED(417, "Expectation Failed"),
// Error
SERVER_UNKNOWN_ERROR(1000, "Server unknown error."),
EMAIL_PASSWORD_INCORRECT(1001, "Email/Password incorrect."),
SOCIAL_PASSWORD_INCORRECT(1002, "Social/Password incorrect."),
PHONE_NUMBER_NOT_EXISTS(1003, "Phone number not exists."),
PASSWORD_IS_NULL_BLANK(1004, "Password is null or blank."),
EMAIL_IS_NULL_BLANK(1005, "Email is null or blank."),
EMAIL_IS_EXISTS(1006, "Email is exists."),
SOCIAL_IS_EXISTS(1007, "Social is exists."),
PHONE_NUMBER_IS_NULL_BLANK(1008, "Phone number is null or blank."),
PHONE_NUMBER_IS_EXISTS(1009, "Phone number is exists."),
STAFF_CODE_IS_NULL_BLANK(1010, "Staff code is null or blank."),
FILE_TOO_LARGE(1011, "File too large."),
FILE_UPLOAD_FAIL(1012, "Upload file fail."),
UNSUPPORTED_MEDIA_TYPE(1013, "Unsupported Media Type."),
UNSUPPORTED_DEVICE(1014, "Unsupported device."),
PHONE_NUMBER_WRONG_FORMAT(1015, "Wrong phone number format."),
EMAIL_WRONG_FORMAT(1016, "Wrong email format."),
USER_NOT_FOUND(1017, "User not found."),
WARNING_DATA_FORMAT(1018, "Warning data format."),
VERIFY_CODE_EXPIRE(1019, "verify code expire."),
VERIFY_CODE_INCORRECT(1020, "verify code is incorrect."),
WRONG_TOO_MANY_TIME(1021, "Entering a wrong too many times.")
}
| 0
|
Kotlin
|
0
| 0
|
495581ca09d1c4a03e2643ce8601886009b39665
| 1,686
|
kotlin-spring-boot-microservices
|
Apache License 2.0
|
02-set-up-the-project/starter/app/src/main/java/com/raywenderlich/android/librarian/database/dao/ReadingListDao.kt
|
GoddayOkos
| 386,239,555
| false
| null |
package com.raywenderlich.android.librarian.database.dao
import androidx.room.*
import com.raywenderlich.android.librarian.model.ReadingList
import kotlinx.coroutines.flow.Flow
@Dao
interface ReadingListDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addReadingList(readingList: ReadingList)
@Query("SELECT * FROM readinglist")
suspend fun getReadListing(): List<ReadingList>
@Transaction
@Query("SELECT * FROM readinglist")
fun getReadingListFlow(): Flow<List<ReadingList>>
@Delete
suspend fun removeReadingList(readingList: ReadingList)
@Query("SELECT * FROM readinglist WHERE id = :listId")
suspend fun getReadingListById(listId: String): ReadingList
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateReadingList(newReadingList: ReadingList)
}
| 0
|
Kotlin
|
0
| 0
|
4ea73dc92ded377f15cfdf7359ffd09f0629163f
| 842
|
Librarian-App
|
Apache License 2.0
|
app/src/main/java/com/trackerbreeze/features/dailyPlan/api/PlanApi.kt
|
DebashisINT
| 598,511,717
| false
|
{"Kotlin": 15827152, "Java": 1025908}
|
package com.trackerbreeze.features.dailyPlan.api
import com.trackerbreeze.app.NetworkConstant
import com.trackerbreeze.base.BaseResponse
import com.trackerbreeze.features.dailyPlan.model.AllPlanListResponseModel
import com.trackerbreeze.features.dailyPlan.model.GetPlanDetailsResponseModel
import com.trackerbreeze.features.dailyPlan.model.GetPlanListResponseModel
import com.trackerbreeze.features.dailyPlan.model.UpdatePlanListInputParamsModel
import io.reactivex.Observable
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* Created by Saikat on 24-12-2019.
*/
interface PlanApi {
@FormUrlEncoded
@POST("FundPlan/FundPlanList")
fun getPlanList(@Field("session_token") session_token: String, @Field("user_id") user_id: String): Observable<GetPlanListResponseModel>
@POST("FundPlan/UpdateFundPlan")
fun updatePlanList(@Body updatePlan: UpdatePlanListInputParamsModel): Observable<BaseResponse>
@FormUrlEncoded
@POST("FundPlan/FundPlanDetailsList")
fun getPlanListDetails(@Field("session_token") session_token: String, @Field("user_id") user_id: String,
@Field("plan_id") plan_id: String): Observable<GetPlanDetailsResponseModel>
@FormUrlEncoded
@POST("FundPlan/GetAllFundPlanList")
fun getAllPlanList(@Field("session_token") session_token: String, @Field("user_id") user_id: String): Observable<AllPlanListResponseModel>
/**
* Companion object to create the GithubApiService
*/
companion object Factory {
fun create(): PlanApi {
val retrofit = Retrofit.Builder()
.client(NetworkConstant.setTimeOut())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(NetworkConstant.BASE_URL)
.build()
return retrofit.create(PlanApi::class.java)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
cc23d7abc8ccd898d5b8f55405c013b6167c2c2c
| 2,162
|
NTC
|
Apache License 2.0
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Textalignright.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Textalignright: ImageVector
get() {
if (_textalignright != null) {
return _textalignright!!
}
_textalignright = Builder(name = "Textalignright", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 5.25f)
horizontalLineTo(3.0f)
curveTo(2.59f, 5.25f, 2.25f, 4.91f, 2.25f, 4.5f)
curveTo(2.25f, 4.09f, 2.59f, 3.75f, 3.0f, 3.75f)
horizontalLineTo(21.0f)
curveTo(21.41f, 3.75f, 21.75f, 4.09f, 21.75f, 4.5f)
curveTo(21.75f, 4.91f, 21.41f, 5.25f, 21.0f, 5.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0013f, 10.25f)
horizontalLineTo(11.5312f)
curveTo(11.1213f, 10.25f, 10.7812f, 9.91f, 10.7812f, 9.5f)
curveTo(10.7812f, 9.09f, 11.1213f, 8.75f, 11.5312f, 8.75f)
horizontalLineTo(21.0013f)
curveTo(21.4113f, 8.75f, 21.7513f, 9.09f, 21.7513f, 9.5f)
curveTo(21.7513f, 9.91f, 21.4113f, 10.25f, 21.0013f, 10.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 15.25f)
horizontalLineTo(3.0f)
curveTo(2.59f, 15.25f, 2.25f, 14.91f, 2.25f, 14.5f)
curveTo(2.25f, 14.09f, 2.59f, 13.75f, 3.0f, 13.75f)
horizontalLineTo(21.0f)
curveTo(21.41f, 13.75f, 21.75f, 14.09f, 21.75f, 14.5f)
curveTo(21.75f, 14.91f, 21.41f, 15.25f, 21.0f, 15.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0013f, 20.25f)
horizontalLineTo(11.5312f)
curveTo(11.1213f, 20.25f, 10.7812f, 19.91f, 10.7812f, 19.5f)
curveTo(10.7812f, 19.09f, 11.1213f, 18.75f, 11.5312f, 18.75f)
horizontalLineTo(21.0013f)
curveTo(21.4113f, 18.75f, 21.7513f, 19.09f, 21.7513f, 19.5f)
curveTo(21.7513f, 19.91f, 21.4113f, 20.25f, 21.0013f, 20.25f)
close()
}
}
.build()
return _textalignright!!
}
private var _textalignright: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 3,885
|
VuesaxIcons
|
MIT License
|
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/jobs/InvoicingJobFactory.kt
|
tiagobluiz
| 630,198,573
| false
| null |
package io.pleo.antaeus.core.jobs
import io.pleo.antaeus.core.services.BillingService
import org.quartz.Job
import org.quartz.Scheduler
import org.quartz.spi.JobFactory
import org.quartz.spi.TriggerFiredBundle
class InvoicingJobFactory(private val billingService: BillingService) : JobFactory {
override fun newJob(bundle: TriggerFiredBundle, scheduler: Scheduler): Job {
val jobDetail = bundle.jobDetail
val jobClass = jobDetail.jobClass
return jobClass.getConstructor(BillingService::class.java).newInstance(billingService)
}
}
| 0
|
Kotlin
|
0
| 0
|
8cb49c4d81f47380d5d115a0f61581cdd66b4cd4
| 566
|
pleo-challenge
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/rs/codingexercisegyg/reviewslist/ReviewsListViewModel.kt
|
ranjeetsinha13
| 238,456,800
| false
| null |
package com.rs.codingexercisegyg.reviewslist
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import com.rs.codingexercisegyg.network.data.Review
import javax.inject.Inject
class ReviewsListViewModel @Inject
constructor(private val reviewsDataSourceFactory: ReviewsDataSourceFactory) : ViewModel() {
private lateinit var reviews: LiveData<PagedList<Review>>
companion object {
private const val PAGE_SIZE = 4
private const val INITIAL_LOAD_SIZE = 100
}
fun onScreenCreated() {
val config = PagedList.Config.Builder()
.setPageSize(PAGE_SIZE)
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(INITIAL_LOAD_SIZE)
.build()
reviews = LivePagedListBuilder(reviewsDataSourceFactory, config).build()
}
fun getReviews(): LiveData<PagedList<Review>> {
return reviews
}
fun initialLoadState(): LiveData<NetworkState> {
return reviewsDataSourceFactory.reviewsDataSource.getInitialLoadStateLiveData()
}
fun paginatedLoadState(): LiveData<NetworkState> {
return reviewsDataSourceFactory.reviewsDataSource.getPaginatedNetworkStateLiveData()
}
override fun onCleared() {
super.onCleared()
reviewsDataSourceFactory.reviewsDataSource.clear()
}
fun retry() {
reviewsDataSourceFactory.reviewsDataSource.retryPagination()
}
}
| 0
|
Kotlin
|
0
| 0
|
f39314bb2962648ade3530e996f4ad05c5749f3b
| 1,505
|
CodingExerciseGYG
|
MIT License
|
peel/src/main/kotlin/net/tjalp/peach/peel/util/GsonHelper.kt
|
tjalp
| 421,781,027
| false
| null |
package net.tjalp.peach.peel.util
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonObject
/**
* Helper class for using Gson functionality
* within peach.
*/
object GsonHelper {
/** The internal Gson builder */
private val globalBuilder: GsonBuilder = GsonBuilder()
private var gsonCache: Gson? = null
private val gsonPrettyCache: Gson = GsonBuilder().setPrettyPrinting().create()
/**
* Returns the builder instance for the global Gson parser
*
* @return The global GsonBuilder
*/
fun modify() : GsonBuilder {
gsonCache = null
return globalBuilder
}
/**
* Returns the global Gson instance. Once this method is
* called, all future modifications to the global gson
* will be prevented.
*
* @return Gson
*/
fun global() : Gson {
return gsonCache ?: globalBuilder.create().also {
gsonCache = it
}
}
/**
* Returns the global pretty Gson instance.
*
* @return Pretty Gson
*/
fun pretty() : Gson {
return gsonPrettyCache
}
private val pathRegex = Regex("^[a-zA-Z_.]+$")
/**
* Resolve the given access path on the supplied JsonObject
*
* @param instance The json object
* @return The resolved element
*/
fun resolve(instance: JsonObject?, path: String) : JsonElement? {
if(!pathRegex.matches(path)) {
throw IllegalArgumentException("Path $path does not match format $pathRegex")
} else if(instance == null) {
return null
}
val segments = path.split(".")
var prev: JsonElement = instance
for(seg in segments) {
prev = prev.asJsonObject[seg] ?: return null
}
return prev
}
}
| 0
|
Kotlin
|
0
| 0
|
0d74c084b3e83dfaaec7a2bf52f056de7a5f6a08
| 1,648
|
peach
|
MIT License
|
vclib/src/commonMain/kotlin/at/asitplus/wallet/lib/data/InstantStringSerializer.kt
|
a-sit-plus
| 602,578,639
| false
|
{"Kotlin": 779179}
|
package at.asitplus.wallet.lib.data
import kotlinx.datetime.Instant
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
class InstantStringSerializer : KSerializer<Instant> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("InstantStringSerializer", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Instant {
return Instant.parse(decoder.decodeString())
}
override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeString(value.toString())
}
}
| 4
|
Kotlin
|
2
| 9
|
cd329850e8ccd735cd2b8f43624059b60dbd0008
| 807
|
kmm-vc-library
|
Apache License 2.0
|
centurion-avro/src/main/kotlin/com/sksamuel/centurion/avro/io/DataWriter.kt
|
sksamuel
| 13,625,531
| false
|
{"Dotenv": 1, "Gradle Kotlin DSL": 9, "YAML": 5, "Markdown": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 113, "INI": 1, "XML": 1, "Java": 2}
|
package com.sksamuel.centurion.avro.io
import org.apache.avro.Schema
import org.apache.avro.file.CodecFactory
import org.apache.avro.file.DataFileWriter
import org.apache.avro.generic.GenericDatumWriter
import org.apache.avro.generic.GenericRecord
import java.io.ByteArrayOutputStream
import java.io.OutputStream
/**
* Creates a [DataWriterFactory] which can then be used to create [DataWriter]s.
*/
class DataWriterFactory(
private val codec: CodecFactory,
) {
/**
* Creates a [DataWriter] that writes to the given [OutputStream].
* Calling close on the created writer will close this stream and ensure data is flushed.
*/
fun writer(schema: Schema, output: OutputStream): DataWriter {
return DataWriter( schema, output, codec)
}
/**
* Creates a [DataWriter] that uses a [ByteArrayOutputStream].
* Once records have been written, users can call bytes() to retrieve the [ByteArray].
*/
fun writer(schema: Schema): DataWriter {
return DataWriter(schema, ByteArrayOutputStream(), codec)
}
/**
* Creates an avro encoded byte array from the given [record].
*
* This method is a convenience function that is useful when you want to write a single record
* in a single method call.
*/
fun toBytes(record: GenericRecord): ByteArray {
return toBytes(listOf(record))
}
/**
* Creates an avro encoded byte array from the given [record]s.
*
* This method is a convenience function that is useful when you want to write a batch
* of records in a single method call.
*/
fun toBytes(records: List<GenericRecord>): ByteArray {
require(records.isNotEmpty())
val writer = DataWriter(records.first().schema, ByteArrayOutputStream(), codec)
records.forEach { writer.write(it) }
writer.close()
return writer.bytes()
}
}
/**
* A [DataWriter] is a non-thread safe, one time use, writer to a given stream, that encodes
* Avro [GenericRecord]s as data-encoded bytes (that is, includes the schema along with the binary).
*
* Call [close] when all records have been written to ensure data is flushed to the underlying stream.
*
* If you do not want to include the schema, see [BinaryWriter].
*/
class DataWriter(
schema: Schema,
private val output: OutputStream,
codecFactory: CodecFactory,
) : AutoCloseable {
private val datum = GenericDatumWriter<GenericRecord>(schema)
private val writer = DataFileWriter(datum).setCodec(codecFactory).create(schema, output)
fun write(record: GenericRecord): DataWriter {
writer.append(record)
return this
}
private fun flush() {
writer.flush()
}
override fun close() {
writer.close()
output.close()
}
/**
* Returns the bytes written as a [ByteArray].
*
* Throws an exception if this [DataWriter] was *not* instantiated with a [ByteArrayOutputStream].
*/
fun bytes(): ByteArray {
close()
return (output as ByteArrayOutputStream).toByteArray()
}
}
| 0
|
Kotlin
|
46
| 326
|
9efc1ca590963a28712ea878a3002bc13d51a496
| 3,029
|
rxhive
|
Apache License 2.0
|
app/src/main/java/com/foreveross/atwork/modules/lite/activity/LiteBindScanActivity.kt
|
AoEiuV020
| 421,650,297
| false
|
{"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559}
|
package com.foreveross.atwork.modules.lite.activity
import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import com.foreveross.atwork.infrastructure.utils.extension.putParcelableDirectly
import com.foreveross.atwork.modules.lite.fragment.LiteBindScanFragment
import com.foreveross.atwork.modules.lite.module.LiteBindConfig
import com.foreveross.atwork.support.SingleFragmentActivity
class LiteBindScanActivity: SingleFragmentActivity(){
override fun createFragment(): Fragment = LiteBindScanFragment()
companion object {
@JvmStatic
fun getIntent(context: Context, liteBindConfig: LiteBindConfig): Intent {
val intent = Intent(context, LiteBindScanActivity::class.java)
intent.putParcelableDirectly(liteBindConfig)
return intent
}
}
}
| 1
| null |
1
| 1
|
1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5
| 858
|
w6s_lite_android
|
MIT License
|
chats/src/main/java/com/cyberland/messenger/chats/components/ConversationInputPanel.kt
|
Era-CyberLabs
| 576,196,269
| false
|
{"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472}
|
package com.bcm.messenger.chats.components
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Vibrator
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.RotateAnimation
import android.widget.EditText
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bcm.messenger.chats.R
import com.bcm.messenger.chats.adapter.BottomPanelAdapter
import com.bcm.messenger.chats.adapter.ChatAtListAdapter
import com.bcm.messenger.chats.bean.BottomPanelItem
import com.bcm.messenger.chats.group.logic.GroupLogic
import com.bcm.messenger.common.ARouterConstants
import com.bcm.messenger.common.AccountContext
import com.bcm.messenger.common.audio.AudioRecorder
import com.bcm.messenger.common.core.AmeGroupMessage
import com.bcm.messenger.common.core.corebean.AmeGroupMemberInfo
import com.bcm.messenger.common.crypto.MasterSecret
import com.bcm.messenger.common.event.MultiSelectEvent
import com.bcm.messenger.common.grouprepository.model.AmeGroupMessageDetail
import com.bcm.messenger.common.provider.AMELogin
import com.bcm.messenger.common.provider.AmeModuleCenter
import com.bcm.messenger.common.recipients.Recipient
import com.bcm.messenger.common.ui.InputAwareLayout
import com.bcm.messenger.common.ui.KeyboardAwareLinearLayout
import com.bcm.messenger.common.ui.popup.ToastUtil
import com.bcm.messenger.common.utils.BcmGroupNameUtil
import com.bcm.messenger.common.utils.getColorCompat
import com.bcm.messenger.utility.StringAppearanceUtil
import com.bcm.messenger.utility.logger.ALog
import com.bcm.messenger.utility.permission.PermissionUtil
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.chats_conversation_input_panel.view.*
import org.greenrobot.eventbus.EventBus
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit
/**
* Created by wjh on 2018/8/24
*/
class ConversationInputPanel : androidx.constraintlayout.widget.ConstraintLayout,
VoiceRecodingPanel.Listener,
KeyboardAwareLinearLayout.OnKeyboardShownListener,
KeyboardAwareLinearLayout.OnKeyboardHiddenListener,
AudioRecorder.IRecorderListener {
interface OnConversationInputListener {
companion object {
const val AUDIO_START = 0
const val AUDIO_COMPLETE = 1
const val AUDIO_CANCEL = 2
const val AUDIO_ERROR = 3
}
//check before send text or audio,true: pass,false: cancel
fun onBeforeTextOrAudioHandle(): Boolean
fun onMessageSend(message: CharSequence, replyContent: AmeGroupMessage.ReplyContent? = null, extContent: AmeGroupMessageDetail.ExtensionContent? = null)
fun onEmojiPanelShow(show: Boolean)
fun onMoreOptionsPanelShow(show: Boolean)
fun onAudioStateChanged(state: Int, recordUri: Uri?, byteSize: Long, playTime: Long)
}
inner class ExtraContainer(val view: View, val isEmojiPanel: Boolean, override var isShowing: Boolean) : InputAwareLayout.InputView {
private var optionOpenAnim = RotateAnimation(0f, 45f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
private var optionCloseAnim = RotateAnimation(45f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
override fun show(height: Int, immediate: Boolean) {
isShowing = true
lockBottomExtraContainer(height)
if (isEmojiPanel) {
showEmojiPanel(true)
} else {
showMoreOptionPanel(true)
}
}
override fun hide(immediate: Boolean) {
isShowing = false
if (isEmojiPanel) {
showEmojiPanel(false)
} else {
showMoreOptionPanel(false)
}
if (mInputAwareLayout?.isKeyboardOpen == false && mEmojiContainer?.isShowing == false && mOptionContainer?.isShowing == false) {
lockBottomExtraContainer(0)
}
}
private fun showMoreOptionPanel(show: Boolean) {
if (show) {
if ((!optionOpenAnim.hasStarted() || optionOpenAnim.hasEnded()) && panel_option_container.visibility != View.VISIBLE) {
panel_more_options_iv.clearAnimation()
optionOpenAnim.duration = 100
optionOpenAnim.fillAfter = true
optionOpenAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
}
override fun onAnimationStart(animation: Animation?) {
panel_option_container.visibility = View.VISIBLE
mListener?.onMoreOptionsPanelShow(show)
}
})
panel_more_options_iv.startAnimation(optionOpenAnim)
}
} else {
if ((optionOpenAnim.hasStarted() && !optionOpenAnim.hasEnded()) || panel_option_container.visibility == View.VISIBLE) {
panel_more_options_iv.clearAnimation()
optionCloseAnim.duration = 100
optionCloseAnim.fillAfter = true
panel_more_options_iv.startAnimation(optionCloseAnim)
panel_option_container.visibility = View.GONE
mListener?.onMoreOptionsPanelShow(show)
}
}
}
/**
* @param show
*/
private fun showEmojiPanel(show: Boolean) {
if (show) {
if (panel_emoji_container.visibility != View.VISIBLE) {
panel_emoji_container.visibility = View.VISIBLE
panel_emoji_toggle.setImageDrawable(context.getDrawable(R.drawable.chats_conversation_keyboard_icon))
mListener?.onEmojiPanelShow(show)
}
} else {
if (panel_emoji_container.visibility == View.VISIBLE) {
panel_emoji_container.visibility = View.GONE
panel_emoji_toggle.setImageDrawable(context.getDrawable(R.drawable.chats_conversation_emoji_icon))
mListener?.onEmojiPanelShow(show)
}
}
}
}
companion object {
private const val TAG = "ConversationInputPanel"
const val OPTION_ITEM_CAMERA = "camera"
const val OPTION_ITEM_IMAGE = "image"
const val OPTION_ITEM_DOCUMENT = "document"
const val OPTION_ITEM_LOCATION = "location"
const val OPTION_ITEM_CALL = "call"
const val OPTION_ITEM_CONTACT = "contact"
const val OPTION_ITEM_RECALL = "recall"
const val OPTION_ITEM_MAX = 4 // item number
const val INPUT_NUM_MAX = 4000 // max char number
const val AUDIO_RECORD_MAX_TIME = 59800L //max 59s
}
constructor(context: Context) : this(context, null)
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) {
LayoutInflater.from(context).inflate(R.layout.chats_conversation_input_panel, this)
initResources(attributeSet)
init(context)
}
private var isGroup = false
private var mCurrentConversationId: Long = 0//group id or threadId
private var mAtDisposable: Disposable? = null
private var mListener: OnConversationInputListener? = null
private lateinit var mOptionAdapter: BottomPanelAdapter
private val mAllAtList = mutableListOf<Recipient>()
private lateinit var mChatAtAdapter: ChatAtListAdapter
private lateinit var audioRecorder: AudioRecorder
lateinit var voiceRecodingPanel: VoiceRecodingPanel
private var mInputAwareLayout: InputAwareLayout? = null
private var mEmojiContainer: ExtraContainer? = null
private var mOptionContainer: ExtraContainer? = null
private var mBatchSelected: Set<Any>? = null
override fun onAttachedToWindow() {
super.onAttachedToWindow()
mInputAwareLayout?.addOnKeyboardShownListener(this)
mInputAwareLayout?.addOnKeyboardHiddenListener(this)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
ALog.d(TAG, "onDetachedFromWindow")
mInputAwareLayout?.removeOnKeyboardHiddenListener(this)
mInputAwareLayout?.removeOnKeyboardShownListener(this)
}
override fun onStartClicked() {
ALog.i(TAG, "onStartClicked")
val pass = mListener?.onBeforeTextOrAudioHandle() ?: true
if (pass) {
if (checkHasAudioPermission()) {
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(10)
setWindowScreenLocked(true)
ALog.i(TAG, "onStartClicked")
audioRecorder.startRecording()
} else {
PermissionUtil.checkAudio(context) {}
}
}
}
override fun onFinishClicked() {
ALog.i(TAG, "onFinishClicked")
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(10)
setWindowScreenLocked(false)
audioRecorder.stopRecording()
panel_compose_text.requestFocus()
}
@SuppressLint("CheckResult")
override fun onCancelClicked() {
ALog.i(TAG, "onCancelClicked")
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(30)
setWindowScreenLocked(false)
audioRecorder.cancelRecording()
panel_compose_text.requestFocus()
}
override fun onRecorderStarted() {
ALog.i(TAG, "onRecorderStarted")
voiceRecodingPanel.showRecordState()
mListener?.onAudioStateChanged(OnConversationInputListener.AUDIO_START, null, 0, 0)
}
override fun onRecorderProgress(millisTime: Long) {
voiceRecodingPanel.showPlayTime(millisTime)
}
override fun onRecorderCanceled() {
ALog.i(TAG, "onRecorderCanceled ")
voiceRecodingPanel.hideRecordState()
}
override fun onRecorderFinished() {
voiceRecodingPanel.hideRecordState()
}
override fun onRecorderSucceed(recordUri: Uri, byteSize: Long, playTime: Long) {
ALog.i(TAG, "onRecordFinished $byteSize, time:$playTime")
if (byteSize > 0 && playTime >= 1000) {
mListener?.onAudioStateChanged(OnConversationInputListener.AUDIO_COMPLETE, recordUri, byteSize, playTime)
} else {
if (playTime < 1000) {
ToastUtil.show(context, context.getString(R.string.chats_record_time_too_short))
}
mListener?.onAudioStateChanged(OnConversationInputListener.AUDIO_CANCEL, recordUri, byteSize, playTime)
}
}
override fun onRecorderFailed(error: Exception) {
voiceRecodingPanel.hideRecordState()
ALog.e(TAG, "onRecorderFailed ", error)
ToastUtil.show(context, resources.getString(R.string.chats_unable_to_record_audio_warning))
mListener?.onAudioStateChanged(OnConversationInputListener.AUDIO_ERROR, null, 0, 0)
}
override fun onKeyboardHidden() {
if (mEmojiContainer?.isShowing == false && mOptionContainer?.isShowing == false) {
lockBottomExtraContainer(0)
}
}
override fun onKeyboardShown() {
ALog.d(TAG, "onKeyboardShown")
voiceRecodingPanel.onKeyboardShown()
mInputAwareLayout?.let {
lockBottomExtraContainer(it.keyboardHeight)
}
}
private fun initResources(attributeSet: AttributeSet?) {
val array = context.obtainStyledAttributes(attributeSet, R.styleable.chats_conversationInputPanelStyle)
isGroup = array.getBoolean(R.styleable.chats_conversationInputPanelStyle_chats_isGroup, false)
array.recycle()
panel_compose_text.background?.setColorFilter(context.getColorCompat(R.color.common_color_white), PorterDuff.Mode.MULTIPLY)
clipChildren = false
clipToPadding = false
}
private fun init(context: Context) {
mEmojiContainer = ExtraContainer(panel_emoji_container, true, false)
mOptionContainer = ExtraContainer(panel_option_container, false, false)
panel_compose_text.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
val text = s.toString().trim()
updateToggleButtonState(text.isNotEmpty())
if (text.length > INPUT_NUM_MAX) {
panel_compose_text.setText(panel_compose_text.text?.subSequence(0, INPUT_NUM_MAX)
?: "")
panel_compose_text.setSelection(INPUT_NUM_MAX)
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onAtTextChanged(panel_compose_text, start, before, count)
}
})
panel_compose_text.setOnClickListener {
panel_compose_text.isFocusableInTouchMode = true
mInputAwareLayout?.showSoftkey(panel_compose_text)
panel_compose_text.postDelayed({ panel_compose_text.requestFocus() }, 200)
}
panel_countdown_send_button.setOnClickListener {
val pass = mListener?.onBeforeTextOrAudioHandle() ?: true
if (pass) {
if (panel_compose_text.textTrimmed.isNotEmpty()) {
val replyContent = panel_reply_content_tv.tag as? AmeGroupMessage.ReplyContent
mListener?.onMessageSend(panel_compose_text.text.toString(), replyContent, getTargetExtensionContent())
panel_compose_text.text?.clear()
setReply(null, null, null)
panel_countdown_send_button.startCountDown()
}
}
}
panel_countdown_send_button.isEnabled = true
panel_more_options_iv.setOnClickListener {
val showOption = panel_option_container.visibility != View.VISIBLE
mOptionContainer?.let {
if (showOption) {
mInputAwareLayout?.show(panel_compose_text, it)
} else {
mInputAwareLayout?.hideAttachedInput(true)
}
}
}
mOptionAdapter = BottomPanelAdapter(context)
panel_option_container.layoutManager = GridLayoutManager(context, OPTION_ITEM_MAX)
panel_option_container.adapter = mOptionAdapter
panel_emoji_toggle.setOnClickListener {
val showEmoji = panel_emoji_container.visibility != View.VISIBLE
mEmojiContainer?.let {
if (showEmoji) {
mInputAwareLayout?.show(panel_compose_text, it)
} else {
mInputAwareLayout?.showSoftkey(panel_compose_text)
}
}
}
panel_emoji_container.setInputCallback { emoji ->
val posStart = panel_compose_text.selectionStart
val posEnd = panel_compose_text.selectionEnd
if (posStart != posEnd) {
panel_compose_text.text?.delete(posStart, posEnd)
}
if (panel_compose_text.textTrimmed.length + emoji.length <= INPUT_NUM_MAX) {
panel_compose_text.text?.insert(posStart, emoji)
}
}
panel_emoji_container.setDeleteCallback {
panel_compose_text.onKeyDown(KeyEvent.KEYCODE_DEL, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
panel_compose_text.onKeyUp(KeyEvent.KEYCODE_DEL, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
}
voiceRecodingPanel = VoiceRecodingPanel()
voiceRecodingPanel.onFinishInflate(this)
voiceRecodingPanel.setListener(this)
audioRecorder = AudioRecorder(context, AUDIO_RECORD_MAX_TIME, null)
audioRecorder.setListener(this)
initAtList()
initMultiSelectAction()
}
override fun clearFocus() {
panel_compose_text.clearFocus()
super.clearFocus()
}
fun hideInput() {
mInputAwareLayout?.hideCurrentInput(panel_compose_text)
}
fun setOnConversationInputListener(listener: OnConversationInputListener) {
mListener = listener
}
fun setConversationId(conversationId: Long) {
mCurrentConversationId = conversationId
}
fun bindInputAwareLayout(inputAwareLayout: InputAwareLayout) {
mInputAwareLayout = inputAwareLayout
inputAwareLayout.addOnKeyboardShownListener(this)
inputAwareLayout.addOnKeyboardHiddenListener(this)
}
@SuppressLint("CheckResult")
fun setAllAtList(accountContext: AccountContext, allAtList: List<AmeGroupMemberInfo>) {
ALog.d(TAG, "setAllAtList size: ${allAtList.size}")
Observable.create(ObservableOnSubscribe<List<Recipient>> {
try {
val self = Recipient.major()
val resultList = mutableListOf<Recipient>()
allAtList.forEach {
val r = Recipient.from(accountContext, it.uid, true)
if (r.address != self.address) {
resultList.add(r)
}
}
it.onNext(resultList)
} finally {
it.onComplete()
}
}).subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
mAllAtList.clear()
mAllAtList.addAll(it)
mChatAtAdapter.setAtList(mAllAtList, "")
if (isGroup) {
mChatAtAdapter.setGroupId(mCurrentConversationId)
}
}, {
ALog.e(TAG, "onAtTextChanged error", it)
})
}
fun setComposeText(text: CharSequence) {
panel_compose_text?.setText(text)
panel_compose_text?.post {
panel_compose_text?.setSelection(panel_compose_text.text?.length ?: 0)
}
}
fun getComposeText(): CharSequence {
return panel_compose_text.text ?: ""
}
fun requestComposeFocus() {
postDelayed({
ALog.d(TAG, "requestComposeFocus")
panel_compose_text?.requestFocus()
mInputAwareLayout?.showSoftkey(panel_compose_text ?: return@postDelayed)
}, 300)
}
fun setMasterSecret(masterSecret: MasterSecret?) {
if (masterSecret != null) {
audioRecorder = AudioRecorder(context, AUDIO_RECORD_MAX_TIME, masterSecret)
audioRecorder.setListener(this)
}
}
fun setRestrictionMode(isRestricted: Boolean, content: CharSequence? = null) {
if (isRestricted) {
panel_restriction_ban.visibility = View.VISIBLE
panel_audio_toggle.isEnabled = false
panel_countdown_send_button.isEnabled = false
panel_compose_text.isEnabled = false
panel_more_options_iv.isEnabled = false
panel_emoji_toggle.isEnabled = false
restriction_ban_txt.text = content
} else {
panel_restriction_ban.visibility = View.GONE
panel_audio_toggle.isEnabled = true
panel_countdown_send_button.isEnabled = true
panel_compose_text.isEnabled = true
panel_more_options_iv.isEnabled = true
panel_emoji_toggle.isEnabled = true
restriction_ban_txt.text = content
}
}
fun addOptionItem(vararg items: BottomPanelItem) {
mOptionAdapter.addItems(items.toMutableList())
}
fun addOptionItem(index: Int, item: BottomPanelItem) {
mOptionAdapter.addItem(index, item)
}
fun getOptionSize(): Int {
return mOptionAdapter.getSize()
}
fun removeAllOptionItems() {
mOptionAdapter.clearItems()
}
fun removeOptionItem(name: String) {
mOptionAdapter.removeItem(name)
}
fun updateOptionItem(item: BottomPanelItem) {
mOptionAdapter.updateItem(item)
}
fun isMoreOptionPanelShowed(): Boolean {
return panel_option_container.visibility == View.VISIBLE
}
fun isEmojiPanelShowed(): Boolean {
return panel_emoji_container.visibility == View.VISIBLE
}
fun insertAtRecipient(recipient: Recipient) {
addAtData(TempAtData(recipient, panel_compose_text.selectionStart))
}
fun showMultiSelectMode(show: Boolean, batchSelected: Set<Any>?) {
if (show) {
if (panel_other_action_layout.visibility != View.VISIBLE) {
mBatchSelected = batchSelected
mInputAwareLayout?.hideCurrentInput(panel_compose_text)
panel_other_action_layout.clearAnimation()
panel_other_action_layout.visibility = View.VISIBLE
panel_other_action_layout.startAnimation(AnimationUtils.loadAnimation(context, R.anim.common_slide_from_bottom_fast))
panel_main_ban.visibility = View.GONE
}
} else {
if (panel_other_action_layout.visibility == View.VISIBLE) {
mBatchSelected = batchSelected
panel_other_action_layout.clearAnimation()
panel_other_action_layout.startAnimation(AnimationUtils.loadAnimation(context, R.anim.common_slide_to_bottom_fast).apply {
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
panel_other_action_layout.visibility = View.GONE
}
override fun onAnimationStart(animation: Animation?) {
}
})
})
panel_main_ban.visibility = View.VISIBLE
}
}
}
fun showAtList(show: Boolean) {
ALog.d(TAG, "showAtList show: $show")
if (mAllAtList.isEmpty()) {
return
}
val visibility = if (show) View.VISIBLE else View.GONE
if (panel_at_list.visibility != visibility) {
mChatAtAdapter.setAtList(mAllAtList, "")
panel_at_list.visibility = visibility
if (visibility == View.VISIBLE) {
val animation = AnimationUtils.loadAnimation(context, R.anim.common_slide_from_bottom)
panel_at_list.clearAnimation()
panel_at_list.startAnimation(animation)
}
}
}
fun setReply(accountContext: AccountContext?, messageDetail: AmeGroupMessageDetail?, locateCallback: ((v: View) -> Unit)?) {
if (messageDetail != null && accountContext != null) {
postDelayed({
panel_compose_text.requestFocus()
mInputAwareLayout?.showSoftkey(panel_compose_text)
panel_reply_layout.visibility = View.VISIBLE
val recipient = messageDetail.getSender(accountContext)
val groupModel = GroupLogic.get(accountContext).getModel(messageDetail.gid)
panel_reply_to_tv.text = if (recipient == null) {
null
} else {
BcmGroupNameUtil.getGroupMemberName(recipient, groupModel?.getGroupMember(recipient.address.serialize()))
}
val replyContent = if (messageDetail.message.type == AmeGroupMessage.CHAT_REPLY) {//If the reply message type is also reply, it is treated as a normal text message, and only the text is returned
val rc = messageDetail.message.content as AmeGroupMessage.ReplyContent
AmeGroupMessage.ReplyContent(messageDetail.serverIndex, messageDetail.senderId, AmeGroupMessage<AmeGroupMessage.TextContent>(AmeGroupMessage.TEXT, AmeGroupMessage.TextContent(rc.text)).toString(), "")
} else {
AmeGroupMessage.ReplyContent(messageDetail.serverIndex, messageDetail.senderId, messageDetail.message.toString(), "")
}
panel_reply_content_tv.tag = replyContent
panel_reply_content_tv.visibility = View.VISIBLE
panel_reply_content_tv.text = replyContent.getReplyDescribe(context, messageDetail.gid, accountContext, false)
panel_reply_text_tv.visibility = View.GONE
panel_reply_close_iv.setOnClickListener {
setReply(accountContext, null, null)
}
panel_reply_layout.setOnClickListener {
locateCallback?.invoke(it)
}
}, 150)
} else {
panel_reply_layout.visibility = View.GONE
panel_reply_content_tv.tag = null
}
}
private fun checkHasAudioPermission(): Boolean {
return PackageManager.PERMISSION_GRANTED == context.packageManager.checkPermission("android.permission.RECORD_AUDIO", context.packageName)
}
/**
* set bottom container height
*/
private fun lockBottomExtraContainer(height: Int) {
ALog.d(TAG, "lockBottomExtraContainer height: $height")
panel_extra_container.layoutParams = panel_extra_container.layoutParams.apply {
this.height = height
}
}
private fun setWindowScreenLocked(lock: Boolean) {
val context = getContext()
if (context is Activity) {
val window = context.window ?: return
if (lock) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
}
private fun initMultiSelectAction() {
panel_forward_btn.setOnClickListener {
val weakThis = WeakReference(this)
AmeModuleCenter.chat(AMELogin.majorContext)?.forwardMessage(context, isGroup, mCurrentConversationId, mBatchSelected
?: return@setOnClickListener) {
if (it.isEmpty()) {
weakThis.get()?.postDelayed({
EventBus.getDefault().post(MultiSelectEvent(isGroup, null))
}, 500)
}
}
}
panel_delete_btn.setOnClickListener {
if (mCurrentConversationId == 0L) {
ALog.i(TAG, "message delete fail, conversationId is 0")
return@setOnClickListener
}
if (mBatchSelected?.isNotEmpty() == true) {
AmeModuleCenter.chat(AMELogin.majorContext)?.deleteMessage(context, isGroup, mCurrentConversationId, mBatchSelected
?: return@setOnClickListener) {
if (it.isEmpty()) {
EventBus.getDefault().post(MultiSelectEvent(isGroup, null))
}
}
} else {
ToastUtil.show(context, context.getString(R.string.chats_select_mode_delete_empty))
}
}
}
private fun initAtList() {
ALog.d(TAG, "initAtList")
mChatAtAdapter = ChatAtListAdapter(AMELogin.majorContext, context, object : ChatAtListAdapter.AtActionListener {
override fun onSelect(recipient: Recipient) {
val lastIndex = getAtingIndex()
remoteNearestAtData(panel_compose_text.text?.length ?: 0)
addAtData(TempAtData(recipient, lastIndex))
}
})
panel_at_list.adapter = mChatAtAdapter
panel_at_list.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
}
private val mCurrentAtDataList = mutableListOf<TempAtData>()
private fun addAtData(data: TempAtData) {
if (data.index < 0) {
ALog.d(TAG, "addAtData fail, index is smaller zero")
return
}
try {
ALog.d(TAG, "addAtData index: ${data.index}")
val recipient = data.recipient
if (recipient != null) {
val atPart = createAtPart(recipient, mCurrentConversationId)
val sourceText = panel_compose_text.text
val spanBuilder = SpannableStringBuilder()
spanBuilder.append(atPart)
spanBuilder.append(" ")
sourceText?.insert(data.index, spanBuilder)
}
var insertIndex = 0
for (d in mCurrentAtDataList) {
//Determine the index of the at data inserted, and ensure that the larger the index, the later
if (data.index > d.index) {
insertIndex++
} else {
break
}
}
mCurrentAtDataList.add(insertIndex, data)
} catch (ex: Exception) {
ALog.e(TAG, "addAtData error", ex)
} finally {
showAtList(getAtingIndex() >= 0)
}
}
private fun remoteNearestAtData(fromIndex: Int) {
try {
var target: TempAtData? = null
for (d in mCurrentAtDataList) {
//Find at data whose index is less than fromIndex and delete it directly
if (d.index <= fromIndex) {
target = d
} else {
break
}
}
if (target != null) {
mCurrentAtDataList.remove(target)
val removeIndex = target.index
ALog.d(TAG, "remoteNearestAtData index: $removeIndex, from: $fromIndex")
val recipient = target.recipient
if (recipient == null) {
if (fromIndex > removeIndex) {
val sourceText = panel_compose_text.text
sourceText?.delete(removeIndex, fromIndex)
}
} else {
val replaceText = panel_compose_text.text?.subSequence(removeIndex, fromIndex)
val atPart = createAtPart(recipient, mCurrentConversationId)
if (replaceText?.endsWith(atPart) == true) {
panel_compose_text.text?.delete(removeIndex, fromIndex)
}
}
}
} catch (ex: Exception) {
ALog.e(TAG, "remoteNearestAtData error", ex)
} finally {
showAtList(getAtingIndex() >= 0)
}
}
private fun updateAtDataIndex(fromIndex: Int, count: Int) {
if (count == 0) {
return
}
val iterator = mCurrentAtDataList.iterator()
while (iterator.hasNext()) {
val d = iterator.next()
// Find all at data whose index is greater than or equal to this fromIndex, increase the index by count, indicating that the input box inserts or deletes text at the fromIndex position,
// and the indexes of all at data after that must be updated
ALog.d(TAG, "updateAtDataIndex i: ${d.index}, from: $fromIndex, count: $count")
if (d.index >= fromIndex) {
d.index += count
if (d.index < 0) {
iterator.remove()
}
}
}
}
private fun getAtingIndex(): Int {
for (d in mCurrentAtDataList) {
if (d.recipient == null) {
return d.index
}
}
return -1
}
private var mLastInputText: CharSequence = ""
@SuppressLint("CheckResult")
private fun onAtTextChanged(inputText: EditText, start: Int, before: Int, count: Int) {
if (mAllAtList.isEmpty()) {
return
}
val add = count - before // If count is greater than before, the total behavior of the current operation is to add characters, otherwise it is remove character
val atingIndex = getAtingIndex()
ALog.d(TAG, "onAtTextChanged sourceText: ${inputText.text}, mLastAtIndex: $atingIndex, start: $start, add: $add")
if (atingIndex >= 0) {
if (start <= atingIndex) {
if (add < 0) {
if (start + before > atingIndex) {
remoteNearestAtData(atingIndex)
}
}
} else {
val search = inputText.text.substring(atingIndex + 1)
ALog.d(TAG, "onAtTextChanged search: $search")
mAtDisposable?.dispose()
mAtDisposable = Observable.create(ObservableOnSubscribe<List<Recipient>> {
try {
if (search.isNullOrEmpty()) {
it.onNext(mAllAtList)
} else {
val model = GroupLogic.get(AMELogin.majorContext).getModel(mCurrentConversationId)
it.onNext(mAllAtList.filter {
val name = BcmGroupNameUtil.getGroupMemberName(it, model?.getGroupMember(it.address.serialize()))
StringAppearanceUtil.containIgnore(name, search)
})
}
} finally {
it.onComplete()
}
}).delaySubscription(500, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
mChatAtAdapter.setAtList(it, search)
}, {
ALog.e(TAG, "onAtTextChanged error", it)
})
}
updateAtDataIndex(start, add)
} else {
updateAtDataIndex(start, add)
val num = Math.abs(add)
if (num == 1) {
if (add > 0) {
if (inputText.text.endsWith(ARouterConstants.CHAT_AT_CHAR)) {
addAtData(TempAtData(null, start))
}
} else {
if (start < mLastInputText.length && start + 1 <= mLastInputText.length && mLastInputText.subSequence(start, start + 1) == " ") {
remoteNearestAtData(start)
}
}
}
}
mLastInputText = inputText.text.toString()
ALog.d(TAG, "onAtTextChanged lastInputText: $mLastInputText")
}
private fun getTargetExtensionContent(): AmeGroupMessageDetail.ExtensionContent {
var atPart: CharSequence
val targetList = mutableListOf<String>()
for (temp in mCurrentAtDataList) {
val at = temp.recipient ?: continue
atPart = createAtPart(at, mCurrentConversationId)
if (panel_compose_text.text?.contains(atPart) == true) {
targetList.add(at.address.serialize())
ALog.d(TAG, "getTargetExtensionContent part: ${at.address.serialize()}")
}
}
mCurrentAtDataList.clear()
showAtList(false)
val ext = AmeGroupMessageDetail.ExtensionContent()
ext.atList = targetList
return ext
}
private fun updateToggleButtonState(hasText: Boolean) {
if (!hasText) {
panel_countdown_send_button.visibility = View.GONE
panel_audio_toggle.visibility = View.VISIBLE
} else {
panel_audio_toggle.visibility = View.GONE
panel_countdown_send_button.visibility = View.VISIBLE
}
}
private fun createAtPart(recipient: Recipient, groupId: Long): CharSequence {
val model = GroupLogic.get(recipient.address.context()).getModel(groupId)
return ARouterConstants.CHAT_AT_CHAR + BcmGroupNameUtil.getGroupMemberAtName(recipient, model?.getGroupMember(recipient.address.serialize()))
}
private class TempAtData(var recipient: Recipient?, var index: Int = -1) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as TempAtData
if (recipient != other.recipient) return false
if (index != other.index) return false
return true
}
override fun hashCode(): Int {
var result = recipient?.hashCode() ?: 0
result = 31 * result + index
return result
}
}
}
| 1
| null |
1
| 1
|
65a11e5f009394897ddc08f4252969458454d052
| 37,705
|
cyberland-android
|
Apache License 2.0
|
packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/RenderExtensions.kt
|
liu-wanshun
| 595,904,109
| true
| null |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.notification.collection.render
import com.android.systemui.statusbar.notification.collection.GroupEntry
/**
* Extension used during the render stage which assumes the summary exists, and throws a more
* helpful error if not.
*/
inline val GroupEntry.requireSummary get() = checkNotNull(summary) { "No Summary: $this" }
| 0
|
Java
|
1
| 2
|
e99201cd9b6a123b16c30cce427a2dc31bb2f501
| 983
|
platform_frameworks_base
|
Apache License 2.0
|
ConfigurationProcessor/src/main/kotlin/com/lukasbrand/configuration_processor/EnvConfiguration.kt
|
LukasBrand
| 527,283,791
| false
|
{"Java": 4542, "Kotlin": 4541}
|
package com.lukasbrand.configuration_processor
interface EnvConfiguration : Configuration {
}
| 1
| null |
1
| 1
|
1fa106844762373f9765f56431ce164ada70a96a
| 94
|
JavaConfiguration
|
MIT License
|
untitled3/src/main/java/org/example/Main.kt
|
longerhhh
| 507,487,467
| false
|
{"Java": 158353, "Kotlin": 54584, "Groovy": 2165, "Go": 1595}
|
package org.example
import org.example.entity.Context
import org.example.entity.OverlayPlugin
object Main {
@JvmStatic
fun main(args: Array<String>) {
OverlayPlugin().onCreate(Context("name", "description"))
}
}
| 1
| null |
1
| 1
|
ecd5f5a8daa54406c589f5eade001ad1e8bf4434
| 233
|
justForLearn
|
Apache License 2.0
|
client/src/main/kotlin/com/ecwid/upsource/rpc/projects/BranchDTO.kt
|
turchenkoalex
| 266,583,029
| false
| null |
// Generated by the codegen. Please DO NOT EDIT!
// source: message.ftl
package com.ecwid.upsource.rpc.projects
/**
* @param projectId Project ID in Upsource
* @param name Branch name
* @param lastRevision See RevisionInfoDTO parameters
* @param isDefault Whether the branch is a default one
* @param stats See BranchStatsDTO parameters
* @param isHosted Whether the branch is from a hosted repository
* @param reviewId ID of the branch review, if one exists
*/
@Suppress("unused")
data class BranchDTO(
/**
* Project ID in Upsource (required)
*/
val projectId: String,
/**
* Branch name (required)
*/
val name: String,
/**
* See RevisionInfoDTO parameters (required)
*
* @see com.ecwid.upsource.rpc.projects.RevisionInfoDTO
*/
val lastRevision: RevisionInfoDTO,
/**
* Whether the branch is a default one (required)
*/
val isDefault: Boolean,
/**
* See BranchStatsDTO parameters (required)
*
* @see com.ecwid.upsource.rpc.projects.BranchStatsDTO
*/
val stats: BranchStatsDTO,
/**
* Whether the branch is from a hosted repository (required)
*/
val isHosted: Boolean,
/**
* ID of the branch review, if one exists (optional)
*/
val reviewId: com.ecwid.upsource.rpc.ids.ReviewIdDTO? = null
) {
@Suppress("unused")
internal constructor() : this(
projectId = "",
name = "",
lastRevision = RevisionInfoDTO(),
isDefault = false,
stats = BranchStatsDTO(),
isHosted = false,
reviewId = null
)
}
| 0
|
Kotlin
|
1
| 3
|
77dda5f8357b35683189f595b9f75f0a58f45e66
| 1,469
|
upsource-rpc
|
Apache License 2.0
|
client/src/main/kotlin/com/ecwid/upsource/rpc/projects/BranchDTO.kt
|
turchenkoalex
| 266,583,029
| false
| null |
// Generated by the codegen. Please DO NOT EDIT!
// source: message.ftl
package com.ecwid.upsource.rpc.projects
/**
* @param projectId Project ID in Upsource
* @param name Branch name
* @param lastRevision See RevisionInfoDTO parameters
* @param isDefault Whether the branch is a default one
* @param stats See BranchStatsDTO parameters
* @param isHosted Whether the branch is from a hosted repository
* @param reviewId ID of the branch review, if one exists
*/
@Suppress("unused")
data class BranchDTO(
/**
* Project ID in Upsource (required)
*/
val projectId: String,
/**
* Branch name (required)
*/
val name: String,
/**
* See RevisionInfoDTO parameters (required)
*
* @see com.ecwid.upsource.rpc.projects.RevisionInfoDTO
*/
val lastRevision: RevisionInfoDTO,
/**
* Whether the branch is a default one (required)
*/
val isDefault: Boolean,
/**
* See BranchStatsDTO parameters (required)
*
* @see com.ecwid.upsource.rpc.projects.BranchStatsDTO
*/
val stats: BranchStatsDTO,
/**
* Whether the branch is from a hosted repository (required)
*/
val isHosted: Boolean,
/**
* ID of the branch review, if one exists (optional)
*/
val reviewId: com.ecwid.upsource.rpc.ids.ReviewIdDTO? = null
) {
@Suppress("unused")
internal constructor() : this(
projectId = "",
name = "",
lastRevision = RevisionInfoDTO(),
isDefault = false,
stats = BranchStatsDTO(),
isHosted = false,
reviewId = null
)
}
| 0
|
Kotlin
|
1
| 3
|
77dda5f8357b35683189f595b9f75f0a58f45e66
| 1,469
|
upsource-rpc
|
Apache License 2.0
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Clover2.kt
|
walter-juan
| 868,046,028
| false
| null |
package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.Clover2: ImageVector
get() {
if (_clover2 != null) {
return _clover2!!
}
_clover2 = Builder(name = "Clover2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.0f, 11.0f)
lineToRelative(-3.397f, -3.44f)
arcToRelative(2.104f, 2.104f, 0.0f, false, true, 0.0f, -2.95f)
arcToRelative(2.04f, 2.04f, 0.0f, false, true, 2.912f, 0.0f)
lineToRelative(0.485f, 0.39f)
lineToRelative(0.485f, -0.39f)
arcToRelative(2.04f, 2.04f, 0.0f, false, true, 2.912f, 0.0f)
arcToRelative(2.104f, 2.104f, 0.0f, false, true, 0.0f, 2.95f)
lineToRelative(-3.397f, 3.44f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.0f, 11.0f)
lineToRelative(-3.397f, 3.44f)
arcToRelative(2.104f, 2.104f, 0.0f, false, false, 0.0f, 2.95f)
arcToRelative(2.04f, 2.04f, 0.0f, false, false, 2.912f, 0.0f)
lineToRelative(0.485f, -0.39f)
lineToRelative(0.485f, 0.39f)
arcToRelative(2.04f, 2.04f, 0.0f, false, false, 2.912f, 0.0f)
arcToRelative(2.104f, 2.104f, 0.0f, false, false, 0.0f, -2.95f)
lineToRelative(-3.397f, -3.44f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.44f, 7.603f)
arcToRelative(2.104f, 2.104f, 0.0f, false, true, 2.95f, 0.0f)
arcToRelative(2.04f, 2.04f, 0.0f, false, true, 0.0f, 2.912f)
lineToRelative(-0.39f, 0.485f)
lineToRelative(0.39f, 0.485f)
arcToRelative(2.04f, 2.04f, 0.0f, false, true, 0.0f, 2.912f)
arcToRelative(2.104f, 2.104f, 0.0f, false, true, -2.95f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.56f, 7.603f)
arcToRelative(2.104f, 2.104f, 0.0f, false, false, -2.95f, 0.0f)
arcToRelative(2.04f, 2.04f, 0.0f, false, false, 0.0f, 2.912f)
lineToRelative(0.39f, 0.485f)
lineToRelative(-0.39f, 0.485f)
arcToRelative(2.04f, 2.04f, 0.0f, false, false, 0.0f, 2.912f)
arcToRelative(2.104f, 2.104f, 0.0f, false, false, 2.95f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.0f, 15.0f)
lineToRelative(6.0f, 6.0f)
}
}
.build()
return _clover2!!
}
private var _clover2: ImageVector? = null
| 0
| null |
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 4,591
|
compose-icon-collections
|
MIT License
|
app/src/main/java/cn/rongcloud/voiceroomdemo/mvp/activity/VoiceRoomListActivity.kt
|
iostyle
| 396,748,047
| true
|
{"Kotlin": 403974, "Java": 168868}
|
/*
* Copyright © 2021 RongCloud. All rights reserved.
*/
package cn.rongcloud.voiceroomdemo.mvp.activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import cn.rongcloud.voiceroomdemo.R
import cn.rongcloud.voiceroomdemo.common.*
import cn.rongcloud.voiceroomdemo.mvp.activity.iview.IVoiceRoomListView
import cn.rongcloud.voiceroomdemo.mvp.fragment.createroom.CreateVoiceRoomDialogFragment
import cn.rongcloud.voiceroomdemo.mvp.fragment.createroom.ICreateVoiceRoomView
import cn.rongcloud.voiceroomdemo.mvp.presenter.VoiceRoomListPresenter
import cn.rongcloud.voiceroomdemo.net.api.ApiConstant
import cn.rongcloud.voiceroomdemo.net.api.bean.respond.VoiceRoomBean
import cn.rongcloud.voiceroomdemo.mvp.adapter.VoiceRoomListAdapter
import cn.rongcloud.voiceroomdemo.ui.dialog.ConfirmDialog
import cn.rongcloud.voiceroomdemo.ui.dialog.InputPasswordDialog
import kotlinx.android.synthetic.main.activity_voice_room_list.*
import kotlinx.android.synthetic.main.layout_input_password_dialog.*
private const val TAG = "VoiceRoomListActivity"
class VoiceRoomListActivity : BaseActivity<VoiceRoomListPresenter, IVoiceRoomListView>(),
IVoiceRoomListView, ICreateVoiceRoomView {
companion object {
fun startActivity(context: Context) {
val intent = Intent(context, VoiceRoomListActivity::class.java)
context.startActivity(intent)
}
}
private var mAdapter: VoiceRoomListAdapter? = null
private var passwordDialog: Dialog? = null
private var createVoiceRoomDialogFragment: CreateVoiceRoomDialogFragment? = null
private var messageDialog: ConfirmDialog? = null
override fun initPresenter(): VoiceRoomListPresenter {
return VoiceRoomListPresenter(this)
}
override fun getContentView(): Int = R.layout.activity_voice_room_list
override fun initView() {
mAdapter = VoiceRoomListAdapter { _, bean ->
gotoVoiceRoomActivity(bean)
}
rv_voice_room.adapter = mAdapter
showBackButton()
iv_create_room.setOnClickListener {
showCreateVoiceRoomDialog()
}
srl_refresh.setOnRefreshListener {
presenter.refreshData()
}
rv_voice_room.useDefaultLoadMore()
rv_voice_room.setLoadMoreListener {
presenter.loadMore()
}
}
private fun gotoVoiceRoomActivity(bean: VoiceRoomBean) {
presenter.gotoVoiceRoomActivity(this, bean.roomId)
}
override fun showInputPasswordDialog(bean: VoiceRoomBean) {
passwordDialog = InputPasswordDialog(this) { password ->
if (password.length < 4) {
showToast(R.string.please_input_complete_password)
return@InputPasswordDialog
}
if (password == bean.password) {
passwordDialog?.dismiss()
presenter.turnToRoom(this,bean)
} else {
showToast(R.string.password_error)
}
}
passwordDialog?.show()
}
private fun showCreateVoiceRoomDialog() {
createVoiceRoomDialogFragment = CreateVoiceRoomDialogFragment(this)
createVoiceRoomDialogFragment?.show(supportFragmentManager, "CreateRoomDialog")
}
override fun initData() {
}
override fun onDestroy() {
super.onDestroy()
passwordDialog?.dismiss()
messageDialog?.dismiss()
}
override fun getActionTitle(): CharSequence? {
return null
}
override fun onDataChange(list: List<VoiceRoomBean>?) {
list?.let {
ui {
srl_refresh.isRefreshing = false
rv_voice_room.loadMoreFinish(false, true)
mAdapter?.refreshData(list)
}
}
}
override fun onLoadError(throwable: Throwable?) {
ui {
srl_refresh.isRefreshing = false
rv_voice_room.loadMoreError(-1, "加载失败,请下拉刷新")
showToast(throwable?.message)
}
}
override fun onCreateRoomSuccess(data: VoiceRoomBean?) {
createVoiceRoomDialogFragment?.dismiss()
data?.let {
gotoVoiceRoomActivity(it)
}
}
override fun onCreateRoomExist(data: VoiceRoomBean?) {
ui {
createVoiceRoomDialogFragment?.dismiss()
data?.let {
messageDialog = ConfirmDialog(this, "您已创建过语聊房,是否直接进入?") {
gotoVoiceRoomActivity(data)
messageDialog?.dismiss()
}
messageDialog?.show()
}
}
}
override fun getRightActionButton(): View {
val imageView = LayoutInflater.from(this)
.inflate(R.layout.layout_right_title_icon, null, false) as AppCompatImageView
imageView.setImageResource(R.drawable.ic_goto_homepage)
imageView.setOnClickListener {
val uri = Uri.parse(ApiConstant.HOME_PAGE)
startActivity(Intent(Intent.ACTION_VIEW, uri))
}
return imageView
}
}
| 0
| null |
0
| 0
|
801268cf14a5e1b65f02ad2d4b6a024c213ad05f
| 5,205
|
rongcloud-scene-android-demo
|
MIT License
|
src/FEMetalSheet.kt
|
danftang
| 140,095,532
| false
|
{"Kotlin": 42153, "Gnuplot": 90}
|
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D
// Finite element metal sheet
class FEMetalSheet {
val material = materials.BellMetal
val iSize : Int = 100
val jSize : Int = 100
val kSize : Int = 2
val physicalSize = Vector3D(0.3,0.3,0.002) // m
val delta : Vector3D = physicalSize/Vector3D(iSize-1.0, jSize-1.0, kSize-1.0) // equilibrium distance between elements
val m = material.rho * delta.volume() // mass of each element (kg)
val T = Vector3D(0.2, 0.2, 0.2) // force per unit displacement on an element (Nm)
val dt = 0.1/44100.0 // timestep (s)
val elements : Array3D<FiniteElement3D> = Array3D(iSize, jSize, kSize, { x, y, z ->
val vi = Vector3D(x.toDouble(), y.toDouble(), z.toDouble())
FiniteElement3D(vi*delta, Vector3D.ZERO)
})
val a : Array3D<Vector3D> = Array3D(iSize-1, jSize-1, kSize-1, { _, _, _->Vector3D.ZERO})
fun calcAcceleration() {
a.set(Vector3D.ZERO)
for(k in 0 until kSize-1) {
for (j in 0 until jSize-1) {
for (i in 0 until iSize-1) {
val xoffset = elements[i+1,j,k].p - elements[i,j,k].p
val xoffsetNorm = xoffset.norm
val xaccel = xoffset*(T.x*(xoffsetNorm-delta.x)/(xoffsetNorm*m))
a[i,j,k] += xaccel
a[i+1,j,k] -= xaccel
// TODO: do the same for y and z
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
338cf2025a73440b1fa3275428085da8745972b4
| 1,505
|
MusicalInstrumentSim
|
MIT License
|
data/src/main/java/com/semicolon/data/repository/UserRepositoryImpl.kt
|
Walkhub
| 443,006,389
| false
| null |
package com.semicolon.data.repository
import com.semicolon.data.local.datasource.LocalUserDataSource
import com.semicolon.data.remote.datasource.RemoteImagesDataSource
import com.semicolon.data.remote.datasource.RemoteUserDataSource
import com.semicolon.data.remote.request.users.*
import com.semicolon.data.remote.response.users.UserSignInResponse
import com.semicolon.data.remote.response.users.toEntity
import com.semicolon.data.util.OfflineCacheUtil
import com.semicolon.data.util.toMultipart
import com.semicolon.domain.entity.users.*
import com.semicolon.domain.param.user.*
import com.semicolon.domain.repository.UserRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class UserRepositoryImpl @Inject constructor(
private val remoteImagesDataSource: RemoteImagesDataSource,
private val localUserDataSource: LocalUserDataSource,
private val remoteUserDateSource: RemoteUserDataSource
) : UserRepository {
override suspend fun verifyUserPhoneNumber(
verifyPhoneNumberSignUpParam: VerifyPhoneNumberSignUpParam
) = remoteUserDateSource.verifyUserPhoneNumber(verifyPhoneNumberSignUpParam.toRequest())
override suspend fun postUserSignUp(
postUserSignUpParam: PostUserSignUpParam
) = remoteUserDateSource.postUserSignUp(postUserSignUpParam.toRequest())
override suspend fun postUserSignIn(
postUserSignInParam: PostUserSignInParam
) {
val response = remoteUserDateSource.postUserSignIn(postUserSignInParam.toRequest())
saveAccount(postUserSignInParam)
saveToken(response)
}
override suspend fun patchUserChangePassword(
patchUserChangePasswordParam: PatchUserChangePasswordParam
) = remoteUserDateSource.patchUserChangePassword(patchUserChangePasswordParam.toRequest())
override suspend fun fetchMyPage(): Flow<UserMyPageEntity> =
OfflineCacheUtil<UserMyPageEntity>()
.remoteData { remoteUserDateSource.fetchMyPage() }
.localData { localUserDataSource.fetchUserMyPage() }
.doOnNeedRefresh { localUserDataSource.insertUserMyPage(it) }
.createFlow()
override suspend fun updateProfile(updateProfileParam: UpdateProfileParam) {
val imageUrl = if (updateProfileParam.profileImage != null) {
remoteImagesDataSource.postImages(
listOf(updateProfileParam.profileImage!!.toMultipart())
).imageUrl.first()
} else ""
remoteUserDateSource.updateProfile(updateProfileParam.toRequest(imageUrl))
}
override suspend fun findUserAccount(phoneNumber: String): Flow<FindUserAccountEntity> =
flow {
emit(remoteUserDateSource.findUserAccount(phoneNumber))
}
override suspend fun patchUserHealth(patchUserHealthParam: PatchUserHealthParam) =
remoteUserDateSource.patchUserHealth(patchUserHealthParam.toRequest())
override suspend fun signUpClass(signUpClassParam: SignUpClassParam) =
remoteUserDateSource.signUpClass(
signUpClassParam.group_id,
signUpClassParam.toRequest()
)
override suspend fun patchSchool(schoolId: Int) =
remoteUserDateSource.patchSchool(schoolId)
override suspend fun autoLogin() {
remoteUserDateSource.postUserSignIn(
UserSignInRequest(
localUserDataSource.fetchId(),
localUserDataSource.fetchPw(),
localUserDataSource.fetchDeviceToken()
)
)
}
override suspend fun patchDailyWalkGoal(patchDailyWalkGoalParam: PatchDailyWalkGoalParam) {
remoteUserDateSource.patchDailyWalkGoal(patchDailyWalkGoalParam.toRequest())
}
override suspend fun fetchCaloriesLevel(): Flow<FetchCaloriesLevelEntity> =
OfflineCacheUtil<FetchCaloriesLevelEntity>()
.remoteData { remoteUserDateSource.fetchCaloriesLevelList() }
.localData { localUserDataSource.fetchCaloriesLevelList() }
.doOnNeedRefresh { localUserDataSource.insertCaloriesLevelList(it) }
.createFlow()
private suspend fun saveToken(userSignInResponse: UserSignInResponse) {
localUserDataSource.apply {
setAccessToken(userSignInResponse.accessToken)
setRefreshToken(userSignInResponse.refreshToken)
setExpiredAt(userSignInResponse.expiredAt)
}
}
private suspend fun saveAccount(userSignInParam: PostUserSignInParam) {
localUserDataSource.apply {
setId(userSignInParam.accountId)
setPw(userSignInParam.password)
setDeviceToken(userSignInParam.deviceToken)
}
}
override suspend fun fetchUserProfile(userId: Int): Flow<UserProfileEntity> =
OfflineCacheUtil<UserProfileEntity>()
.remoteData { remoteUserDateSource.fetchUserProfile(userId) }
.localData { localUserDataSource.fetchUserProfile(userId) }
.doOnNeedRefresh { localUserDataSource.insertUserProfile(it) }
.createFlow()
fun PatchDailyWalkGoalParam.toRequest() =
PatchDailyWalkGoalRequest(
dailyWalkCountGoal = dailyWalkCountGoal
)
fun SignUpClassParam.toRequest() =
SignUpClassRequest(
classCode = classCode,
number = number
)
fun PatchUserHealthParam.toRequest() =
PatchUserHealthRequest(
height = height,
weight = weight
)
fun UpdateProfileParam.toRequest(profileImageUrl: String) =
UpdateProfileRequest(
name = name,
profileImageUrl = profileImageUrl,
sex = sex
)
fun VerifyPhoneNumberSignUpParam.toRequest() =
VerifyPhoneNumberSignUpRequest(
phoneNumber = phoneNumber
)
fun PostUserSignUpParam.toRequest() =
UserSignUpRequest(
accountId = accountId,
password = <PASSWORD>,
name = name,
phoneNumber = phoneNumber,
authCode = authCode,
schoolName = schoolName
)
fun PostUserSignInParam.toRequest() =
UserSignInRequest(
accountId = accountId,
password = <PASSWORD>,
deviceToken = deviceToken
)
fun PatchUserChangePasswordParam.toRequest() =
UserChangePasswordRequest(
accountId = accountId,
phoneNumber = phoneNumber,
authCode = authCode,
newPassword = <PASSWORD>
)
}
| 30
|
Kotlin
|
1
| 15
|
c2d85ebb9ae8b200be22e9029dcfdcbfed19e473
| 6,562
|
walkhub_android
|
MIT License
|
protocol/osrs-225/osrs-225-desktop/src/main/kotlin/net/rsprot/protocol/game/incoming/codec/misc/client/MapBuildCompleteDecoder.kt
|
blurite
| 771,753,685
| false
|
{"Kotlin": 9348194}
|
package net.rsprot.protocol.game.incoming.codec.misc.client
import net.rsprot.buffer.JagByteBuf
import net.rsprot.protocol.ClientProt
import net.rsprot.protocol.game.incoming.misc.client.MapBuildComplete
import net.rsprot.protocol.game.incoming.prot.GameClientProt
import net.rsprot.protocol.message.codec.MessageDecoder
import net.rsprot.protocol.metadata.Consistent
@Consistent
public class MapBuildCompleteDecoder : MessageDecoder<MapBuildComplete> {
override val prot: ClientProt = GameClientProt.MAP_BUILD_COMPLETE
override fun decode(buffer: JagByteBuf): MapBuildComplete = MapBuildComplete
}
| 4
|
Kotlin
|
6
| 27
|
349184703744ee53a0c260c2aad88846b95dcb93
| 610
|
rsprot
|
MIT License
|
app/src/main/java/com/sandoval/recipesapp/utils/RecipesDiffUtil.kt
|
juanchosandox90
| 623,182,583
| false
| null |
package com.sandoval.recipesapp.utils
import androidx.recyclerview.widget.DiffUtil
class RecipesDiffUtil<T>(
private val oldRecipes: List<T>,
private val newRecipes: List<T>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldRecipes.size
}
override fun getNewListSize(): Int {
return newRecipes.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldRecipes[oldItemPosition] === newRecipes[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldRecipes[oldItemPosition] == newRecipes[newItemPosition]
}
}
| 0
|
Kotlin
|
0
| 2
|
30ff9752624e4d917949089f051f8a1c759ea094
| 712
|
RecipesApp
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsremandandsentencingapi/service/SentenceTypeService.kt
|
ministryofjustice
| 688,886,051
| false
|
{"Kotlin": 168987, "Dockerfile": 1373}
|
package uk.gov.justice.digital.hmpps.hmppsremandandsentencingapi.service
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.hmppsremandandsentencingapi.controller.dto.SentenceType
import uk.gov.justice.digital.hmpps.hmppsremandandsentencingapi.jpa.repository.SentenceTypeRepository
import java.time.LocalDate
@Service
class SentenceTypeService(private val sentenceTypeRepository: SentenceTypeRepository) {
fun search(age: Int, convictionDate: LocalDate): List<SentenceType> {
return sentenceTypeRepository.findByAgeInAndConvictionDateIn(age, convictionDate).map { SentenceType.from(it) }
}
}
| 1
|
Kotlin
|
0
| 0
|
594c66fa3c01dc2fc1b344bfdd2998619c8d7c66
| 633
|
hmpps-remand-and-sentencing-api
|
MIT License
|
src/main/kotlin/ao/co/nextbss/requirekt/Preconditions.kt
|
nextbss
| 291,957,016
| false
| null |
package ao.co.nextbss.requirekt
import org.springframework.beans.BeansException
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.core.SpringProperties
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import java.lang.IllegalStateException
import java.util.logging.Logger
import kotlin.collections.ArrayList
/**
* Throws an [ApiException] with the result of calling [lazyMessage] if the [value] is false.
* Note: HttpStatus is [Bad_REQUEST] by default.
*/
inline fun require(value: Boolean, lazyMessage: () -> Any) {
if (!value) {
throw ApiException(
DefaultErrorViewModel(
HttpStatus.BAD_REQUEST.value(),
"",
lazyMessage().toString()
).toJSON())
}
}
/**
* Throws an [ApiException] for a CustomError with the result of [args] if the [value] is false
*/
inline fun require(value: Boolean, vararg args: ArrayList<Any>) {
val logger: Logger = Logger.getLogger("Preconditions")
if (!value) {
val customErrorBeanFinder = SpringContext.getBean(CustomErrorBeanFinder::class.java)
val errors: List<AbstractErrorResponse> = customErrorBeanFinder.errors
logger.info { "Number of error types found: ${errors.size} " }
errors.forEach { println(it.javaClass.canonicalName) }
val filteredListOfCustomErrors = errors.filterNot {
it.javaClass.canonicalName == "ao.co.nextbss.requirekt.DefaultErrorViewModel"
|| it.javaClass.canonicalName == "ao.co.nextbss.requirekt.ErrorResponse"
|| it.javaClass.canonicalName == "ao.co.nextbss.requirekt.ErrorResponse"
}
logger.info { "Number of filtered error types found: ${filteredListOfCustomErrors.size}" }
filteredListOfCustomErrors.forEach { println(it.javaClass.canonicalName) }
val nameOfCustomClassToInstantiate = if (customErrorBeanFinder.environment.activeProfiles.contains("test")) {
filteredListOfCustomErrors[0].javaClass.canonicalName
} else {
try {
filteredListOfCustomErrors[1].javaClass.canonicalName
} catch (e: IndexOutOfBoundsException) {
throw IllegalStateException("No CustomError added. Add a Custom Error that subclasses AbstractErrorResponse and annotate it with @ErrorResponse")
}
}
logger.info("Canonical name of class that will instantiated as a custom error: $nameOfCustomClassToInstantiate")
val customError: AbstractErrorResponse = Class.forName(nameOfCustomClassToInstantiate)
.getDeclaredConstructor().newInstance() as AbstractErrorResponse
throw ApiException(
customError.toJSON(*args),
fromArgsAsInt(
0,
args
)
)
}
}
/**
* Throws an [ApiException] with the result of calling [lazyMessage] if the [value] is false.
*
*/
inline fun require(value: Boolean, httpStatus: HttpStatus, lazyMessage: () -> Any) {
if (!value) {
throw ApiException(
DefaultErrorViewModel(
httpStatus.value(),
"",
lazyMessage().toString()
).toJSON(),
httpStatus.value())
}
}
/**
* Throws an [ApiException] with the result of calling [lazyMessage] if the [value] is false.
*
*/
inline fun require(value: Boolean, status: HttpStatus, errorCode: String, lazyMessage: () -> Any) {
if (!value) {
throw ApiException(
DefaultErrorViewModel(
status.value(),
errorCode,
lazyMessage().toString()
).toJSON(),
status.value())
}
}
| 1
|
Kotlin
|
0
| 8
|
25823a3cae462c2ea97e09399cc0cb84275119f6
| 3,826
|
requirekt
|
MIT License
|
bitcoincore/src/main/kotlin/io/definenulls/bitcoincore/managers/IUnspentOutputProvider.kt
|
toEther
| 677,363,684
| false
| null |
package io.definenulls.bitcoincore.managers
import io.definenulls.bitcoincore.storage.UnspentOutput
interface IUnspentOutputProvider {
fun getSpendableUtxo(): List<UnspentOutput>
}
| 0
|
Kotlin
|
0
| 0
|
bbd7c809a027dd33c1fd393f6a53684d84dcbe14
| 187
|
bitcoin-kit-android_s
|
MIT License
|
app/src/main/java/com/earlier/yma/ui/settings/Settings.kt
|
namhyun-gu
| 59,075,138
| false
|
{"Kotlin": 106247, "Shell": 131}
|
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.earlier.yma.ui.settings
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.earlier.yma.BuildConfig
import com.earlier.yma.R
import com.earlier.yma.ui.common.AppBar
import com.earlier.yma.ui.common.ClickableListItem
import com.earlier.yma.ui.common.ContentPanel
import com.earlier.yma.ui.theme.MealViewerTheme
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
@Composable
fun Settings(
navController: NavController,
) {
val context = LocalContext.current
Scaffold(
topBar = {
AppBar(
title = {
Text(stringResource(R.string.activity_title_setting))
},
navigationIcon = {
IconButton(
onClick = {
navController.navigateUp()
}
) {
Icon(Icons.Rounded.ArrowBack, null)
}
}
)
}
) {
Column(
modifier = Modifier.padding(16.dp)
) {
ContentPanel {
Column {
ClickableListItem(
title = stringResource(R.string.subtitle_version),
subtitle = BuildConfig.VERSION_NAME
)
Divider(startIndent = 16.dp)
ClickableListItem(
title = stringResource(R.string.subtitle_open_source_license),
) {
openOpenSourceLicense(context)
}
Divider(startIndent = 16.dp)
ClickableListItem(
title = stringResource(R.string.subtitle_feedback),
) {
openSendFeedback(context)
}
}
}
}
}
}
private fun openOpenSourceLicense(context: Context) {
val intent = Intent(context, OssLicensesMenuActivity::class.java)
OssLicensesMenuActivity.setActivityTitle(
context.getString(R.string.subtitle_open_source_license)
)
context.startActivity(intent)
}
private fun openSendFeedback(context: Context) {
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:<EMAIL>")
}
context.startActivity(intent)
}
@Preview(showBackground = true)
@Composable
fun SettingActivityContent_Preview() {
MealViewerTheme {
Settings(rememberNavController())
}
}
| 4
|
Kotlin
|
0
| 0
|
424830c4f6550160a72cc8bc2955b99275761171
| 3,930
|
MealViewer
|
Apache License 2.0
|
src/main/kotlin/com/example/data/dtos/sns/Sns.kt
|
itshedimisawi
| 851,502,962
| false
|
{"Kotlin": 42498}
|
package com.example.data.dtos.sns
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class SNSSubscribeNotification(
@SerialName("Token")
val token: String
)
@Serializable
data class SNSNotification(
@SerialName("Message")
val message: String
)
@Serializable
data class SNSResponse(val success: Boolean, val message: String)
| 0
|
Kotlin
|
0
| 3
|
07f0607f09aa028ea7dd98fe16c2153b11f2c539
| 396
|
ktor-integrations
|
MIT License
|
tuiutils/src/main/java/com/tans/tuiutils/adapter/impl/viewcreatators/SingleItemViewCreatorImpl.kt
|
Tans5
| 776,328,098
| false
|
{"Kotlin": 144830}
|
package com.tans.tuiutils.adapter.impl.viewcreatators
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.tans.tuiutils.adapter.AdapterBuilder
import com.tans.tuiutils.adapter.ItemViewCreator
import com.tans.tuiutils.Internal
class SingleItemViewCreatorImpl<Data : Any>(
@LayoutRes
private val itemViewLayoutRes: Int
) : ItemViewCreator<Data> {
@Internal
override fun getItemViewType(positionInDataSource: Int, data: Data): Int? = null
@Internal
override fun createItemView(parent: ViewGroup, itemViewType: Int): View {
return LayoutInflater.from(parent.context).inflate(itemViewLayoutRes, parent, false)
}
@Internal
override var attachedBuilder: AdapterBuilder<Data>? = null
@Internal
override var attachedRecyclerView: RecyclerView? = null
}
| 0
|
Kotlin
|
1
| 1
|
ba61bca0f26b9a4ea7664414cb8122ff18aa765c
| 935
|
tUiUtils
|
Apache License 2.0
|
core/src/main/kotlin/com/heroslender/hmf/core/ui/modifier/node/ComponentWrapper.kt
|
heroslender
| 341,310,824
| false
| null |
package com.heroslender.hmf.core.ui.modifier.node
import com.heroslender.hmf.core.Canvas
import com.heroslender.hmf.core.ui.Component
import com.heroslender.hmf.core.ui.Measurable
import com.heroslender.hmf.core.ui.MeasureScope
import com.heroslender.hmf.core.ui.AbstractPlaceable
abstract class ComponentWrapper(open val component: Component) : AbstractPlaceable(), Measurable {
open val wrapped: ComponentWrapper? = null
/**
* Whether this is the outer component in the chain.
*/
var isOuter: Boolean = false
private var _measureResult: MeasureScope.MeasureResult? = null
var measureResult: MeasureScope.MeasureResult
get() = _measureResult ?: error("Unmeasured wrapper")
protected set(value) {
if (value == _measureResult) {
return
}
_measureResult = value
width = value.width
height = value.height
}
var x: Int = 0
var y: Int = 0
abstract fun draw(canvas: Canvas)
inline fun withOffset(canvas: Canvas, op: () -> Unit) {
if (isOuter) {
op()
return
}
val x = this.x
val y = this.y
canvas.addOffset(x, y)
op()
canvas.addOffset(-x, -y)
}
}
| 1
|
Kotlin
|
4
| 58
|
23c601aa0680ae1366f63b761cfa9b74b80833ab
| 1,280
|
menu-framework
|
MIT License
|
ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstate/SavedStateAdapter.kt
|
wada811
| 213,007,272
| false
| null |
package com.wada811.viewmodelsavedstate
interface SavedStateAdapter<TValue, TState> {
fun toSavedState(value: TValue): TState
fun fromSavedState(state: TState): TValue
}
| 0
|
Kotlin
|
1
| 20
|
5631632821588ffbed28b709e675ad2cce818a10
| 178
|
ViewModel-SavedState-ktx
|
Apache License 2.0
|
integration/maven-plugin-integration-tests/integration/complete-setup-kotlinx/src/main/kotlin/com/example/UUIDScalarConverter.kt
|
ExpediaGroup
| 148,706,161
| false
|
{"Kotlin": 2410561, "MDX": 720089, "HTML": 12165, "JavaScript": 10447, "CSS": 297, "Dockerfile": 147}
|
package com.example
import com.expediagroup.graphql.client.converter.ScalarConverter
import java.util.UUID
class UUIDScalarConverter : ScalarConverter<UUID> {
override fun toScalar(rawValue: Any): UUID = UUID.fromString(rawValue.toString())
override fun toJson(value: UUID): Any = value.toString()
}
| 68
|
Kotlin
|
345
| 1,739
|
d3ad96077fc6d02471f996ef34c67066145acb15
| 310
|
graphql-kotlin
|
Apache License 2.0
|
ocgena-domain/src/main/kotlin/ru/misterpotz/ocgena/simulation_old/transition/TransitionInstanceCreatorFacadeOriginal.kt
|
MisterPotz
| 605,293,662
| false
|
{"Kotlin": 749008, "TypeScript": 495751, "JavaScript": 36713, "CSS": 14489, "Python": 8026, "HTML": 3173, "Ruby": 285, "EJS": 274, "Java": 140}
|
package ru.misterpotz.ocgena.simulation_old.transition
import ru.misterpotz.ocgena.simulation_old.collections.ObjectTokenRealAmountRegistry
import ru.misterpotz.ocgena.simulation_old.collections.PlaceToObjectMarkingDelta
import ru.misterpotz.ocgena.simulation_old.generator.original.TransitionInstanceDurationGeneratorOriginal
import ru.misterpotz.ocgena.simulation_old.generator.original.TransitionNextInstanceAllowedTimeGeneratorOriginal
import ru.misterpotz.ocgena.simulation_old.state.CurrentSimulationDelegate
import ru.misterpotz.ocgena.simulation_old.logging.SimulationDBLogger
import ru.misterpotz.ocgena.simulation_old.binding.EnabledBindingWithTokens
import ru.misterpotz.ocgena.simulation_old.state.original.CurrentSimulationStateOriginal
import javax.inject.Inject
class TransitionInstanceCreatorFacadeOriginal @Inject constructor(
private val activityAllowedTimeSelector: TransitionNextInstanceAllowedTimeGeneratorOriginal,
private val transitionInstanceDurationGeneratorOriginal: TransitionInstanceDurationGeneratorOriginal,
private val simulationDBLogger: SimulationDBLogger,
private val transitionInstanceCreationFactory: TransitionInstanceCreationFactory,
private val currentSimulationDelegate: CurrentSimulationDelegate,
private val objectTokenRealAmountRegistry: ObjectTokenRealAmountRegistry,
private val currentSimulationStateOriginal: CurrentSimulationStateOriginal
) : CurrentSimulationDelegate by currentSimulationDelegate {
private fun recordActiveTransition(enabledBindingWithTokens: EnabledBindingWithTokens) {
val transition = enabledBindingWithTokens.transition
val randomSelectedDuration = transitionInstanceDurationGeneratorOriginal.newDuration(transition)
val tMarkingValue = transitionInstanceCreationFactory.create(
transition = transition,
lockedObjectTokens = enabledBindingWithTokens.involvedObjectTokens,
duration = randomSelectedDuration,
startedAt = simGlobalTime,
tokenSynchronizationTime = enabledBindingWithTokens.synchronizationTime
)
currentSimulationStateOriginal.tMarking.pushTMarking(tMarkingValue)
val newNextAllowedTime = activityAllowedTimeSelector.getNewActivityNextAllowedTime(transition)
currentSimulationStateOriginal.tTimesMarking.setNextAllowedTime(
transition = transition,
time = newNextAllowedTime
)
simulationDBLogger.onStartTransition(transition = tMarkingValue)
}
private fun lockTokensInPMarking(enabledBindingWithTokens: EnabledBindingWithTokens) {
pMarking.minus(enabledBindingWithTokens.involvedObjectTokens as PlaceToObjectMarkingDelta)
for (place in enabledBindingWithTokens.involvedObjectTokens.keys) {
val tokens = enabledBindingWithTokens.involvedObjectTokens[place].size
objectTokenRealAmountRegistry.decreaseRealAmountAt(place, decrementValue = tokens)
}
}
fun lockTokensAndRecordNewTransitionInstance(enabledBindingWithTokens: EnabledBindingWithTokens) {
lockTokensInPMarking(enabledBindingWithTokens)
recordActiveTransition(enabledBindingWithTokens)
}
}
| 0
|
Kotlin
|
0
| 1
|
32a25441882c4780ed6b964a24430ef086222b76
| 3,210
|
ocgena
|
MIT License
|
src/main/kotlin/pl/alpheratzteam/obfuscator/util/ConditionUtil.kt
|
alpheratzteam
| 204,757,128
| false
| null |
package pl.alpheratzteam.obfuscator.util
/**
* @author Unix
* @since 30.03.2021
*/
object ConditionUtil {
/**
* Checks some conditions.
* if **true**, runs [Runnable].
* @param condition as conditions to check.
* @param runnable as runnable to run.
* @see [Runnable]
*/
fun checkCondition(condition: Boolean, runnable: Runnable) {
if (!condition) {
return
}
runnable.run()
}
}
| 0
|
Kotlin
|
14
| 96
|
a03cc48293a7feb1826581fe5e175cf7ef3ce95c
| 462
|
obfuscator
|
MIT License
|
api/src/main/kotlin/com/okeicalm/scrumBoost/Application.kt
|
okeicalm
| 628,295,165
| false
| null |
package com.okeicalm.scrumBoost
import com.okeicalm.scrumBoost.plugins.configureDatabases
import com.okeicalm.scrumBoost.plugins.configureRouting
import com.okeicalm.scrumBoost.plugins.configureSecurity
import com.okeicalm.scrumBoost.plugins.graphQLModule
import io.ktor.server.application.Application
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module() {
configureDatabases()
configureSecurity()
configureRouting()
graphQLModule()
}
| 1
|
Kotlin
|
0
| 0
|
b034edebe557b54ba14d0e764cfcda1d138f331f
| 507
|
scrum_boost
|
MIT License
|
src/main/kotlin/no/nav/pensjon/innsyn/common/PersonNotFoundException.kt
|
navikt
| 191,574,968
| false
| null |
package no.nav.pensjon.innsyn.common
class PersonNotFoundException: Throwable()
| 0
|
Kotlin
|
0
| 0
|
0f82ac51c401a6f10ff62d6416d7c40de70ed132
| 80
|
pensjon-pol-innsyn
|
MIT License
|
app/src/main/java/com/personal/weathering/aq/domain/models/EuAqType.kt
|
Avvami
| 702,061,643
| false
|
{"Kotlin": 473583}
|
package com.personal.weathering.aq.domain.models
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.ui.graphics.Color
import com.personal.weathering.R
import com.personal.weathering.ui.theme.aqiEuExtremelyPoorUsHazardousPrimary
import com.personal.weathering.ui.theme.aqiEuExtremelyPoorUsHazardousSecondary
import com.personal.weathering.ui.theme.aqiEuFairUsGoodPrimary
import com.personal.weathering.ui.theme.aqiEuFairUsGoodSecondary
import com.personal.weathering.ui.theme.aqiEuGoodPrimary
import com.personal.weathering.ui.theme.aqiEuGoodSecondary
import com.personal.weathering.ui.theme.aqiEuPoorUsUnhealthyPrimary
import com.personal.weathering.ui.theme.aqiEuPoorUsUnhealthySecondary
import com.personal.weathering.ui.theme.aqiEuUsModeratePrimary
import com.personal.weathering.ui.theme.aqiEuUsModerateSecondary
import com.personal.weathering.ui.theme.aqiEuVeryPoorUsVeryUnhealthyPrimary
import com.personal.weathering.ui.theme.aqiEuVeryPoorUsVeryUnhealthySecondary
sealed class EuAqType(
val aqValue: Int,
@StringRes val aqIndexRes: Int,
@StringRes val aqDescRes: Int,
@DrawableRes val iconSmallRes: Int,
@DrawableRes val iconLargeRes: Int,
val gradientPrimary: Color,
val gradientSecondary: Color
) {
data class Good(val value: Int): EuAqType(
aqValue = value,
aqIndexRes = R.string.good,
aqDescRes = R.string.eu_good_aqi_general_description,
iconSmallRes = R.drawable.icon_eco_fill1_wght400,
iconLargeRes = R.drawable.icon_eco_fill0_wght200,
gradientPrimary = aqiEuGoodPrimary,
gradientSecondary = aqiEuGoodSecondary
)
data class Fair(val value: Int): EuAqType(
aqValue = value,
aqIndexRes = R.string.fair,
aqDescRes = R.string.eu_fair_aqi_general_description,
iconSmallRes = R.drawable.icon_sentiment_neutral_fill1_wght400,
iconLargeRes = R.drawable.icon_sentiment_neutral_fill0_wght200,
gradientPrimary = aqiEuFairUsGoodPrimary,
gradientSecondary = aqiEuFairUsGoodSecondary
)
data class Moderate(val value: Int): EuAqType(
aqValue = value,
aqIndexRes = R.string.moderate,
aqDescRes = R.string.eu_moderate_aqi_general_description,
iconSmallRes = R.drawable.icon_ecg_heart_fill1_wght400,
iconLargeRes = R.drawable.icon_ecg_heart_fill0_wght200,
gradientPrimary = aqiEuUsModeratePrimary,
gradientSecondary = aqiEuUsModerateSecondary
)
data class Poor(val value: Int): EuAqType(
aqValue = value,
aqIndexRes = R.string.poor,
aqDescRes = R.string.eu_poor_aqi_general_description,
iconSmallRes = R.drawable.icon_masks_fill1_wght400,
iconLargeRes = R.drawable.icon_masks_fill0_wght200,
gradientPrimary = aqiEuPoorUsUnhealthyPrimary,
gradientSecondary = aqiEuPoorUsUnhealthySecondary
)
data class VeryPoor(val value: Int): EuAqType(
aqValue = value,
aqIndexRes = R.string.very_poor,
aqDescRes = R.string.eu_very_poor_aqi_general_description,
iconSmallRes = R.drawable.icon_sentiment_very_dissatisfied_fill1_wght400,
iconLargeRes = R.drawable.icon_sentiment_very_dissatisfied_fill0_wght200,
gradientPrimary = aqiEuVeryPoorUsVeryUnhealthyPrimary,
gradientSecondary = aqiEuVeryPoorUsVeryUnhealthySecondary
)
data class ExtremelyPoor(val value: Int): EuAqType(
aqValue = value,
aqIndexRes = R.string.extremely_poor,
aqDescRes = R.string.eu_extremely_poor_aqi_general_description,
iconSmallRes = R.drawable.icon_skull_fill1_wght400,
iconLargeRes = R.drawable.icon_skull_fill0_wght200,
gradientPrimary = aqiEuExtremelyPoorUsHazardousPrimary,
gradientSecondary = aqiEuExtremelyPoorUsHazardousSecondary
)
companion object {
fun fromAQI(value: Int): EuAqType {
return when(value) {
in 0 until 21 -> Good(value)
in 21 until 41 -> Fair(value)
in 41 until 61 -> Moderate(value)
in 61 until 81 -> Poor(value)
in 81 until 101 -> VeryPoor(value)
else -> ExtremelyPoor(value)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fabd0313b1d8c20dec02b498a61886fa69bf9d5f
| 4,275
|
Weathering
|
MIT License
|
services/csm.cloud.reset/src/main/kotlin/com/bosch/pt/iot/smartsite/importer/boundary/DynamicTestDataExtender.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2022
*
* ************************************************************************
*/
package com.bosch.pt.iot.smartsite.importer.boundary
import com.bosch.pt.iot.smartsite.dataimport.project.model.Milestone
import com.bosch.pt.iot.smartsite.dataimport.project.model.MilestoneTypeEnum.PROJECT
import com.bosch.pt.iot.smartsite.dataimport.project.model.Project
import com.bosch.pt.iot.smartsite.dataimport.project.model.WorkArea
import com.bosch.pt.iot.smartsite.dataimport.task.model.DayCard
import com.bosch.pt.iot.smartsite.dataimport.task.model.Task
import com.bosch.pt.iot.smartsite.dataimport.task.model.Topic
import com.bosch.pt.iot.smartsite.importer.boundary.AbstractDataImportService.Companion.getResources
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ClasspathResourceScanner
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum.daycard
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum.milestone
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum.project
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum.task
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum.topic
import com.bosch.pt.iot.smartsite.importer.boundary.resource.ResourceTypeEnum.workarea
import com.fasterxml.jackson.core.type.TypeReference
import java.util.UUID.randomUUID
import java.util.concurrent.ThreadLocalRandom
import kotlin.math.ceil
import org.springframework.core.io.Resource
object DynamicTestDataExtender {
fun generateData(dataset: String, numberOfAdditionalWorkAreas: Int): GeneratedData {
val resources: Map<ResourceTypeEnum, Resource> = ClasspathResourceScanner.scan(dataset)
if (resources.isEmpty()) {
throw IllegalStateException("The specified dataset does not contain any files")
}
// Load existing data from json files
val existingWorkAreas =
getResources(resources, workarea, object : TypeReference<List<WorkArea>>() {})
val existingTasks = getResources(resources, task, object : TypeReference<List<Task>>() {})
val existingTopics = getResources(resources, topic, object : TypeReference<List<Topic>>() {})
val existingDayCards =
getResources(resources, daycard, object : TypeReference<List<DayCard>>() {})
val existingMilestones =
getResources(resources, milestone, object : TypeReference<List<Milestone>>() {})
// Copy lists to be extended
val newWorkAreas = existingWorkAreas.toMutableList()
val newTasks = existingTasks.toMutableList()
val newTopics = existingTopics.toMutableList()
val newDayCards = existingDayCards.toMutableList()
val newMilestones = existingMilestones.toMutableList()
// Generate data for each project
val projects = getResources(resources, project, object : TypeReference<List<Project>>() {})
projects.forEach { project ->
// Find the work area with the most tasks to take ist as a template to duplicate
val workAreaIdWithMostTasks =
existingTasks
.filter { it.projectId == project.id && it.workAreaId != null }
.groupingBy { it.workAreaId }
.eachCount()
.maxWithOrNull(Comparator.comparingInt { it.value })
?.key
if (workAreaIdWithMostTasks != null) {
// Find data to duplicate
val templateWorkArea = existingWorkAreas.single { it.id == workAreaIdWithMostTasks }
val templateTasks = existingTasks.filter { it.workAreaId == workAreaIdWithMostTasks }
var dateOffset = 0
var workAreaListEtag =
existingWorkAreas.filter { it.projectId == project.id }.maxOf { it.etag.toInt() } + 1
// Duplicate the work area and data belonging it
for (workAreaIndex in 1..numberOfAdditionalWorkAreas) {
// Duplicate work area
val duplicatedWorkArea =
duplicateWorkArea(templateWorkArea, workAreaIndex, workAreaListEtag++).also {
newWorkAreas.add(it)
}
// Duplicate tasks of work area
val oldTaskIdsToNewTaskIdsMapping =
copyTasks(duplicatedWorkArea.id, templateTasks, dateOffset).let {
newTasks.addAll(it.first)
it.second
}
// Duplicate topics and day cards
fun isCopiedTask(id: String) = oldTaskIdsToNewTaskIdsMapping.keys.contains(id)
copyTopics(
existingTopics.filter { isCopiedTask(it.taskId) }, oldTaskIdsToNewTaskIdsMapping)
.also { newTopics.addAll(it) }
copyDayCards(
existingDayCards.filter { isCopiedTask(it.taskId) }, oldTaskIdsToNewTaskIdsMapping)
.also { newDayCards.addAll(it) }
// Add the next work area where tasks start with a delay of 2 days (compared to the
// previous copy of the work area)
dateOffset += 2
}
// Generate additional day cards to have more tasks with day cards
generateDayCards(newTasks, newDayCards)
}
newMilestones.addAll(generateWorkAreaMilestones(newWorkAreas, newTasks, project))
newMilestones.addAll(generateProjectMilestones(newTasks, project))
}
return GeneratedData(newWorkAreas, newTasks, newTopics, newDayCards, newMilestones)
}
private fun generateDayCards(tasks: List<Task>, dayCards: MutableList<DayCard>) {
val dayCardsByTaskId = dayCards.groupBy { it.taskId }
tasks.forEach { task ->
// Add day cards if a task has a schedule with a start and end date
if (task.end != null && task.start != null) {
val taskDuration = (task.end - task.start) + 1
require(taskDuration >= 0) { "Negative task duration" }
val dayCardsOfTask = dayCardsByTaskId[task.id]
val daysWithDayCards = dayCardsOfTask?.count() ?: 0
val currentDayCardPercentage = daysWithDayCards / taskDuration.toFloat()
// Do it only if the task's schedule has less than 20% of its timespan filled with day
// cards. Do it only in 80% if the cases.
if (currentDayCardPercentage < 0.2 && ThreadLocalRandom.current().nextFloat() > 0.2) {
// Calculate numbers/metrics for the day cards to create
val expectedMinimumOfDayCards = ceil(taskDuration * 0.2).toInt()
val missingDayCards = expectedMinimumOfDayCards - daysWithDayCards
// Generate dates where in the schedule the new day cards should be added
val additionalDayCardDays =
(1..missingDayCards)
.map { ThreadLocalRandom.current().nextInt(0, taskDuration) }
.toMutableSet()
val existingDays = dayCardsOfTask?.map { it.date }?.toSet() ?: emptySet()
additionalDayCardDays.removeAll(existingDays)
// Generate new day cards based on the previously calculated parameters
val newDayCards =
additionalDayCardDays.sorted().map {
require(task.start == task.end && it == 0 || task.start + it <= task.end) {
"Day card date outside of schedule"
}
DayCard(
id = randomUUID().toString(),
taskId = task.id,
title = task.name,
manpower = ThreadLocalRandom.current().nextInt(1, 6).toBigDecimal(),
date = it,
createWithUserId = task.createWithUserId)
}
dayCards.addAll(newDayCards)
}
}
}
}
private fun generateWorkAreaMilestones(
workAreas: List<WorkArea>,
tasks: List<Task>,
project: Project
): List<Milestone> =
tasks
.asSequence()
.filter { it.projectId == project.id && it.workAreaId != null }
.filter { it.start != null && it.end != null }
.groupBy { requireNotNull(it.workAreaId) }
.filter { it.value.isNotEmpty() }
.map { (workAreaId, tasksOfWorkArea) ->
// Create a milestone per work area
val workArea = workAreas.single { it.id == workAreaId }
// Calculate the date of the milestone
val latestEnd = tasksOfWorkArea.maxOf { it.end!! }
// Put the milestone randomly in a 10 days date range after the last
// task of the work area
val date = latestEnd + ThreadLocalRandom.current().nextInt(0, 10)
Milestone(
id = randomUUID().toString(),
projectId = project.id,
name = workArea.name,
type = PROJECT,
header = false,
date = date,
workAreaId = workAreaId,
createWithUserId = workArea.createWithUserId)
}
private fun generateProjectMilestones(tasks: List<Task>, project: Project): List<Milestone> {
// Generate project milestones in 5% steps to indicate project progress
val latestEnd = tasks.maxOf { it.end ?: 0 }
val earliestStart = tasks.minOf { it.start ?: 0 }
val projectDuration = latestEnd - earliestStart
// If the project is shorter than 20 days don't create the milestones
if (projectDuration < 20) {
return emptyList()
}
// Create the milestones
fun createProjectMilestone(name: String, date: Int) =
Milestone(
id = randomUUID().toString(),
projectId = project.id,
name = name,
type = PROJECT,
header = true,
date = date,
description = "$name progress milestone",
createWithUserId = requireNotNull(project.createWithUserId))
return (5..100 step 5).map { progressInPercent ->
val date = earliestStart + progressInPercent * (projectDuration / 100.0)
createProjectMilestone("$progressInPercent%", date.toInt())
}
}
private fun copyDayCards(
existingDayCards: List<DayCard>,
oldTaskIdsToNewTaskIdsMapping: Map<String, String>
): List<DayCard> =
existingDayCards.map {
it.copy(
id = randomUUID().toString(),
taskId = requireNotNull(oldTaskIdsToNewTaskIdsMapping[it.taskId]))
}
private fun copyTopics(
existingTopics: List<Topic>,
oldTaskIdsToNewTaskIdsMapping: Map<String, String>
): List<Topic> =
existingTopics.map {
it.copy(
id = randomUUID().toString(),
taskId = requireNotNull(oldTaskIdsToNewTaskIdsMapping[it.taskId]))
}
private fun copyTasks(
targetWorkAreaId: String,
existingTasks: List<Task>,
dateOffset: Int
): Pair<List<Task>, Map<String, String>> {
val oldTaskIdsToNewTaskIdsMapping = mutableMapOf<String, String>()
val copiedTasks =
existingTasks.map { task ->
val newTaskId = randomUUID().toString()
oldTaskIdsToNewTaskIdsMapping[task.id] = newTaskId
task.copy(
id = newTaskId,
workAreaId = targetWorkAreaId,
start = task.start?.let { it + dateOffset },
end = task.end?.let { it + dateOffset })
}
return Pair(copiedTasks, oldTaskIdsToNewTaskIdsMapping)
}
private fun duplicateWorkArea(workArea: WorkArea, number: Int, etag: Int): WorkArea =
workArea.copy(
id = randomUUID().toString(),
name = "Additional Work Area $number",
etag = "$etag",
)
}
class GeneratedData(
val workAreas: List<WorkArea>,
val tasks: List<Task>,
val topics: List<Topic>,
val dayCards: List<DayCard>,
val milestones: List<Milestone>
)
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 11,875
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
src/nativeGen/kotlin/godot/GIProbe.kt
|
piiertho
| 237,614,467
| true
|
{"Kotlin": 5300589}
|
// DO NOT EDIT, THIS FILE IS GENERATED FROM api.json
package godot
import gdnative.godot_method_bind
import godot.core.Godot
import godot.core.Variant
import godot.core.VariantArray
import godot.core.Vector3
import kotlin.Boolean
import kotlin.Float
import kotlin.Int
import kotlin.Unit
import kotlin.reflect.KCallable
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.cstr
import kotlinx.cinterop.invoke
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.reinterpret
open class GIProbe(
_handle: COpaquePointer
) : VisualInstance(_handle) {
var bias: Float
get() {
return getBias()
}
set(value) {
setBias(value)
}
var compress: Boolean
get() {
return isCompressed()
}
set(value) {
setCompress(value)
}
var data: GIProbeData
get() {
return getProbeData()
}
set(value) {
setProbeData(value)
}
var dynamicRange: Int
get() {
return getDynamicRange()
}
set(value) {
setDynamicRange(value)
}
var energy: Float
get() {
return getEnergy()
}
set(value) {
setEnergy(value)
}
var extents: Vector3
get() {
return getExtents()
}
set(value) {
setExtents(value)
}
var interior: Boolean
get() {
return isInterior()
}
set(value) {
setInterior(value)
}
var normalBias: Float
get() {
return getNormalBias()
}
set(value) {
setNormalBias(value)
}
var propagation: Float
get() {
return getPropagation()
}
set(value) {
setPropagation(value)
}
var subdiv: Subdiv
get() {
return getSubdiv()
}
set(value) {
setSubdiv(value.value)
}
/**
* Specialized setter for extents
*/
fun extents(cb: Vector3.() -> Unit) {
val _p = extents
cb(_p)
extents = _p
}
fun bake(fromNode: Node, createVisualDebug: Boolean = false) {
val _args = mutableListOf<Variant>()
_args.add(Variant.fromAny(fromNode))
_args.add(Variant.fromAny(createVisualDebug))
__method_bind.bake.call(this._handle, _args)
}
fun debugBake() {
__method_bind.debugBake.call(this._handle)
}
fun getBias(): Float {
val _ret = __method_bind.getBias.call(this._handle)
return _ret.asFloat()
}
fun getDynamicRange(): Int {
val _ret = __method_bind.getDynamicRange.call(this._handle)
return _ret.asInt()
}
fun getEnergy(): Float {
val _ret = __method_bind.getEnergy.call(this._handle)
return _ret.asFloat()
}
fun getExtents(): Vector3 {
val _ret = __method_bind.getExtents.call(this._handle)
return _ret.asVector3()
}
fun getNormalBias(): Float {
val _ret = __method_bind.getNormalBias.call(this._handle)
return _ret.asFloat()
}
fun getProbeData(): GIProbeData {
val _ret = __method_bind.getProbeData.call(this._handle)
return _ret.asObject(::GIProbeData)!!
}
fun getPropagation(): Float {
val _ret = __method_bind.getPropagation.call(this._handle)
return _ret.asFloat()
}
fun getSubdiv(): Subdiv {
val _ret = __method_bind.getSubdiv.call(this._handle)
return GIProbe.Subdiv.from(_ret.asInt())
}
fun isCompressed(): Boolean {
val _ret = __method_bind.isCompressed.call(this._handle)
return _ret.asBoolean()
}
fun isInterior(): Boolean {
val _ret = __method_bind.isInterior.call(this._handle)
return _ret.asBoolean()
}
fun setBias(max: Float) {
val _arg = Variant.new(max)
__method_bind.setBias.call(this._handle, listOf(_arg))
}
fun setCompress(enable: Boolean) {
val _arg = Variant.new(enable)
__method_bind.setCompress.call(this._handle, listOf(_arg))
}
fun setDynamicRange(max: Int) {
val _arg = Variant.new(max)
__method_bind.setDynamicRange.call(this._handle, listOf(_arg))
}
fun setEnergy(max: Float) {
val _arg = Variant.new(max)
__method_bind.setEnergy.call(this._handle, listOf(_arg))
}
fun setExtents(extents: Vector3) {
val _arg = Variant.new(extents)
__method_bind.setExtents.call(this._handle, listOf(_arg))
}
fun setInterior(enable: Boolean) {
val _arg = Variant.new(enable)
__method_bind.setInterior.call(this._handle, listOf(_arg))
}
fun setNormalBias(max: Float) {
val _arg = Variant.new(max)
__method_bind.setNormalBias.call(this._handle, listOf(_arg))
}
fun setProbeData(data: GIProbeData) {
val _arg = Variant.new(data)
__method_bind.setProbeData.call(this._handle, listOf(_arg))
}
fun setPropagation(max: Float) {
val _arg = Variant.new(max)
__method_bind.setPropagation.call(this._handle, listOf(_arg))
}
fun setSubdiv(subdiv: Int) {
val _arg = Variant.new(subdiv)
__method_bind.setSubdiv.call(this._handle, listOf(_arg))
}
enum class Subdiv(
val value: Int
) {
SUBDIV_64(0),
SUBDIV_128(1),
SUBDIV_256(2),
SUBDIV_512(3),
SUBDIV_MAX(4);
companion object {
fun from(value: Int): Subdiv {
for (enumValue in values()) {
if (enumValue.value == value) {
return enumValue
}
}
throw AssertionError("""Unsupported enum value: $value""")
}
}
}
companion object {
val SUBDIV_128: Int = 1
val SUBDIV_256: Int = 2
val SUBDIV_512: Int = 3
val SUBDIV_64: Int = 0
val SUBDIV_MAX: Int = 4
fun new(): GIProbe = memScoped {
val fnPtr = checkNotNull(Godot.gdnative.godot_get_class_constructor)("GIProbe".cstr.ptr)
requireNotNull(fnPtr) { "No instance found for GIProbe" }
val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>()
GIProbe(
fn()
)
}
fun from(ptr: COpaquePointer): GIProbe = GIProbe(ptr)
/**
* Container for method_bind pointers for GIProbe
*/
private object __method_bind {
val bake: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"bake".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method bake" }
}
val debugBake: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"debug_bake".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method debug_bake" }
}
val getBias: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_bias".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_bias" }
}
val getDynamicRange: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_dynamic_range".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_dynamic_range" }
}
val getEnergy: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_energy".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_energy" }
}
val getExtents: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_extents".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_extents" }
}
val getNormalBias: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_normal_bias".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_normal_bias" }
}
val getProbeData: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_probe_data".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_probe_data" }
}
val getPropagation: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_propagation".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_propagation" }
}
val getSubdiv: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"get_subdiv".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_subdiv" }
}
val isCompressed: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"is_compressed".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method is_compressed" }
}
val isInterior: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"is_interior".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method is_interior" }
}
val setBias: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_bias".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_bias" }
}
val setCompress: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_compress".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_compress" }
}
val setDynamicRange: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_dynamic_range".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_dynamic_range" }
}
val setEnergy: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_energy".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_energy" }
}
val setExtents: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_extents".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_extents" }
}
val setInterior: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_interior".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_interior" }
}
val setNormalBias: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_normal_bias".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_normal_bias" }
}
val setProbeData: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_probe_data".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_probe_data" }
}
val setPropagation: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_propagation".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_propagation" }
}
val setSubdiv: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("GIProbe".cstr.ptr,
"set_subdiv".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_subdiv" }
}}
}
}
| 0
| null |
0
| 1
|
3a8c598040f9b47b2b8cf8f5432543f61d6f83e8
| 12,665
|
godot-kotlin
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.