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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/org/ghilardi/salestaxesproblem/context/STPContextBuilder.kt | dghilardi | 204,846,456 | false | null | /*
* The MIT License
*
* Copyright (c) 2019 <NAME>
*
* 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 org.ghilardi.salestaxesproblem.context
import org.ghilardi.salestaxesproblem.action.impl.BasketItemTypeFromConfigurationExtractor
import org.ghilardi.salestaxesproblem.command.ProduceReceiptCommand
import org.ghilardi.salestaxesproblem.factory.action.BasicSalesTaxCalculatorFactory
import org.ghilardi.salestaxesproblem.factory.action.ImportDutySalesTaxCalculatorFactory
import org.ghilardi.salestaxesproblem.factory.action.ItemReceiptSerializerFactory
import org.ghilardi.salestaxesproblem.factory.entity.ShoppingBasketEntityFactory
import org.ghilardi.salestaxesproblem.factory.entity.ShoppingBasketItemEntityFactory
import org.ghilardi.salestaxesproblem.model.BasketItemType
import org.ghilardi.salestaxesproblem.model.STPConfiguration
import org.ghilardi.salestaxesproblem.parser.BasketItemParser
import org.ghilardi.salestaxesproblem.parser.BasketParser
import java.math.BigDecimal
class STPContextBuilder {
fun buildContext(): STPContext {
val stpConfiguration = STPConfiguration(
basicSalesTaxRate = BigDecimal("10.0"),
importDutySalesTaxRate = BigDecimal("5.0"),
roundingStep = BigDecimal("0.05"),
basketItemTypeMap = mapOf(
"book" to BasketItemType.BOOK,
"music CD" to BasketItemType.OTHER,
"chocolate bar" to BasketItemType.FOOD,
"bottle of perfume" to BasketItemType.OTHER,
"packet of headache pills" to BasketItemType.MEDICAL_PRODUCT,
"box of chocolates" to BasketItemType.FOOD
)
)
val basicSalesTaxCalculatorFactory = BasicSalesTaxCalculatorFactory(stpConfiguration)
val importDutySalesTaxCalculatorFactory = ImportDutySalesTaxCalculatorFactory(stpConfiguration)
val itemReceiptSerializerFactory = ItemReceiptSerializerFactory()
val shoppingBasketItemEntityFactory = ShoppingBasketItemEntityFactory(
basicSalesTaxCalculatorFactory = basicSalesTaxCalculatorFactory,
importDutySalesTaxCalculatorFactory = importDutySalesTaxCalculatorFactory,
itemReceiptSerializerFactory = itemReceiptSerializerFactory
)
val basketEntityFactory = ShoppingBasketEntityFactory(shoppingBasketItemEntityFactory)
val basketItemTypeExtractor = BasketItemTypeFromConfigurationExtractor(stpConfiguration)
val basketItemParser = BasketItemParser(basketItemTypeExtractor)
val basketParser = BasketParser(basketItemParser)
val produceReceiptCommand = ProduceReceiptCommand(
basketParser = basketParser,
basketEntityFactory = basketEntityFactory
)
return STPContext(
stpConfiguration = stpConfiguration,
basicSalesTaxCalculatorFactory = basicSalesTaxCalculatorFactory,
importDutySalesTaxCalculatorFactory = importDutySalesTaxCalculatorFactory,
itemReceiptSerializerFactory = itemReceiptSerializerFactory,
shoppingBasketItemEntityFactory = shoppingBasketItemEntityFactory,
basketEntityFactory = basketEntityFactory,
basketItemTypeExtractor = basketItemTypeExtractor,
basketItemParser = basketItemParser,
basketParser = basketParser,
produceReceiptCommand = produceReceiptCommand
)
}
} | 0 | Kotlin | 0 | 0 | 13397ad4680fbee3385ec2a2db7dfd58cd8c4509 | 4,616 | sales-taxes-problem | MIT License |
library/src/main/java/com/alexstyl/contactstore/MutableContact.kt | virendersran01 | 413,287,844 | true | {"Kotlin": 132637} | package com.alexstyl.contactstore
import android.provider.ContactsContract
import com.alexstyl.contactstore.ContactColumn.EVENTS
import com.alexstyl.contactstore.ContactColumn.GROUP_MEMBERSHIPS
import com.alexstyl.contactstore.ContactColumn.IMAGE
import com.alexstyl.contactstore.ContactColumn.MAILS
import com.alexstyl.contactstore.ContactColumn.NAMES
import com.alexstyl.contactstore.ContactColumn.NOTE
import com.alexstyl.contactstore.ContactColumn.ORGANIZATION
import com.alexstyl.contactstore.ContactColumn.PHONES
import com.alexstyl.contactstore.ContactColumn.POSTAL_ADDRESSES
import com.alexstyl.contactstore.ContactColumn.WEB_ADDRESSES
import com.alexstyl.contactstore.ContactColumn.values
class MutableContact internal constructor(
override var contactId: Long = -1L,
imageData: ImageData?,
phones: MutableList<LabeledValue<PhoneNumber>>,
mails: MutableList<LabeledValue<MailAddress>>,
events: MutableList<LabeledValue<EventDate>>,
postalAddresses: MutableList<LabeledValue<PostalAddress>>,
webAddresses: MutableList<LabeledValue<WebAddress>>,
note: Note?,
override var isStarred: Boolean,
firstName: String?,
lastName: String?,
middleName: String?,
prefix: String?,
suffix: String?,
phoneticFirstName: String?,
phoneticMiddleName: String?,
phoneticLastName: String?,
fullNameStyle: Int,
phoneticNameStyle: Int,
nickname: String?,
organization: String?,
jobTitle: String?,
groups: MutableList<GroupMembership>,
override val columns: List<ContactColumn>,
) : Contact {
override var imageData: ImageData? by readWriteField(IMAGE, imageData)
override val phones: MutableList<LabeledValue<PhoneNumber>> by readField(PHONES, phones)
override val mails: MutableList<LabeledValue<MailAddress>> by readField(MAILS, mails)
override val events: MutableList<LabeledValue<EventDate>> by readField(EVENTS, events)
override val postalAddresses: MutableList<LabeledValue<PostalAddress>>
by readField(POSTAL_ADDRESSES, postalAddresses)
override val webAddresses: MutableList<LabeledValue<WebAddress>>
by readField(WEB_ADDRESSES, webAddresses)
override var note: Note? by readWriteField(NOTE, note)
override val groups: MutableList<GroupMembership> by readField(GROUP_MEMBERSHIPS, groups)
override var organization: String? by readWriteField(ORGANIZATION, organization)
override var jobTitle: String? by readWriteField(ORGANIZATION, jobTitle)
override var firstName: String? by readWriteField(NAMES, firstName)
override var lastName: String? by readWriteField(NAMES, lastName)
override var middleName: String? by readWriteField(NAMES, middleName)
override var prefix: String? by readWriteField(NAMES, prefix)
override var suffix: String? by readWriteField(NAMES, suffix)
override var phoneticLastName: String? by readWriteField(NAMES, phoneticLastName)
override var phoneticFirstName: String? by readWriteField(NAMES, phoneticFirstName)
override var phoneticMiddleName: String? by readWriteField(NAMES, phoneticMiddleName)
override var fullNameStyle: Int by readWriteField(NAMES, fullNameStyle)
override var phoneticNameStyle: Int by readWriteField(NAMES, phoneticNameStyle)
override var nickname: String? by readWriteField(NAMES, nickname)
constructor() : this(
contactId = -1L,
imageData = null,
phones = mutableListOf(),
mails = mutableListOf(),
events = mutableListOf(),
postalAddresses = mutableListOf(),
webAddresses = mutableListOf(),
note = null,
isStarred = false,
firstName = null,
lastName = null,
middleName = null,
prefix = null,
suffix = null,
phoneticFirstName = null,
phoneticMiddleName = null,
phoneticLastName = null,
fullNameStyle = ContactsContract.FullNameStyle.UNDEFINED,
phoneticNameStyle = ContactsContract.PhoneticNameStyle.UNDEFINED,
nickname = null,
organization = null,
jobTitle = null,
groups = mutableListOf(),
columns = values().toList() // allow editing of all columns for new contacts
)
override val displayName: String
get() = buildString {
appendWord(buildStringFromNames())
if (isEmpty()) {
phoneticFirstName?.let { append(it) }
phoneticMiddleName?.let { appendWord(it) }
phoneticLastName?.let { appendWord(it) }
}
if (isEmpty()) {
append(nickname.orEmpty())
}
if (isEmpty()) {
append(organization.orEmpty())
}
if (isEmpty()) {
phones.firstOrNull()?.let { append(it.value.raw) }
}
if (isEmpty()) {
mails.firstOrNull()?.let { append(it.value.raw) }
}
}
override fun containsColumn(column: ContactColumn): Boolean {
return columns.contains(column)
}
override fun equals(other: Any?): Boolean {
return equalContacts(other as Contact?)
}
override fun hashCode(): Int {
return contactHashCode()
}
override fun toString(): String {
return toFullString()
}
} | 0 | null | 0 | 0 | ca0d0a6a7a0c0412c39cb1d3db23116ef04d5ee1 | 5,323 | contactstore | Apache License 2.0 |
src/main/kotlin/com/catcher/base/exception/BusinessException.kt | comtihon | 178,599,177 | false | null | package com.catcher.base.exception
open class BusinessException(msg: String) : RuntimeException(msg)
class ExecutionFailedException(msg: String) : BusinessException(msg) | 7 | Kotlin | 1 | 1 | 73a492a6e545e78a9e058f7a6933aa6d66962b0a | 171 | catcher_base | Apache License 2.0 |
kohii/src/main/java/kohii/v1/ViewPlayback.kt | Mina-Mikhail | 196,247,544 | true | {"Kotlin": 500143, "Java": 28428, "Prolog": 2635} | /*
* Copyright (c) 2018 <NAME>, <EMAIL>
*
* 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 kohii.v1
import android.graphics.Point
import android.graphics.Rect
import android.util.Log
import android.view.View
import androidx.annotation.CallSuper
import androidx.core.view.ViewCompat
import kotlin.LazyThreadSafetyMode.NONE
import kotlin.math.max
/**
* @author eneim (2018/06/24).
*/
open class ViewPlayback<V : View, RENDERER : Any>(
kohii: Kohii,
playable: Playable<RENDERER>,
manager: PlaybackManager,
target: V,
options: Config
) : Playback<RENDERER>(
kohii,
playable,
manager,
target,
options
) {
private val keepScreenOnListener by lazy(NONE) {
object : PlaybackEventListener {
override fun beforePlay(playback: Playback<*>) {
target.keepScreenOn = true
}
override fun afterPause(playback: Playback<*>) {
target.keepScreenOn = false
}
override fun onEnd(playback: Playback<*>) {
target.keepScreenOn = false
}
}
}
// For debugging purpose only.
private val debugListener: PlaybackEventListener by lazy {
object : PlaybackEventListener {
override fun onFirstFrameRendered(playback: Playback<*>) {
Log.d(TAG, "first frame: ${this@ViewPlayback}")
}
override fun onBuffering(
playback: Playback<*>,
playWhenReady: Boolean
) {
Log.d(TAG, "buffering: ${this@ViewPlayback}")
}
override fun beforePlay(playback: Playback<*>) {
Log.w(TAG, "beforePlay: ${this@ViewPlayback}")
}
override fun onPlay(playback: Playback<*>) {
Log.d(TAG, "playing: ${this@ViewPlayback}")
}
override fun onPause(playback: Playback<*>) {
Log.w(TAG, "paused: ${this@ViewPlayback}")
}
override fun afterPause(playback: Playback<*>) {
Log.w(TAG, "afterPause: ${this@ViewPlayback}")
}
override fun onEnd(playback: Playback<*>) {
Log.d(TAG, "ended: ${this@ViewPlayback}")
}
}
}
// TODO [20190112] deal with scaled/transformed View and/or its Parent.
override val token: ViewToken
get() {
val viewTarget = target as View
val playerRect = Rect()
if (!ViewCompat.isAttachedToWindow(viewTarget)) {
return ViewToken(this.config, playerRect, -1F)
}
val visible = viewTarget.getGlobalVisibleRect(playerRect, Point())
if (!visible) return ViewToken(this.config, playerRect, -1F)
val drawRect = Rect()
viewTarget.getDrawingRect(drawRect)
val drawArea = drawRect.width() * drawRect.height()
var offset = 0f
if (drawArea > 0) {
val visibleArea = playerRect.height() * playerRect.width()
offset = visibleArea / drawArea.toFloat()
}
return ViewToken(this.config, playerRect, offset)
}
@CallSuper
override fun onAdded() {
super.onAdded()
if (config.keepScreenOn) super.addPlaybackEventListener(keepScreenOnListener)
if (BuildConfig.DEBUG) super.addPlaybackEventListener(this.debugListener)
}
@CallSuper
override fun onRemoved() {
if (BuildConfig.DEBUG) super.removePlaybackEventListener(this.debugListener)
if (config.keepScreenOn) super.removePlaybackEventListener(keepScreenOnListener)
super.onRemoved()
}
override fun compareWidth(
other: Playback<*>,
orientation: Int
): Int {
if (other !is ViewPlayback<*, *>) {
return 0
}
val thisToken = this.token
val thatToken = other.token
val verticalOrder by lazy { CENTER_Y.compare(thisToken, thatToken) }
val horizontalOrder by lazy { CENTER_X.compare(thisToken, thatToken) }
var result = when (orientation) {
TargetHost.VERTICAL -> verticalOrder
TargetHost.HORIZONTAL -> horizontalOrder
TargetHost.BOTH_AXIS -> max(verticalOrder, horizontalOrder)
TargetHost.NONE_AXIS -> max(verticalOrder, horizontalOrder)
else -> 0
}
if (result == 0) result = compareValues(thisToken.areaOffset, thatToken.areaOffset)
return result
}
@Suppress("UNCHECKED_CAST")
override val renderer: RENDERER?
get() = this.target as? RENDERER
// Location on screen, with visible offset within target's parent.
data class ViewToken constructor(
val config: Config,
val viewRect: Rect,
val areaOffset: Float
) : Token() {
override fun shouldPrepare(): Boolean {
return areaOffset >= 0f
}
override fun shouldPlay(): Boolean {
return areaOffset >= config.threshold
}
override fun toString(): String {
return "Token::$viewRect::$areaOffset"
}
}
companion object {
val CENTER_Y: Comparator<ViewToken> = Comparator { o1, o2 ->
compareValues(o1.viewRect.centerY(), o2.viewRect.centerY())
}
val CENTER_X: Comparator<ViewToken> = Comparator { o1, o2 ->
compareValues(o1.viewRect.centerX(), o2.viewRect.centerX())
}
}
}
| 0 | Kotlin | 0 | 0 | 63ae4471953a2a8f5e0fd9f5fb13cd98cd38bd2e | 5,456 | kohii | Apache License 2.0 |
app/src/main/java/com/example/premierepage/workoutGoal.kt | abderrahmen-Baccouch | 468,118,218 | false | {"Kotlin": 288746} | package com.example.premierepage
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color.*
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.premierepage.model.Exercices
import com.example.premierepage.view.ExerciceAdapter
import com.mikhaellopez.circularprogressbar.CircularProgressBar
import kotlinx.android.synthetic.main.activity_fifth.*
import kotlinx.android.synthetic.main.activity_workout_goal.*
import kotlinx.android.synthetic.main.activity_workout_goal.buttonDatePicker
import kotlinx.android.synthetic.main.item_exercice.*
import retrofit2.Call
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class workoutGoal : AppCompatActivity() {
private var cYear: Int? = null
private var cMonth: Int? = null
private var cDay: Int? = null
private var retrofitInterface: RetrofitInterface? = null
private lateinit var recv: RecyclerView
var myshared: SharedPreferences?=null
//var arr = emptyArray<Int>()
//val tab = arrayOf (Int)
val arr = intArrayOf(0)
val tab = ArrayList<Int>()
private var nbr1: Int? = 0
private var nbr2: Int? = 0
private var nbr3: Int? = 0
private lateinit var KcalNbr : TextView
@SuppressLint("SetTextI18n", "NotifyDataSetChanged")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_workout_goal)
KcalNbr=findViewById(R.id.KcalNbr)
val retrofit = RetrofitClient.getInstance()
retrofitInterface = retrofit.create(RetrofitInterface::class.java)
recv = findViewById(R.id.exercicesRecycler)//esm recycler badlou choufou fil workoutGoal
val calendar: TextView =findViewById(R.id.calendar)
val intent = intent
val nbrKcal1 = intent.getIntExtra("nbrKcal1",0)
val name = intent.getStringExtra("name").toString()
/**-------------------------------------myshared-------------------------------------------------- */
myshared=getSharedPreferences("myshared",0)
var token =myshared?.getString("token","")
// val nbrKcal2 = intent.getStringExtra("nbrKcal2").toString()
//val name2 = intent.getStringExtra("name2").toString()
// val names = name
val pattern = "dd-MM-yyyy"
val simpleDateFormat = SimpleDateFormat(pattern)
val date: String = simpleDateFormat.format(Date())
calendar.text=date
getExercices(token!!,calendar.text.toString())
//Calendar
val c = Calendar.getInstance()
var year = c.get(Calendar.YEAR)
var month = c.get(Calendar.MONTH)
var day = c.get(Calendar.DAY_OF_MONTH)
//button click to show DatePicker
buttonDatePicker.setOnClickListener{
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener
{ view, mYear, mMonth, mDay ->
day = mDay
month = mMonth
year = mYear
//set to textView
cYear=year
cMonth=month+1
cDay=day
calendar.text ="${cDay.toString().padStart(2, '0')}-${cMonth.toString().padStart(2, '0')}-${cYear.toString()}"
getExercices(token,calendar.text.toString())
// age.text= "${cAge.toString()}"
},year,month,day)
//Show dialog
dpd.show()
}
/*tab.add(nbrKcal1)
for(index in 0..tab.size-1){
nbr2 = tab[index] + nbr2!!
}
val c = nbr2.toString()
//calerie.text = c
KcalNbr.text = c*/
/** if (arr[0]==0){
arr.set(0,number)
}else{
var i = 1
var b =false
while(b==false){
if(arr[i]==null){
arr.set(i,number)
b=true
}
else{
i++ }}}
for (j in 0..arr.size-1){
val a = nbr1
nbr1 = a!! + arr.get(j) }
val c = nbr1.toString()
*/
progress_circular_workout.apply {
progress = 0f
setProgressWithAnimation(100f,3000)
progressBarWidth = 12f
backgroundProgressBarWidth = 16f
progressBarColorStart = CYAN
progressBarColorEnd = WHITE
roundBorder = true
progressBarColorDirection = CircularProgressBar.GradientDirection.TOP_TO_BOTTOM
// Set background ProgressBar Color
backgroundProgressBarColor = GRAY
// or with gradient
backgroundProgressBarColorStart = WHITE
backgroundProgressBarColorEnd = rgb(220,20,60)
backgroundProgressBarColorDirection = CircularProgressBar.GradientDirection.TOP_TO_BOTTOM
}
}
fun getExercices(token:String,dateUser:String){
val map = HashMap<String?, String?>()
map["dateUser"] = dateUser
val call = retrofitInterface!!.executeAllExerciceTermine(map,token)
call.enqueue(object : retrofit2.Callback<MutableList<Exercices>> {
override fun onResponse(call: Call<MutableList<Exercices>>, response: Response<MutableList<Exercices>>) {
if (response.code()==200){
var listExerciceTermine=response.body()
var calConsome=0
for(i in 0..listExerciceTermine!!.size-1) {
Toast.makeText(this@workoutGoal,i.toString(),Toast.LENGTH_LONG).show()
calConsome=calConsome+listExerciceTermine[i].calories.toInt()
}
KcalNbr.text= calConsome.toString()
recv.apply {
recv.layoutManager = LinearLayoutManager(this@workoutGoal)
adapter= ExerciceAdapter(this@workoutGoal,response.body()!!,"2",object: ExerciceAdapter.onItemClickListener{
override fun onItemClick(position: Int) {
}
}/*object:ExerciceAdapter.onItemClickListener{
override fun onItemClick(position: Int) {}}*/)
}
}else if (response.code()==400){
}
}
override fun onFailure(call: Call<MutableList<Exercices>>, t: Throwable) {
Toast.makeText(this@workoutGoal, t.message, Toast.LENGTH_LONG).show()
}
})
}
} | 1 | Kotlin | 1 | 0 | c2ceee994ee947004bca4717fa899ed68aa370cf | 6,804 | LifeBalance | MIT License |
app/src/main/java/com/abcd/firebasemlkt01/baseDialog/BaseDialogMain.kt | AliAzaz | 202,393,512 | false | null | package com.abcd.firebasemlkt01.baseDialog
import android.app.AlertDialog
import android.content.Context
import android.view.Gravity
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
open class BaseDialogMain(context: Context) : BaseDialogView.UIView, ProgressBar(context) {
private val llPadding = 30
private val ll: LinearLayout = LinearLayout(context)
private val tvText: TextView = TextView(context)
private val builder = AlertDialog.Builder(context)
private lateinit var llParam: LinearLayout.LayoutParams
private lateinit var baseDialog: AlertDialog
init {
setAlertDialog()
}
private fun setAlertDialog() {
ll.orientation = LinearLayout.HORIZONTAL
ll.gravity = Gravity.CENTER
llParam = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
ll.layoutParams = llParam
this.isIndeterminate = true
// this.setPadding(30, 30, 30, 30)
tvText.layoutParams = llParam
setViewToBuilder()
}
override fun dismissDialog(dialog: AlertDialog) {
dialog.dismiss()
}
override fun showDialog(dialog: AlertDialog) {
dialog.show()
if (dialog.window != null) {
val layoutParams = WindowManager.LayoutParams()
layoutParams.copyFrom(dialog.window.attributes)
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
dialog.window.attributes = layoutParams
}
}
override fun message(message: String) {
tvText.text = message
}
override fun textColor(color: Int) {
tvText.setTextColor(color)
}
override fun textSize(txtsize: Float) {
tvText.textSize = txtsize
}
override fun alertCancellable(cancel: Boolean) {
builder.setCancelable(cancel)
}
override fun getAlertBuilder(): AlertDialog {
return baseDialog
}
override fun padding(left: Int, top: Int, right: Int, bottom: Int) {
this.setPadding(left, top, right, bottom)
}
private fun setViewToBuilder() {
if (ll.parent != null) ll.removeAllViews()
ll.addView(this)
ll.addView(tvText)
builder.setView(ll)
baseDialog = builder.create()
}
} | 3 | Kotlin | 6 | 9 | 8d9eef69f7d5a47263600e5d6f31e44ec6a7ff78 | 2,486 | FirebaseML01 | MIT License |
app/src/main/java/cz/leaderboard/app/presentation/intro/IntroPresenter.kt | semanticer | 94,618,499 | true | {"Kotlin": 55539, "Java": 10663} | package cz.leaderboard.app.presentation.intro
import com.hannesdorfmann.mosby3.mvp.MvpNullObjectBasePresenter
import cz.leaderboard.app.data.model.Board
import cz.leaderboard.app.domain.board.AddBoardUseCase
import cz.leaderboard.app.domain.board.GetTopBoardsUseCase
import cz.leaderboard.app.presentation.board.IntroView
import cz.leaderboard.app.presentation.common.PresentationObserver
import javax.inject.Inject
/**
* Created by semanticer on 17.06.2017.
*/
class IntroPresenter @Inject constructor(val addBoardUseCase: AddBoardUseCase, val getTopBoardsUseCase: GetTopBoardsUseCase) : MvpNullObjectBasePresenter<IntroView>() {
override fun attachView(view: IntroView) {
super.attachView(view)
getTopBoardsUseCase.execute(TopBoardsObserver(view), GetTopBoardsUseCase.Params())
}
override fun detachView(retainInstance: Boolean) {
addBoardUseCase.dispose()
getTopBoardsUseCase.dispose()
}
fun onSearchClicked(searchText: String) {
addBoardUseCase.execute(AddBoardObserver(view), AddBoardUseCase.Params(searchText) )
}
class AddBoardObserver constructor(view: IntroView): PresentationObserver<Board, IntroView>(view) {
override fun onNext(boards: Board) {
onView { it.showFoundBoard(boards) }
}
override fun onError(e: Throwable?) {
onView { it.showSearchError() }
}
}
class TopBoardsObserver constructor(view: IntroView): PresentationObserver<List<Board>, IntroView>(view) {
override fun onNext(boards: List<Board>) {
onView { it.showTopBoards(boards) }
}
}
} | 0 | Kotlin | 0 | 1 | f7ba6cfed874016172ff062ee5d1b017debae765 | 1,641 | LeaderboardApp | Apache License 2.0 |
src/main/kotlin/magicsquare/quartumbackend/web/dto/ArticleRatingDto.kt | MagicSquareTeam | 458,905,234 | false | null | package magicsquare.quartumbackend.web.dto
import java.io.Serializable
/**
* Модель DTO для оценок статьи
*/
data class ArticleRatingDto(val id: Long? = null) : Serializable
| 0 | Kotlin | 0 | 0 | 35ed0f9594da403a9d39f7fe481a5669d6599df2 | 178 | quartum-backend | MIT License |
androidutils/src/main/java/com/xihad/androidutils/observers/Subject.kt | xihadulislam | 381,070,812 | false | null | package com.xihad.androidutils.observers
/**
* created by @ziad ( 30/11/2022 )
*/
interface Subject {
fun register(spectator: Spectator?)
fun unregister(spectator: Spectator?)
fun notifyObservers(key: String, data: Any)
fun clear()
} | 0 | Kotlin | 2 | 13 | 3a089bc60ec838c8fedbd5b250b5b43be61ea35e | 258 | AndroidUtils | Apache License 2.0 |
plugin-core/src/main/kotlin/dev/aporofobia/order/OrderedPlugin.kt | DreamPoland | 809,070,088 | false | {"Kotlin": 15244} | package dev.aporofobia.order
import cc.dreamcode.command.bukkit.BukkitCommandProvider
import cc.dreamcode.notice.adventure.BukkitNoticeProvider
import cc.dreamcode.notice.adventure.serializer.BukkitNoticeSerializer
import cc.dreamcode.platform.DreamVersion
import cc.dreamcode.platform.bukkit.DreamBukkitConfig
import cc.dreamcode.platform.bukkit.DreamBukkitPlatform
import cc.dreamcode.platform.bukkit.component.ConfigurationResolver
import cc.dreamcode.platform.component.ComponentService
import cc.dreamcode.platform.kotlin.registerComponent
import cc.dreamcode.platform.other.component.DreamCommandExtension
import dev.aporofobia.order.command.SharpenItemsCommand
import dev.aporofobia.order.command.handler.InvalidInputHandlerImpl
import dev.aporofobia.order.command.handler.InvalidPermissionHandlerImpl
import dev.aporofobia.order.command.handler.InvalidSenderHandlerImpl
import dev.aporofobia.order.command.handler.InvalidUsageHandlerImpl
import dev.aporofobia.order.command.result.BukkitNoticeResolver
import dev.aporofobia.order.config.MessageConfig
import dev.aporofobia.order.config.PluginConfig
import dev.aporofobia.order.controller.PlayerDeathController
import eu.okaeri.configs.serdes.OkaeriSerdesPack
import eu.okaeri.configs.serdes.SerdesRegistry
import eu.okaeri.tasker.bukkit.BukkitTasker
class OrderedPlugin : DreamBukkitPlatform(), DreamBukkitConfig {
override fun load(componentService: ComponentService) {
orderedPlugin = this
}
override fun enable(componentService: ComponentService) {
componentService.isDebug = false
this.registerInjectable(BukkitTasker.newPool(this))
this.registerInjectable(BukkitNoticeProvider.create(this))
this.registerInjectable(BukkitCommandProvider.create(this))
componentService.registerExtension(DreamCommandExtension::class.java)
componentService.registerResolver(ConfigurationResolver::class.java)
componentService.registerComponent(MessageConfig::class)
componentService.registerComponent(BukkitNoticeResolver::class)
componentService.registerComponent(InvalidInputHandlerImpl::class)
componentService.registerComponent(InvalidPermissionHandlerImpl::class)
componentService.registerComponent(InvalidSenderHandlerImpl::class)
componentService.registerComponent(InvalidUsageHandlerImpl::class)
componentService.registerComponent(PluginConfig::class) { pluginConfig: PluginConfig ->
// enable additional logs and debug messages
componentService.isDebug = pluginConfig.debug
}
componentService.registerComponent(PlayerDeathController::class)
componentService.registerComponent(SharpenItemsCommand::class)
}
override fun disable() {
// features need to be call when server is stopping
}
override fun getDreamVersion(): DreamVersion {
return DreamVersion.create("sharpenItemsAfterDeath", "1.0.1", "5star")
}
override fun getConfigSerdesPack(): OkaeriSerdesPack {
return OkaeriSerdesPack { registry: SerdesRegistry -> registry.register(BukkitNoticeSerializer()) }
}
companion object {
lateinit var orderedPlugin: OrderedPlugin
}
} | 3 | Kotlin | 0 | 0 | 3f18e9b6e8b162e72a9fcd0c5f0cb605f033dd51 | 3,233 | dreamz-sharpenItemsAfterDeath | MIT License |
src/main/kotlin/com/autonomousapps/internal/utils/xml.kt | jrodbx | 288,874,368 | true | {"Kotlin": 548209, "Groovy": 121909, "Java": 72101, "ANTLR": 68053, "Shell": 579} | package com.autonomousapps.internal.utils
import org.w3c.dom.Document
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
internal fun buildDocument(file: File): Document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(file).also {
it.documentElement.normalize()
}
| 0 | null | 0 | 1 | 3e36ef979bc3b543c260e209f7a21c87bfcca4e3 | 313 | dependency-analysis-android-gradle-plugin | Apache License 2.0 |
frontend/compose/src/commonMain/kotlin/screen/composables/tabconversational/OdTurningGeometryDataView.kt | 85vmh | 543,628,296 | false | null | //package screen.composables.tabconversational
//
//import androidx.compose.foundation.layout.Arrangement
//import androidx.compose.foundation.layout.Column
//import androidx.compose.foundation.layout.padding
//import androidx.compose.runtime.Composable
//import androidx.compose.runtime.remember
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.unit.dp
//import screen.uimodel.InputType
//import screen.viewmodel.OdTurningViewModel
//import usecase.model.TeachInAxis
//
//@Composable
//fun OdTurningGeometryData() {
// val odTurningViewModel: OdTurningViewModel = OdTurningViewModel()
// val data = remember { odTurningViewModel.getOdTurningDataState() }
//
// Column(
// modifier = Modifier.padding(horizontal = 8.dp),
// verticalArrangement = Arrangement.spacedBy(8.dp)
// ) {
// InputSetting(
// inputType = InputType.X_START,
// value = data.xInitial.value.toString(),
// teachInAxis = TeachInAxis.X,
// onTeachInClicked = {}
// ) {
// data.xInitial.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.X_END,
// value = data.xFinal.value.toString(),
// teachInAxis = TeachInAxis.X,
// onTeachInClicked = {}
// ) {
// data.xFinal.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.Z_START,
// value = data.zStart.value.toString(),
// teachInAxis = TeachInAxis.Z,
// onTeachInClicked = {}
// ) {
// data.zStart.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.Z_END,
// value = data.zEnd.value.toString(),
// teachInAxis = TeachInAxis.Z,
// onTeachInClicked = {}
// ) {
// data.zEnd.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.FILLET_RADIUS,
// value = data.fillet.value.toString(),
// onTeachInClicked = {}
// ) {
// data.fillet.value = it.toDouble()
// }
// }
//} | 0 | null | 1 | 3 | 5cf42426895ba8691c9b53ba1b97c274bbdabc07 | 2,164 | mindovercnclathe | Apache License 2.0 |
frontend/compose/src/commonMain/kotlin/screen/composables/tabconversational/OdTurningGeometryDataView.kt | 85vmh | 543,628,296 | false | null | //package screen.composables.tabconversational
//
//import androidx.compose.foundation.layout.Arrangement
//import androidx.compose.foundation.layout.Column
//import androidx.compose.foundation.layout.padding
//import androidx.compose.runtime.Composable
//import androidx.compose.runtime.remember
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.unit.dp
//import screen.uimodel.InputType
//import screen.viewmodel.OdTurningViewModel
//import usecase.model.TeachInAxis
//
//@Composable
//fun OdTurningGeometryData() {
// val odTurningViewModel: OdTurningViewModel = OdTurningViewModel()
// val data = remember { odTurningViewModel.getOdTurningDataState() }
//
// Column(
// modifier = Modifier.padding(horizontal = 8.dp),
// verticalArrangement = Arrangement.spacedBy(8.dp)
// ) {
// InputSetting(
// inputType = InputType.X_START,
// value = data.xInitial.value.toString(),
// teachInAxis = TeachInAxis.X,
// onTeachInClicked = {}
// ) {
// data.xInitial.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.X_END,
// value = data.xFinal.value.toString(),
// teachInAxis = TeachInAxis.X,
// onTeachInClicked = {}
// ) {
// data.xFinal.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.Z_START,
// value = data.zStart.value.toString(),
// teachInAxis = TeachInAxis.Z,
// onTeachInClicked = {}
// ) {
// data.zStart.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.Z_END,
// value = data.zEnd.value.toString(),
// teachInAxis = TeachInAxis.Z,
// onTeachInClicked = {}
// ) {
// data.zEnd.value = it.toDouble()
// }
// InputSetting(
// inputType = InputType.FILLET_RADIUS,
// value = data.fillet.value.toString(),
// onTeachInClicked = {}
// ) {
// data.fillet.value = it.toDouble()
// }
// }
//} | 0 | null | 1 | 3 | 5cf42426895ba8691c9b53ba1b97c274bbdabc07 | 2,164 | mindovercnclathe | Apache License 2.0 |
app/src/main/java/com/example/tasktracker2/model/ActivityModel.kt | kikichechka | 832,651,277 | false | {"Kotlin": 41988} | package com.example.tasktracker2.model
enum class ActivityModel {
ACTIVE,
COMPLETED
}
fun Activity.map(): ActivityModel {
return when (this) {
Activity.ACTIVE -> ActivityModel.ACTIVE
Activity.COMPLETED -> ActivityModel.COMPLETED
}
}
fun ActivityModel.mapToDomain(): Activity {
return when (this) {
ActivityModel.ACTIVE -> Activity.ACTIVE
ActivityModel.COMPLETED -> Activity.COMPLETED
}
}
| 0 | Kotlin | 0 | 0 | bb20926d1b15d5fc8dbbc744429fd8d6b12f7d7b | 448 | Task-tracker-2.0 | Apache License 2.0 |
app/src/main/java/com/example/mytrainingpal/model/repositories/MusclePainEntryMapRepository.kt | MichaelBuessemeyer | 572,939,495 | false | {"Kotlin": 256987} | package com.example.mytrainingpal.model.repositories
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mytrainingpal.model.MusclePainEntryMap
import com.example.mytrainingpal.model.daos.MusclePainEntryMapDao
import com.example.mytrainingpal.model.intermediate_entities.MusclePainEntryWithMuscles
import kotlinx.coroutines.*
// How to implement repository and viewmodel classes taken from
// https://www.answertopia.com/jetpack-compose/a-jetpack-compose-room-database-and-repository-tutorial/
class MusclePainEntryMapRepository(private val musclePainEntryMapDao: MusclePainEntryMapDao) {
val allMusclePainEntryMaps: LiveData<List<MusclePainEntryMap>> =
musclePainEntryMapDao.getAllSoreMuscleEntryMaps()
val allMusclePainEntriesWithMuscles: LiveData<List<MusclePainEntryWithMuscles>> =
musclePainEntryMapDao.getAllMusclePainEntriesWithMusclesAsLiveData()
val searchResults = MutableLiveData<List<MusclePainEntryMap>>()
val searchResult = MutableLiveData<MusclePainEntryWithMuscles>()
private val coroutineScope = CoroutineScope(Dispatchers.Main)
fun insertMusclePainEntryMap(newMusclePainEntryMap: MusclePainEntryMap) {
coroutineScope.launch(Dispatchers.IO) {
musclePainEntryMapDao.insert(newMusclePainEntryMap)
}
}
fun deleteMusclePainEntryMap(musclePainEntryMap: MusclePainEntryMap) {
coroutineScope.launch(Dispatchers.IO) {
musclePainEntryMapDao.deleteMusclePainEntryMap(musclePainEntryMap)
}
}
fun deleteAllSoreMusclesForMusclePainEntry(musclePainEntryId: Long) {
coroutineScope.launch(Dispatchers.IO) {
musclePainEntryMapDao.deleteAllSoreMusclesForMusclePainEntry(musclePainEntryId)
}
}
fun deleteAllSoreMusclesForMusclePainEntryOnCurrentThread(musclePainEntryId: Long) {
musclePainEntryMapDao.deleteAllSoreMusclesForMusclePainEntry(musclePainEntryId)
}
fun findMusclePainEntryMapById(id: Long) {
coroutineScope.launch(Dispatchers.Main) {
searchResults.value = listOf(findMusclePainEntryMapOnlyByIdAsync(id).await())
}
}
private fun findMusclePainEntryMapOnlyByIdAsync(id: Long): Deferred<MusclePainEntryMap> =
coroutineScope.async(Dispatchers.IO) {
return@async musclePainEntryMapDao.getMusclePainEntryMapByMusclePainEntryIdMap(id)
}
fun getMusclePainEntryByIdWithMuscles(id: Long) {
coroutineScope.launch(Dispatchers.Main) {
searchResult.value = findMusclePainEntryMapWithMusclesByIdAsync(id).await()
}
}
private fun findMusclePainEntryMapWithMusclesByIdAsync(id: Long): Deferred<MusclePainEntryWithMuscles> =
coroutineScope.async(Dispatchers.IO) {
return@async musclePainEntryMapDao.getMusclePainEntryByIdWithMuscles(id)
}
fun insertForMusclePainEntryIdAndMuscleName(
musclePainEntryId: Long,
muscleName: String,
painIntensity: Long
) {
coroutineScope.launch(Dispatchers.IO) {
musclePainEntryMapDao.insertForMusclePainEntryIdAndMuscleName(
musclePainEntryId,
muscleName,
painIntensity
)
}
}
} | 14 | Kotlin | 0 | 2 | 5ef8c98c684bf2bb863dc6781a457c16ab8bb6e1 | 3,279 | MyTrainingsPal | Apache License 2.0 |
app/src/main/java/com/samyak2403/nativerecyclerview/MainActivity.kt | samyak2403 | 840,801,804 | false | {"Kotlin": 18017, "Java": 17358} | package com.samyak2403.nativerecyclerview
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.com.samyak2403.nativerecyclerview.R
import com.com.samyak2403.nativerecyclerview.databinding.ActivityMainBinding
import com.google.rvadapter.AdmobNativeAdAdapter
import com.samyak2403.bannerads.Control
import com.samyak2403.nativerecyclerview.adapter.MyAdapter
import com.samyak2403.nativerecyclerview.model.UserModel
class MainActivity : AppCompatActivity() {
private val myAdapter by lazy { MyAdapter() }
private lateinit var binding: ActivityMainBinding
private var dataList = arrayOf(
"Samyak Kamble",
"Tanushree ",
"Samruddhi",
"Ramisvari",
"Sam game",
"Pratiksh Patil",
"Samruddhi Powar"
)
private var data = mutableListOf<UserModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val control = Control(this)
val adUnitId = getString(R.string.admob_banner_id) // Fetch the AdMob banner ID from resources
control.loadBannerAd(R.id.bannerAdContainer, adUnitId)
binding.apply {
recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
val admobNativeAdAdapter: AdmobNativeAdAdapter = AdmobNativeAdAdapter.Builder
.with(
"ca-app-pub-3940256099942544/2247696110", //Create a native ad id from admob console
myAdapter, //The adapter you would normally set to your recyClerView
"small" //Set it with "small","medium" or "custom"
)
.adItemIterval(2) //native ad repeating interval in the recyclerview
.build()
recyclerView.adapter = admobNativeAdAdapter
}
for (i in 0 until dataList.size) {
data.add(UserModel(dataList[i]))
}
myAdapter.differ.submitList(data)
}
} | 0 | Kotlin | 0 | 0 | 4cb875b0f470a4958cf463e1e59ec48c361653b4 | 2,138 | NativeAds-Recyclerview | MIT License |
fluxo-kmp-conf/src/main/kotlin/fluxo/conf/dsl/container/target/JsTarget.kt | fluxo-kt | 705,309,218 | false | {"Kotlin": 797072, "Shell": 1410} | package fluxo.conf.dsl.container.target
import DEFAULT_COMMON_JS_CONFIGURATION
import fluxo.conf.dsl.container.KotlinTargetContainer
import org.jetbrains.kotlin.gradle.plugin.KotlinJsCompilerType
import org.jetbrains.kotlin.gradle.targets.js.dsl.KotlinJsTargetDsl
public interface JsTarget : KotlinTargetContainer<KotlinJsTargetDsl> {
/**
*
* @see org.jetbrains.kotlin.gradle.plugin.KotlinJsCompilerTypeHolder.defaultJsCompilerType
*/
public var compilerType: KotlinJsCompilerType?
public interface Configure {
public fun js(
compiler: KotlinJsCompilerType? = null,
targetName: String = "js",
action: JsTarget.() -> Unit = DEFAULT_COMMON_JS_CONFIGURATION,
)
}
}
| 0 | Kotlin | 0 | 5 | 3379d2d8db4165721a962239270308d4a0c6f774 | 751 | fluxo-kmp-conf | Apache License 2.0 |
app/src/main/java/com/chelseatroy/canary/api/LoginService.kt | YanjieZhou | 336,905,478 | false | null | package com.chelseatroy.canary.api
import retrofit2.http.GET
interface LoginService {
@GET("/v2/5ed1d35132000070005ca001")
suspend fun authenticate(): CanarySession
} | 2 | Kotlin | 0 | 0 | bf901ef4678d2df24dddb298e0276e86ad524234 | 176 | Mood-Tracker | MIT License |
libBase/src/main/java/com/effective/android/base/util/StorageUtils.kt | YummyLau | 118,240,800 | false | null | package com.effective.android.base.util
import android.content.Context
import android.os.Environment
import android.os.Environment.*
import android.text.TextUtils
import java.io.File
/**
* 目录管理,一般每个app都需要一些目录用于存放特定内容,比如缓存,data,下载内容,图片等
* 需要新增哪些目录直接在这里添加就可以了。
* 应用管理中存在两个按钮
* CLEAR DATA 会清除 data/data 数据
* CLEAR CACHE 会清除 data/data/projectName/cache 和 mnt/sdcard/Android/projectName/cache
* Email <EMAIL>
* Created by yummylau on 2019/06/16.
*/
object StorageUtils {
enum class StorageType(var dirName: String = "temp") {
// 放在私有内部,比如uuid文件等等
IMPORTANT_FILE("important"),
// 直接放在外部方便导入
CRASH("crash"),
// 放在私有内部
CHANNEL("channel"),
}
@JvmStatic
private fun storage(context: Context, type: StorageType): String {
var root = when (type) {
StorageType.CRASH -> {
getExternalFiles(context)
}
StorageType.CHANNEL -> {
getCache(context)
}
else -> {
getFiles(context)
}
}
val dir = File(root + "/" + type.dirName)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.absolutePath + "/"
}
@JvmStatic
fun getCrashDir(context: Context) = storage(context, StorageType.CRASH)
@JvmStatic
fun getChannelDir(context: Context) = storage(context, StorageType.CHANNEL)
@JvmStatic
fun getImportantDir(context: Context) = storage(context, StorageType.IMPORTANT_FILE)
@JvmStatic
private fun getCache(context: Context): String {
return if (MEDIA_MOUNTED == getExternalStorageState() || !isExternalStorageRemovable()) {
getExternalCache(context)!!
} else {
getInternalCache(context)
}
}
@JvmStatic
private fun getFiles(context: Context): String {
return if (MEDIA_MOUNTED == getExternalStorageState() || !isExternalStorageRemovable()) {
getExternalFiles(context)!!
} else {
getInternalFiles(context)
}
}
/**
* 获取 app 内部私有cache
*/
@JvmStatic
fun getInternalCache(context: Context): String = context.cacheDir.absolutePath
/**
* 获取 app 外部私有cache
*/
@JvmStatic
fun getExternalCache(context: Context): String? = context.externalCacheDir?.absolutePath
/**
* 获取 app 内部私有文件
*/
@JvmStatic
fun getInternalFiles(context: Context): String = context.filesDir.absolutePath
/**
* 获取 app 外部私有文件
*/
@JvmStatic
fun getExternalFiles(context: Context): String? = context.getExternalFilesDir(null)?.absolutePath
/**
* 外部存储
* /storage/sdcard0/Alarms
*/
@JvmStatic
fun getExternalAlarms(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_ALARMS).absolutePath
/**
* 外部存储
* /storage/sdcard0/DCIM
*/
@JvmStatic
fun getExternalDcim(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM).absolutePath
/**
* 外部存储
* /storage/sdcard0/Download
*/
@JvmStatic
fun getExternalDownload(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).absolutePath
/**
* 外部存储
* /storage/sdcard0/Movies
*/
@JvmStatic
fun getExternalMovies(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES).absolutePath
/**
* 外部存储
* /storage/sdcard0/Music
*/
@JvmStatic
fun getExternalMusic(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC).absolutePath
/**
* 外部存储
* /storage/sdcard0/Notifications
*/
@JvmStatic
fun getExternalNotifications(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_NOTIFICATIONS).absolutePath
/**
* 外部存储
* /storage/sdcard0/Pictures
*/
@JvmStatic
fun getExternalPictures(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES).absolutePath
/**
* 外部存储
* /storage/sdcard0/Podcasts
*/
@JvmStatic
fun getExternalPodcasts(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_PODCASTS).absolutePath
/**
* 外部存储
* /storage/sdcard0/Ringtones
*/
@JvmStatic
fun getExternalRingtones(): String = Environment.getExternalStoragePublicDirectory(DIRECTORY_RINGTONES).absolutePath
} | 1 | null | 32 | 187 | f9bad2216051e5b848b2d862cab7958f1bcdc5e8 | 4,417 | AndroidModularArchiteture | MIT License |
app/src/main/java/com/task/ui/component/splash/SplashActivity.kt | phamthetruyen | 521,086,801 | false | null | package com.task.ui.component.splash
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.activity.viewModels
import com.task.databinding.SplashLayoutBinding
import com.task.ui.base.BaseActivity
import com.task.ui.component.login.LoginActivity
import com.task.SPLASH_DELAY
import com.task.databinding.SplashActivityBinding
import dagger.hilt.android.AndroidEntryPoint
/**
* Created by TruyenDev
*/
@AndroidEntryPoint
class SplashActivity : BaseActivity(){
private lateinit var binding: SplashActivityBinding
override fun initViewBinding() {
binding = SplashActivityBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
navigateToMainScreen()
}
override fun observeViewModel() {
}
private fun navigateToMainScreen() {
Handler().postDelayed({
val nextScreenIntent = Intent(this, LoginActivity::class.java)
startActivity(nextScreenIntent)
finish()
}, SPLASH_DELAY.toLong())
}
}
| 0 | Kotlin | 0 | 0 | 3cb37aa25e1134f50085165c36ad6d6be8444f3f | 1,169 | MobiBeat | Apache License 2.0 |
app/src/main/java/com/skydoves/githubfollows/view/ui/search/SearchActivity.kt | ONO-Group | 121,474,662 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 65, "JSON": 3, "XML": 21, "Java": 3, "Gradle Kotlin DSL": 1} | package com.skydoves.githubfollows.view.ui.search
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.KeyEvent
import android.view.ViewTreeObserver
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.skydoves.githubfollows.R
import com.skydoves.githubfollows.extension.checkIsMaterialVersion
import com.skydoves.githubfollows.extension.circularRevealed
import com.skydoves.githubfollows.extension.circularUnRevealed
import com.skydoves.githubfollows.extension.inVisible
import com.skydoves.githubfollows.factory.AppViewModelFactory
import com.skydoves.githubfollows.models.GithubUser
import com.skydoves.githubfollows.models.History
import com.skydoves.githubfollows.models.Resource
import com.skydoves.githubfollows.models.Status
import com.skydoves.githubfollows.view.adapter.HistoryAdapter
import com.skydoves.githubfollows.view.viewholder.HistoryViewHolder
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.toolbar_search.*
import org.jetbrains.anko.toast
import javax.inject.Inject
/**
* Developed by skydoves on 2018-01-22.
* Copyright (c) 2018 skydoves rights reserved.
*/
class SearchActivity : AppCompatActivity(), TextView.OnEditorActionListener, HistoryViewHolder.Delegate {
@Inject lateinit var viewModelFactory: AppViewModelFactory
private val viewModel by lazy { ViewModelProviders.of(this, viewModelFactory).get(SearchActivityViewModel::class.java) }
private val adapter by lazy { HistoryAdapter(this) }
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
startCircularRevealed(savedInstanceState)
observeViewModel()
initializeAdapter()
toolbar_search_home.setOnClickListener { onBackPressed() }
toolbar_search_input.setOnEditorActionListener(this)
}
private fun startCircularRevealed(savedInstanceState: Bundle?) {
if (savedInstanceState == null && checkIsMaterialVersion()) {
search_layout.inVisible()
val viewTreeObserver = search_layout.viewTreeObserver
if (viewTreeObserver.isAlive) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
circularRevealed(search_layout ,search_layout.width, 0)
search_layout.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
}
}
private fun observeViewModel() {
viewModel.selectHistories().observe(this, Observer { it?.let { adapter.updateItemList(it) } })
viewModel.githubUserLiveData.observe(this, Observer { it?.let { onChangeUser(it) } })
}
private fun initializeAdapter() {
search_recyclerView.layoutManager = LinearLayoutManager(this)
search_recyclerView.adapter = adapter
viewModel.selectHistories()
}
override fun onEditorAction(p0: TextView?, actionId: Int, event: KeyEvent?): Boolean {
val searchKeyword = toolbar_search_input.text
if(actionId == EditorInfo.IME_ACTION_SEARCH) {
searchKeyword?.let {
viewModel.login.postValue(it.toString())
return true
}
}
return false
}
override fun onItemClicked(history: History) {
onSetResult(history.search)
}
override fun onDeleteHistory(history: History) {
viewModel.deleteHistory(history)
}
private fun onChangeUser(resource: Resource<GithubUser>) {
when(resource.status) {
Status.SUCCESS -> onSetResult(resource.data?.login!!)
Status.ERROR -> toast(resource.message.toString())
Status.LOADING -> {}
}
}
private fun onSetResult(user: String) {
viewModel.insertHistory(user)
setResult(intent_requestCode, Intent().putExtra(viewModel.getPreferenceUserKeyName(), user))
onBackPressed()
}
override fun onBackPressed() {
when(checkIsMaterialVersion()) {
true -> circularUnRevealed(search_layout , search_layout.width, 0)
false -> super.onBackPressed()
}
}
companion object {
const val intent_requestCode = 1001
}
}
| 1 | null | 1 | 1 | d4a3342fc08f75ceb3145e2de7744345e35fa3d5 | 4,670 | GithubFollows | MIT License |
libraries/tools/kotlin-gradle-plugin-idea-proto/src/generated/kotlin/org/jetbrains/kotlin/gradle/idea/proto/generated/kpm/IdeaKpmUnresolvedBinaryDependencyProtoKt.kt | JetBrains | 3,432,266 | false | null | //Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto_kpm.proto
package org.jetbrains.kotlin.gradle.idea.proto.generated.kpm;
@kotlin.jvm.JvmName("-initializeideaKpmUnresolvedBinaryDependencyProto")
inline fun ideaKpmUnresolvedBinaryDependencyProto(block: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProtoKt.Dsl.() -> kotlin.Unit): org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto =
org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProtoKt.Dsl._create(org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto.newBuilder()).apply { block() }._build()
object IdeaKpmUnresolvedBinaryDependencyProtoKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
private val _builder: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto = _builder.build()
/**
* <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto extras = 1;</code>
*/
var extras: org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto
@JvmName("getExtras")
get() = _builder.getExtras()
@JvmName("setExtras")
set(value) {
_builder.setExtras(value)
}
/**
* <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto extras = 1;</code>
*/
fun clearExtras() {
_builder.clearExtras()
}
/**
* <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto extras = 1;</code>
* @return Whether the extras field is set.
*/
fun hasExtras(): kotlin.Boolean {
return _builder.hasExtras()
}
val IdeaKpmUnresolvedBinaryDependencyProtoKt.Dsl.extrasOrNull: org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto?
get() = _builder.extrasOrNull
/**
* <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmBinaryCoordinatesProto coordinates = 2;</code>
*/
var coordinates: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmBinaryCoordinatesProto
@JvmName("getCoordinates")
get() = _builder.getCoordinates()
@JvmName("setCoordinates")
set(value) {
_builder.setCoordinates(value)
}
/**
* <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmBinaryCoordinatesProto coordinates = 2;</code>
*/
fun clearCoordinates() {
_builder.clearCoordinates()
}
/**
* <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmBinaryCoordinatesProto coordinates = 2;</code>
* @return Whether the coordinates field is set.
*/
fun hasCoordinates(): kotlin.Boolean {
return _builder.hasCoordinates()
}
val IdeaKpmUnresolvedBinaryDependencyProtoKt.Dsl.coordinatesOrNull: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmBinaryCoordinatesProto?
get() = _builder.coordinatesOrNull
/**
* <code>optional string cause = 3;</code>
*/
var cause: kotlin.String
@JvmName("getCause")
get() = _builder.getCause()
@JvmName("setCause")
set(value) {
_builder.setCause(value)
}
/**
* <code>optional string cause = 3;</code>
*/
fun clearCause() {
_builder.clearCause()
}
/**
* <code>optional string cause = 3;</code>
* @return Whether the cause field is set.
*/
fun hasCause(): kotlin.Boolean {
return _builder.hasCause()
}
}
}
@kotlin.jvm.JvmSynthetic
inline fun org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto.copy(block: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProtoKt.Dsl.() -> kotlin.Unit): org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProto =
org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProtoKt.Dsl._create(this.toBuilder()).apply { block() }._build()
val org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProtoOrBuilder.extrasOrNull: org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto?
get() = if (hasExtras()) getExtras() else null
val org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmUnresolvedBinaryDependencyProtoOrBuilder.coordinatesOrNull: org.jetbrains.kotlin.gradle.idea.proto.generated.kpm.IdeaKpmBinaryCoordinatesProto?
get() = if (hasCoordinates()) getCoordinates() else null
| 155 | Kotlin | 5608 | 45,423 | 2db8f31966862388df4eba2702b2f92487e1d401 | 5,152 | kotlin | Apache License 2.0 |
src/main/kotlin/org/opensearch/commons/notifications/model/Feature.kt | andrejbiriuck752 | 387,869,492 | true | {"Gradle": 2, "Markdown": 14, "XML": 1, "YAML": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Java": 12, "Python": 1, "INI": 1, "Kotlin": 103} | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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 org.opensearch.commons.notifications.model
import org.opensearch.commons.utils.EnumParser
/**
* Features using notification plugin
*/
enum class Feature(val tag: String) {
NONE("none") {
override fun toString(): String {
return tag
}
},
ALERTING("alerting") {
override fun toString(): String {
return tag
}
},
INDEX_MANAGEMENT("index_management") {
override fun toString(): String {
return tag
}
},
REPORTS("reports") {
override fun toString(): String {
return tag
}
};
companion object {
private val tagMap = values().associateBy { it.tag }
val enumParser = EnumParser { fromTagOrDefault(it) }
/**
* Get Feature from tag or NONE if not found
* @param tag the tag
* @return Feature corresponding to tag. NONE if invalid tag.
*/
fun fromTagOrDefault(tag: String): Feature {
return tagMap[tag] ?: NONE
}
}
}
| 0 | null | 0 | 0 | a968da203e542cc4d44ec84cab4de42dc8d183fd | 1,950 | common-utils | Apache License 2.0 |
ui-exercises/src/main/java/com/gerosprime/gylog/ui/exercises/templatesets/EditTemplateSetsViewModel.kt | gerosprime | 213,372,637 | false | {"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "INI": 9, "Proguard": 10, "Kotlin": 326, "XML": 133, "Java": 11} | package com.gerosprime.gylog.ui.exercises.templatesets
import androidx.lifecycle.MutableLiveData
import com.gerosprime.gylog.base.FetchState
import com.gerosprime.gylog.models.exercises.templates.ExerciseTemplateEntity
import com.gerosprime.gylog.models.exercises.templatesets.LoadTemplateSetsToCacheResult
import com.gerosprime.gylog.models.exercises.templatesets.TemplateSetEntity
import com.gerosprime.gylog.models.exercises.templatesets.add.CreateTemplateSetToCacheResult
import com.gerosprime.gylog.models.exercises.templatesets.commit.CommitTemplateSetsToWorkoutResult
import com.gerosprime.gylog.models.exercises.templatesets.remove.RemoveTemplateFromCacheResult
interface EditTemplateSetsViewModel {
val loadTemplateSetsMutableLiveData : MutableLiveData<LoadTemplateSetsToCacheResult>
val fetchStateMutableLiveData : MutableLiveData<FetchState>
val removeTemplateResultMutableLiveData : MutableLiveData<RemoveTemplateFromCacheResult>
val addTemplateResultMutableLiveData : MutableLiveData<CreateTemplateSetToCacheResult>
val commitTemplateResultMutableLiveData : MutableLiveData<CommitTemplateSetsToWorkoutResult>
fun loadTemplateSets(workoutIndex : Int, workoutExercisesIndex : Int)
fun addTemplate(workoutIndex : Int, workoutExercisesIndex : Int)
fun commitTemplates(workoutIndex : Int, workoutExercisesIndex : Int)
fun removeTemplate(templatesetIndex: Int,
workoutIndex : Int, workoutExercisesIndex : Int)
} | 0 | Kotlin | 0 | 1 | a775377e6a8bdb81e405eb1b04ca5fd14f5dd9c6 | 1,484 | gylog-android-app | Apache License 2.0 |
android/src/com/android/tools/idea/npw/benchmark/ConfigureBenchmarkModuleStep.kt | zakharchanka | 314,699,321 | true | {"Text": 342, "EditorConfig": 1, "Markdown": 54, "Ignore List": 133, "Starlark": 86, "XML": 11605, "Java": 8168, "Kotlin": 4229, "Gradle": 802, "Proguard": 121, "INI": 42, "JSON": 77, "Graphviz (DOT)": 1, "Ant Build System": 1, "Protocol Buffer": 1, "HTML": 60, "Shell": 19, "Batchfile": 12, "Java Properties": 130, "Gradle Kotlin DSL": 51, "C": 26, "Checksums": 248, "CMake": 14, "C++": 7, "Smali": 5, "SVG": 1109, "AIDL": 9, "JFlex": 8, "Prolog": 6, "QMake": 2, "RenderScript": 1, "NSIS": 4, "Diff": 1, "Python": 2, "GraphQL": 5, "Makefile": 8, "YAML": 1, "HAProxy": 1, "Org": 2, "Fluent": 1, "JavaScript": 3} | /*
* Copyright (C) 2019 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.tools.idea.npw.benchmark
import com.android.sdklib.AndroidVersion.VersionCodes
import com.android.tools.adtui.LabelWithEditButton
import com.android.tools.adtui.util.FormScalingUtil
import com.android.tools.adtui.validation.Validator
import com.android.tools.adtui.validation.Validator.Result
import com.android.tools.adtui.validation.Validator.Severity
import com.android.tools.adtui.validation.ValidatorPanel
import com.android.tools.idea.gradle.npw.project.GradleAndroidModuleTemplate.createDefaultTemplateAt
import com.android.tools.idea.npw.FormFactor.MOBILE
import com.android.tools.idea.npw.model.NewProjectModel.Companion.getInitialDomain
import com.android.tools.idea.npw.module.AndroidApiLevelComboBox
import com.android.tools.idea.npw.platform.AndroidVersionsInfo
import com.android.tools.idea.npw.platform.AndroidVersionsInfo.VersionItem
import com.android.tools.idea.npw.platform.Language
import com.android.tools.idea.npw.project.DomainToPackageExpression
import com.android.tools.idea.npw.template.components.LanguageComboProvider
import com.android.tools.idea.npw.validator.ModuleValidator
import com.android.tools.idea.observable.BindingsManager
import com.android.tools.idea.observable.ListenerManager
import com.android.tools.idea.observable.core.BoolValueProperty
import com.android.tools.idea.observable.core.StringValueProperty
import com.android.tools.idea.observable.ui.SelectedItemProperty
import com.android.tools.idea.observable.ui.TextProperty
import com.android.tools.idea.ui.wizard.StudioWizardStepPanel
import com.android.tools.idea.ui.wizard.WizardUtils
import com.android.tools.idea.wizard.model.SkippableWizardStep
import com.intellij.ui.ContextHelpLabel
import com.intellij.ui.components.JBLabel
import com.intellij.uiDesigner.core.GridConstraints
import com.intellij.uiDesigner.core.GridConstraints.ANCHOR_NORTH
import com.intellij.uiDesigner.core.GridConstraints.ANCHOR_NORTHWEST
import com.intellij.uiDesigner.core.GridLayoutManager
import org.jetbrains.android.refactoring.isAndroidx
import org.jetbrains.android.util.AndroidBundle.message
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Font
import java.util.Optional
import java.util.function.Consumer
import javax.swing.JPanel
import javax.swing.JTextField
class ConfigureBenchmarkModuleStep(
model: NewBenchmarkModuleModel, title: String, private val minSdkLevel: Int
) : SkippableWizardStep<NewBenchmarkModuleModel>(model, title) {
private val androidVersionsInfo = AndroidVersionsInfo()
private val bindings = BindingsManager()
private val listeners = ListenerManager()
private val screenTitle = JBLabel(message("android.wizard.module.config.title")).apply {
font = Font(null, Font.BOLD, 18)
}
private val moduleName = JTextField()
private val moduleNameLabel = JBLabel("Module name:").apply {
labelFor = moduleName
}
private val moduleNameContextHelp = ContextHelpLabel.create(message("android.wizard.module.help.name"))
private val moduleNameLabelWithHelp = JPanel(FlowLayout(FlowLayout.LEFT)).apply {
add(moduleNameLabel)
add(moduleNameContextHelp)
}
private val packageName = LabelWithEditButton()
private val packageNameLabel = JBLabel("Package name:").apply {
labelFor = packageName
}
private val languageComboBox = LanguageComboProvider().createComponent()
private val languageComboBoxLabel = JBLabel("Language:").apply {
labelFor = languageComboBox
}
private val apiLevelComboBox = AndroidApiLevelComboBox()
private val apiLevelComboBoxLabel = JBLabel("Minimum SDK:").apply {
labelFor = apiLevelComboBox
}
// TODO(qumeric): replace with TabularLayout
private val panel = JPanel(GridLayoutManager(6, 3)).apply {
val anySize = Dimension(-1, -1)
val lcSize = Dimension(150, -1)
add(screenTitle, GridConstraints(0, 0, 1, 3, ANCHOR_NORTH, 0, 0, 0, anySize, anySize, anySize))
add(moduleNameLabelWithHelp, GridConstraints(1, 0, 1, 1, ANCHOR_NORTHWEST, 0, 0, 0, lcSize, lcSize, anySize))
add(packageNameLabel, GridConstraints(2, 0, 1, 1, ANCHOR_NORTHWEST, 0, 0, 0, lcSize, lcSize, anySize))
add(languageComboBoxLabel, GridConstraints(3, 0, 1, 1, ANCHOR_NORTHWEST, 0, 0, 0, lcSize, lcSize, anySize))
add(apiLevelComboBoxLabel, GridConstraints(4, 0, 1, 1, ANCHOR_NORTHWEST, 0, 0, 0, lcSize, lcSize, anySize))
add(moduleName, GridConstraints(1, 1, 1, 2, ANCHOR_NORTH, 1, 6, 0, anySize, anySize, anySize))
add(packageName, GridConstraints(2, 1, 1, 2, ANCHOR_NORTH, 1, 6, 0, anySize, anySize, anySize))
add(languageComboBox, GridConstraints(3, 1, 1, 2, ANCHOR_NORTH, 1, 6, 0, anySize, anySize, anySize))
add(apiLevelComboBox, GridConstraints(4, 1, 1, 2, ANCHOR_NORTH, 1, 6, 0, anySize, anySize, anySize))
}
private val validatorPanel = ValidatorPanel(this, panel)
private val rootPanel = StudioWizardStepPanel(validatorPanel)
init {
val moduleNameText = TextProperty(moduleName)
val packageNameText = TextProperty(packageName)
val language = SelectedItemProperty<Language>(languageComboBox)
val isPackageNameSynced = BoolValueProperty(true)
val moduleValidator = ModuleValidator(model.project)
val packageNameValidator = object: Validator<String> {
override fun validate(value: String) = Result.fromNullableMessage(WizardUtils.validatePackageName(value))
}
val minSdkValidator = object: Validator<Optional<VersionItem>> {
override fun validate(value: Optional<VersionItem>): Result = when {
!value.isPresent -> Result(Severity.ERROR, message("select.target.dialog.text"))
value.get().targetApiLevel >= VersionCodes.Q && !model.project.isAndroidx() ->
Result(Severity.ERROR, message("android.wizard.validate.module.needs.androidx"))
else -> Result.OK
}
}
moduleName.text = WizardUtils.getUniqueName(model.moduleName.get(), moduleValidator)
val computedPackageName = DomainToPackageExpression(StringValueProperty(getInitialDomain()), model.moduleName)
validatorPanel.apply {
registerValidator(moduleNameText, moduleValidator)
registerValidator(model.packageName, packageNameValidator)
registerValidator(model.androidSdkInfo, minSdkValidator)
}
bindings.apply {
bind(model.moduleName, moduleNameText, validatorPanel.hasErrors().not())
bind(packageNameText, computedPackageName, isPackageNameSynced)
bind(model.packageName, packageNameText)
bindTwoWay(language, model.language)
bind(model.androidSdkInfo, SelectedItemProperty(apiLevelComboBox))
}
listeners.listen(packageNameText) { value: String -> isPackageNameSynced.set(value == computedPackageName.get()) }
FormScalingUtil.scaleComponentTree(this.javaClass, rootPanel)
}
override fun onEntering() {
androidVersionsInfo.loadLocalVersions()
apiLevelComboBox.init(MOBILE, androidVersionsInfo.getKnownTargetVersions(MOBILE, minSdkLevel))
androidVersionsInfo.loadRemoteTargetVersions(
MOBILE, minSdkLevel, Consumer { items -> apiLevelComboBox.init(MOBILE, items) }
)
}
override fun onProceeding() {
// Now that the module name was validated, update the model template
model.template.set(createDefaultTemplateAt(model.project.basePath!!, model.moduleName.get()))
}
override fun canGoForward() = validatorPanel.hasErrors().not()
override fun getComponent() = rootPanel
override fun getPreferredFocusComponent() = packageName
override fun dispose() {
bindings.releaseAll()
listeners.releaseAll()
}
} | 0 | null | 0 | 0 | cd393da1a11d2dfe572f4baa6eef882256e95d6a | 8,163 | android-1 | Apache License 2.0 |
tenextll/src/main/java/com/tenext/auth/listener/LoginExpiredListener.kt | wenext-ops | 250,197,017 | false | {"Text": 3, "Markdown": 2, "Gradle": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "JSON": 1, "Kotlin": 203, "XML": 105, "Java": 4} | package com.tenext.auth.listener
import com.tenext.auth.entity.User
/**
* 登录过期监听器
*/
interface LoginExpiredListener {
fun expired(user: User)
} | 0 | Kotlin | 1 | 0 | 4266bd268686ab0bf6799ac0168967281fdc2051 | 153 | LLForAndroid | MIT License |
AndroidStudioProjects/ch13/app/src/main/java/com/example/chapter13/FirstFragment.kt | kimchist | 368,477,118 | false | null | package com.example.chapter13
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController
import io.realm.Realm
import io.realm.Sort
import io.realm.kotlin.where
import kotlinx.android.synthetic.main.fragment_first.*
/**
* A simple [Fragment] subclass as the default destination in the navigation.
*/
class FirstFragment : Fragment() {
private val realm = Realm.getDefaultInstance() //Realm 객체를 초기화합니다
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// 전체 할 일 정보를 가져와서 날짜순으로 내림차순 정렬
val realmResult = realm.where<Todo>().findAll().sort("date", Sort.DESCENDING)
val adapter = TodoListAdapter(realmResult)
listView.adapter = adapter
// 데이터가 변경되면 어댑터에 적용
realmResult.addChangeListener { _ -> adapter.notifyDataSetChanged() }
listView.setOnItemClickListener { parent, view, position, id ->
// 할 일 수정
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment,
bundleOf("id" to id))
}
fab.setOnClickListener { findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment) }
}
override fun onDestroy() {
super.onDestroy()
realm.close() // Realm 객체를 해제합니다.
}
} | 1 | null | 1 | 1 | 35a227f5fcba5d206aab14abe412a1c7857b1213 | 1,804 | learn_kotlin | MIT License |
app/src/main/java/ru/smartms/rfidreaderwriter/data/local/ScanDataRepository.kt | smartms | 160,518,806 | false | {"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "JSON": 1, "Kotlin": 28, "XML": 15, "Java": 2} | package ru.smartms.rfidreaderwriter.data.local
import javax.inject.Inject
import javax.inject.Singleton
import androidx.lifecycle.LiveData
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import ru.smartms.rfidreaderwriter.db.dao.ScanDataDao
import ru.smartms.rfidreaderwriter.db.entity.ScanData
@Singleton
class ScanDataRepository @Inject constructor(private val scanDataDao: ScanDataDao) {
fun getScanData(): LiveData<List<ScanData>> = scanDataDao.getAll()
fun deleteAll() = GlobalScope.launch { scanDataDao.deleteAll() }
fun insert(scanData: ScanData) = GlobalScope.launch { scanDataDao.insert(scanData) }
fun deleteScanData(barcode: String?) {
scanDataDao.delete(barcode)
}
fun getScanDataBarcode(): LiveData<ScanData>? = scanDataDao.getBarcode()
fun deleteScanDataBarcode() = scanDataDao.deleteBarcode()
} | 0 | Kotlin | 1 | 1 | de6a202d6aa77faf0cce86bb1c65e67df3411637 | 874 | rfid-reader-writer | Apache License 2.0 |
jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/pom/PomRewriteRule.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.core.pom
import com.android.tools.build.jetifier.core.utils.Log
import com.google.gson.annotations.SerializedName
import java.nio.file.Path
/**
* Rule that defines how to rewrite a dependency element in a POM file.
*
* Any dependency that is matched against [from] should be rewritten to the dependency defined
* in [to].
*/
data class PomRewriteRule(val from: PomDependency, val to: PomDependency) {
init {
validate(from, checkVersion = false)
validate(to, checkVersion = true)
}
companion object {
val TAG: String = "PomRule"
private fun validate(dep: PomDependency, checkVersion: Boolean) {
if (dep.groupId == null || dep.groupId.isEmpty()) {
throw IllegalArgumentException("GroupId is missing in the POM rule!")
}
if (dep.artifactId == null || dep.artifactId.isEmpty()) {
throw IllegalArgumentException("ArtifactId is missing in the POM rule!")
}
if (checkVersion && (dep.version == null || dep.version!!.isEmpty())) {
throw IllegalArgumentException(
"Version is missing in the POM rule for ${dep.groupId}:${dep.artifactId}!"
)
}
}
}
fun getReversed(): PomRewriteRule {
return PomRewriteRule(from = to, to = from)
}
/**
* Validates that the given [input] dependency has a valid version.
*/
fun validateVersion(input: PomDependency, pomPath: Path? = null): Boolean {
if (from.version == null || input.version == null) {
return true
}
if (!matches(input)) {
return true
}
if (!areVersionsMatching(from.version!!, input.version!!)) {
Log.e(
TAG,
"Version mismatch! Expected version '%s' but found version '%s' for " +
"'%s:%s' in '%s' file.",
from.version, input.version, input.groupId,
input.artifactId, pomPath.toString()
)
return false
}
return true
}
/**
* Checks if the given [version] is supported to be rewritten with a rule having [ourVersion].
*
* Version entry can be actually quite complicated, see the full documentation at:
* https://maven.apache.org/pom.html#Dependencies
*/
private fun areVersionsMatching(ourVersion: String, version: String): Boolean {
if (version == "latest" || version == "release") {
return true
}
if (version.endsWith(",)") || version.endsWith(",]")) {
return true
}
if (version.endsWith("$ourVersion]")) {
return true
}
return ourVersion == version
}
fun matches(input: PomDependency): Boolean {
return input.artifactId == from.artifactId && input.groupId == from.groupId
}
/** Returns JSON data model of this class */
fun toJson(): JsonData {
return JsonData(from, to)
}
/**
* JSON data model for [PomRewriteRule].
*/
data class JsonData(
@SerializedName("from")
val from: PomDependency,
@SerializedName("to")
val to: PomDependency
) {
/** Creates instance of [PomRewriteRule] */
fun toRule(): PomRewriteRule {
return PomRewriteRule(from, to)
}
}
} | 0 | null | 0 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 4,080 | androidx | Apache License 2.0 |
app/src/main/java/com/fenghuang/caipiaobao/widget/pop/LiveGiftNumPop.kt | tracyly | 262,531,465 | false | {"Java": 1886821, "Kotlin": 1650417, "HTML": 41991} | package com.fenghuang.caipiaobao.widget.pop
import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.widget.LinearLayout
import android.widget.TextView
import com.fenghuang.baselib.utils.ViewUtils
import com.fenghuang.baselib.widget.popup.BasePopupWindow
import com.fenghuang.caipiaobao.R
/**
*
* @ Author QinTian
* @ Date 2020-02-26
* @ Describe
*
*/
class LiveGiftNumPop(context: Context) : BasePopupWindow(context, R.layout.pop_live_gift_num) {
var tv1314: LinearLayout
var tv520: LinearLayout
var tv88: LinearLayout
var tv58: LinearLayout
var tv10: LinearLayout
var tv1: LinearLayout
init {
width = ViewUtils.dp2px(120)
tv1314 = findView(R.id.tv1314)
tv520 = findView(R.id.tv520)
tv88 = findView(R.id.tv88)
tv58 = findView(R.id.tv58)
tv10 = findView(R.id.tv10)
tv1 = findView(R.id.tv1)
getSelectText()
}
private var getSelectTextListener: ((it: String) -> Unit)? = null
fun getUserDiamondSuccessListener(getTextListener: ((it: String) -> Unit)) {
getSelectTextListener = getTextListener
}
private fun getSelectText() {
tv1314.setOnClickListener {
getSelectTextListener?.invoke("1314")
dismiss()
}
tv520.setOnClickListener {
getSelectTextListener?.invoke("520")
dismiss()
}
tv88.setOnClickListener {
getSelectTextListener?.invoke("88")
dismiss()
}
tv58.setOnClickListener {
getSelectTextListener?.invoke("58")
dismiss()
}
tv10.setOnClickListener {
getSelectTextListener?.invoke("10")
dismiss()
}
tv1.setOnClickListener {
getSelectTextListener?.invoke("1")
dismiss()
}
}
} | 1 | null | 1 | 1 | b4f57b41ba0018299d47be4d7705f0dfb1b8cf04 | 1,986 | cpb2.0 | Apache License 2.0 |
coders/kotlin/CampoMinado/src/visao/TelaPrincipal.kt | flaviogf | 161,988,896 | false | {"Text": 141, "Ignore List": 130, "Markdown": 108, "Microsoft Visual Studio Solution": 92, "C#": 1548, "XML": 847, "JSON": 369, "Python": 439, "EditorConfig": 65, "Batchfile": 22, "Maven POM": 68, "INI": 82, "Java": 749, "Gradle": 96, "Java Properties": 51, "Shell": 72, "Proguard": 18, "Gemfile.lock": 55, "YAML": 416, "Dockerfile": 127, "Option List": 39, "Ruby": 1312, "Emacs Lisp": 7, "Go": 401, "Go Module": 186, "Go Checksums": 20, "SQL": 22, "HTML": 248, "JavaScript": 706, "CSS": 156, "SVG": 79, "Org": 7, "HCL": 4, "Go Workspace": 4, "Makefile": 119, "TOML": 4, "Mako": 1, "Kotlin": 138, "Dart": 93, "OpenStep Property List": 42, "Objective-C": 17, "Swift": 14, "Unity3D Asset": 28, "JSON with Comments": 33, "PHP": 155, "Git Attributes": 10, "Browserslist": 13, "robots.txt": 17, "SCSS": 69, "HTML+ERB": 147, "C": 142, "PLpgSQL": 1, "Vim Script": 3, "Common Lisp": 28, "F#": 16, "JavaScript+ERB": 1, "C++": 4, "CoffeeScript": 20, "Protocol Buffer": 2, "Haskell": 2, "HTTP": 6, "Dotenv": 3, "TSX": 18, "Handlebars": 3, "Starlark": 2, "Nginx": 2, "Java Server Pages": 17, "ASP.NET": 16, "HTML+Razor": 202, "Vue": 5, "Puppet": 1, "TSQL": 17, "PowerShell": 27, "ApacheConf": 1, "Blade": 4, "JAR Manifest": 1, "Clojure": 18, "kvlang": 5, "Procfile": 1} | package visao
import modelo.Tabuleiro
import modelo.TabuleiroEvento
import javax.swing.JFrame
import javax.swing.JOptionPane
import javax.swing.SwingUtilities
fun main(args: Array<String>) {
TelaPrincipal()
}
class TelaPrincipal : JFrame() {
private val tabuleiro = Tabuleiro(qtdLinhas = 16, qtdColunas = 30, qtdMinas = 10)
private val painelTabuleiro = PainelTabuleiro(tabuleiro)
init {
tabuleiro.onEvento {
SwingUtilities.invokeLater {
val msg = when (it) {
TabuleiroEvento.VITORIA -> "Você Ganhou!"
else -> "Você Perdeu... :P"
}
JOptionPane.showMessageDialog(this, msg)
tabuleiro.reiniciar()
painelTabuleiro.repaint()
painelTabuleiro.validate()
}
}
add(painelTabuleiro)
setSize(690, 438)
setLocationRelativeTo(null)
defaultCloseOperation = EXIT_ON_CLOSE
title = "Campo Minado"
isVisible = true
}
} | 30 | C# | 1 | 2 | 9bf0c8cb00134047d648043a87980f24659b046e | 1,050 | courses | MIT License |
app/src/main/java/com/wzq/sample/bean/BaseUrlData.kt | hloong | 276,354,680 | true | {"Java Properties": 3, "Gradle": 5, "Shell": 1, "Markdown": 1, "Batchfile": 1, "XML": 61, "Ignore List": 3, "INI": 1, "Proguard": 2, "Java": 49, "Kotlin": 71, "JSON": 2} | package com.wzq.sample.bean
class BaseUrlData {
var code:Int=0
var message:String=""
var result:String=""
} | 0 | Java | 0 | 1 | 4b15231d21af098a1e8b224a35db0854eca51863 | 120 | MVVMSmart | Apache License 2.0 |
platform/lang-impl/src/com/intellij/ide/util/scopeChooser/AbstractScopeModel.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.util.scopeChooser
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.ui.popup.ListSeparator
interface AbstractScopeModel : Disposable {
fun addScopeModelListener(listener: ScopeModelListener)
fun removeScopeModelListener(listener: ScopeModelListener)
fun setOption(option: ScopeOption, value: Boolean)
fun setFilter(filter: (ScopeDescriptor) -> Boolean)
fun refreshScopes(dataContext: DataContext? = null)
suspend fun getScopes(dataContext: DataContext): ScopesSnapshot
@Deprecated("Slow and blocking, use getScopes() in a suspending context, or addScopeModelListener() and refreshScopes()")
fun getScopesImmediately(dataContext: DataContext): ScopesSnapshot
}
interface ScopesSnapshot {
val scopeDescriptors: List<ScopeDescriptor>
fun getSeparatorFor(scopeDescriptor: ScopeDescriptor): ListSeparator?
}
interface ScopeModelListener {
fun scopesUpdated(scopes: ScopesSnapshot)
}
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,126 | intellij-community | Apache License 2.0 |
Kth_Smallest_Element_in_a_BST_v3.kt | xiekch | 166,329,519 | false | null | import java.util.*
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
// inorder traversal of BST
class Solution {
fun kthSmallest(root: TreeNode?, k: Int): Int {
if (root == null) {
return 0;
}
val st = Stack<TreeNode>()
var node = root
var count = 0
while (true) {
while (node != null) {
st.push(node)
node = node.left
}
node = st.pop()
if (++count == k) {
return node.`val`
}
node = node.right
}
}
}
fun main(args: Array<String>) {
val solution = Solution()
val testset = arrayOf(
arrayOf("3", "1", "4", "null", "2"),
arrayOf("5", "3", "6", "2", "4", "null", "null", "1")
)
val ks = intArrayOf(1, 3)
for (i in 0..testset.lastIndex) {
val root = TreeUtils.buildTree(testset[i])
TreeUtils.printTree(root)
println(solution.kthSmallest(root, ks[i]))
}
} | 1 | null | 1 | 1 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,175 | leetcode | MIT License |
common/src/main/java/com/ishow/common/utils/image/select/SelectImageUtils.kt | i-show | 62,766,394 | false | null | /*
* Copyright (C) 2016 The yuhaiyang Android 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.ishow.common.utils.image.select
import android.Manifest
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.IntDef
import androidx.annotation.IntRange
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.ishow.common.R
import com.ishow.common.entries.Image
import com.ishow.common.modules.image.cutter.PhotoCutterActivity
import com.ishow.common.modules.image.select.ImageSelectorActivity
import com.ishow.common.utils.ToastUtils
import com.ishow.common.utils.image.ImageUtils
import com.ishow.common.utils.image.compress.ImageCompress
import com.ishow.common.utils.log.LogUtils
import com.ishow.common.utils.permission.PermissionManager
import com.ishow.common.widget.dialog.BaseDialog
import com.ishow.common.widget.loading.LoadingDialog
import java.io.File
/**
* 基类
*/
class SelectImageUtils(private val activity: Activity, @param:SelectMode private var mSelectMode: Int) :
DialogInterface.OnClickListener, DialogInterface.OnDismissListener {
/**
* Camera拍照输出的地址
*/
private var cameraFileUri: Uri? = null
/**
* 选择方式的Dialog
*/
private var selectDialog: BaseDialog? = null
private var loadingDialog: LoadingDialog? = null
/**
* 选择图片的Listener
*/
private var selectPhotoListener: OnSelectImageListener? = null
/**
* 图片选择后是 压缩还是剪切
*/
private var resultMode: Int = 0
/**
* 剪切模式-X轴比例
*/
private var scaleX: Int = 0
/**
* 剪切模式-Y轴比例
*/
private var scaleY: Int = 0
/**
* 可以选择的最大数量
*/
private var maxSelectCount: Int = 0
/**
* Format
*/
private lateinit var compressFormat: Bitmap.CompressFormat
var fragment: Fragment? = null
/**
* 设置选择模式
*/
fun setSelectMode(@SelectMode selectMode: Int) {
mSelectMode = selectMode
}
@JvmOverloads
fun select(format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG) {
compressFormat = format
if (mSelectMode == SelectMode.SINGLE) {
resultMode = ResultMode.COMPRESS
} else {
resultMode = ResultMode.COMPRESS
maxSelectCount = MAX_SELECT_COUNT
}
showSelectDialog()
}
/**
* 选择图片
*/
@JvmOverloads
fun select(@IntRange(from = 1) maxCount: Int, format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG) {
compressFormat = format
if (mSelectMode == SelectMode.SINGLE) {
throw IllegalStateException("only multiple selection use")
}
maxSelectCount = maxCount
resultMode = ResultMode.COMPRESS
showSelectDialog()
}
/**
* 选择图片模式为剪切模式
*
* @param scaleX 单选图片-X轴的比例
* @param scaleY 单选图片-Y轴的比例
*/
@JvmOverloads
fun select(@IntRange(from = 1) scaleX: Int, @IntRange(from = 1) scaleY: Int, format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG) {
compressFormat = format
if (mSelectMode == SelectMode.MULTIPLE) {
throw IllegalStateException("only single select SelectMode can set scaleX and scaleY")
}
resultMode = ResultMode.CROP
this.scaleX = scaleX
this.scaleY = scaleY
showSelectDialog()
}
@JvmOverloads
fun selectByCamera(file: File? = null) {
mSelectMode = SelectMode.SINGLE
selectPhotoByCamera(file)
}
/**
* 显示选择框
*/
private fun showSelectDialog() {
if (selectDialog == null) {
selectDialog = BaseDialog.Builder(activity, R.style.Theme_Dialog_Bottom)
.setNegativeButton(R.string.cancel)
.fromBottom(true)
.setItems(R.array.select_photos) { dialog, which -> onClick(dialog, which) }
.setOnDismissListener(this)
.create()
}
if (!selectDialog!!.isShowing) {
selectDialog?.show()
}
}
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
SELECT_PHOTO_CAMERA -> selectPhotoByCamera()
SELECT_PHOTO_GALLERY -> selectPhotoByGallery()
}
}
/**
* 通过相机来选择图片
*/
@Suppress("SpellCheckingInspection")
private fun selectPhotoByCamera(file: File? = null) {
if (!requestCameraPermission()) {
return
}
var resultFile = file
val authority = activity.packageName + ".fileprovider"
if (resultFile == null) resultFile = ImageUtils.genImageFile(activity)
cameraFileUri = Uri.fromFile(resultFile)
val uri = FileProvider.getUriForFile(activity, authority, resultFile)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
when (mSelectMode) {
SelectMode.SINGLE -> {
if (fragment == null) {
activity.startActivityForResult(intent, Request.REQUEST_SINGLE_CAMERA)
} else {
fragment?.startActivityForResult(intent, Request.REQUEST_SINGLE_CAMERA)
}
}
SelectMode.MULTIPLE -> {
if (fragment == null) {
activity.startActivityForResult(intent, Request.REQUEST_MULTI_CAMERA)
} else {
fragment?.startActivityForResult(intent, Request.REQUEST_MULTI_CAMERA)
}
}
}
}
/**
* 通过相册来选择图片
*/
private fun selectPhotoByGallery() {
val intent = Intent(activity, ImageSelectorActivity::class.java)
when (mSelectMode) {
SelectMode.SINGLE -> {
intent.putExtra(Image.Key.EXTRA_SELECT_MODE, Image.Key.MODE_SINGLE)
if (fragment == null) {
activity.startActivityForResult(intent, Request.REQUEST_SINGLE_PICK)
} else {
fragment?.startActivityForResult(intent, Request.REQUEST_SINGLE_PICK)
}
}
SelectMode.MULTIPLE -> {
intent.putExtra(Image.Key.EXTRA_SELECT_MODE, Image.Key.MODE_MULTI)
intent.putExtra(Image.Key.EXTRA_SELECT_COUNT, maxSelectCount)
if (fragment == null) {
activity.startActivityForResult(intent, Request.REQUEST_MULTI_PICK)
} else {
fragment?.startActivityForResult(intent, Request.REQUEST_MULTI_PICK)
}
}
}
}
override fun onDismiss(dialog: DialogInterface) {
selectDialog = null
}
/**
* 用来接管activity的result
*/
fun onActivityResult(requestCode: Int, resultCode: Int, intentData: Intent?) {
if (resultCode == Activity.RESULT_CANCELED) {
LoadingDialog.dismiss(loadingDialog)
resolveResultCanceled(requestCode)
return
}
when (requestCode) {
// 不管多选还是单选 相机处理是一样的
Request.REQUEST_SINGLE_CAMERA,
Request.REQUEST_MULTI_CAMERA -> resolveSingleResult(cameraFileUri!!.path)
Request.REQUEST_SINGLE_PICK -> {
if (intentData == null) {
LoadingDialog.dismiss(loadingDialog)
return
}
val path = intentData.getStringExtra(Image.Key.EXTRA_RESULT)
resolveSingleResult(path)
}
Request.REQUEST_MULTI_PICK -> {
if (intentData == null) {
LoadingDialog.dismiss(loadingDialog)
return
}
val pathList = intentData.getStringArrayListExtra(Image.Key.EXTRA_RESULT)
resolveMultiResult(pathList)
}
Request.REQUEST_CROP_IMAGE -> {
if (intentData == null) {
LoadingDialog.dismiss(loadingDialog)
return
}
val picPath = intentData.getStringExtra(PhotoCutterActivity.KEY_RESULT_PATH)
picPath?.let { notifySelectPhoto(File(it)) }
}
else -> LogUtils.i(TAG, "requestCode = $requestCode")
}
}
/**
* onActivityResult 裁掉canceled的事件
*/
private fun resolveResultCanceled(requestCode: Int) {
when (requestCode) {
Request.REQUEST_SINGLE_PICK,
Request.REQUEST_SINGLE_CAMERA,
Request.REQUEST_MULTI_PICK,
Request.REQUEST_MULTI_CAMERA,
Request.REQUEST_CROP_IMAGE -> ToastUtils.show(activity, R.string.cancel_photo)
}
}
/**
* onActivityResult 处理 单选
*/
private fun resolveSingleResult(picPath: String?) {
if (picPath.isNullOrEmpty()) {
Log.i(TAG, "resolveSingleResult: picPath is empty")
return
}
val photos = mutableListOf(picPath)
when (resultMode) {
ResultMode.COMPRESS -> resolveResultPhotosForCompress(photos)
ResultMode.CROP -> gotoCrop(picPath)
}
}
/**
* onActivityResult 处理 单选
*/
private fun resolveMultiResult(pathList: List<String>?) {
if (pathList == null || pathList.isEmpty()) {
Log.i(TAG, "resolveMultiResult: pathList is empty")
return
}
loadingDialog = LoadingDialog.show(activity, loadingDialog)
resolveResultPhotosForCompress(pathList)
}
/**
* 处理返回的图片-通过压缩图片的方式
*/
private fun resolveResultPhotosForCompress(photos: List<String>) {
loadingDialog = LoadingDialog.show(activity, loadingDialog)
ImageCompress.with(activity)
.compress(photos.map { Uri.parse(it) })
.savePath("select")
.compressListener { notifySelectPhoto(it.imageList, it.image) }
.start()
}
/**
* 跳转剪切
*/
private fun gotoCrop(path: String?) {
val intent = Intent(activity, PhotoCutterActivity::class.java)
intent.putExtra(PhotoCutterActivity.KEY_PATH, path)
intent.putExtra(PhotoCutterActivity.KEY_RATIO_X, scaleX)
intent.putExtra(PhotoCutterActivity.KEY_RATIO_Y, scaleY)
intent.putExtra(PhotoCutterActivity.KEY_FORMAT, compressFormat)
if (fragment == null) {
activity.startActivityForResult(intent, Request.REQUEST_CROP_IMAGE)
} else {
fragment?.startActivityForResult(intent, Request.REQUEST_CROP_IMAGE)
}
}
/**
* 提示已经选了多少图片
*/
private fun notifySelectPhoto(image: File?) {
image?.let {
notifySelectPhoto(mutableListOf(it), image)
}
}
/**
* 提示已经选了多少图片
*/
private fun notifySelectPhoto(imageList: MutableList<File?>, image: File?) {
LoadingDialog.dismiss(loadingDialog)
selectPhotoListener?.onSelectedPhoto(imageList, image)
}
/**
* 设置选择图片的监听
*/
fun setOnSelectPhotoListener(listener: OnSelectImageListener) {
selectPhotoListener = listener
}
private fun requestCameraPermission(): Boolean {
val permissions = arrayOf(
Manifest.permission.CAMERA
)
if (!PermissionManager.hasPermission(activity, *permissions)) {
PermissionManager.newTask(activity)
.permissions(*permissions)
.request()
return false
}
return true
}
/**
* 定义图片是单选还是多选
*/
@IntDef(SelectMode.SINGLE, SelectMode.MULTIPLE)
@Retention(AnnotationRetention.SOURCE)
annotation class SelectMode {
companion object {
/**
* 单选
*/
const val SINGLE = 1
/**
* 多选
*/
const val MULTIPLE = 2
}
}
object ResultMode {
/**
* 压缩
*/
const val COMPRESS = 1
/**
* 剪切
*/
const val CROP = 2
}
/**
* 公共类方便调用 request
*/
object Request {
/**
* 单选调用摄像头
*/
internal const val REQUEST_SINGLE_CAMERA = 1 shl 8
/**
* 多选调用摄像头
*/
internal const val REQUEST_MULTI_CAMERA = REQUEST_SINGLE_CAMERA + 1
/**
* 单选图片
*/
internal const val REQUEST_SINGLE_PICK = REQUEST_SINGLE_CAMERA + 2
/**
* 多选图片
*/
internal const val REQUEST_MULTI_PICK = REQUEST_SINGLE_CAMERA + 3
/**
* 剪切图片
*/
const val REQUEST_CROP_IMAGE = REQUEST_SINGLE_CAMERA + 4
}
companion object {
private const val TAG = "SelectPhotoUtils"
/**
* 多选模式下最多可以选多少张图片
*/
private const val MAX_SELECT_COUNT = 9
/**
* 通过拍照 来选择
*/
private const val SELECT_PHOTO_CAMERA = 0
/**
* 通过画廊来选择
*/
private const val SELECT_PHOTO_GALLERY = 1
}
}
| 1 | null | 1 | 1 | 0b823a69256345078a0c110798c8e9ac4ae2b565 | 13,882 | android-Common | Apache License 2.0 |
languages/kotlin/kotlin-in-action/src/ch10/10.2.1_3_ReflectionAPI2.kt | JiniousChoi | 137,426,553 | false | {"Text": 116, "Ignore List": 24, "Markdown": 69, "Python": 278, "JavaScript": 29, "C": 209, "Makefile": 31, "SQL": 6, "Roff Manpage": 2, "RPM Spec": 1, "Shell": 76, "C++": 23, "QMake": 2, "Java": 47, "Vim Script": 18, "Ruby": 16, "CSS": 6, "HTML": 19, "YAML": 24, "Unix Assembly": 6, "Motorola 68K Assembly": 8, "Clojure": 12, "Elixir": 16, "Scala": 202, "INI": 12, "Scheme": 1, "Procfile": 1, "XML": 21, "Gradle": 9, "Maven POM": 1, "Batchfile": 4, "Go": 2, "Haskell": 12, "Kotlin": 314, "Java Properties": 2, "Git Config": 1, "Scilab": 67, "Assembly": 2, "Gerber Image": 55, "Hack": 3, "Dockerfile": 1, "JSON": 1, "ASL": 2} | package ch10.ex2_1_3_ReflectionAPI2
var counter = 0
fun main(args: Array<String>) {
val kProperty = ::counter
kProperty.setter.call(21)
println(kProperty.get())
}
| 3 | Python | 0 | 1 | 77bc551a03a2a3e3808e50016ece14adb5cfbd96 | 177 | encyclopedia-in-code | MIT License |
app/src/main/kotlin/com/fashare/mvvm_juejin/JueJinApp.kt | fashare2015 | 102,467,998 | false | null | package com.fashare.mvvm_juejin
import android.app.Application
import android.content.Context
import android.util.Log
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.Utils
import com.fashare.mvvm_juejin.repo.Response
import com.fashare.mvvm_juejin.repo.local.LocalUser
import com.fashare.net.ApiFactory
import com.fashare.net.widget.OkHttpFactory
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Interceptor
import okhttp3.ResponseBody
/**
* <pre>
* author : jinliangshan
* e-mail : <EMAIL>
* desc :
* </pre>
*/
class JueJinApp: Application() {
companion object {
lateinit var instance: Context
val GSON = Gson()
}
override fun onCreate() {
super.onCreate()
instance = this
Utils.init(this)
initNet()
}
private fun initNet() {
ApiFactory.okhttpClient = OkHttpFactory.create(Interceptor {
val originRequest = it.request()
// 添加 header 以及公共的 GET 参数
val newRequest = originRequest.newBuilder()
.addHeader("X-Juejin-Src", "android")
.url(originRequest.url().newBuilder()
.addQueryParameter("uid", LocalUser.userToken?.user_id?:"unlogin")
.addQueryParameter("token", LocalUser.userToken?.token?:"")
.addQueryParameter("device_id", DeviceUtils.getAndroidID())
.addQueryParameter("src", "android")
.build()
).build()
/** 处理不规范的返回值
* <-- 400 Bad Request
* {
* "s": 10012,
* "m": "密码错误",
* "d": [] // 应该返回 空对象{}, 否则 Json 解析异常
* }
*/
var response = it.proceed(newRequest)
response.newBuilder()
.apply {
val originBody = response.body()
var json = originBody?.string()
var res : Response<Any>? = null
try {
res = GSON.fromJson(json, object: TypeToken<Response<Any>>(){}.type)
}catch (e: Exception){
Log.e("initNet", "interceptor response" + e)
}
try {
res = GSON.fromJson(json, object: TypeToken<Response<List<Any>>>(){}.type)
}catch (e: Exception){
Log.e("initNet", "interceptor response" + e)
}
// 不成功,则移除 "d" 字段
if(1 != res?.s){
res?.d = null
}
json = GSON.toJson(res)
this.body(ResponseBody.create(originBody?.contentType(), json))
}
.apply {
this.code(if(response.code() in 400 .. 500) 200 else response.code())
}
.build()
})
}
}
| 8 | Java | 60 | 402 | 182ec504145e326eb5f448879f558933b1a94799 | 3,199 | MVVM-JueJin | MIT License |
app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/deviceproviders/JsonRpcRequest.kt | jeffcharles | 48,834,757 | false | {"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 2, "Ignore List": 2, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Proguard": 1, "XML": 23, "Kotlin": 53, "HTML": 1, "Java": 1} | package com.beyondtechnicallycorrect.visitordetector.deviceproviders
class JsonRpcRequest(val jsonrpc: String, val id: String, val method: String, val params: Array<String>)
| 1 | null | 1 | 1 | 1333c320442d119bfb0056cad0d404aa215c3625 | 175 | visitor-detector | MIT License |
android/JetpackDemo/navigation/src/main/java/com/android/cooper/app/navigation/Delegate.kt | cuixbo | 538,532,557 | true | {"Markdown": 17, "Text": 16, "Ignore List": 37, "Java Properties": 16, "Gradle": 50, "Shell": 8, "Batchfile": 8, "Kotlin": 365, "INI": 13, "XML": 145, "Checksums": 6, "Proguard": 15, "Java": 419, "Makefile": 1, "EditorConfig": 1, "YAML": 5, "JSON": 13, "robots.txt": 2, "HTML": 3, "JavaScript": 29, "CSS": 3, "Git Attributes": 1, "Starlark": 2, "Ruby": 1, "Objective-C": 5, "OpenStep Property List": 8, "Dart": 14, "Go Checksums": 1, "Go": 14, "Go Module": 3, "Protocol Buffer": 2, "Python": 21, "Thrift": 1, "Swift": 1} | package com.android.cooper.app.navigation
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.viewbinding.ViewBinding
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Created by cooper
* 21-1-12.
* Email: [email protected]
*/
//inline fun <reified T : Activity> Activity.startActivity() {
// startActivity(Intent(this, T::class.java).apply {
// addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
// })
//}
inline fun <reified T : Activity> Context.startActivity() {
startActivity(Intent(this, T::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
}
inline fun <reified T : ViewBinding> Activity.viewBinding() =
ActivityViewBindingDelegate(T::class.java)
class ActivityViewBindingDelegate<T : ViewBinding>(
private val bindingClass: Class<T>,
) : ReadOnlyProperty<Activity, T> {
private var binding: T? = null
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Activity, property: KProperty<*>): T {
binding?.let { return it }
val inflateMethod = bindingClass.getMethod("inflate", LayoutInflater::class.java)
binding = inflateMethod.invoke(null, thisRef.layoutInflater) as T
thisRef.setContentView(binding!!.root)
return binding!!
}
}
inline fun <reified T : ViewBinding> Fragment.viewBinding() =
FragmentViewBindingDelegate(this, T::class.java)
class FragmentViewBindingDelegate<T : ViewBinding>(
fragment: Fragment,
private val bindingClass: Class<T>,
) : ReadOnlyProperty<Fragment, T> {
private val clearBindingHandler by lazy { Handler(Looper.getMainLooper()) }
private var binding: T? = null
init {
fragment.viewLifecycleOwnerLiveData.observe(fragment) {
it.lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
clearBindingHandler.post { binding = null }
}
})
}
}
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
binding?.let { return it }
val bindMethod = bindingClass.getMethod(
"bind",
View::class.java,
)
val lifecycle = thisRef.viewLifecycleOwner.lifecycle
if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
error("Cannot access view bindings. View lifecycle is ${lifecycle.currentState}")
}
binding = bindMethod.invoke(null, thisRef.requireView()) as T
return binding!!
}
} | 0 | null | 0 | 0 | 50753b0f0eebbdb931910dc8b2c6036440356c93 | 2,935 | ShengSiYuan | Apache License 2.0 |
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownHeader.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.intellij.plugins.markdown.lang.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.navigation.ColoredItemPresentation
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.elementType
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.psi.MarkdownElementVisitor
import org.intellij.plugins.markdown.lang.stubs.impl.MarkdownHeaderStubElement
import org.intellij.plugins.markdown.lang.stubs.impl.MarkdownHeaderStubElementType
import org.intellij.plugins.markdown.structureView.MarkdownStructureColors
import javax.swing.Icon
@Suppress("DEPRECATION")
class MarkdownHeader: MarkdownHeaderImpl {
constructor(node: ASTNode): super(node)
constructor(stub: MarkdownHeaderStubElement, type: MarkdownHeaderStubElementType): super(stub, type)
val level
get() = calculateHeaderLevel()
override fun accept(visitor: PsiElementVisitor) {
@Suppress("DEPRECATION")
when (visitor) {
is MarkdownElementVisitor -> visitor.visitHeader(this)
else -> super.accept(visitor)
}
}
override fun getPresentation(): ItemPresentation {
val headerText = getHeaderText()
val text = headerText ?: "Invalid header: $text"
return object: ColoredItemPresentation {
override fun getPresentableText(): String {
val prevSibling = prevSibling
if (Registry.`is`("markdown.structure.view.list.visibility") && MarkdownTokenTypeSets.LIST_MARKERS.contains(prevSibling.elementType)) {
return prevSibling.text + text
}
return text
}
override fun getIcon(open: Boolean): Icon? = null
override fun getTextAttributesKey(): TextAttributesKey? {
return when (level) {
1 -> MarkdownStructureColors.MARKDOWN_HEADER_BOLD
else -> MarkdownStructureColors.MARKDOWN_HEADER
}
}
}
}
override fun getName(): String? {
return getHeaderText()
}
private fun getHeaderText(): String? {
if (!isValid) {
return null
}
val contentHolder = findChildByType<PsiElement>(MarkdownTokenTypeSets.INLINE_HOLDING_ELEMENT_TYPES) ?: return null
return StringUtil.trim(contentHolder.text)
}
}
| 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 2,578 | intellij-community | Apache License 2.0 |
scalechain-proto-codec/src/test/kotlin/io/scalechain/blockchain/proto/codec/messages/MempoolSpec.kt | ScaleChain | 45,332,311 | false | null | package io.scalechain.blockchain.proto.codec.messages
import io.kotlintest.KTestJUnitRunner
import io.scalechain.blockchain.proto.*
import io.scalechain.blockchain.proto.codec.*
import io.scalechain.util.HexUtil.bytes
import org.junit.runner.RunWith
/**
* <Bitcoin Core Packets Not Captured>
* No Payload
*/
/*
@RunWith(KTestJUnitRunner::class)
class FilterClearSpec : PayloadTestSuite<FilterClear>() {
override val codec = FilterClearCodec
override val payload = bytes("") // No Payload.
override val message = FilterClear()
}
*/ | 11 | Kotlin | 67 | 234 | e39b789928256b75c18acee847ccc2c2dc2dec5a | 549 | scalechain | Intel Open Source License |
InkBetterAndroidViews/src/main/java/com/inlacou/inkbetterandroidviews/layoutmanagers/CarouselLinearLayoutManager.kt | inlacou | 400,138,100 | false | {"Kotlin": 513611, "Shell": 139} | package com.inlacou.inkbetterandroidviews.layoutmanagers
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import timber.log.Timber
import kotlin.math.abs
import kotlin.math.min
class CarouselLinearLayoutManager: LinearLayoutManager {
constructor(context: Context, orientation: Int, reverseLayout: Boolean): super(context, orientation, reverseLayout)
constructor(context: Context, orientation: Int, reverseLayout: Boolean, scaleOnScroll: Boolean): super(context, orientation, reverseLayout) {
this.scaleOnScroll = scaleOnScroll
}
constructor(context: Context, orientation: Int, reverseLayout: Boolean, scalingFactor: Float): super(context, orientation, reverseLayout) {
this.scalingFactor = scalingFactor
}
constructor(context: Context, orientation: Int, reverseLayout: Boolean, scaleOnScroll: Boolean, scalingFactor: Float): super(context, orientation, reverseLayout) {
this.scaleOnScroll = scaleOnScroll
this.scalingFactor = scalingFactor
}
var scaleOnScroll = false
/**
* 0f is no scale, bigger the number, scale more.
*/
var scalingFactor = 0f
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
super.onLayoutChildren(recycler, state)
scrollHorizontallyBy(0, recycler, state)
}
override fun scrollHorizontallyBy(
dx: Int,
recycler: RecyclerView.Recycler?,
state: RecyclerView.State?
): Int {
val scrolled = super.scrollHorizontallyBy(dx, recycler, state)
if (scaleOnScroll) {
try {
for (i in 0 until childCount) {
getChildAt(i)?.let { child ->
val childWidth = child.right - child.left.toFloat()
val childWidthHalf = childWidth / 2f
val childCenter = child.left + childWidthHalf
val parentWidth = width.toFloat()
val parentWidthHalf = parentWidth / 2f
val d0 = 0f
val mShrinkDistance = .75f
val d1 = mShrinkDistance * parentWidthHalf
val s0 = 1f
val mShrinkAmount = scalingFactor
val s1 = 1f - mShrinkAmount
val d = min(d1, abs(parentWidthHalf - childCenter))
//wtf
val scalingFactor = s0 + (s1 - s0) * (d - d0) / (d1 - d0)
child.resizeView(scalingFactor, true)
}
}
} catch (e: Exception) {
Timber.e("error8")
Timber.e(e)
e.printStackTrace()
}
}
return scrolled
}
private var maxWidth: Int? = null
private var maxHeight: Int? = null
private fun View.resizeView(scaleFactor: Float, workAroundCenterVertical: Boolean = false) {
val lp = layoutParams ?: return
if(maxWidth==null) {
maxWidth = this.width
maxHeight = this.height
}
val targetWidth = (maxWidth!! * scaleFactor).toInt()
val targetHeight = (maxHeight!! * scaleFactor).toInt()
if (lp.width.compareWithThreshold(targetWidth, 0)) return
if (scaleFactor >= 0) {
lp.height = targetHeight
lp.width = targetWidth
}
if (workAroundCenterVertical && lp is ViewGroup.MarginLayoutParams) {
val verticalMargin = (maxHeight!! - targetHeight) / 2
lp.setMargins(10, verticalMargin, 10, verticalMargin)
}
layoutParams = lp
}
fun Int.compareWithThreshold(other: Int, threshold: Int): Boolean {
return this>=other-threshold && this<other+threshold
}
} | 0 | Kotlin | 0 | 0 | aa90dfc787a4fae77765d333d327929750da7d18 | 4,127 | InkCommons | MIT License |
diktat-common/src/main/kotlin/org/cqfn/diktat/common/cli/CliArgument.kt | cybernetics | 315,785,871 | true | {"Kotlin": 1133909, "TeX": 9932, "Java": 2002, "Shell": 601} | package org.cqfn.diktat.common.cli
import kotlinx.serialization.*
import org.apache.commons.cli.Option
/**
* This class is used to serialize/deserialize json representation
* that is used to store command line arguments
* @property shortName short argument representation like -h
* @property longName long argument representation like --help
* @property hasArgs indicates if option should have explicit argument
*/
@Serializable
data class CliArgument(
private val shortName: String,
private val helpDescr: String,
private val longName: String,
private val hasArgs: Boolean,
private val isRequired: Boolean) {
/**
* Converts parameters received from json to [Option]
*
* @return an [Option]
*/
fun convertToOption(): Option {
val resOption = Option(shortName, longName, hasArgs, helpDescr)
resOption.isRequired = isRequired
return resOption
}
}
| 1 | null | 0 | 0 | bc2e7122cbd2be8062ff8862c9fb5defd95c84d6 | 949 | diKTat | MIT License |
src/Day01.kt | mkfsn | 573,042,358 | false | null | fun main() {
fun makeGroups(input: List<String>): List<Int> {
return input.chunkedBy { ele -> ele == "" }.map { nums -> nums.sumOf { it.toInt() } }
}
fun part1(input: List<String>): Int {
return makeGroups(input).max()
}
fun part2(input: List<String>): Int {
return makeGroups(input).sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 3 | 8c7bdd66f8550a82030127aa36c2a6a4262592cd | 651 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/test/java/com/babylon/wallet/android/domain/usecases/SearchFeePayersUseCaseTest.kt | radixdlt | 513,047,280 | false | {"Kotlin": 4178054, "HTML": 215350, "Ruby": 2757, "Shell": 1962} | package com.babylon.wallet.android.domain.usecases
import com.babylon.wallet.android.data.repository.state.StateRepository
import com.babylon.wallet.android.data.transaction.TransactionConfig
import com.babylon.wallet.android.data.transaction.model.TransactionFeePayers
import com.babylon.wallet.android.domain.model.assets.AccountWithAssets
import com.babylon.wallet.android.fakes.FakeProfileRepository
import com.radixdlt.sargon.Account
import com.radixdlt.sargon.AccountAddress
import com.radixdlt.sargon.AccountOrAddressOf
import com.radixdlt.sargon.ComponentAddress
import com.radixdlt.sargon.Decimal192
import com.radixdlt.sargon.Gateway
import com.radixdlt.sargon.NetworkId
import com.radixdlt.sargon.NonFungibleLocalId
import com.radixdlt.sargon.PerAssetFungibleResource
import com.radixdlt.sargon.PerAssetFungibleTransfer
import com.radixdlt.sargon.PerAssetTransfers
import com.radixdlt.sargon.PerAssetTransfersOfFungibleResource
import com.radixdlt.sargon.PoolAddress
import com.radixdlt.sargon.Profile
import com.radixdlt.sargon.ResourceAddress
import com.radixdlt.sargon.TransactionManifest
import com.radixdlt.sargon.ValidatorAddress
import com.radixdlt.sargon.extensions.ProfileEntity
import com.radixdlt.sargon.extensions.forNetwork
import com.radixdlt.sargon.extensions.perAssetTransfers
import com.radixdlt.sargon.extensions.toDecimal192
import com.radixdlt.sargon.samples.sample
import com.radixdlt.sargon.samples.sampleMainnet
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
import rdx.works.core.domain.DApp
import rdx.works.core.domain.TransactionManifestData
import rdx.works.core.domain.assets.StakeClaim
import rdx.works.core.domain.assets.ValidatorWithStakes
import rdx.works.core.domain.resources.Pool
import rdx.works.core.domain.resources.Resource
import rdx.works.core.domain.resources.Validator
import rdx.works.core.domain.resources.XrdResource
import rdx.works.core.domain.resources.metadata.PublicKeyHash
import rdx.works.core.sargon.activeAccountsOnCurrentNetwork
import rdx.works.core.sargon.changeGateway
import rdx.works.core.sargon.unHideAllEntities
import rdx.works.profile.domain.GetProfileUseCase
class SearchFeePayersUseCaseTest {
private val profile = Profile.sample().changeGateway(Gateway.forNetwork(NetworkId.MAINNET)).unHideAllEntities()
private val account1 = profile.activeAccountsOnCurrentNetwork[0]
private val account2 = profile.activeAccountsOnCurrentNetwork[1]
private val profileUseCase = GetProfileUseCase(profileRepository = FakeProfileRepository(profile))
private val useCase = SearchFeePayersUseCase(
profileUseCase = profileUseCase,
stateRepository = StateRepositoryFake
)
@Test
fun `when account with enough xrd exists, returns the selected fee payer`() =
runTest {
val manifestData = manifestDataWithAddress(account1)
val result = useCase(manifestData, TransactionConfig.DEFAULT_LOCK_FEE.toDecimal192()).getOrThrow()
assertEquals(
TransactionFeePayers(
selectedAccountAddress = account1.address,
candidates = listOf(
TransactionFeePayers.FeePayerCandidate(account1, 100.toDecimal192()),
TransactionFeePayers.FeePayerCandidate(account2, 0.toDecimal192())
)
),
result
)
}
@Test
fun `when account with xrd does not exist, returns the null fee payer`() =
runTest {
val manifestData = manifestDataWithAddress(account1)
val result = useCase(manifestData, 200.toDecimal192()).getOrThrow()
assertEquals(
TransactionFeePayers(
selectedAccountAddress = null,
candidates = listOf(
TransactionFeePayers.FeePayerCandidate(account1, 100.toDecimal192()),
TransactionFeePayers.FeePayerCandidate(account2, 0.toDecimal192())
)
),
result
)
}
companion object {
private fun manifestDataWithAddress(
account: Account
) = TransactionManifestData.from(
manifest = TransactionManifest.perAssetTransfers(
transfers = PerAssetTransfers(
fromAccount = account.address,
fungibleResources = listOf(
PerAssetTransfersOfFungibleResource(
resource = PerAssetFungibleResource(
resourceAddress = XrdResource.address(networkId = account.networkId),
divisibility = 18.toUByte()
),
transfers = listOf(
PerAssetFungibleTransfer(
useTryDepositOrAbort = true,
amount = 10.toDecimal192(),
recipient = AccountOrAddressOf.AddressOfExternalAccount(
value = AccountAddress.sampleMainnet.random()
)
)
)
)
),
nonFungibleResources = emptyList()
)
)
)
private object StateRepositoryFake : StateRepository {
override fun observeAccountsOnLedger(accounts: List<Account>, isRefreshing: Boolean): Flow<List<AccountWithAssets>> {
TODO("Not yet implemented")
}
override suspend fun getNextNFTsPage(
account: Account,
resource: Resource.NonFungibleResource
): Result<Resource.NonFungibleResource> {
TODO("Not yet implemented")
}
override suspend fun updateLSUsInfo(
account: Account,
validatorsWithStakes: List<ValidatorWithStakes>
): Result<List<ValidatorWithStakes>> {
TODO("Not yet implemented")
}
override suspend fun updateStakeClaims(account: Account, claims: List<StakeClaim>): Result<List<StakeClaim>> {
TODO("Not yet implemented")
}
override suspend fun getResources(
addresses: Set<ResourceAddress>,
underAccountAddress: AccountAddress?,
withDetails: Boolean
): Result<List<Resource>> {
TODO("Not yet implemented")
}
override suspend fun getPools(poolAddresses: Set<PoolAddress>): Result<List<Pool>> {
TODO("Not yet implemented")
}
override suspend fun getValidators(validatorAddresses: Set<ValidatorAddress>): Result<List<Validator>> {
TODO("Not yet implemented")
}
override suspend fun getNFTDetails(
resourceAddress: ResourceAddress,
localIds: Set<NonFungibleLocalId>
): Result<List<Resource.NonFungibleResource.Item>> {
TODO("Not yet implemented")
}
override suspend fun getOwnedXRD(accounts: List<Account>): Result<Map<Account, Decimal192>> {
return Result.success(accounts.associateWith {
if (it == accounts.first()) {
100.toDecimal192()
} else {
0.toDecimal192()
}
})
}
override suspend fun getEntityOwnerKeys(entities: List<ProfileEntity>): Result<Map<ProfileEntity, List<PublicKeyHash>>> {
TODO("Not yet implemented")
}
override suspend fun getDAppsDetails(definitionAddresses: List<AccountAddress>, isRefreshing: Boolean): Result<List<DApp>> {
TODO("Not yet implemented")
}
override suspend fun getDAppDefinitions(componentAddresses: List<ComponentAddress>): Result<Map<ComponentAddress, AccountAddress?>> {
TODO("Not yet implemented")
}
override suspend fun cacheNewlyCreatedResources(newResources: List<Resource>): Result<Unit> {
TODO("Not yet implemented")
}
override suspend fun clearCachedState(): Result<Unit> {
TODO("Not yet implemented")
}
}
}
}
| 12 | Kotlin | 11 | 6 | def84e8b19afb8ca7e092b1a69a45bc614ed9c71 | 8,632 | babylon-wallet-android | Apache License 2.0 |
src/commonMain/kotlin/me/devnatan/yoki/models/volume/Volume.kt | DevNatan | 392,883,613 | false | {"Kotlin": 195907} | package me.devnatan.dockerkt.models.volume
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class Volume(
@SerialName("Name") public val name: String,
@SerialName("Driver") public val driver: String,
@SerialName("Scope") public val scope: String,
@SerialName("Mountpoint") public val mountPoint: String,
@SerialName("CreatedAt") public val createdAt: String?,
@SerialName("Labels") public val labels: Map<String, String>?,
@SerialName("Options") public val options: Map<String, String>?,
)
| 7 | Kotlin | 4 | 19 | dfe370c33247ccc88b4dcf36737598874bcd4b92 | 579 | yoki | MIT License |
src/main/kotlin/movieApiExample/model/Cast.kt | RajashekarRaju | 371,490,731 | false | null | package movieApiExample.model
data class Cast(
val castId: Int,
val name: String?,
val profileUrl: String?,
val popularity: Double?,
val character: String?
)
| 0 | Kotlin | 0 | 0 | e8b32d871a34b877df4a618bc74c899147822cb9 | 179 | desktop-compose-examples | Apache License 2.0 |
fs/datacap-fs-qiniu/src/main/kotlin/io/edurt/datacap/fs/qiniu/QiniuFs.kt | devlive-community | 537,719,266 | false | {"Java": 1998447, "Vue": 742066, "Kotlin": 462615, "TypeScript": 217485, "ANTLR": 188268, "Shell": 13094, "JavaScript": 3357, "CSS": 1627, "HTML": 357, "Dockerfile": 329} | package io.edurt.datacap.fs.qiniu
import io.edurt.datacap.fs.Fs
import io.edurt.datacap.fs.FsRequest
import io.edurt.datacap.fs.FsResponse
import io.edurt.datacap.fs.qiniu.IOUtils.Companion.copy
import org.slf4j.LoggerFactory.getLogger
import java.io.File
import java.lang.String.join
class QiniuFs : Fs {
private val log = getLogger(QiniuFs::class.java)
override fun writer(request: FsRequest?): FsResponse {
requireNotNull(request) { "request must not be null" }
log.info("QiniuFs writer origin path [ {} ]", request.fileName)
val targetPath = join(File.separator, request.endpoint, request.bucket, request.fileName)
val response = FsResponse.builder()
.origin(request.fileName)
.remote(targetPath)
.successful(true)
.build()
log.info("QiniuFs writer target path [ {} ]", request.fileName)
try {
val key = copy(request, request.stream, request.fileName)
response.remote = key
log.info("QiniuFs writer [ {} ] successfully", key)
}
catch (e: Exception) {
log.error("QiniuFs writer error", e)
response.isSuccessful = false
response.message = e.message
}
return response
}
override fun reader(request: FsRequest?): FsResponse {
requireNotNull(request) { "request must not be null" }
log.info("QiniuFs reader origin path [ {} ]", request.fileName)
val response = FsResponse.builder()
.remote(request.fileName)
.successful(true)
.build()
try {
response.context = IOUtils.reader(request)
log.info("QiniuFs reader [ {} ] successfully", request.fileName)
}
catch (e: java.lang.Exception) {
log.error("QiniuFs reader error", e)
response.isSuccessful = false
response.message = e.message
}
return response
}
override fun delete(request: FsRequest?): FsResponse {
requireNotNull(request) { "request must not be null" }
try {
val status = IOUtils.delete(request)
log.info("QiniuFs delete [ {} ] successfully", request.fileName)
return FsResponse.builder()
.successful(status)
.build()
}
catch (e: java.lang.Exception) {
log.error("QiniuFs delete error", e)
return FsResponse.builder()
.successful(false)
.message(e.message)
.build()
}
}
}
| 36 | Java | 94 | 865 | 1d6be5c990ed3f952bc28699ea15a68b1e2bc265 | 2,652 | datacap | Apache License 2.0 |
app/src/main/java/co/utils/recycle/loadmoreadapter/LoadMoreViewHolder.kt | CANDY-HOUSE | 280,844,064 | false | {"Kotlin": 675713, "Shell": 406} | package co.utils.recycle.loadmoreadapter
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import co.utils.L
internal interface ILoadMore {
/**
* 加载更多中
*/
fun readty()
/**
* 加载更多中
*/
fun loading()
/**
* 加载完成-已无更多数据
*/
fun noMoreData()
// /**
// * 加载失败
// */
// fun loadFailed()
}
/**
* 底部加载更多的ViewHolder
*/
internal class LoadMoreViewHolder(itemView: View, private val mFooter: ILoadMoreFooter) : RecyclerView.ViewHolder(itemView), ILoadMore {
/**
* 设置状态
*/
fun setViewState(stateType: Int) {
// L.d("hcia", "stateType:" + stateType)
when (stateType) {
LoadMoreAdapter.STATE_IS_LOADING -> loading()
LoadMoreAdapter.STATE_NORMAL -> readty()
// LoadMoreAdapter.STATE_LOAD_FAILED -> loadFailed()
LoadMoreAdapter.STATE_NO_MORE_DATA -> noMoreData()
}
}
override fun readty() {
mFooter.ready(itemView)
}
override fun loading() {
mFooter.loading(itemView)
}
override fun noMoreData() {
mFooter.noMoreData(itemView)
}
// override fun loadFailed() {
// mFooter.loadFailed(itemView)
// }
} | 14 | Kotlin | 11 | 24 | e1cf834bc30b619751566542034079ee45239ba5 | 1,304 | SesameSDK_Android_with_DemoApp | MIT License |
lib/DevEngine/src/main/java/dev/engine/compress/CompressConfig.kt | afkT | 147,776,221 | false | null | package dev.engine.compress
/**
* detail: Image Compress Config
* @author Ttt
*/
open class CompressConfig @JvmOverloads constructor(
// 单位 KB 默认 100 kb 以下不压缩
val ignoreSize: Int,
// 是否保留透明通道
val focusAlpha: Boolean = true,
// 压缩图片存储路径
val targetDir: String? = null
) : ICompressEngine.EngineConfig() {
// 压缩失败、异常是否结束压缩
private var mFailFinish = false
constructor(targetDir: String?) : this(100, true, targetDir)
constructor(
ignoreSize: Int,
targetDir: String?
) : this(ignoreSize, true, targetDir)
// =
fun isFailFinish(): Boolean {
return mFailFinish
}
fun setFailFinish(failFinish: Boolean): CompressConfig {
mFailFinish = failFinish
return this
}
} | 2 | null | 302 | 1,329 | 00b0e4638b48b3ed196e74b732e649deb21e9b2d | 767 | DevUtils | Apache License 2.0 |
libB/src/main/java/package_B_0/Foo_B_011.kt | lekz112 | 118,451,085 | false | null | package package_B_0
class Foo_B_011 {
fun foo0() {
var i=0
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
Foo_B_010().foo0()
}
} | 0 | Kotlin | 0 | 0 | 8182b7f6e92f9d65efb954c32ca640fe50ae6b79 | 581 | ModuleTest | Apache License 2.0 |
Hogwarts/Hogwarts/app/src/main/java/com/bigaton/hogwarts/data/repository/RepositoryImpl.kt | brunobigaton | 463,618,141 | false | null | package com.bigaton.hogwarts.data.repository
import com.bigaton.hogwarts.data.remote.RemoteDataSource
class RepositoryImpl(private val remoteDataSource: RemoteDataSource) : Repository {
override suspend fun getCharacters(type: String) =
remoteDataSource.getCharacters(type)
} | 0 | Kotlin | 0 | 0 | d1d746112bc8e25c1ebb203b82c12130dcb3d8f3 | 293 | Potter | MIT License |
app/src/main/java/com/a60n1/ejashkojme/remote/IGoogleAPI.kt | 460N1 | 224,923,090 | false | null | package com.a60n1.ejashkojme.remote
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Url
interface IGoogleAPI {
@GET
fun getPath(@Url url: String?): Call<String?>?
} | 0 | Kotlin | 0 | 0 | 974490a24bf7106b9b63b89878e2ac0890c51fc5 | 196 | Eja-Shkojme | MIT License |
src/main/kotlin/com/theoparis/cw/entity/render/model/CreamerModel.kt | theoparis | 484,579,728 | false | null | package com.theoparis.cw.entity.render.model
import com.theoparis.cw.CursedWeirdosMod
import com.theoparis.cw.entity.CreamerEntity
import net.minecraft.util.Identifier
import software.bernie.geckolib3.model.AnimatedGeoModel
// Made with Blockbench 3.7.4
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
class CreamerModel : AnimatedGeoModel<CreamerEntity>() {
companion object {
@JvmStatic
fun getTexture() = Identifier(CursedWeirdosMod.modID, "textures/entity/creamer.png")
}
override fun getModelLocation(obj: CreamerEntity): Identifier {
return Identifier(CursedWeirdosMod.modID, "geo/creamer.geo.json")
}
override fun getTextureLocation(obj: CreamerEntity): Identifier {
return getTexture()
}
override fun getAnimationFileLocation(obj: CreamerEntity): Identifier {
return Identifier(CursedWeirdosMod.modID, "animations/creamer.animation.json")
}
}
| 2 | Kotlin | 0 | 0 | 64a713c8ffc64088bfd5234de0faef46e1595677 | 987 | cursed-insanity-mod | MIT License |
search-service/src/test/kotlin/com/egm/stellio/search/util/AttributeInstanceUtilsTests.kt | stellio-hub | 257,818,724 | false | null | package com.egm.stellio.search.util
import com.egm.stellio.search.model.TemporalEntityAttribute
import com.egm.stellio.shared.model.WKTCoordinates
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.springframework.test.context.ActiveProfiles
import java.net.URI
import java.time.LocalTime
@ActiveProfiles("test")
class AttributeInstanceUtilsTests {
@Test
fun `it should guess the value type of a property`() {
assertEquals(
guessAttributeValueType(TemporalEntityAttribute.AttributeType.Property, "A string"),
TemporalEntityAttribute.AttributeValueType.STRING
)
assertEquals(
guessAttributeValueType(TemporalEntityAttribute.AttributeType.Property, LocalTime.now()),
TemporalEntityAttribute.AttributeValueType.TIME
)
}
@Test
fun `it should guess the value type of a geo-property`() {
assertEquals(
guessAttributeValueType(TemporalEntityAttribute.AttributeType.GeoProperty, WKTCoordinates("0 0")),
TemporalEntityAttribute.AttributeValueType.GEOMETRY
)
}
@Test
fun `it should guess the value type of a relationship`() {
assertEquals(
guessAttributeValueType(TemporalEntityAttribute.AttributeType.Relationship, URI("urn:ngsi-ld")),
TemporalEntityAttribute.AttributeValueType.URI
)
}
}
| 30 | Kotlin | 9 | 21 | 63541822eeae9cd143d5d9cf1b766009eef946c6 | 1,428 | stellio-context-broker | Apache License 2.0 |
src/test/kotlin/app/kundi/safelogs/core/LocationReplacerTest.kt | jantoniucci | 188,491,255 | false | null | package app.kundi.safelogs.core
import kotlin.test.Test
import kotlin.test.assertEquals
class LocationReplacerTest {
@Test fun `Replaces a simple location`() {
assertEquals( "The customer city is [LOCATION]", LocationReplacer("The customer city is New York", "[LOCATION]") )
}
}
| 0 | Kotlin | 0 | 2 | 9c396f7e9de708b8569e79cb6e60786b6a84be77 | 300 | safe-logs | MIT License |
src/main/kotlin/jempasam/hexlink/spirit/EntitySpirit.kt | Jempasam | 674,693,089 | false | {"Kotlin": 314532, "Java": 5001, "mcfunction": 299} | package jempasam.hexlink.spirit
import com.google.common.base.Predicates
import net.minecraft.entity.Entity
import net.minecraft.entity.EntityType
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.SpawnGroup
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.SpawnEggItem
import net.minecraft.nbt.NbtElement
import net.minecraft.nbt.NbtString
import net.minecraft.server.world.ServerWorld
import net.minecraft.text.Text
import net.minecraft.util.DyeColor
import net.minecraft.util.Identifier
import net.minecraft.util.math.Box
import net.minecraft.util.math.ColorHelper
import net.minecraft.util.math.Vec3d
import net.minecraft.util.registry.Registry
import net.minecraft.world.World
import kotlin.jvm.optionals.getOrNull
import kotlin.math.sin
class EntitySpirit(val entityType: EntityType<*>): Spirit {
// Spawn At
fun spawn(world: World, position: Vec3d, count: Int, modifier: (Int, Entity)->Unit): Spirit.Manifestation{
if(!entityType.isSummonable)
return Spirit.NONE_MANIFESTATION
else
return Spirit.Manifestation(1,count){
for(i in 0..<it){
val summoned = entityType.create(world)
if(summoned!=null) {
summoned.setPosition(position)
modifier(i, summoned)
world.spawnEntity(summoned)
}
}
}
}
override fun manifestAt(caster: PlayerEntity, world: ServerWorld, position: Vec3d, count: Int): Spirit.Manifestation {
return spawn(world, position, count){_,_->}
}
override fun manifestBetween(caster: PlayerEntity, world: ServerWorld, from: Vec3d, to: Vec3d, count: Int): Spirit.Manifestation {
var direction=to.subtract(from)
if(direction.length()>5)direction=direction.normalize().multiply(5.0)
return spawn(world, from, count){ i,e->
e.setVelocity(direction.x, direction.y+i*0.5, direction.z)
}
}
override fun manifestBetween(caster: PlayerEntity, world: ServerWorld, from: Entity, to: Vec3d, count: Int): Spirit.Manifestation {
return spawn(world, to, count){ i, e ->
if(from is LivingEntity && e is LivingEntity)from.attacker=e
}
}
// Spawn Riding
fun spawn(world: World, rided: Entity, count: Int, modifier: (Entity)->Unit): Spirit.Manifestation{
if(!entityType.isSummonable)
return Spirit.NONE_MANIFESTATION
else
return Spirit.Manifestation(1,count){
var riding=rided
for(i in 0..<it){
val summoned = entityType.create(world)
if(summoned!=null) {
summoned.setPosition(riding.pos)
summoned.velocity=riding.velocity
world.spawnEntity(summoned)
riding.startRiding(summoned)
riding=summoned
}
}
modifier(riding)
}
}
override fun manifestIn(caster: PlayerEntity, world: ServerWorld, entity: Entity, count: Int): Spirit.Manifestation {
return spawn(world, entity, count){}
}
override fun manifestBetween(caster: PlayerEntity, world: ServerWorld, from: Entity, to: Entity, count: Int): Spirit.Manifestation {
return spawn(world, from, count){
if(it is LivingEntity && to is LivingEntity)it.attacker=to
}
}
override fun lookIn(caster: PlayerEntity, world: ServerWorld, entity: Entity): Boolean {
return entity.type==entityType
}
override fun lookAt(caster: PlayerEntity, world: ServerWorld, position: Vec3d): Boolean {
val entities=world.getEntitiesByType( entityType, Box.of(position, 0.7, 0.7, 0.7), Predicates.alwaysTrue())
return entities.isNotEmpty()
}
override fun equals(other: Any?): Boolean = other is EntitySpirit && entityType===other.entityType
override fun hashCode(): Int = entityType.hashCode()*36
override fun getColor(): Int{
val egg=SpawnEggItem.forEntity(entityType)
if(egg!=null){
val forward=sin((System.currentTimeMillis()%2000)/2000f*Math.PI)
val revert=1f-forward
val tint1=egg.getColor(0)
val tint2=egg.getColor(1)
return ColorHelper.Argb.getArgb(
255,
(ColorHelper.Argb.getRed(tint1)*forward+ColorHelper.Argb.getRed(tint2)*revert).toInt(),
(ColorHelper.Argb.getGreen(tint1)*forward+ColorHelper.Argb.getGreen(tint2)*revert).toInt(),
(ColorHelper.Argb.getBlue(tint1)*forward+ColorHelper.Argb.getBlue(tint2)*revert).toInt()
)
}
else if(entityType.isFireImmune)return DyeColor.ORANGE.fireworkColor
else{
val color= from_group_to_color[entityType.spawnGroup]
if(color!=null)return color
else return DyeColor.RED.fireworkColor
}
}
override fun getName(): Text = entityType.name
override fun serialize(): NbtElement {
return NbtString.of(Registry.ENTITY_TYPE.getId(entityType).toString())
}
override fun getType(): Spirit.SpiritType<*> = Type
object Type: Spirit.SpiritType<EntitySpirit>{
override fun getName(): Text {
return Text.translatable("hexlink.spirit.entity")
}
override fun deserialize(nbt: NbtElement): EntitySpirit? {
if(nbt is NbtString){
val type=Registry.ENTITY_TYPE.getOrEmpty(Identifier.tryParse(nbt.asString())).getOrNull()
return type?.let{EntitySpirit(it)}
}
else throw IllegalArgumentException()
}
}
companion object{
private val from_group_to_color= mapOf(
SpawnGroup.MONSTER to DyeColor.RED.fireworkColor,
SpawnGroup.CREATURE to DyeColor.LIME.fireworkColor,
SpawnGroup.AMBIENT to DyeColor.WHITE.fireworkColor,
SpawnGroup.AXOLOTLS to DyeColor.PINK.fireworkColor,
SpawnGroup.UNDERGROUND_WATER_CREATURE to DyeColor.BLUE.fireworkColor,
SpawnGroup.WATER_CREATURE to DyeColor.LIGHT_BLUE.fireworkColor,
SpawnGroup.WATER_AMBIENT to DyeColor.LIGHT_BLUE.fireworkColor,
SpawnGroup.MISC to DyeColor.PURPLE.fireworkColor
)
}
} | 1 | Kotlin | 1 | 1 | 1d4fac0db502a68921f1275c84eb9541f7f714fc | 6,509 | Hexlink | MIT License |
app/src/main/java/com/jawad/newsapp/ui/newsList/adapter/NewsViewHolder.kt | Jawad52 | 247,662,918 | false | {"Gradle": 3, "Java Properties": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "Ignore List": 1, "Kotlin": 53, "XML": 16, "Java": 1, "JSON": 1} | package com.jawad.newsapp.ui.newsList.adapter
import android.view.View
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.jawad.newsapp.data.local.model.NewsItem
import com.jawad.newsapp.ui.newsList.NewsListFragmentDirections
import com.jawad.newsapp.util.DateConverter
import com.jawad.newsapp.util.bindImageFromUrl
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.news_item.*
/**
* The class NewItemViewHolder
*
* @author <NAME>
* @web www.jawadusman.com
* @version 1.0
* @since 18 Mar 2020
*/
class NewsViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView),
LayoutContainer {
/**
* Called when onBindViewHolder is triggered in RecyclerView adapter
* The new bind will be used to set the values to display items
* @param newsEntity contains the values to set in UI
*/
fun bind(newsItem: NewsItem) {
tv_title.text = newsItem.title ?: ""
tv_caption.text = newsItem.byline ?: ""
var date = newsItem.updatedDate
date = date.subSequence(0, date.lastIndexOf("-")).toString()
tv_time.text = DateConverter.getConvertedDate(date)
if (!newsItem.multimedia.isNullOrEmpty()) {
for (newItem in newsItem.multimedia) {
if (newItem.format == "thumbLarge") {
bindImageFromUrl(iv_news_item_image, newItem.url)
break
}
}
}
cl_news_item.setOnClickListener {
val action =
NewsListFragmentDirections.actionNewsListFragmentToNewsDetailsFragment(newsItem.id)
it.findNavController().navigate(action)
}
}
} | 1 | null | 1 | 1 | 261929c52377f75502af000660d8fd2b229e39c3 | 1,765 | News-App | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/model/RuleMetadata.kt | navikt | 257,523,904 | false | null | package no.nav.syfo.model
import java.time.LocalDateTime
data class RuleMetadata(
val signatureDate: LocalDateTime,
val receivedDate: LocalDateTime,
val innbyggerident: String,
val legekontorOrgnr: String?,
val tssid: String?,
val avsenderfnr: String
)
| 2 | Kotlin | 0 | 1 | eff4595eb477829a9d7241466039c564a0a16bdf | 279 | padm2 | MIT License |
src/main/kotlin/no/nav/helse/domene/aiy/organisasjon/Mod11.kt | navikt | 157,684,573 | false | {"Kotlin": 756905, "Shell": 328, "Dockerfile": 47} | package no.nav.helse.domene.aiy.organisasjon
object Mod11 {
private fun vekttall(i: Int) = 2 + i % 6
fun kontrollsiffer(number: String) =
number.reversed().mapIndexed { i, char ->
if (!Character.isDigit(char)) {
throw IllegalArgumentException("$char is not a digit")
}
Character.getNumericValue(char) * vekttall(i)
}.sum().let(Mod11::kontrollsifferFraSum)
private fun kontrollsifferFraSum(sum: Int) = sum.rem(11).let { rest ->
when (rest) {
0 -> '0'
1 -> '-'
else -> "${11 - rest}"[0]
}
}
}
| 0 | Kotlin | 0 | 1 | ed034e9b111afd53715c410029b67c8b06aaf702 | 654 | helse-sparkel | MIT License |
packages/expo-dev-launcher/android/src/main/java/expo/modules/devlauncher/launcher/manifest/DevLauncherManifestTypes.kt | betomoedano | 462,599,485 | true | {"TypeScript": 7804102, "Kotlin": 3383974, "Objective-C": 2722124, "Swift": 1723956, "Java": 1686584, "JavaScript": 847793, "C++": 310224, "C": 237463, "Objective-C++": 191888, "Ruby": 167983, "Shell": 59271, "HTML": 31107, "CMake": 25754, "Batchfile": 89, "CSS": 42} | package expo.modules.devlauncher.launcher.manifest
object DevLauncherOrientation {
const val DEFAULT = "default"
const val PORTRAIT = "portrait"
const val LANDSCAPE = "landscape"
}
object DevLauncherUserInterface {
const val AUTOMATIC = "automatic"
const val DARK = "dark"
const val LIGHT = "light"
}
object DevLauncherStatusBarStyle {
const val DARK = "dark-content"
const val LIGHT = "light-content"
}
object DevLauncherNavigationBarStyle {
const val DARK = "dark-content"
const val LIGHT = "light-content"
}
object DevLauncherNavigationBarVisibility {
const val LEANBACK = "leanback"
const val IMMERSIVE = "immersive"
const val STICKY_IMMERSIVE = "sticky-immersive"
}
| 668 | TypeScript | 5226 | 4 | 52d6405570a39a87149648d045d91098374f4423 | 702 | expo | MIT License |
src/main/java/com/dzen/campfire/api/requests/post/RPostChangePage.kt | ZeonXX | 381,983,751 | false | {"Kotlin": 1087578} | package com.dzen.campfire.api.requests.post
import com.dzen.campfire.api.models.publications.post.Page
import com.dzen.campfire.api.tools.client.Request
import com.sup.dev.java.libs.json.Json
open class RPostChangePage(
var publicationId: Long,
var page: Page?,
var pageIndex: Int
) : Request<RPostChangePage.Response>() {
companion object {
val E_BAD_STATUS = "E_BAD_STATUS"
val E_BAD_PAGE_INDEX = "E_BAD_PAGE_INDEX"
val E_BAD_TYPE = "E_BAD_TYPE"
val E_BAD_PAGE = "E_BAD_PAGE"
}
init {
if (page != null) page!!.addInsertData(this)
}
override fun updateDataOutput() {
page!!.restoreInsertData(this, 0)
}
override fun jsonSub(inp: Boolean, json: Json) {
publicationId = json.m(inp, "unitId", publicationId)
page = json.mNull(inp, "page", page, Page::class)
pageIndex = json.m(inp, "pageIndex", pageIndex)
}
override fun instanceResponse(json: Json): Response {
return Response(json)
}
class Response : Request.Response {
var page: Page? = null
constructor(json: Json) {
json(false, json)
}
constructor(page: Page) {
this.page = page
}
override fun json(inp: Boolean, json: Json) {
page = json.mNull(inp, "page", page, Page::class)
}
}
} | 0 | Kotlin | 2 | 5 | 6f3b371624fb66a065bcbaa6302830c574c55e9f | 1,394 | CampfireApi | Apache License 2.0 |
compiler/testData/codegen/box/jvmStatic/privateMethod.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // TARGET_BACKEND: JVM
// WITH_STDLIB
object A {
private @JvmStatic fun a(): String {
return "OK"
}
object Z {
val p = a()
}
}
fun box(): String {
return A.Z.p
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 203 | kotlin | Apache License 2.0 |
app/src/androidTest/java/org/bobstuff/bobboardview/app/trello/CustomTestRunner.kt | bobthekingofegypt | 123,321,465 | false | null | package org.bobstuff.bobboardview.app.trello
import com.facebook.testing.screenshot.ScreenshotRunner
import android.os.Bundle
import com.facebook.testing.screenshot.ScreenshotRunner.onCreate
import androidx.test.runner.AndroidJUnitRunner
/**
* Created by bob
*/
class CustomTestRunner : AndroidJUnitRunner() {
override fun onCreate(args: Bundle) {
ScreenshotRunner.onCreate(this, args)
super.onCreate(args)
}
override fun finish(resultCode: Int, results: Bundle) {
ScreenshotRunner.onDestroy()
super.finish(resultCode, results)
}
} | 1 | null | 1 | 4 | a13505aabc152ab9eb62b96c84204e10f5b777c2 | 585 | BobBoardView | Apache License 2.0 |
idea/idea-frontend-fir/src/org/jetbrains/kotlin/idea/asJava/annotations/FirLightAnnotationForAnnotationCall.kt | AdamMc331 | 142,794,614 | true | {"Markdown": 66, "Gradle": 728, "Gradle Kotlin DSL": 559, "Java Properties": 15, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 8, "Kotlin": 61093, "Protocol Buffer": 12, "Java": 6639, "Proguard": 12, "XML": 1602, "Text": 12271, "INI": 179, "JavaScript": 275, "JAR Manifest": 2, "Roff": 213, "Roff Manpage": 38, "AsciiDoc": 1, "HTML": 494, "SVG": 50, "Groovy": 33, "JSON": 179, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 9, "Ant Build System": 50, "Graphviz (DOT)": 77, "C": 1, "Ruby": 5, "Objective-C": 8, "OpenStep Property List": 5, "Swift": 5, "Scala": 1, "YAML": 16} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.asJava
import com.intellij.psi.*
import com.intellij.psi.impl.PsiImplUtil
import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.asJava.classes.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtAnnotationCall
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSimpleConstantValue
import org.jetbrains.kotlin.psi.KtCallElement
internal class FirLightAnnotationForAnnotationCall(
private val annotationCall: KtAnnotationCall,
parent: PsiElement,
) : FirLightAbstractAnnotation(parent) {
override fun findAttributeValue(attributeName: String?): PsiAnnotationMemberValue? =
PsiImplUtil.findAttributeValue(this, attributeName)
override fun findDeclaredAttributeValue(attributeName: String?) =
PsiImplUtil.findDeclaredAttributeValue(this, attributeName)
private val _parameterList: PsiAnnotationParameterList by lazyPub {
FirAnnotationParameterList(this@FirLightAnnotationForAnnotationCall, annotationCall)
}
override fun getParameterList(): PsiAnnotationParameterList = _parameterList
override val kotlinOrigin: KtCallElement? = annotationCall.psi
override fun getQualifiedName(): String? = annotationCall.classId?.asSingleFqName()?.asString()
override fun getName(): String? = qualifiedName
override fun equals(other: Any?): Boolean =
this === other ||
(other is FirLightAnnotationForAnnotationCall &&
kotlinOrigin == other.kotlinOrigin &&
annotationCall == other.annotationCall)
override fun hashCode(): Int = kotlinOrigin.hashCode()
override fun isEquivalentTo(another: PsiElement?): Boolean =
basicIsEquivalentTo(this, another as? PsiAnnotation)
}
private fun escapeString(str: String): String = buildString {
str.forEach { char ->
val escaped = when (char) {
'\n' -> "\\n"
'\r' -> "\\r"
'\t' -> "\\t"
'\"' -> "\\\""
'\\' -> "\\\\"
else -> "$char"
}
append(escaped)
}
}
private fun KtSimpleConstantValue<*>.asStringForPsiLiteral(parent: PsiElement): String =
when (val value = this.constant) {
is String -> "\"${escapeString(value)}\""
is Long -> "${value}L"
is Float -> "${value}f"
else -> value?.toString() ?: "null"
}
internal fun KtSimpleConstantValue<*>.createPsiLiteral(parent: PsiElement): PsiExpression? {
val asString = asStringForPsiLiteral(parent)
val instance = PsiElementFactory.getInstance(parent.project)
return try {
instance.createExpressionFromText(asString, parent)
} catch (_: IncorrectOperationException) {
null
}
}
| 0 | Kotlin | 0 | 1 | 66bc142f92085047a1ca64f9a291f0496e33dd98 | 2,986 | kotlin | Apache License 2.0 |
app/src/main/java/com/masterplus/mesnevi/features/books/domain/model/BookInfoEnum.kt | Ramazan713 | 615,289,510 | false | {"Kotlin": 443947} | package com.masterplus.mesnevi.features.books.domain.model
import com.masterplus.mesnevi.R
import com.masterplus.mesnevi.core.domain.util.UiText
enum class BookInfoEnum(val bookId: Int) {
book1(1),
book2(2),
book3(3),
book4(4),
book5(5),
book6(6);
val title: UiText get() {
return UiText.Resource(R.string.n_notebook, listOf(this.bookId.toString()))
}
companion object{
fun fromBookId(bookId: Int): BookInfoEnum{
return when(bookId){
1 -> book1
2 -> book2
3 -> book3
4 -> book4
5 -> book5
6 -> book6
else -> book1
}
}
}
} | 0 | Kotlin | 0 | 0 | 7e29fcb261f1d4b3dc2d23d8ae27f7797da1a2c3 | 725 | Mesnevi | Apache License 2.0 |
src/main/kotlin/com/vermouthx/stocker/views/windows/StockerSettingWindow.kt | WhiteVermouth | 281,630,639 | false | {"Kotlin": 64732, "Java": 20100} | package com.vermouthx.stocker.views.windows
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.bindItem
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.builder.toMutableProperty
import com.intellij.ui.dsl.builder.toNullableProperty
import com.vermouthx.stocker.enums.StockerQuoteColorPattern
import com.vermouthx.stocker.enums.StockerQuoteProvider
import com.vermouthx.stocker.settings.StockerSetting
class StockerSettingWindow : BoundConfigurable("Stocker") {
private val setting = StockerSetting.instance
private var colorPattern: StockerQuoteColorPattern = setting.quoteColorPattern
private var quoteProviderTitle: String = setting.quoteProvider.title
override fun createPanel(): DialogPanel {
return panel {
group("General") {
row("Provider: ") {
comboBox(
StockerQuoteProvider.values()
.map { it.title }).bindItem(::quoteProviderTitle.toNullableProperty())
}
}
group("Appearance") {
buttonsGroup("Color Pattern: ") {
row {
radioButton("Red up and green down", StockerQuoteColorPattern.RED_UP_GREEN_DOWN)
}
row {
radioButton("Green up and red down", StockerQuoteColorPattern.GREEN_UP_RED_DOWN)
}
row {
radioButton("None", StockerQuoteColorPattern.NONE)
}
}.bind(::colorPattern.toMutableProperty(), StockerQuoteColorPattern::class.java)
}
onApply {
setting.quoteProvider = setting.quoteProvider.fromTitle(quoteProviderTitle)
setting.quoteColorPattern = colorPattern
}
onIsModified {
quoteProviderTitle != setting.quoteProvider.title
colorPattern != setting.quoteColorPattern
}
onReset {
quoteProviderTitle = setting.quoteProvider.title
colorPattern = setting.quoteColorPattern
}
}
}
}
| 11 | Kotlin | 12 | 96 | c08547ebd08d465f9d3d46555a89a30cb03e8687 | 2,277 | intellij-investor-dashboard | Apache License 2.0 |
app/src/main/java/com/balanza/android/harrypotter/domain/interactor/character/GetPointsWin.kt | Balanzini | 81,840,050 | false | null | package com.balanza.android.harrypotter.domain.interactor.character
/**
* Created by balanza on 26/02/17.
*/
interface GetPointsWin {
fun getPoints(callbackPoints: (Int, String) -> Unit)
} | 1 | Kotlin | 1 | 4 | 08e7e66516bb968d8c664593b20e2ac70c5c751f | 193 | kotlin-example-master-detail | MIT License |
2022/project/src/test/kotlin/Day05KtTest.kt | ric2b | 159,961,626 | false | {"TypeScript": 144924, "Haskell": 117945, "Kotlin": 97335, "Svelte": 89864, "HTML": 3763, "JavaScript": 3612} | import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class Day05KtTest {
private val testInput =
"""
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
val myInput = this::class.java.classLoader.getResource("day05.txt")!!.readText()
@Test
fun `test part 1 with example`() = assertEquals("CMZ", day05.part1(testInput))
@Test
fun `test part 1 with my input`() = assertEquals("GFTNRBZPF", day05.part1(myInput))
@Test
fun `test part 2 with example`() = assertEquals("MCD", day05.part2(testInput))
@Test
fun `test part 2 with my input`() = assertEquals("VRQWPDSGP", day05.part2(myInput))
} | 0 | TypeScript | 0 | 0 | 04b68836b582c241e6c854b40b6be35d406a2c7e | 867 | advent-of-code | MIT License |
src/me/anno/blocks/multiplayer/Client.kt | AntonioNoack | 354,467,907 | false | null | package me.anno.blocks.multiplayer
import me.anno.blocks.ClientInstance
import me.anno.gpu.GFX
import me.anno.blocks.multiplayer.SendRecvUtils.readName8
import me.anno.blocks.multiplayer.SendRecvUtils.readString8
import me.anno.blocks.multiplayer.SendRecvUtils.writeString8
import me.anno.blocks.multiplayer.Server.Companion.defaultIP
import me.anno.blocks.multiplayer.Server.Companion.defaultPort
import me.anno.blocks.multiplayer.packets.Packet
import me.anno.blocks.multiplayer.packets.PlayerListPacket
import me.anno.blocks.world.World
import me.anno.blocks.world.generator.NothingGenerator
import org.apache.logging.log4j.LogManager
import java.io.DataInputStream
import java.io.DataOutputStream
import java.net.Socket
import kotlin.concurrent.thread
class Client(
name: String,
val ui: ClientInstance,
val ip: String = defaultIP,
val port: Int = defaultPort
) : ServerSideClient(name, getDimension()) {
var playerInfo: List<PlayerListPacket.PlayerInfo>? = null
val position = entity.position
val rotation = entity.rotation
val world = dimension.world
var password = ""
var serverName = ""
var serverMotd = ""
var crashMessage: String? = null
val hasCrashed get() = crashMessage != null
companion object {
fun getDimension() = World().createDimension(NothingGenerator(), "void")
}
fun start(async: Boolean) {
if (async) {
thread(name = "Client"){ start(false) }
return
}
socket = Socket(ip, port)
LOGGER.info("Connected to $ip:$port")
input = DataInputStream(socket.getInputStream())
output = DataOutputStream(socket.getOutputStream())
try {
handshake()
readAllPackets()
} catch (e: Exception) {
crashMessage = e.message ?: e.javaClass.toString()
e.printStackTrace()
close(crashMessage!!)
}
}
fun readAllPackets() {
LOGGER.info("Reading all packets from server")
while (true) {
val packet = Packet.read(input, false)
packet.onClient(this)
}
}
fun handshake() {
serverName = input.readName8()
serverMotd = input.readString8()
LOGGER.info("Connected to $serverName ($serverMotd)")
output.writeString8(this.name)
output.writeString8(this.password)
output.writeLong(GFX.gameTime)
}
private val LOGGER = LogManager.getLogger(Client::class)
} | 0 | Kotlin | 0 | 0 | 007f224334236822ad74ac12954ea506bf5dd8ce | 2,503 | ModCraft | Apache License 2.0 |
jb/src/main/kotlin/system/Platform.kt | TeamCodeStream | 148,423,109 | false | null | package com.codestream.system
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.system.CpuArch
val platform: Platform by lazy {
when {
SystemInfo.isLinux -> when {
CpuArch.isArm64() -> Platform.LINUX_ARM64
else -> Platform.LINUX_X64
}
SystemInfo.isMac -> when {
CpuArch.isArm64() -> Platform.MAC_ARM64
else -> Platform.MAC_X64
}
SystemInfo.isWindows -> when {
CpuArch.isArm64() || CpuArch.isIntel64() -> Platform.WIN_X64
else -> Platform.WIN_32
}
else -> throw IllegalStateException("Unable to detect system platform")
}
}
enum class Platform(val isPosix: Boolean) {
LINUX_X64(true),
LINUX_ARM64(true),
MAC_X64(true),
MAC_ARM64(true),
WIN_X64(false),
WIN_32(false)
}
| 21 | null | 182 | 930 | 3989ca8f40ab33312f32887bf390262323676b5e | 849 | codestream | Apache License 2.0 |
app/src/main/kotlin/mobi/cwiklinski/smsbyt/network/Api.kt | emce | 87,217,045 | false | null | package mobi.cwiklinski.smsbyt.network
import mobi.cwiklinski.smsbyt.model.telegram.Message
import mobi.cwiklinski.smsbyt.model.telegram.TextMessage
import retrofit2.http.Body
import retrofit2.http.POST
import rx.Single
interface Api {
@POST("sendMessage")
fun sendMessage(@Body message: TextMessage): Single<Message>
@POST("getUpdates")
fun getUpdates(): Single<List<Message>>
} | 0 | Kotlin | 0 | 0 | 2374667819fa345802c1d03221672bb1aa1c4ac4 | 400 | smsbyt | Apache License 2.0 |
app/src/main/java/com/ae/apps/c19counter/data/business/SummaryConsumer.kt | midhunhk | 293,998,083 | false | null | package com.ae.apps.c19counter.data.business
import com.ae.apps.c19counter.data.models.Code
import com.ae.apps.c19counter.data.models.Summary
/**
* Interface for implementing callback for reading Summary
*/
interface SummaryConsumer {
/**
* Callback method when a summary is read
*/
fun onSummaryRead(summary: Summary)
/**
*
*/
fun addPlace(code: Code)
/**
*
*/
fun removePlace(code: Code)
/**
* Callback when an error occurred while requesting for the data
*/
fun onRequestError(message:String)
} | 0 | Kotlin | 0 | 1 | 0fd8d9143d2ab235b124a5c3af05380cbeb90c75 | 577 | c19-counter-app | MIT License |
app/src/main/java/com/samuelokello/kazihub/presentation/business/home/components/StatsCard.kt | OkelloSam21 | 749,782,789 | false | {"Kotlin": 278163} | package com.samuelokello.kazihub.presentation.business.home.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ShoppingBag
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.samuelokello.kazihub.ui.theme.primaryLight
@Composable
fun StatsCard(
statIcon: @Composable () -> Unit,
title: String,
value: String,
) {
val containerColor: Color = primaryLight
val contentColor: Color = Color.White
Box(
modifier = Modifier
.size(width = 200.dp, height = 120.dp),
contentAlignment = Alignment.Center
) {
Card(
modifier = Modifier
.fillMaxSize(),
colors = CardDefaults.cardColors(
containerColor = containerColor,
contentColor = contentColor
),
elevation = CardDefaults.elevatedCardElevation(
defaultElevation = 4.dp
),
shape = RoundedCornerShape(10.dp)
) {
Column (
modifier = Modifier
.padding(horizontal = 26.dp, vertical = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
statIcon()
Spacer(modifier = Modifier.height(8.dp))
Text(text = title, style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(8.dp))
Text(text = value, style = MaterialTheme.typography.bodyLarge)
}
}
}
}
@Preview(showBackground = true)
@Composable
private fun StatsCardPreview() {
StatsCard(
statIcon = { Icons.Default.ShoppingBag},
title = "Total Expenditure",
value = "Ksh 100,000",
)
} | 0 | Kotlin | 0 | 0 | 510745d20b259d7930fa58481181080fd70a4a9f | 2,661 | KaziHub | MIT License |
kmp-observableviewmodel-core/src/nonAndroidxMain/kotlin/com/rickclephas/kmp/observableviewmodel/Closeables.kt | rickclephas | 568,920,097 | false | null | package com.rickclephas.kmp.observableviewmodel
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
/**
* A collection of [AutoCloseable]s behaving similar to the
* [AndroidX ViewModel implementation](https://cs.android.com/androidx/platform/frameworks/support/+/58618bec2592c538b0a9e469f1492365ef2233e3:lifecycle/lifecycle-viewmodel/src/commonMain/kotlin/androidx/lifecycle/viewmodel/internal/ViewModelImpl.kt).
*/
internal class Closeables(
private val closeables: MutableSet<AutoCloseable> = mutableSetOf(),
private val keyedCloseables: MutableMap<String, AutoCloseable> = mutableMapOf()
): SynchronizedObject(), AutoCloseable {
private var isClosed = false
operator fun plusAssign(closeable: AutoCloseable): Unit = synchronized(this) {
if (isClosed) {
closeWithRuntimeException(closeable)
return
}
closeables += closeable
}
operator fun set(key: String, closeable: AutoCloseable): Unit = synchronized(this) {
if (isClosed) {
closeWithRuntimeException(closeable)
return
}
closeWithRuntimeException(keyedCloseables.put(key, closeable))
}
operator fun get(key: String): AutoCloseable? = synchronized(this) {
keyedCloseables[key]
}
override fun close(): Unit = synchronized(this) {
if (isClosed) return
isClosed = true
for (closeable in keyedCloseables.values) {
closeWithRuntimeException(closeable)
}
for (closeable in closeables) {
closeWithRuntimeException(closeable)
}
closeables.clear()
}
private fun closeWithRuntimeException(closeable: AutoCloseable?) {
try {
closeable?.close()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
| 8 | null | 28 | 578 | 805c41ff1305b02909c3b50a7e34a46b3c029c04 | 1,878 | KMP-ObservableViewModel | MIT License |
src/main/kotlin/brightpspark/edsmbot/listener/JDAEventListener.kt | thebrightspark | 257,715,389 | false | null | package brightpspark.edsmbot.listener
import brightpspark.edsmbot.command.DiscordContext
import bvanseg.kotlincommons.any.getLogger
import bvanseg.kotlincommons.armada.CommandManager
import net.dv8tion.jda.api.OnlineStatus
import net.dv8tion.jda.api.events.ReadyEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.hooks.SubscribeEvent
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
/**
* Class for JDA event listeners.
* This is where we set the bot status to [OnlineStatus.ONLINE] once JDA is ready, and listen for messages to send them
* to our Armada [CommandManager] for processing.
*
* @author bright_spark
*/
@Component
class JDAEventListener {
private val log = getLogger()
@Autowired
private lateinit var commandManager: CommandManager<Long>
@SubscribeEvent
fun onReady(event: ReadyEvent) {
log.info("JDA ready with ${event.guildAvailableCount} / ${event.guildTotalCount} guilds!")
// The bot is now ready, so set the status to ONLINE
event.jda.presence.setStatus(OnlineStatus.ONLINE)
}
@SubscribeEvent
fun onMessage(event: MessageReceivedEvent) {
val author = event.author
// Ensure we're not handling commands from bots
if (author.isBot) return
val raw = event.message.contentRaw
log.debug("Received command from $author: $raw")
try {
// Send the message to the Armada command manager
commandManager.execute(raw, DiscordContext(event))
} catch (e: Exception) {
log.error("Error executing command '$raw'", e)
}
}
}
| 0 | Kotlin | 0 | 0 | d312271becf07475b30d6d72a96deacdc2049a75 | 1,582 | EDSM-Bot | MIT License |
src/main/kotlin/pcimcioch/gitlabci/dsl/serializer/StringRepresentationSerializer.kt | pcimcioch | 247,550,225 | false | null | package pcimcioch.gitlabci.dsl.serializer
import kotlinx.serialization.*
import pcimcioch.gitlabci.dsl.StringRepresentation
open class StringRepresentationSerializer<T : StringRepresentation>(
val name: String
) : KSerializer<T> {
override val descriptor: SerialDescriptor = PrimitiveDescriptor(name, PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: T) {
encoder.encodeString(value.stringRepresentation)
}
override fun deserialize(decoder: Decoder): T {
throw IllegalStateException(descriptor.serialName)
}
} | 0 | Kotlin | 3 | 8 | 143addd240588a70988bb1c23c2d5155eb1701ce | 577 | gitlab-ci-kotlin-dsl | Apache License 2.0 |
provider-plugin-kcp/src/main/kotlin/com/g985892345/provider/plugin/kcp/KtProviderGradlePlugin.kt | 985892345 | 657,472,390 | false | {"Kotlin": 54982} | package com.g985892345.provider.plugin.kcp
import com.google.auto.service.AutoService
import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
import org.jetbrains.kotlin.compiler.plugin.CliOption
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.CompilerConfigurationKey
import java.io.File
/**
* .
*
* @author 985892345
* 2023/6/13 23:04
*/
@AutoService(CommandLineProcessor::class)
@OptIn(ExperimentalCompilerApi::class)
class KtProviderGradlePlugin : CommandLineProcessor {
companion object {
private const val OPTION_IS_CHECK_IMPL = "isCheckImpl"
private const val OPTION_CACHE_PATH = "cachePath"
private const val OPTION_INITIALIZER_CLASS = "initializerClass"
val ARG_IS_CHECK_IMPL = CompilerConfigurationKey<Boolean>(OPTION_IS_CHECK_IMPL)
val ARG_CACHE_PATH = CompilerConfigurationKey<File>(OPTION_CACHE_PATH)
val ARG_INITIALIZER_CLASS = CompilerConfigurationKey<String>(OPTION_INITIALIZER_CLASS)
}
override val pluginId: String = BuildConfig.PLUGIN_ID
override val pluginOptions: Collection<AbstractCliOption> = listOf(
CliOption(
optionName = OPTION_IS_CHECK_IMPL,
valueDescription = "boolean",
description = "是否检查被注解类是注解中标注参数的实现类(默认开启)",
required = false
),
CliOption(
optionName = OPTION_CACHE_PATH,
valueDescription = "String",
description = "缓存目录的路径,用于保存开启增量编译后需要编译信息",
required = true
),
CliOption(
optionName = OPTION_INITIALIZER_CLASS,
valueDescription = "String",
description = "KtProviderInitializer 的实现类全称,用于 ir 插桩",
required = true
),
)
override fun processOption(option: AbstractCliOption, value: String, configuration: CompilerConfiguration) {
when (option.optionName) {
OPTION_IS_CHECK_IMPL -> configuration.put(ARG_IS_CHECK_IMPL, value.toBooleanStrictOrNull() ?: true)
OPTION_CACHE_PATH -> configuration.put(ARG_CACHE_PATH, File(value))
OPTION_INITIALIZER_CLASS -> configuration.put(ARG_INITIALIZER_CLASS, value)
}
}
} | 0 | Kotlin | 0 | 4 | f4cbb66013ce3d6721eddf9ef2164823b02b9064 | 2,197 | KtProvider | Apache License 2.0 |
BooksApp/app/src/main/java/com/canerture/booksapp/ui/login/signin/SignInFragmentViewModel.kt | Android-Student-Club-Turkey | 433,017,579 | false | {"Kotlin": 88163} | package com.canerture.booksapp.ui.login.signin
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.canerture.booksapp.data.repos.UsersRepository
class SignInFragmentViewModel : ViewModel() {
private var usersRepo = UsersRepository()
private var _isSignIn = MutableLiveData<Boolean>()
val isSignIn: LiveData<Boolean>
get() = _isSignIn
init {
_isSignIn = usersRepo.getIsSignIn()
}
fun signIn(eMail: String, password: String) {
usersRepo.signIn(eMail, password)
}
} | 0 | Kotlin | 0 | 4 | ea92fd2c051d98329680a12f1afa95857346d5b8 | 593 | Android-Project-Examples | MIT License |
sdk/src/test/java/com/qonversion/android/sdk/requests/queue/RequestQueueTest.kt | suriksarkisyan | 422,569,073 | false | {"Gemfile.lock": 1, "Gradle": 4, "Java Properties": 3, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Ruby": 2, "YAML": 1, "Proguard": 3, "JSON": 2, "Kotlin": 70, "XML": 15, "Java": 11} | package com.qonversion.android.sdk.requests.queue
import com.qonversion.android.sdk.RequestsQueue
import com.qonversion.android.sdk.logger.StubLogger
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class RequestQueueTest {
@Test
fun addOneRequestTest() {
val queue = RequestsQueue(StubLogger())
queue.add(Util.QONVERSION_REQUEST)
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(1, queue.size())
}
@Test
fun addAndPollOneRequestTest() {
val queue = RequestsQueue(StubLogger())
queue.add(Util.QONVERSION_REQUEST)
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(1, queue.size())
queue.poll()
Assert.assertTrue(queue.isEmpty())
Assert.assertEquals(0, queue.size())
}
@Test
fun addAndPollManyRequestTest() {
val queue = RequestsQueue(StubLogger())
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(5, queue.size())
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(4, queue.size())
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(3, queue.size())
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(2, queue.size())
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(1, queue.size())
queue.poll()
Assert.assertTrue(queue.isEmpty())
Assert.assertEquals(0, queue.size())
}
@Test
fun addAndPollMixManyRequestTest() {
val queue = RequestsQueue(StubLogger())
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(2, queue.size())
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(1, queue.size())
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(3, queue.size())
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(2, queue.size())
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
queue.add(Util.QONVERSION_REQUEST)
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(7, queue.size())
queue.poll()
queue.poll()
queue.poll()
Assert.assertFalse(queue.isEmpty())
Assert.assertEquals(4, queue.size())
}
} | 1 | Kotlin | 0 | 0 | c143fc35aefa73cf409634f719039110486f5981 | 3,019 | TestRep | MIT License |
codegen-server/python/src/main/kotlin/software/amazon/smithy/rust/codegen/server/python/smithy/PythonType.kt | awslabs | 308,027,791 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rust.codegen.server.python.smithy
import software.amazon.smithy.rust.codegen.core.rustlang.RustType
/**
* A hierarchy of Python types handled by Smithy codegen.
*
* Mostly copied from [RustType] and modified for Python accordingly.
*/
sealed class PythonType {
/**
* A Python type that contains [member], another [PythonType].
* Used to generically operate over shapes that contain other shape.
*/
sealed interface Container {
val member: PythonType
val namespace: String?
val name: String
}
/**
* Name refers to the top-level type for import purposes.
*/
abstract val name: String
open val namespace: String? = null
object None : PythonType() {
override val name: String = "None"
}
object Bool : PythonType() {
override val name: String = "bool"
}
object Int : PythonType() {
override val name: String = "int"
}
object Float : PythonType() {
override val name: String = "float"
}
object Str : PythonType() {
override val name: String = "str"
}
object Any : PythonType() {
override val name: String = "Any"
override val namespace: String = "typing"
}
data class List(override val member: PythonType) : PythonType(), Container {
override val name: String = "List"
override val namespace: String = "typing"
}
data class Dict(val key: PythonType, override val member: PythonType) : PythonType(), Container {
override val name: String = "Dict"
override val namespace: String = "typing"
}
data class Set(override val member: PythonType) : PythonType(), Container {
override val name: String = "Set"
override val namespace: String = "typing"
}
data class Optional(override val member: PythonType) : PythonType(), Container {
override val name: String = "Optional"
override val namespace: String = "typing"
}
data class Awaitable(override val member: PythonType) : PythonType(), Container {
override val name: String = "Awaitable"
override val namespace: String = "typing"
}
data class Callable(val args: kotlin.collections.List<PythonType>, val rtype: PythonType) : PythonType() {
override val name: String = "Callable"
override val namespace: String = "typing"
}
data class Union(val args: kotlin.collections.List<PythonType>) : PythonType() {
override val name: String = "Union"
override val namespace: String = "typing"
}
data class Opaque(override val name: String, val rustNamespace: String? = null) : PythonType() {
// Since Python doesn't have a something like Rust's `crate::` we are using a custom placeholder here
// and in our stub generation script we will replace placeholder with the real root module name.
private val pythonRootModulePlaceholder = "__root_module_name__"
override val namespace: String? = rustNamespace?.split("::")?.joinToString(".") {
when (it) {
"crate" -> pythonRootModulePlaceholder
// In Python, we expose submodules from `aws_smithy_http_server_python`
// like `types`, `middleware`, `tls` etc. from `__root_module__name`
"aws_smithy_http_server_python" -> pythonRootModulePlaceholder
else -> it
}
}
}
}
/**
* Return corresponding [PythonType] for a [RustType].
*/
fun RustType.pythonType(): PythonType =
when (this) {
is RustType.Unit -> PythonType.None
is RustType.Bool -> PythonType.Bool
is RustType.Float -> PythonType.Float
is RustType.Integer -> PythonType.Int
is RustType.String -> PythonType.Str
is RustType.Vec -> PythonType.List(this.member.pythonType())
is RustType.Slice -> PythonType.List(this.member.pythonType())
is RustType.HashMap -> PythonType.Dict(this.key.pythonType(), this.member.pythonType())
is RustType.HashSet -> PythonType.Set(this.member.pythonType())
is RustType.Reference -> this.member.pythonType()
is RustType.Option -> PythonType.Optional(this.member.pythonType())
is RustType.Box -> this.member.pythonType()
is RustType.Dyn -> this.member.pythonType()
is RustType.Opaque -> PythonType.Opaque(this.name, this.namespace)
// TODO(Constraints): How to handle this?
// Revisit as part of https://github.com/awslabs/smithy-rs/issues/2114
is RustType.MaybeConstrained -> this.member.pythonType()
}
/**
* Render this type, including references and generic parameters.
* It generates something like `typing.Dict[String, String]`.
*/
fun PythonType.render(fullyQualified: Boolean = true): String {
val namespace = if (fullyQualified) {
this.namespace?.let { "$it." } ?: ""
} else {
""
}
val base = when (this) {
is PythonType.None -> this.name
is PythonType.Bool -> this.name
is PythonType.Float -> this.name
is PythonType.Int -> this.name
is PythonType.Str -> this.name
is PythonType.Any -> this.name
is PythonType.Opaque -> this.name
is PythonType.List -> "${this.name}[${this.member.render(fullyQualified)}]"
is PythonType.Dict -> "${this.name}[${this.key.render(fullyQualified)}, ${this.member.render(fullyQualified)}]"
is PythonType.Set -> "${this.name}[${this.member.render(fullyQualified)}]"
is PythonType.Awaitable -> "${this.name}[${this.member.render(fullyQualified)}]"
is PythonType.Optional -> "${this.name}[${this.member.render(fullyQualified)}]"
is PythonType.Callable -> {
val args = this.args.joinToString(", ") { it.render(fullyQualified) }
val rtype = this.rtype.render(fullyQualified)
"${this.name}[[$args], $rtype]"
}
is PythonType.Union -> {
val args = this.args.joinToString(", ") { it.render(fullyQualified) }
"${this.name}[$args]"
}
}
return "$namespace$base"
}
/**
* Renders [PythonType] with proper escaping for Docstrings.
*/
fun PythonType.renderAsDocstring(): String =
this.render()
.replace("[", "\\[")
.replace("]", "\\]")
| 317 | Rust | 119 | 306 | d14357c2e210e6f0681ef8ed189b5b45b80431ef | 6,480 | smithy-rs | Apache License 2.0 |
app/src/main/java/com/fakhir/mobile/todolistcompose/common/composable/CardComposable.kt | fakhirsh | 580,681,070 | false | null | package com.fakhir.mobile.todolistcompose.common.composable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.fakhir.mobile.todolistcompose.common.ext.dropdownSelector
@Composable
fun DangerousCardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
modifier: Modifier,
onEditClick: () -> Unit
) {
CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.primary, modifier)
}
@Composable
fun RegularCardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
modifier: Modifier,
onEditClick: () -> Unit
) {
CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.onSurface, modifier)
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun CardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
onEditClick: () -> Unit,
highlightColor: Color,
modifier: Modifier
) {
Card(
backgroundColor = MaterialTheme.colors.onPrimary,
modifier = modifier,
onClick = onEditClick
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(16.dp)
) {
Column(modifier = Modifier.weight(1f)) { Text(stringResource(title), color = highlightColor) }
if (content.isNotBlank()) {
Text(text = content, modifier = Modifier.padding(16.dp, 0.dp))
}
Icon(painter = painterResource(icon), contentDescription = "Icon", tint = highlightColor)
}
}
}
@Composable
fun CardSelector(
@StringRes label: Int,
options: List<String>,
selection: String,
modifier: Modifier,
onNewValue: (String) -> Unit
) {
Card(backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier) {
DropdownSelector(label, options, selection, Modifier.dropdownSelector(), onNewValue)
}
} | 0 | Kotlin | 0 | 0 | 0448de32ccd5bd9bb6b5969f8cb6c3f7bd33c7b6 | 2,481 | ToDoListCompose | MIT License |
app/src/main/java/com/danielpriddle/drpnews/viewmodels/ArticleSearchViewModel.kt | DPriddle96 | 529,001,714 | false | {"Kotlin": 83827} | package com.danielpriddle.drpnews.viewmodels
import com.danielpriddle.drpnews.data.models.Article
import com.danielpriddle.drpnews.data.repository.ArticleRepository
import com.danielpriddle.drpnews.utils.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ArticleSearchViewModel @Inject constructor(
private val articleRepository: ArticleRepository,
) : Logger {
private val _articles = MutableStateFlow<List<Article>>(mutableListOf())
val articles: StateFlow<List<Article>> = _articles
fun searchArticles(searchString: String) {
CoroutineScope(IO).launch {
if (searchString.isEmpty()) {
_articles.value = mutableListOf()
} else {
val filteredArticles = articleRepository.searchArticles("%$searchString%")
_articles.value = filteredArticles
}
}
}
} | 0 | Kotlin | 0 | 0 | 4438f071a550c6acd62ef2af7197331031b2eb83 | 1,106 | DRPNews | MIT License |
bungie/src/main/kotlin/pl/nanoray/glint/bungie/api/model/DestinyStatDisplayDefinition.kt | Nanoray-pl | 363,267,648 | false | null | package pl.nanoray.glint.bungie.api.model
import kotlinx.serialization.Serializable
import pl.nanoray.glint.bungie.api.model.custom.ManifestId
@Serializable
data class DestinyStatDisplayDefinition(
val statHash: ManifestId<DestinyStatDefinition>,
val maximumValue: Int,
val displayAsNumeric: Boolean
) | 10 | Kotlin | 0 | 0 | 7b55e33873341bd201b8d068b6c51fbefe664af3 | 315 | Glint | Apache License 2.0 |
app/src/main/java/io/github/skywalkerdarren/simpleaccounting/util/network/Address.kt | nidhinmp | 598,363,579 | true | {"Java Properties": 2, "Shell": 1, "Markdown": 3, "Batchfile": 1, "Proguard": 1, "Java": 43, "Kotlin": 81} | package io.github.skywalkerdarren.simpleaccounting.util.network
object Address {
const val apiLayer = "http://apilayer.net/"
} | 0 | null | 0 | 0 | 485e94dbca4a4b2c02f90fd35a410c8d23eab227 | 131 | SimpleAccounting | MIT License |
core/src/main/kotlin/com/icecreamqaq/yuq/util/MessageUtil.kt | YuQWorks | 272,461,974 | false | {"Kotlin": 136421, "Java": 1296} | package com.icecreamqaq.yuq.util
import com.icecreamqaq.yuq.message.Message
import com.icecreamqaq.yuq.message.Message.Companion.firstString
import com.icecreamqaq.yuq.message.Message.Companion.toChain
import com.icecreamqaq.yuq.message.Message.Companion.toMessage
import com.icecreamqaq.yuq.message.Message.Companion.toMessageByRainCode
import com.icecreamqaq.yuq.message.Text.Companion.toText
class MessageUtil {
companion object{
@JvmStatic
fun stringToText(string: String) = string.toText()
@JvmStatic
fun stringToChain(string: String) = string.toChain()
@JvmStatic
fun stringToMessageByRainCode(rainCodeString: String) = rainCodeString.toMessageByRainCode()
@JvmStatic
fun stringToMessage(string: String) = string.toMessage()
@JvmStatic
fun firstString(message: Message) = message.firstString()
}
} | 11 | Kotlin | 7 | 59 | 36e2e6d991125c8fc0763922df8d5fd813ff6cb8 | 899 | YuQ | Apache License 2.0 |
app/src/main/java/de/drtobiasprinz/summitbook/ui/SwipeToDeleteCallback.kt | prinztob | 370,702,913 | false | null | package de.drtobiasprinz.summitbook.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import de.drtobiasprinz.summitbook.R
import de.drtobiasprinz.summitbook.adapter.SummitViewAdapter
import java.util.*
class SwipeToDeleteCallback(private val mAdapter: SummitViewAdapter, val context: Context, val mRecyclerView: RecyclerView) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
private val icon: Drawable?
private val background: ColorDrawable
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
val entry = mAdapter.getItem(position)
if (entry != null) {
mAdapter.showDeleteEntryDialog(context, entry, mRecyclerView)
}
}
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
super.onChildDraw(c, recyclerView, viewHolder, dX,
dY, actionState, isCurrentlyActive)
val itemView = viewHolder.itemView
val backgroundCornerOffset = 20
val iconMargin = (itemView.height - icon!!.intrinsicHeight) / 2
val iconTop = itemView.top + (itemView.height - icon.intrinsicHeight) / 2
val iconBottom = iconTop + icon.intrinsicHeight
if (dX > 0) { // Swiping to the right
val iconLeft = itemView.left + iconMargin + icon.intrinsicWidth
val iconRight = itemView.left + iconMargin
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
background.setBounds(itemView.left, itemView.top,
itemView.left + dX.toInt() + backgroundCornerOffset,
itemView.bottom)
} else if (dX < 0) { // Swiping to the left
val iconLeft = itemView.right - iconMargin - icon.intrinsicWidth
val iconRight = itemView.right - iconMargin
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
background.setBounds(itemView.right + dX.toInt() - backgroundCornerOffset,
itemView.top, itemView.right, itemView.bottom)
} else { // view is unSwiped
background.setBounds(0, 0, 0, 0)
}
background.draw(c)
icon.draw(c)
}
init {
icon = ContextCompat.getDrawable(Objects.requireNonNull(context),
R.drawable.ic_delete_black_24dp)
background = ColorDrawable(Color.RED)
}
} | 0 | Kotlin | 0 | 0 | 5234dc025e3732ebc85100645c575ac98be090da | 2,966 | summitbook | MIT License |
app/src/main/java/dev/sertan/android/paper/ui/addnote/AddNoteFragment.kt | scnplt | 385,908,880 | false | null | package dev.sertan.android.paper.ui.addnote
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import dev.sertan.android.paper.R
import dev.sertan.android.paper.databinding.FragmentAddNoteBinding
import dev.sertan.android.paper.ui.common.BaseFragment
import dev.sertan.android.paper.ui.main.MainActivity
@AndroidEntryPoint
internal class AddNoteFragment : BaseFragment<FragmentAddNoteBinding>() {
private val viewModel by viewModels<AddNoteViewModel>()
override fun getLayoutRes(): Int = R.layout.fragment_add_note
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = viewModel
(requireActivity() as? MainActivity)?.onFabClicked { viewModel.save(view) }
}
}
| 0 | Kotlin | 0 | 0 | e64ff251d9d3a3cf85b078ee40c0648504f53682 | 871 | paper | MIT License |
app/src/main/java/com/dluvian/nozzle/data/room/dao/PostDao.kt | dluvian | 645,936,540 | false | null | package com.dluvian.nozzle.data.room.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.MapInfo
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.RewriteQueriesToDropUnusedColumns
import androidx.room.Transaction
import com.dluvian.nozzle.data.nostr.utils.EncodingUtils
import com.dluvian.nozzle.data.room.entity.HashtagEntity
import com.dluvian.nozzle.data.room.entity.MentionEntity
import com.dluvian.nozzle.data.room.entity.PostEntity
import com.dluvian.nozzle.data.room.entity.RepostEntity
import com.dluvian.nozzle.data.room.helper.extended.PostEntityExtended
import com.dluvian.nozzle.data.utils.UrlUtils.isWebsocketUrl
import com.dluvian.nozzle.data.utils.escapeSQLPercentChars
import com.dluvian.nozzle.model.MentionedPost
import com.dluvian.nozzle.model.NoteId
import com.dluvian.nozzle.model.nostr.Event
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
@Dao
interface PostDao {
suspend fun getMainFeedBasePosts(
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
authorPubkeys: Collection<String>?,
relays: Collection<String>?,
until: Long,
limit: Int,
): List<PostEntity> {
// TODO: Combine it into single query.
// Currently not possible because the null check will make the query too long
return if (authorPubkeys == null && relays == null) {
internalGetGlobalFeedBasePosts(
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
until = until,
limit = limit
)
} else if (!authorPubkeys.isNullOrEmpty() && relays == null) {
internalGetAuthoredGlobalFeedBasePosts(
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
authorPubkeys = authorPubkeys,
until = until,
limit = limit
)
} else if (authorPubkeys == null && !relays.isNullOrEmpty()) {
internalGetRelayedGlobalFeedBasePosts(
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
relays = relays,
until = until,
limit = limit
)
} else {
if (authorPubkeys!!.isEmpty() || relays!!.isEmpty()) emptyList()
else internalGetMainFeedBasePosts(
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
authorPubkeys = authorPubkeys,
relays = relays,
until = until,
limit = limit
)
}
}
@Query(
"SELECT * " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND createdAt < :until " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"AND pubkey IN (:authorPubkeys) " +
"AND id IN (SELECT DISTINCT eventId FROM eventRelay WHERE relayUrl IN (:relays)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit"
)
suspend fun internalGetMainFeedBasePosts(
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
authorPubkeys: Collection<String>,
relays: Collection<String>,
until: Long,
limit: Int,
): List<PostEntity>
@Query(
"SELECT * " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND createdAt < :until " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit"
)
suspend fun internalGetGlobalFeedBasePosts(
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
until: Long,
limit: Int,
): List<PostEntity>
@Query(
"SELECT * " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND createdAt < :until " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"AND pubkey IN (:authorPubkeys) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit"
)
suspend fun internalGetAuthoredGlobalFeedBasePosts(
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
authorPubkeys: Collection<String>,
until: Long,
limit: Int,
): List<PostEntity>
@Query(
"SELECT * " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND createdAt < :until " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"AND id IN (SELECT DISTINCT eventId FROM eventRelay WHERE relayUrl IN (:relays)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit"
)
suspend fun internalGetRelayedGlobalFeedBasePosts(
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
relays: Collection<String>,
until: Long,
limit: Int,
): List<PostEntity>
fun getNumOfNewMainFeedPostsFlow(
oldPostIds: List<String>,
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
authorPubkeys: Collection<String>?,
relays: Collection<String>?,
limit: Int,
): Flow<Int> {
return if (authorPubkeys == null && relays == null) {
internalGetNumOfNewGlobalFeedPostsFlow(
oldPostIds = oldPostIds,
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
limit = limit,
)
} else if (!authorPubkeys.isNullOrEmpty() && relays == null) {
internalGetNumOfNewAuthoredGlobalFeedPostsFlow(
oldPostIds = oldPostIds,
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
authorPubkeys = authorPubkeys,
limit = limit
)
} else if (authorPubkeys == null && !relays.isNullOrEmpty()) {
internalGetNumOfNewRelayedGlobalPostsFlow(
oldPostIds = oldPostIds,
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
relays = relays,
limit = limit
)
} else {
if (authorPubkeys!!.isEmpty() || relays!!.isEmpty()) flowOf(0)
else internalGetNumOfNewMainFeedPostsFlow(
oldPostIds = oldPostIds,
isPosts = isPosts,
isReplies = isReplies,
hashtag = hashtag,
authorPubkeys = authorPubkeys,
relays = relays,
limit = limit
)
}
}
@Query(
"SELECT COUNT(*) " +
"FROM (" +
"SELECT id " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"AND pubkey IN (:authorPubkeys) " +
"AND id IN (SELECT DISTINCT eventId FROM eventRelay WHERE relayUrl IN (:relays)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit" +
") " +
"WHERE id NOT IN (:oldPostIds)"
)
fun internalGetNumOfNewMainFeedPostsFlow(
oldPostIds: List<String>,
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
authorPubkeys: Collection<String>,
relays: Collection<String>,
limit: Int,
): Flow<Int>
@Query(
"SELECT COUNT(*) " +
"FROM (SELECT id " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit" +
") " +
"WHERE id NOT IN (:oldPostIds)"
)
fun internalGetNumOfNewGlobalFeedPostsFlow(
oldPostIds: List<String>,
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
limit: Int
): Flow<Int>
@Query(
"SELECT COUNT(*) " +
"FROM (SELECT id " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"AND pubkey IN (:authorPubkeys) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit" +
") " +
"WHERE id NOT IN (:oldPostIds)"
)
fun internalGetNumOfNewAuthoredGlobalFeedPostsFlow(
oldPostIds: List<String>,
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
authorPubkeys: Collection<String>,
limit: Int
): Flow<Int>
@Query(
"SELECT COUNT(*) " +
"FROM (SELECT id " +
"FROM post " +
"WHERE ((:isReplies AND replyToId IS NOT NULL) OR (:isPosts AND replyToId IS NULL)) " +
"AND (:hashtag IS NULL OR id IN (SELECT eventId FROM hashtag WHERE hashtag = :hashtag)) " +
"AND id IN (SELECT DISTINCT eventId FROM eventRelay WHERE relayUrl IN (:relays)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit" +
") " +
"WHERE id NOT IN (:oldPostIds)"
)
fun internalGetNumOfNewRelayedGlobalPostsFlow(
oldPostIds: List<String>,
isPosts: Boolean,
isReplies: Boolean,
hashtag: String?,
relays: Collection<String>,
limit: Int,
): Flow<Int>
@Query(
"SELECT * " +
"FROM post " +
"WHERE createdAt < :until " +
"AND (id IN (SELECT eventId FROM mention WHERE pubkey = (SELECT pubkey FROM account WHERE isActive = 1)) " +
" AND pubkey != (SELECT pubkey FROM account WHERE isActive = 1)" +
") " +
"AND id IN (SELECT DISTINCT eventId FROM eventRelay WHERE relayUrl IN (:relays)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit"
)
suspend fun getInboxPosts(
relays: Collection<String>,
until: Long,
limit: Int,
): List<PostEntity>
@Query(
"SELECT COUNT(*) " +
"FROM (" +
"SELECT id " +
"FROM post " +
"WHERE id IN (SELECT DISTINCT eventId FROM eventRelay WHERE relayUrl IN (:relays)) " +
"AND (id IN (SELECT eventId FROM mention WHERE pubkey = (SELECT pubkey FROM account WHERE isActive = 1)) " +
" AND pubkey != (SELECT pubkey FROM account WHERE isActive = 1)" +
") " +
"ORDER BY createdAt DESC " +
"LIMIT :limit" +
") " +
"WHERE id NOT IN (:oldPostIds)"
)
fun getNumOfNewInboxPostsFlow(
oldPostIds: List<String>,
relays: Collection<String>,
limit: Int
): Flow<Int>
@Query(
"SELECT * " +
"FROM post " +
"WHERE createdAt < :until " +
"AND id IN (SELECT eventId FROM reaction WHERE pubkey = (SELECT pubkey FROM account WHERE isActive = 1)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit"
)
suspend fun getLikedPosts(
until: Long,
limit: Int,
): List<PostEntity>
@Query(
"SELECT COUNT(*) " +
"FROM (" +
"SELECT id " +
"FROM post " +
"WHERE id IN (SELECT eventId FROM reaction WHERE pubkey = (SELECT pubkey FROM account WHERE isActive = 1)) " +
"ORDER BY createdAt DESC " +
"LIMIT :limit" +
") " +
"WHERE id NOT IN (:oldPostIds)"
)
fun getNumOfNewLikedPostsFlow(
oldPostIds: List<String>,
limit: Int
): Flow<Int>
@Query(
// SELECT PostEntity
"SELECT mainPost.*, " +
// SELECT likedByMe
"(SELECT eventId IS NOT NULL " +
"FROM reaction " +
"WHERE eventId = mainPost.id AND pubkey = (SELECT pubkey FROM account WHERE isActive = 1)) " +
"AS isLikedByMe, " +
// SELECT name
"mainProfile.name, " +
// SELECT numOfReplies
"(SELECT COUNT(*) FROM post WHERE post.replyToId = mainPost.id) " +
"AS numOfReplies, " +
// SELECT replyToPubkey
"(SELECT post.pubkey " +
"FROM post " +
"WHERE post.id = mainPost.replyToId) " +
"AS replyToPubkey, " +
// SELECT replyToName
"(SELECT profile.name " +
"FROM profile " +
"JOIN post " +
"ON (profile.pubkey = post.pubkey AND post.id = mainPost.replyToId)) " +
"AS replyToName " +
// PostEntity
"FROM post AS mainPost " +
// Join author
"LEFT JOIN profile AS mainProfile " +
"ON mainPost.pubkey = mainProfile.pubkey " +
// Conditioned by ids
"WHERE mainPost.id IN (:postIds) " +
"ORDER BY createdAt DESC "
)
fun listExtendedPostsFlow(postIds: Collection<String>): Flow<List<PostEntityExtended>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertOrIgnore(vararg posts: PostEntity)
@Transaction
suspend fun insertWithHashtagsAndMentions(
events: Collection<Event>,
hashtagDao: HashtagDao,
mentionDao: MentionDao,
) {
val postEvents = events.filter { it.isPost() }
if (postEvents.isEmpty()) return
val posts = postEvents.map { PostEntity.fromEvent(it) }
insertOrIgnore(*posts.toTypedArray())
val hashtags = postEvents.flatMap { HashtagEntity.fromEvent(it) }
if (hashtags.isNotEmpty()) {
hashtagDao.insertOrIgnore(*hashtags.toTypedArray())
}
val mentions = postEvents.flatMap { MentionEntity.fromEvent(it) }
if (mentions.isNotEmpty()) {
mentionDao.insertOrIgnore(*mentions.toTypedArray())
}
}
@Transaction
suspend fun insertRepost(events: Collection<Event>, repostDao: RepostDao) {
val reposts = events
.filter { it.isRepost() }
.mapNotNull {
val repostedId = it.getRepostedId() ?: return@mapNotNull null
val relay = it.getRepostedRelayUrlHint()
val neventUri = EncodingUtils.createNeventUri(
postId = repostedId,
relays = if (relay.isNullOrBlank() || !relay.isWebsocketUrl()) emptyList()
else listOf(relay)
) ?: return@mapNotNull null
PostEntity
.fromEvent(it)
.copy(content = neventUri, replyToId = null, replyRelayHint = null)
}
if (reposts.isEmpty()) return
val repostEntities = reposts.map { RepostEntity(eventId = it.id) }
insertOrIgnore(*reposts.toTypedArray())
repostDao.insertOrIgnore(*repostEntities.toTypedArray())
}
@Query("SELECT * FROM post WHERE id = :id")
suspend fun getPost(id: String): PostEntity?
@Query(
"SELECT * " +
"FROM post " +
"WHERE replyToId = :currentPostId " + // All replies to current post
"OR id = :currentPostId" // Current post
)
suspend fun getPostAndReplies(currentPostId: String): List<PostEntity>
@MapInfo(keyColumn = "id")
@Query(
"SELECT id, post.pubkey, content, name, picture, post.createdAt " +
"FROM post " +
"LEFT JOIN profile ON post.pubkey = profile.pubkey " +
"WHERE id IN (:postIds) "
)
@RewriteQueriesToDropUnusedColumns
fun getMentionedPostsByIdFlow(postIds: Collection<String>): Flow<Map<String, MentionedPost>>
@Query(
"SELECT id, post.pubkey, content, name, picture, post.createdAt " +
"FROM post " +
"LEFT JOIN profile ON post.pubkey = profile.pubkey " +
"WHERE id = :postId"
)
@RewriteQueriesToDropUnusedColumns
suspend fun getMentionedPost(postId: String): MentionedPost?
@Query(
"SELECT id " +
"FROM post " +
"WHERE id IN (:postIds)"
)
suspend fun filterExistingIds(postIds: Collection<String>): List<String>
@Query(
"DELETE FROM post " +
"WHERE id NOT IN (:exclude) " +
"AND pubkey NOT IN (SELECT pubkey FROM account) " +
"AND id NOT IN (" +
// Exclude newest without the ones already excluded
"SELECT id FROM post WHERE id NOT IN (:exclude) " +
"AND pubkey NOT IN (SELECT pubkey FROM account) " +
"ORDER BY createdAt DESC LIMIT :amountToKeep" +
")"
)
suspend fun deleteAllExceptNewest(
amountToKeep: Int,
exclude: Collection<String>,
): Int
@Query(
"SELECT pubkey " +
"FROM post " +
"WHERE id IN (:postIds) " +
"AND pubkey NOT IN (SELECT pubkey FROM profile)"
)
suspend fun getUnknownAuthors(postIds: Collection<String>): List<String>
// UNION ALL retains order
@Query(
"SELECT * FROM post WHERE content LIKE :start ESCAPE '\\' " +
"UNION ALL " +
"SELECT * FROM post WHERE content LIKE :somewhere ESCAPE '\\' " +
"LIMIT :limit"
)
suspend fun internalGetPostsWithSimilarContent(
start: String,
somewhere: String,
limit: Int
): List<PostEntity>
suspend fun getPostsWithSimilarContent(content: String, limit: Int): List<PostEntity> {
val fixedContent = content.escapeSQLPercentChars()
return internalGetPostsWithSimilarContent(
start = "$fixedContent%",
somewhere = "%$fixedContent%",
limit = limit
)
}
@Query("DELETE FROM post WHERE id = :postId")
suspend fun deletePost(postId: NoteId)
}
| 5 | null | 3 | 35 | 30ffd7b88fdb612afd80e422a0bfe92a74733338 | 19,338 | Nozzle | MIT License |
app/src/main/java/com/example/project_music/ui/adapters/BaseAdapter.kt | Ikrom27 | 671,861,023 | false | null | package com.example.project_music.adapters.base_adapters
import android.annotation.SuppressLint
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<T>: RecyclerView.Adapter<BaseViewHolder<T>>() {
protected var mDataList: List<T> = ArrayList()
protected var mCallBack: BaseAdapterCallBack<T>? = null
fun attachCallBack(callBack: BaseAdapterCallBack<T>){
this.mCallBack = callBack
}
fun detachCallBack(){
this.mCallBack = null
}
@SuppressLint("NotifyDataSetChanged")
fun setList(items: List<T>){
(mDataList as ArrayList).addAll(items)
notifyDataSetChanged()
}
fun addItem(item: T){
(mDataList as ArrayList).add(item)
notifyItemInserted(mDataList.size - 1)
}
fun addItemToTop(item: T){
(mDataList as ArrayList).add(0, item)
notifyItemInserted(0)
}
fun updateItems(items: List<T>){
(mDataList as ArrayList).clear()
setList(items)
}
@SuppressLint("NotifyDataSetChanged")
fun clear(){
(mDataList as ArrayList).clear()
notifyDataSetChanged()
}
fun getItems(): List<T>{
return mDataList
}
override fun getItemCount(): Int {
return mDataList.count()
}
override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
val item: T = mDataList[position]
holder.bind(item)
holder.bindClickListener(item, mCallBack)
}
} | 0 | Kotlin | 0 | 0 | 79de5a3ae904553900ddbedb2916a7e097411f2e | 1,483 | MusicClub | MIT License |
app/src/main/java/com/masscode/manime/data/source/remote/network/ApiConfig.kt | agustiyann | 310,628,999 | false | null | package com.masscode.manime.data.source.remote.network
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
object ApiConfig {
val api: ApiServices
private val moshi: Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
init {
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.jikan.moe/v3/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(okHttpClient)
.build()
api = retrofit.create(ApiServices::class.java)
}
} | 0 | Kotlin | 3 | 24 | 76cc368799ddcbb1feca4a3d9cf5d9ccb368d792 | 1,038 | Manime | Apache License 2.0 |
common/common-core/src/main/kotlin/com/blank/common/core/utils/reflect/ReflectUtils.kt | qq781846712 | 705,955,843 | false | {"Kotlin": 848640, "Vue": 376959, "TypeScript": 137544, "Java": 45954, "HTML": 29445, "SCSS": 19657, "JavaScript": 3399, "Batchfile": 2056, "Shell": 1786, "Dockerfile": 1306} | package com.blank.common.core.utils.reflect
import cn.hutool.core.util.ReflectUtil
import org.apache.commons.lang3.StringUtils
/**
* 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
*/
object ReflectUtils {
private const val SETTER_PREFIX = "set"
private const val GETTER_PREFIX = "get"
/**
* 调用Getter方法.
* 支持多级,如:对象名.对象名.方法
*/
fun <E> invokeGetter(obj: Any, propertyName: String): E {
var `object` = obj
for (name in StringUtils.split(propertyName, ".")) {
val getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name)
`object` = ReflectUtil.invoke(`object`, getterMethodName)
}
return `object` as E
}
/**
* 调用Setter方法, 仅匹配方法名。
* 支持多级,如:对象名.对象名.方法
*/
fun <E> invokeSetter(obj: Any, propertyName: String, value: E) {
var `object` = obj
val names: Array<String> = StringUtils.split(propertyName, ".")
for (i in names.indices) {
if (i < names.size - 1) {
val getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i])
`object` = ReflectUtil.invoke(`object`, getterMethodName)
} else {
val setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i])
val method = ReflectUtil.getMethodByName(`object`.javaClass, setterMethodName)
ReflectUtil.invoke<Any>(`object`, method, value)
}
}
}
}
| 1 | Kotlin | 0 | 0 | dd6ef2a3a51f1c745e9d17c6abdf9b5c64abb592 | 1,504 | Ruoyi-Vue-Plus-Kotlin | Apache License 2.0 |
examples/cat-facts/src/main/java/com/fermion/example/cat_fact/di/AppComponent.kt | audibhavesh-fermion | 758,416,045 | false | {"Kotlin": 42525} | package com.fermion.example.cat_fact.di
import android.app.Application
import com.fermion.android.base.di.BaseAppModule
import com.fermion.android.dagger_processor.DaggerAppComponent
import com.fermion.example.cat_fact.di.generated.CommonBuilderModule
import com.fermion.example.cat_fact.network.CatNetworkModule
import com.fermion.example.cat_fact.ui.application.CatFactsApplication
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
@Singleton
@Component(
modules = [
AndroidSupportInjectionModule::class,
BaseAppModule::class,
CatNetworkModule::class,
CommonBuilderModule::class,
],
)
@DaggerAppComponent
interface AppComponent : AndroidInjector<CatFactsApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun withApplication(application: Application): Builder
fun build(): AppComponent
}
} | 0 | Kotlin | 0 | 0 | 1220ddf5d68263cdb2eb6555fb62e3bb1431fcd7 | 1,021 | android-native-dagger | Apache License 2.0 |
examples/cat-facts/src/main/java/com/fermion/example/cat_fact/di/AppComponent.kt | audibhavesh-fermion | 758,416,045 | false | {"Kotlin": 42525} | package com.fermion.example.cat_fact.di
import android.app.Application
import com.fermion.android.base.di.BaseAppModule
import com.fermion.android.dagger_processor.DaggerAppComponent
import com.fermion.example.cat_fact.di.generated.CommonBuilderModule
import com.fermion.example.cat_fact.network.CatNetworkModule
import com.fermion.example.cat_fact.ui.application.CatFactsApplication
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
@Singleton
@Component(
modules = [
AndroidSupportInjectionModule::class,
BaseAppModule::class,
CatNetworkModule::class,
CommonBuilderModule::class,
],
)
@DaggerAppComponent
interface AppComponent : AndroidInjector<CatFactsApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun withApplication(application: Application): Builder
fun build(): AppComponent
}
} | 0 | Kotlin | 0 | 0 | 1220ddf5d68263cdb2eb6555fb62e3bb1431fcd7 | 1,021 | android-native-dagger | Apache License 2.0 |
core/persistence/src/commonMain/kotlin/org/michaelbel/movies/persistence/database/ktx/PagingKeyPojoKtx.kt | michaelbel | 115,437,864 | false | {"Kotlin": 908384, "Swift": 692, "HTML": 606, "Shell": 235} | package org.michaelbel.movies.persistence.database.ktx
import org.michaelbel.movies.persistence.database.entity.PagingKeyDb
import org.michaelbel.movies.persistence.database.entity.pojo.PagingKeyPojo
internal val PagingKeyPojo.pagingKeyDb: PagingKeyDb
get() = PagingKeyDb(
pagingKey = pagingKey,
page = page,
totalPages = totalPages
) | 8 | Kotlin | 36 | 271 | 1da1d67e093ecb76057a06da0ef17f746ca06888 | 368 | movies | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/synthetics/CfnCanaryProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 142794926} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.synthetics
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.Boolean
import kotlin.Deprecated
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
/**
* Properties for defining a `CfnCanary`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.synthetics.*;
* CfnCanaryProps cfnCanaryProps = CfnCanaryProps.builder()
* .artifactS3Location("artifactS3Location")
* .code(CodeProperty.builder()
* .handler("handler")
* // the properties below are optional
* .s3Bucket("s3Bucket")
* .s3Key("s3Key")
* .s3ObjectVersion("s3ObjectVersion")
* .script("script")
* .sourceLocationArn("sourceLocationArn")
* .build())
* .executionRoleArn("executionRoleArn")
* .name("name")
* .runtimeVersion("runtimeVersion")
* .schedule(ScheduleProperty.builder()
* .expression("expression")
* // the properties below are optional
* .durationInSeconds("durationInSeconds")
* .build())
* // the properties below are optional
* .artifactConfig(ArtifactConfigProperty.builder()
* .s3Encryption(S3EncryptionProperty.builder()
* .encryptionMode("encryptionMode")
* .kmsKeyArn("kmsKeyArn")
* .build())
* .build())
* .deleteLambdaResourcesOnCanaryDeletion(false)
* .failureRetentionPeriod(123)
* .runConfig(RunConfigProperty.builder()
* .activeTracing(false)
* .environmentVariables(Map.of(
* "environmentVariablesKey", "environmentVariables"))
* .memoryInMb(123)
* .timeoutInSeconds(123)
* .build())
* .startCanaryAfterCreation(false)
* .successRetentionPeriod(123)
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .visualReference(VisualReferenceProperty.builder()
* .baseCanaryRunId("baseCanaryRunId")
* // the properties below are optional
* .baseScreenshots(List.of(BaseScreenshotProperty.builder()
* .screenshotName("screenshotName")
* // the properties below are optional
* .ignoreCoordinates(List.of("ignoreCoordinates"))
* .build()))
* .build())
* .vpcConfig(VPCConfigProperty.builder()
* .securityGroupIds(List.of("securityGroupIds"))
* .subnetIds(List.of("subnetIds"))
* // the properties below are optional
* .vpcId("vpcId")
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html)
*/
public interface CfnCanaryProps {
/**
* A structure that contains the configuration for canary artifacts, including the
* encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig)
*/
public fun artifactConfig(): Any? = unwrap(this).getArtifactConfig()
/**
* The location in Amazon S3 where Synthetics stores artifacts from the runs of this canary.
*
* Artifacts include the log file, screenshots, and HAR files. Specify the full location path,
* including `s3://` at the beginning of the path.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifacts3location)
*/
public fun artifactS3Location(): String
/**
* Use this structure to input your script code for the canary.
*
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version are
* also included. If the script is passed into the canary directly, the script code is contained in
* the value of `Script` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code)
*/
public fun code(): Any
/**
* (deprecated) Deletes associated lambda resources created by Synthetics if set to True.
*
* Default is False
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-deletelambdaresourcesoncanarydeletion)
* @deprecated this property has been deprecated
*/
@Deprecated(message = "deprecated in CDK")
public fun deleteLambdaResourcesOnCanaryDeletion(): Any? =
unwrap(this).getDeleteLambdaResourcesOnCanaryDeletion()
/**
* The ARN of the IAM role to be used to run the canary.
*
* This role must already exist, and must include `lambda.amazonaws.com` as a principal in the
* trust policy. The role must also have the following permissions:
*
* * `s3:PutObject`
* * `s3:GetBucketLocation`
* * `s3:ListAllMyBuckets`
* * `cloudwatch:PutMetricData`
* * `logs:CreateLogGroup`
* * `logs:CreateLogStream`
* * `logs:PutLogEvents`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn)
*/
public fun executionRoleArn(): String
/**
* The number of days to retain data about failed runs of this canary.
*
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-failureretentionperiod)
*/
public fun failureRetentionPeriod(): Number? = unwrap(this).getFailureRetentionPeriod()
/**
* The name for this canary.
*
* Be sure to give it a descriptive name that distinguishes it from other canaries in your
* account.
*
* Do not include secrets or proprietary information in your canary names. The canary name makes
* up part of the canary ARN, and the ARN is included in outbound calls over the internet. For more
* information, see [Security Considerations for Synthetics
* Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-name)
*/
public fun name(): String
/**
* A structure that contains input information for a canary run.
*
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig)
*/
public fun runConfig(): Any? = unwrap(this).getRunConfig()
/**
* Specifies the runtime version to use for the canary.
*
* For more information about runtime versions, see [Canary Runtime
* Versions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runtimeversion)
*/
public fun runtimeVersion(): String
/**
* A structure that contains information about how often the canary is to run, and when these runs
* are to stop.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule)
*/
public fun schedule(): Any
/**
* Specify TRUE to have the canary start making runs immediately after it is created.
*
* A canary that you create using CloudFormation can't be used to monitor the CloudFormation stack
* that creates the canary or to roll back that stack if there is a failure.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-startcanaryaftercreation)
*/
public fun startCanaryAfterCreation(): Any? = unwrap(this).getStartCanaryAfterCreation()
/**
* The number of days to retain data about successful runs of this canary.
*
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-successretentionperiod)
*/
public fun successRetentionPeriod(): Number? = unwrap(this).getSuccessRetentionPeriod()
/**
* The list of key-value pairs that are associated with the canary.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* If this canary performs visual monitoring by comparing screenshots, this structure contains the
* ID of the canary run to use as the baseline for screenshots, and the coordinates of any parts of
* the screen to ignore during the visual monitoring comparison.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference)
*/
public fun visualReference(): Any? = unwrap(this).getVisualReference()
/**
* If this canary is to test an endpoint in a VPC, this structure contains information about the
* subnet and security groups of the VPC endpoint.
*
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig)
*/
public fun vpcConfig(): Any? = unwrap(this).getVpcConfig()
/**
* A builder for [CfnCanaryProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param artifactConfig A structure that contains the configuration for canary artifacts,
* including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*/
public fun artifactConfig(artifactConfig: IResolvable)
/**
* @param artifactConfig A structure that contains the configuration for canary artifacts,
* including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*/
public fun artifactConfig(artifactConfig: CfnCanary.ArtifactConfigProperty)
/**
* @param artifactConfig A structure that contains the configuration for canary artifacts,
* including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("9023fcd521a70bff7f30d89364cec6a1defd5536978a80348e8db6bce0364b34")
public fun artifactConfig(artifactConfig: CfnCanary.ArtifactConfigProperty.Builder.() -> Unit)
/**
* @param artifactS3Location The location in Amazon S3 where Synthetics stores artifacts from
* the runs of this canary.
* Artifacts include the log file, screenshots, and HAR files. Specify the full location path,
* including `s3://` at the beginning of the path.
*/
public fun artifactS3Location(artifactS3Location: String)
/**
* @param code Use this structure to input your script code for the canary.
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*/
public fun code(code: IResolvable)
/**
* @param code Use this structure to input your script code for the canary.
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*/
public fun code(code: CfnCanary.CodeProperty)
/**
* @param code Use this structure to input your script code for the canary.
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("01b43f122b7425dd79484e68b6cf4dcfeaaa9f061282a09280c00d54fd757432")
public fun code(code: CfnCanary.CodeProperty.Builder.() -> Unit)
/**
* @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by
* Synthetics if set to True.
* Default is False
* @deprecated this property has been deprecated
*/
@Deprecated(message = "deprecated in CDK")
public fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: Boolean)
/**
* @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by
* Synthetics if set to True.
* Default is False
* @deprecated this property has been deprecated
*/
@Deprecated(message = "deprecated in CDK")
public
fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: IResolvable)
/**
* @param executionRoleArn The ARN of the IAM role to be used to run the canary.
* This role must already exist, and must include `lambda.amazonaws.com` as a principal in the
* trust policy. The role must also have the following permissions:
*
* * `s3:PutObject`
* * `s3:GetBucketLocation`
* * `s3:ListAllMyBuckets`
* * `cloudwatch:PutMetricData`
* * `logs:CreateLogGroup`
* * `logs:CreateLogStream`
* * `logs:PutLogEvents`
*/
public fun executionRoleArn(executionRoleArn: String)
/**
* @param failureRetentionPeriod The number of days to retain data about failed runs of this
* canary.
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*/
public fun failureRetentionPeriod(failureRetentionPeriod: Number)
/**
* @param name The name for this canary.
* Be sure to give it a descriptive name that distinguishes it from other canaries in your
* account.
*
* Do not include secrets or proprietary information in your canary names. The canary name makes
* up part of the canary ARN, and the ARN is included in outbound calls over the internet. For more
* information, see [Security Considerations for Synthetics
* Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html)
* .
*/
public fun name(name: String)
/**
* @param runConfig A structure that contains input information for a canary run.
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*/
public fun runConfig(runConfig: IResolvable)
/**
* @param runConfig A structure that contains input information for a canary run.
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*/
public fun runConfig(runConfig: CfnCanary.RunConfigProperty)
/**
* @param runConfig A structure that contains input information for a canary run.
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("95f2add22a5f361b1ae40d2f5574cb20e8cebf4216aaf41edc9ad2b55203c439")
public fun runConfig(runConfig: CfnCanary.RunConfigProperty.Builder.() -> Unit)
/**
* @param runtimeVersion Specifies the runtime version to use for the canary.
* For more information about runtime versions, see [Canary Runtime
* Versions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html)
* .
*/
public fun runtimeVersion(runtimeVersion: String)
/**
* @param schedule A structure that contains information about how often the canary is to run,
* and when these runs are to stop.
*/
public fun schedule(schedule: IResolvable)
/**
* @param schedule A structure that contains information about how often the canary is to run,
* and when these runs are to stop.
*/
public fun schedule(schedule: CfnCanary.ScheduleProperty)
/**
* @param schedule A structure that contains information about how often the canary is to run,
* and when these runs are to stop.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("3482ba41884599df1c8c020dc4ddf53c42bf23df0d9fdc1e4699f128f9922250")
public fun schedule(schedule: CfnCanary.ScheduleProperty.Builder.() -> Unit)
/**
* @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately
* after it is created.
* A canary that you create using CloudFormation can't be used to monitor the CloudFormation
* stack that creates the canary or to roll back that stack if there is a failure.
*/
public fun startCanaryAfterCreation(startCanaryAfterCreation: Boolean)
/**
* @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately
* after it is created.
* A canary that you create using CloudFormation can't be used to monitor the CloudFormation
* stack that creates the canary or to roll back that stack if there is a failure.
*/
public fun startCanaryAfterCreation(startCanaryAfterCreation: IResolvable)
/**
* @param successRetentionPeriod The number of days to retain data about successful runs of this
* canary.
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*/
public fun successRetentionPeriod(successRetentionPeriod: Number)
/**
* @param tags The list of key-value pairs that are associated with the canary.
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags The list of key-value pairs that are associated with the canary.
*/
public fun tags(vararg tags: CfnTag)
/**
* @param visualReference If this canary performs visual monitoring by comparing screenshots,
* this structure contains the ID of the canary run to use as the baseline for screenshots, and the
* coordinates of any parts of the screen to ignore during the visual monitoring comparison.
*/
public fun visualReference(visualReference: IResolvable)
/**
* @param visualReference If this canary performs visual monitoring by comparing screenshots,
* this structure contains the ID of the canary run to use as the baseline for screenshots, and the
* coordinates of any parts of the screen to ignore during the visual monitoring comparison.
*/
public fun visualReference(visualReference: CfnCanary.VisualReferenceProperty)
/**
* @param visualReference If this canary performs visual monitoring by comparing screenshots,
* this structure contains the ID of the canary run to use as the baseline for screenshots, and the
* coordinates of any parts of the screen to ignore during the visual monitoring comparison.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f28d0616e5457fd9b52b67cc85a38dbd57a32be581e7414a43fe10e53ea3a854")
public
fun visualReference(visualReference: CfnCanary.VisualReferenceProperty.Builder.() -> Unit)
/**
* @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains
* information about the subnet and security groups of the VPC endpoint.
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*/
public fun vpcConfig(vpcConfig: IResolvable)
/**
* @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains
* information about the subnet and security groups of the VPC endpoint.
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*/
public fun vpcConfig(vpcConfig: CfnCanary.VPCConfigProperty)
/**
* @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains
* information about the subnet and security groups of the VPC endpoint.
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("e60142d3e19dbffd9227f65176beee64498ccf695c8a131c34bfb96824cb0bd4")
public fun vpcConfig(vpcConfig: CfnCanary.VPCConfigProperty.Builder.() -> Unit)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanaryProps.Builder =
software.amazon.awscdk.services.synthetics.CfnCanaryProps.builder()
/**
* @param artifactConfig A structure that contains the configuration for canary artifacts,
* including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*/
override fun artifactConfig(artifactConfig: IResolvable) {
cdkBuilder.artifactConfig(artifactConfig.let(IResolvable.Companion::unwrap))
}
/**
* @param artifactConfig A structure that contains the configuration for canary artifacts,
* including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*/
override fun artifactConfig(artifactConfig: CfnCanary.ArtifactConfigProperty) {
cdkBuilder.artifactConfig(artifactConfig.let(CfnCanary.ArtifactConfigProperty.Companion::unwrap))
}
/**
* @param artifactConfig A structure that contains the configuration for canary artifacts,
* including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("9023fcd521a70bff7f30d89364cec6a1defd5536978a80348e8db6bce0364b34")
override
fun artifactConfig(artifactConfig: CfnCanary.ArtifactConfigProperty.Builder.() -> Unit):
Unit = artifactConfig(CfnCanary.ArtifactConfigProperty(artifactConfig))
/**
* @param artifactS3Location The location in Amazon S3 where Synthetics stores artifacts from
* the runs of this canary.
* Artifacts include the log file, screenshots, and HAR files. Specify the full location path,
* including `s3://` at the beginning of the path.
*/
override fun artifactS3Location(artifactS3Location: String) {
cdkBuilder.artifactS3Location(artifactS3Location)
}
/**
* @param code Use this structure to input your script code for the canary.
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*/
override fun code(code: IResolvable) {
cdkBuilder.code(code.let(IResolvable.Companion::unwrap))
}
/**
* @param code Use this structure to input your script code for the canary.
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*/
override fun code(code: CfnCanary.CodeProperty) {
cdkBuilder.code(code.let(CfnCanary.CodeProperty.Companion::unwrap))
}
/**
* @param code Use this structure to input your script code for the canary.
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("01b43f122b7425dd79484e68b6cf4dcfeaaa9f061282a09280c00d54fd757432")
override fun code(code: CfnCanary.CodeProperty.Builder.() -> Unit): Unit =
code(CfnCanary.CodeProperty(code))
/**
* @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by
* Synthetics if set to True.
* Default is False
* @deprecated this property has been deprecated
*/
@Deprecated(message = "deprecated in CDK")
override
fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: Boolean) {
cdkBuilder.deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion)
}
/**
* @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by
* Synthetics if set to True.
* Default is False
* @deprecated this property has been deprecated
*/
@Deprecated(message = "deprecated in CDK")
override
fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: IResolvable) {
cdkBuilder.deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion.let(IResolvable.Companion::unwrap))
}
/**
* @param executionRoleArn The ARN of the IAM role to be used to run the canary.
* This role must already exist, and must include `lambda.amazonaws.com` as a principal in the
* trust policy. The role must also have the following permissions:
*
* * `s3:PutObject`
* * `s3:GetBucketLocation`
* * `s3:ListAllMyBuckets`
* * `cloudwatch:PutMetricData`
* * `logs:CreateLogGroup`
* * `logs:CreateLogStream`
* * `logs:PutLogEvents`
*/
override fun executionRoleArn(executionRoleArn: String) {
cdkBuilder.executionRoleArn(executionRoleArn)
}
/**
* @param failureRetentionPeriod The number of days to retain data about failed runs of this
* canary.
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*/
override fun failureRetentionPeriod(failureRetentionPeriod: Number) {
cdkBuilder.failureRetentionPeriod(failureRetentionPeriod)
}
/**
* @param name The name for this canary.
* Be sure to give it a descriptive name that distinguishes it from other canaries in your
* account.
*
* Do not include secrets or proprietary information in your canary names. The canary name makes
* up part of the canary ARN, and the ARN is included in outbound calls over the internet. For more
* information, see [Security Considerations for Synthetics
* Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html)
* .
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param runConfig A structure that contains input information for a canary run.
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*/
override fun runConfig(runConfig: IResolvable) {
cdkBuilder.runConfig(runConfig.let(IResolvable.Companion::unwrap))
}
/**
* @param runConfig A structure that contains input information for a canary run.
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*/
override fun runConfig(runConfig: CfnCanary.RunConfigProperty) {
cdkBuilder.runConfig(runConfig.let(CfnCanary.RunConfigProperty.Companion::unwrap))
}
/**
* @param runConfig A structure that contains input information for a canary run.
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("95f2add22a5f361b1ae40d2f5574cb20e8cebf4216aaf41edc9ad2b55203c439")
override fun runConfig(runConfig: CfnCanary.RunConfigProperty.Builder.() -> Unit): Unit =
runConfig(CfnCanary.RunConfigProperty(runConfig))
/**
* @param runtimeVersion Specifies the runtime version to use for the canary.
* For more information about runtime versions, see [Canary Runtime
* Versions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html)
* .
*/
override fun runtimeVersion(runtimeVersion: String) {
cdkBuilder.runtimeVersion(runtimeVersion)
}
/**
* @param schedule A structure that contains information about how often the canary is to run,
* and when these runs are to stop.
*/
override fun schedule(schedule: IResolvable) {
cdkBuilder.schedule(schedule.let(IResolvable.Companion::unwrap))
}
/**
* @param schedule A structure that contains information about how often the canary is to run,
* and when these runs are to stop.
*/
override fun schedule(schedule: CfnCanary.ScheduleProperty) {
cdkBuilder.schedule(schedule.let(CfnCanary.ScheduleProperty.Companion::unwrap))
}
/**
* @param schedule A structure that contains information about how often the canary is to run,
* and when these runs are to stop.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("3482ba41884599df1c8c020dc4ddf53c42bf23df0d9fdc1e4699f128f9922250")
override fun schedule(schedule: CfnCanary.ScheduleProperty.Builder.() -> Unit): Unit =
schedule(CfnCanary.ScheduleProperty(schedule))
/**
* @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately
* after it is created.
* A canary that you create using CloudFormation can't be used to monitor the CloudFormation
* stack that creates the canary or to roll back that stack if there is a failure.
*/
override fun startCanaryAfterCreation(startCanaryAfterCreation: Boolean) {
cdkBuilder.startCanaryAfterCreation(startCanaryAfterCreation)
}
/**
* @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately
* after it is created.
* A canary that you create using CloudFormation can't be used to monitor the CloudFormation
* stack that creates the canary or to roll back that stack if there is a failure.
*/
override fun startCanaryAfterCreation(startCanaryAfterCreation: IResolvable) {
cdkBuilder.startCanaryAfterCreation(startCanaryAfterCreation.let(IResolvable.Companion::unwrap))
}
/**
* @param successRetentionPeriod The number of days to retain data about successful runs of this
* canary.
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*/
override fun successRetentionPeriod(successRetentionPeriod: Number) {
cdkBuilder.successRetentionPeriod(successRetentionPeriod)
}
/**
* @param tags The list of key-value pairs that are associated with the canary.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags The list of key-value pairs that are associated with the canary.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
/**
* @param visualReference If this canary performs visual monitoring by comparing screenshots,
* this structure contains the ID of the canary run to use as the baseline for screenshots, and the
* coordinates of any parts of the screen to ignore during the visual monitoring comparison.
*/
override fun visualReference(visualReference: IResolvable) {
cdkBuilder.visualReference(visualReference.let(IResolvable.Companion::unwrap))
}
/**
* @param visualReference If this canary performs visual monitoring by comparing screenshots,
* this structure contains the ID of the canary run to use as the baseline for screenshots, and the
* coordinates of any parts of the screen to ignore during the visual monitoring comparison.
*/
override fun visualReference(visualReference: CfnCanary.VisualReferenceProperty) {
cdkBuilder.visualReference(visualReference.let(CfnCanary.VisualReferenceProperty.Companion::unwrap))
}
/**
* @param visualReference If this canary performs visual monitoring by comparing screenshots,
* this structure contains the ID of the canary run to use as the baseline for screenshots, and the
* coordinates of any parts of the screen to ignore during the visual monitoring comparison.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f28d0616e5457fd9b52b67cc85a38dbd57a32be581e7414a43fe10e53ea3a854")
override
fun visualReference(visualReference: CfnCanary.VisualReferenceProperty.Builder.() -> Unit):
Unit = visualReference(CfnCanary.VisualReferenceProperty(visualReference))
/**
* @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains
* information about the subnet and security groups of the VPC endpoint.
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*/
override fun vpcConfig(vpcConfig: IResolvable) {
cdkBuilder.vpcConfig(vpcConfig.let(IResolvable.Companion::unwrap))
}
/**
* @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains
* information about the subnet and security groups of the VPC endpoint.
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*/
override fun vpcConfig(vpcConfig: CfnCanary.VPCConfigProperty) {
cdkBuilder.vpcConfig(vpcConfig.let(CfnCanary.VPCConfigProperty.Companion::unwrap))
}
/**
* @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains
* information about the subnet and security groups of the VPC endpoint.
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("e60142d3e19dbffd9227f65176beee64498ccf695c8a131c34bfb96824cb0bd4")
override fun vpcConfig(vpcConfig: CfnCanary.VPCConfigProperty.Builder.() -> Unit): Unit =
vpcConfig(CfnCanary.VPCConfigProperty(vpcConfig))
public fun build(): software.amazon.awscdk.services.synthetics.CfnCanaryProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.synthetics.CfnCanaryProps,
) : CdkObject(cdkObject), CfnCanaryProps {
/**
* A structure that contains the configuration for canary artifacts, including the
* encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig)
*/
override fun artifactConfig(): Any? = unwrap(this).getArtifactConfig()
/**
* The location in Amazon S3 where Synthetics stores artifacts from the runs of this canary.
*
* Artifacts include the log file, screenshots, and HAR files. Specify the full location path,
* including `s3://` at the beginning of the path.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifacts3location)
*/
override fun artifactS3Location(): String = unwrap(this).getArtifactS3Location()
/**
* Use this structure to input your script code for the canary.
*
* This structure contains the Lambda handler with the location where the canary should start
* running the script. If the script is stored in an S3 bucket, the bucket name, key, and version
* are also included. If the script is passed into the canary directly, the script code is
* contained in the value of `Script` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code)
*/
override fun code(): Any = unwrap(this).getCode()
/**
* (deprecated) Deletes associated lambda resources created by Synthetics if set to True.
*
* Default is False
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-deletelambdaresourcesoncanarydeletion)
* @deprecated this property has been deprecated
*/
@Deprecated(message = "deprecated in CDK")
override fun deleteLambdaResourcesOnCanaryDeletion(): Any? =
unwrap(this).getDeleteLambdaResourcesOnCanaryDeletion()
/**
* The ARN of the IAM role to be used to run the canary.
*
* This role must already exist, and must include `lambda.amazonaws.com` as a principal in the
* trust policy. The role must also have the following permissions:
*
* * `s3:PutObject`
* * `s3:GetBucketLocation`
* * `s3:ListAllMyBuckets`
* * `cloudwatch:PutMetricData`
* * `logs:CreateLogGroup`
* * `logs:CreateLogStream`
* * `logs:PutLogEvents`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn)
*/
override fun executionRoleArn(): String = unwrap(this).getExecutionRoleArn()
/**
* The number of days to retain data about failed runs of this canary.
*
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-failureretentionperiod)
*/
override fun failureRetentionPeriod(): Number? = unwrap(this).getFailureRetentionPeriod()
/**
* The name for this canary.
*
* Be sure to give it a descriptive name that distinguishes it from other canaries in your
* account.
*
* Do not include secrets or proprietary information in your canary names. The canary name makes
* up part of the canary ARN, and the ARN is included in outbound calls over the internet. For more
* information, see [Security Considerations for Synthetics
* Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-name)
*/
override fun name(): String = unwrap(this).getName()
/**
* A structure that contains input information for a canary run.
*
* If you omit this structure, the frequency of the canary is used as canary's timeout value, up
* to a maximum of 900 seconds.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig)
*/
override fun runConfig(): Any? = unwrap(this).getRunConfig()
/**
* Specifies the runtime version to use for the canary.
*
* For more information about runtime versions, see [Canary Runtime
* Versions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runtimeversion)
*/
override fun runtimeVersion(): String = unwrap(this).getRuntimeVersion()
/**
* A structure that contains information about how often the canary is to run, and when these
* runs are to stop.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule)
*/
override fun schedule(): Any = unwrap(this).getSchedule()
/**
* Specify TRUE to have the canary start making runs immediately after it is created.
*
* A canary that you create using CloudFormation can't be used to monitor the CloudFormation
* stack that creates the canary or to roll back that stack if there is a failure.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-startcanaryaftercreation)
*/
override fun startCanaryAfterCreation(): Any? = unwrap(this).getStartCanaryAfterCreation()
/**
* The number of days to retain data about successful runs of this canary.
*
* If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-successretentionperiod)
*/
override fun successRetentionPeriod(): Number? = unwrap(this).getSuccessRetentionPeriod()
/**
* The list of key-value pairs that are associated with the canary.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* If this canary performs visual monitoring by comparing screenshots, this structure contains
* the ID of the canary run to use as the baseline for screenshots, and the coordinates of any
* parts of the screen to ignore during the visual monitoring comparison.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference)
*/
override fun visualReference(): Any? = unwrap(this).getVisualReference()
/**
* If this canary is to test an endpoint in a VPC, this structure contains information about the
* subnet and security groups of the VPC endpoint.
*
* For more information, see [Running a Canary in a
* VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig)
*/
override fun vpcConfig(): Any? = unwrap(this).getVpcConfig()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnCanaryProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanaryProps):
CfnCanaryProps = CdkObjectWrappers.wrap(cdkObject) as? CfnCanaryProps ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnCanaryProps):
software.amazon.awscdk.services.synthetics.CfnCanaryProps = (wrapped as CdkObject).cdkObject
as software.amazon.awscdk.services.synthetics.CfnCanaryProps
}
}
| 4 | Kotlin | 0 | 4 | e15f2e27e08adeb755ad44b2424c195521a6f5ba | 45,141 | kotlin-cdk-wrapper | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/component/GardenListItem.kt | clockvoid | 347,287,370 | false | null | /*
* Copyright 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
*
* 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.example.androiddevchallenge.ui.component
import android.net.Uri
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.width
import androidx.compose.material.Checkbox
import androidx.compose.material.CheckboxDefaults
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import com.example.androiddevchallenge.model.Garden
import com.example.androiddevchallenge.ui.theme.MyTheme
import dev.chrisbanes.accompanist.coil.CoilImage
@Composable
fun GardenListItem(garden: Garden) {
val state = mutableStateOf(false)
Surface(
color = MaterialTheme.colors.background,
modifier = Modifier.fillMaxWidth()
) {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp)
) {
val (image, name, description, checkBox, line) = createRefs()
CoilImage(
data = garden.imageUrl,
contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.height(64.dp)
.width(64.dp)
.constrainAs(image) {
top.linkTo(parent.top)
start.linkTo(parent.start)
}
)
Text(
text = garden.name,
style = MaterialTheme.typography.h2,
modifier = Modifier
.constrainAs(name) {
start.linkTo(image.end, 16.dp)
}
.paddingFromBaseline(top = 24.dp)
)
Text(
text = garden.description,
style = MaterialTheme.typography.body1,
modifier = Modifier
.constrainAs(description) {
start.linkTo(image.end, 16.dp)
top.linkTo(name.bottom)
}
.paddingFromBaseline(bottom = 24.dp)
)
Checkbox(
checked = state.value,
onCheckedChange = { state.value = it },
colors = CheckboxDefaults.colors(checkmarkColor = MaterialTheme.colors.onSecondary),
modifier = Modifier.constrainAs(checkBox) {
top.linkTo(image.top)
bottom.linkTo(image.bottom)
end.linkTo(parent.end)
}
)
Divider(
color = MaterialTheme.colors.onBackground,
thickness = 1.dp,
modifier = Modifier
.constrainAs(line) {
bottom.linkTo(image.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.padding(start = 72.dp)
)
}
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightGardenListItemPreview() {
val sampleGarden = Garden(
imageUrl = Uri.EMPTY,
name = "Sample"
)
MyTheme {
GardenListItem(sampleGarden)
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun DarkGardenListItemPreview() {
val sampleGarden = Garden(
imageUrl = Uri.EMPTY,
name = "Sample"
)
MyTheme(darkTheme = true) {
GardenListItem(sampleGarden)
}
}
| 0 | Kotlin | 0 | 0 | 6b7152d18a5dfa386939bdd5107d250cea2f6b36 | 4,792 | compose-speed-round | Apache License 2.0 |
cryptography-providers-tests-api/src/wasmJsMain/kotlin/TestPlatform.wasmJs.kt | whyoleg | 492,907,371 | false | {"Kotlin": 1074574, "JavaScript": 318} | /*
* Copyright (c) 2023-2024 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.whyoleg.cryptography.providers.tests.api
internal actual val currentTestPlatform: TestPlatform = jsPlatform().run {
when {
isNode -> TestPlatform.WasmJs.NodeJS(
version = nodeVersion ?: "",
os = nodeOs ?: "",
arch = nodeArch ?: "",
)
else -> TestPlatform.WasmJs.Browser(
brand = browserBrand ?: "",
platform = browserPlatform ?: "",
userAgent = browserUserAgent ?: "",
)
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData
// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform
//language=JavaScript
private fun jsPlatform(): JsPlatform {
js(
code = """
var isNodeJs = typeof process !== 'undefined' && process.versions != null && process.versions.node != null
if (isNodeJs) {
return {
isNode: true,
nodeVersion: process.version,
nodeOs: process.platform,
nodeArch: process.arch
};
} else {
return {
isNode: false,
browserBrand: navigator.userAgentData ? navigator.userAgentData.brand : '',
browserPlatform: navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
browserUserAgent: window.navigator.userAgent
};
}
"""
)
}
private external interface JsPlatform : JsAny {
val isNode: Boolean
// nodeJs
val nodeVersion: String?
val nodeOs: String?
val nodeArch: String?
// browser
val browserBrand: String?
val browserPlatform: String?
val browserUserAgent: String?
}
| 10 | Kotlin | 20 | 302 | 69b77a88b4b81109704475ed02be48d263d1a1c8 | 1,849 | cryptography-kotlin | Apache License 2.0 |
src/main/kotlin/resource/ApiTokens.kt | Jeliuc-Labs | 765,983,556 | false | {"Kotlin": 76599} | /*
* Copyright 2024 Jeliuc.com S.R.L. and Turso SDK contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jeliuc.turso.sdk.resource
import com.jeliuc.turso.sdk.TursoClient
import com.jeliuc.turso.sdk.model.CreateApiTokenResponse
import com.jeliuc.turso.sdk.model.ListApiTokensResponse
import com.jeliuc.turso.sdk.model.RevokeApiTokenResponse
import com.jeliuc.turso.sdk.model.ValidateTokenResponse
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.http.ContentType
import io.ktor.http.contentType
val TursoClient.apiTokens: ApiTokens
get() = ApiTokens(this)
/**
* Turso API Tokens API Resource
*
* ```kotlin
* // client: TursoClient
* val apiTokens = client.apiTokens.list()
* ```
*/
class ApiTokens(private val client: TursoClient) : ResponseHandler() {
/**
* Creates API token
*
* @see [https://docs.turso.tech/api-reference/tokens/create]
*/
suspend fun create(tokenName: String) =
client.httpClient.post(Resources.tokenPath(tokenName)) {
contentType(ContentType.Application.Json)
}.let { response ->
handleResponse<CreateApiTokenResponse>(response)
}
/**
* Validates the current API token
*
* @see [https://docs.turso.tech/api-reference/tokens/validate]
*/
suspend fun validate() =
client.httpClient.get(Resources.validatePath()) {
contentType(ContentType.Application.Json)
}.let { response ->
handleResponse<ValidateTokenResponse>(response)
}
/**
* Lists all API tokens
*
* @see [https://docs.turso.tech/api-reference/tokens/list]
*/
suspend fun list() =
client.httpClient.get(Resources.basePath()) {
contentType(ContentType.Application.Json)
}.let { response ->
handleResponse<ListApiTokensResponse>(response)
}
/**
* Revokes an API token
*
* @see [https://docs.turso.tech/api-reference/tokens/revoke]
*/
suspend fun revoke(tokenName: String) =
client.httpClient.delete(Resources.tokenPath(tokenName)) {
contentType(ContentType.Application.Json)
}.let {
handleResponse<RevokeApiTokenResponse>(it)
}
internal object Resources {
private const val BASE_PATH = "/v1/auth/api-tokens"
fun basePath() = BASE_PATH
fun tokenPath(tokenName: String) = "$BASE_PATH/$tokenName"
fun validatePath() = "/v1/auth/validate"
}
}
| 0 | Kotlin | 1 | 1 | c93484ad58151c746174a9196e81d0969f429890 | 2,634 | turso-sdk | Apache License 2.0 |
mbcarkit/src/main/java/com/daimler/mbcarkit/socket/observable/VehicleDataObservable.kt | Daimler | 199,815,262 | false | null | package com.daimler.mbcarkit.socket.observable
import com.daimler.mbcarkit.business.model.vehicle.VehicleData
import com.daimler.mbcarkit.business.model.vehicle.VehicleStatus
import com.daimler.mbcarkit.util.isUpdatedBy
class VehicleDataObservable(vehicleData: VehicleData) : VehicleObservableMessage<VehicleData>(vehicleData) {
override fun hasChanged(oldVehicleStatus: VehicleStatus?, updatedVehicleStatus: VehicleStatus): Boolean {
return oldVehicleStatus == null || vehicleDataChanged(oldVehicleStatus.vehicle, updatedVehicleStatus.vehicle)
}
private fun vehicleDataChanged(oldVehicleData: VehicleData, updatedVehicleData: VehicleData) =
oldVehicleData.getAllAttributes().isUpdatedBy(updatedVehicleData.getAllAttributes())
}
| 1 | null | 8 | 15 | 3721af583408721b9cd5cf89dd7b99256e9d7dda | 761 | MBSDK-Mobile-Android | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.